-
Notifications
You must be signed in to change notification settings - Fork 0
/
featureExtract.py
309 lines (272 loc) · 9.59 KB
/
featureExtract.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#import librosa
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import random
from pyAudioAnalysis import audioBasicIO
from pyAudioAnalysis import audioFeatureExtraction
from os import listdir, walk
import os
from os.path import isfile, join
class dataHolder:
def __init__(self, FLAGS):
self.featuresFileName = "features"
self.labelsFileName = "labels"
self.FLAGS = FLAGS
self.indices = FLAGS.indices
filenames = self.getAllFilenames()
# self.testFileReading()
self.data, self.labels = self.getAllFeatures(filenames)
self.train, self.valid, self.test, self.classifier_train, self.train_labels, self.valid_labels, self.test_labels, self.classifier_train_labels = self.splitData(self.data, self.labels)
def splitData(self, data, dataLabels):
classifier_train = int(.1*float(len(data)))
valid = int(.8*float(len(data)))
test = int(.9*float(len(data)))
return data[0:valid], data[valid:test], data[test:], data[0:classifier_train], dataLabels[0:valid], dataLabels[valid:test], dataLabels[test:], dataLabels[0:classifier_train]
def getBatchOf(self, size, length, out_type):
returnBatch = []
returnLabels = []
takenFrom = self.train
for i in range(size):
item = takenFrom[random.randint(0,len(takenFrom)-1)]
endind = random.randint(length, len(item)-1)
startind = endind-length
returnBatch.append(item[startind:endind])
if out_type.lower() == "vanilla autoencoder":
returnLabels.append(item[startind:endind])
elif out_type.lower() == "predict single next":
returnLabels.append(item[endind])
elif out_type.lower() == "predict <timestep> next":
returnLabels.append(item[startind+1:endind+1])
else:
raise NotImplementedError
return np.array(returnBatch), np.array(returnLabels)
def getBatchValid(self, size, length, out_type):
returnBatch = []
returnLabels = []
takenFrom = self.valid
for i in range(size):
item = takenFrom[random.randint(0,len(takenFrom)-1)]
endind = random.randint(length, len(item)-1)
startind = endind-length
returnBatch.append(item[startind:endind])
if out_type.lower() == "vanilla autoencoder":
returnLabels.append(item[startind:endind])
elif out_type.lower() == "predict single next":
returnLabels.append(item[endind])
elif out_type.lower() == "predict <timestep> next":
returnLabels.append(item[startind+1:endind+1])
else:
raise NotImplementedError
return np.array(returnBatch), np.array(returnLabels)
def getBatchClassifierTrainWithLabels(self, size, length):
returnBatch = []
returnLabels = []
takenFrom = self.classifier_train
labelsTaken = self.classifier_train_labels
for i in range(size):
index = random.randint(0,len(takenFrom)-1)
item = takenFrom[index]
endind = random.randint(length, len(item)-1)
startind = endind-length
returnBatch.append(item[startind:endind])
returnLabels.append(labelsTaken[index])
# print np.shape(np.array(returnBatch)), np.shape(np.array(returnLabels))
return np.array(returnBatch), np.array(returnLabels)
def getBatchWithLabels(self, size, length):
returnBatch = []
returnLabels = []
takenFrom = self.train
labelsTaken = self.train_labels
for i in range(size):
index = random.randint(0,len(takenFrom)-1)
item = takenFrom[index]
endind = random.randint(length, len(item)-1)
startind = endind-length
returnBatch.append(item[startind:endind])
returnLabels.append(labelsTaken[index])
return np.array(returnBatch), np.array(returnLabels)
def getBatchWithLabelsValid(self, size, length):
returnBatch = []
returnLabels = []
takenFrom = self.valid
labelsTaken = self.valid_labels
for i in range(size):
index = random.randint(0,len(takenFrom)-1)
item = takenFrom[index]
endind = random.randint(length, len(item)-1)
startind = endind-length
returnBatch.append(item[startind:endind])
returnLabels.append(labelsTaken[index])
# print np.shape(np.array(returnBatch)), np.shape(np.array(returnLabels))
return np.array(returnBatch), np.array(returnLabels)
def getAllValidationBatchesRandom(self, size, length):
# print "get all validation batches random"
batches = []
#random.seed(48392)
batch_index = 0
# print "len(self.valid)", len(self.valid)
# print "size", size
# print "length", length
while batch_index <= len(self.valid) - size:
# print batch_index
batch = []
labels = []
for i in range(size):
index = batch_index + i
item = self.valid[index]
endind = random.randint(length, len(item)-1)
startind = endind-length
batch.append(item[startind:endind])
labels.append(self.valid_labels[index])
pairForBatch = [np.array(batch), np.array(labels)]
batches.append(pairForBatch)
batch_index += size
# print "shape", np.shape(batches)
return batches
def getAllValidationBatches(self, size, length):
# print "get all validation batches"
batches = []
batch_index = 0
# print "len(self.valid)", len(self.valid)
# print "size", size
# print "length", length
# we want some number of batches
# each batch is of length size
# each batch has a series of audio which are "length" timesteps
# we enumerate through the files to create batches
batch = []
labels = []
for index, item in enumerate(self.valid):
for startInd in [length*x for x in range(len(item)/length)]:
if len(batch) == size:
pairForBatch = [np.array(batch), np.array(labels)]
batches.append(pairForBatch)
batch = []
labels = []
endInd = startInd + length
values = item[startInd:endInd]
batch.append(values)
labels.append(self.valid_labels[index])
return batches
def getAllValidationBatchesFromMiddle(self, size, length):
# print "get all validation batches"
batches = []
#random.seed(48392)
batch_index = 0
# print "len(self.valid)", len(self.valid)
# print "size", size
# print "length", length
# we want some number of batches
# each batch is of length size
# each batch has a series of audio which are "length" timesteps
# we enumerate through the files to create batches
batch = []
labels = []
for index, item in enumerate(self.valid):
startIndices = [length*x for x in range(len(item)/length)]
startIndicesMiddle = startIndices[len(startIndices)/3:len(startIndices) *2/3]
for startInd in startIndicesMiddle:
if len(batch) == size:
pairForBatch = [np.array(batch), np.array(labels)]
batches.append(pairForBatch)
batch = []
labels = []
endInd = startInd + length
values = item[startInd:endInd]
batch.append(values)
labels.append(self.valid_labels[index])
return batches
def getAllTestBatches(self, size, length):
# print "get all validation batches"
batches = []
batch_index = 0
# print "len(self.valid)", len(self.test)
# print "size", size
# print "length", length
# we want some number of batches
# each batch is of length size
# each batch has a series of audio which are "length" timesteps
# we enumerate through the files to create batches
batch = []
labels = []
for index, item in enumerate(self.test):
for startInd in [length*x for x in range(len(item)/length)]:
if len(batch) == size:
pairForBatch = [np.array(batch), np.array(labels)]
batches.append(pairForBatch)
batch = []
labels = []
endInd = startInd + length
values = item[startInd:endInd]
batch.append(values)
labels.append(self.test_labels[index])
return batches
def getAllFeatures(self, filenames):
allIndices = range(34)
try:
features = np.load(self.featuresFileName + ".npy")
labels = np.load(self.labelsFileName + ".npy")
sliced_features = [x[:,self.indices] for x in features]
return sliced_features, labels
except IOError:
# print "Generating features"
features, labels = self.parseAllFeatures(allIndices, filenames)
np.save(self.featuresFileName, features)
np.save(self.labelsFileName, labels)
sliced_features = [x[:,self.indices] for x in features]
return sliced_features, labels
def parseAllFeatures(self, indices, filenames):
returnList = []
returnLabels = []
tot = np.zeros(len(indices))
num = 0
for el in filenames:
classname = el.split('/')[-1].strip()
# print (el, classname)
try:
[Fs, x] = audioBasicIO.readAudioFile(el);
except ValueError:
continue
F = None
if len(x.shape) == 1:
F = audioFeatureExtraction.stFeatureExtraction(x, Fs, 0.050*Fs, 0.025*Fs);
else:
F = audioFeatureExtraction.stFeatureExtraction(x[:,0], Fs, 0.050*Fs, 0.025*Fs);
tot += np.mean(F[indices,:],axis=1)
num +=1
returnList.append(F[indices,:].T)
if classname[0] == 'a':
returnLabels.append(0)
elif classname[0] == 'd':
returnLabels.append(1)
elif classname[0] == 'f':
returnLabels.append(2)
elif classname[0] == 'h':
returnLabels.append(3)
elif classname[0] == 'n':
returnLabels.append(4)
elif classname[0:2] == 'sa':
returnLabels.append(5)
else:
returnLabels.append(6)
returnListLength = len(returnList)
random.seed(13921)
shuffledIndices = random.sample(range(returnListLength), returnListLength)
shuffledReturnList = [ returnList[i] for i in shuffledIndices]
shuffledReturnLabels = [ returnLabels[i] for i in shuffledIndices]
return shuffledReturnList, shuffledReturnLabels
#return returnList, returnLabels
def getAllFilenames(self):
#fileTypes = ['a']
#numbers = [5]
returnList = []
paths = []
paths.extend(['RML2/s' + str(i+1) for i in range(8)])
paths.extend(['data/DC', 'data/JE', 'data/JK', 'data/KL'])
for mypath in paths:
for (dirpath, dirnames, filenames) in walk(mypath):
for f in filenames:
if f.split('.')[1] == 'wav':
returnList.append(dirpath + "/" + f)
return returnList