-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrain_audioTPOT.py
230 lines (188 loc) · 7.55 KB
/
train_audioTPOT.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
'''
================================================
## VOICEBOOK REPOSITORY ##
================================================
repository name: voicebook
repository version: 1.0
repository link: https://github.com/jim-schwoebel/voicebook
author: Jim Schwoebel
author contact: [email protected]
description: a book and repo to get you started programming voice applications in Python - 10 chapters and 200+ scripts.
license category: opensource
license: Apache 2.0 license
organization name: NeuroLex Laboratories, Inc.
location: Seattle, WA
website: https://neurolex.ai
release date: 2018-09-28
This code (voicebook) is hereby released under a Apache 2.0 license license.
For more information, check out the license terms below.
================================================
## LICENSE TERMS ##
================================================
Copyright 2018 NeuroLex Laboratories, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
## SERVICE STATEMENT ##
================================================
If you are using the code written for a larger project, we are
happy to consult with you and help you with deployment. Our team
has >10 world experts in Kafka distributed architectures, microservices
built on top of Node.js / Python / Docker, and applying machine learning to
model speech and text data.
We have helped a wide variety of enterprises - small businesses,
researchers, enterprises, and/or independent developers.
If you would like to work with us let us know @ [email protected].
================================================
## TRAIN_AUDIOTPOT.PY ##
================================================
Auto optimize the parameters for a classification model.
Follows TPOT documentation
https://github.com/EpistasisLab/tpot
'''
import json, os, random
import numpy as np
from tpot import TPOTClassifier
from tpot import TPOTRegressor
from sklearn.model_selection import train_test_split
import librosa_features as lf
## helper function
def find_wav(listdir):
wavfiles=list()
for j in range(len(listdir)):
if listdir[j][-4:]=='.wav':
wavfiles.append(listdir[j])
return wavfiles
def featurize_json(wavfile):
features, labels = lf.librosa_featurize(wavfile, False)
jsonfile=open(wavfile[0:-4]+'.json','w')
data={'features': features.tolist(),
'labels': labels}
json.dump(data,jsonfile)
jsonfile.close()
return features
## initialize directories and classes
model_dir=os.getcwd()+'/models/'
data_dir=os.getcwd()+'/data/'
os.chdir(data_dir)
mtype=input('classification (c) or regression (r) problem? \n').lower().replace(' ','')
while mtype not in ['c','r', 'classification','regression']:
print('input not recognized')
mtype=input('is this classification (c) or regression (r) problem? \n').lower().replace(' ','')
one=input('what is the name of class 1? \n')
two=input('what is the name of class 2? \n')
jsonfilename=one+'_'+two+'.json'
onelist=list()
twolist=list()
if jsonfilename not in os.listdir():
os.chdir(one)
listdir=os.listdir()
wavfiles_one=find_wav(listdir)
for i in range(len(wavfiles_one)):
features=featurize_json(wavfiles_one[i])
onelist.append(features.tolist())
os.chdir(data_dir)
os.chdir(two)
listdir=os.listdir()
wavfiles_two=find_wav(listdir)
for i in range(len(wavfiles_two)):
features=featurize_json(wavfiles_two[i])
twolist.append(features.tolist())
os.chdir(data_dir)
jsonfile=open(jsonfilename,'w')
# shuffle lists
random.shuffle(onelist)
random.shuffle(twolist)
# make it so classes have equal lengths
if len(onelist) > len(twolist):
onelist=onelist[0:len(twolist)]
elif len(twolist) > len(onelist):
twolist=twolist[0:len(onelist)]
print(len(twolist))
print(len(onelist))
data={one: onelist,
two: twolist}
json.dump(data,jsonfile)
jsonfile.close()
try:
g=json.load(open(jsonfilename))
one=g[one]
two=g[two]
os.chdir(model_dir)
# now preprocess data
alldata=list()
for i in range(len(one)):
alldata.append(one[i])
for i in range(len(two)):
alldata.append(two[i])
labels=list()
for i in range(len(one)):
labels.append(0)
for i in range(len(two)):
labels.append(1)
alldata=np.asarray(alldata)
labels=np.asarray(labels)
# get train and test data
X_train, X_test, y_train, y_test = train_test_split(alldata, labels, train_size=0.750, test_size=0.250)
if mtype in [' classification', 'c']:
tpot=TPOTClassifier(generations=5, population_size=50, verbosity=2, n_jobs=-1)
tpotname='%s_tpotclassifier.py'%(jsonfilename[0:-5])
elif mtype in ['regression','r']:
tpot = TPOTRegressor(generations=5, population_size=20, verbosity=2)
tpotname='%s_tpotregression.py'%(jsonfilename[0:-5])
tpot.fit(X_train, y_train)
accuracy=tpot.score(X_test,y_test)
tpot.export(tpotname)
# export data to .json format
data={
'data': alldata.tolist(),
'labels': labels.tolist(),
}
jsonfilename='%s_.json'%(tpotname[0:-3])
jsonfile=open(jsonfilename,'w')
json.dump(data,jsonfile)
jsonfile.close()
# now edit the file and run it
g=open(tpotname).read()
g=g.replace("import numpy as np", "import numpy as np \nimport json, pickle")
g=g.replace("tpot_data = pd.read_csv(\'PATH/TO/DATA/FILE\', sep=\'COLUMN_SEPARATOR\', dtype=np.float64)","g=json.load(open('%s'))\ntpot_data=g['labels']"%(jsonfilename))
g=g.replace("features = tpot_data.drop('target', axis=1).values","features=g['data']\n")
g=g.replace("tpot_data['target'].values", "tpot_data")
g=g.replace("results = exported_pipeline.predict(testing_features)", "print('saving classifier to disk')\nf=open('%s','wb')\npickle.dump(exported_pipeline,f)\nf.close()"%(jsonfilename[0:-6]+'.pickle'))
g1=g.find('exported_pipeline = ')
g2=g.find('exported_pipeline.fit(training_features, training_target)')
modeltype=g[g1:g2]
os.remove(tpotname)
t=open(tpotname,'w')
t.write(g)
t.close()
os.system('python3 %s'%(tpotname))
# now write an accuracy label
os.remove(jsonfilename)
jsonfilename='%s.json'%(tpotname[0:-3])
print('saving .JSON file (%s)'%(jsonfilename))
jsonfile=open(jsonfilename,'w')
if mtype in ['classification', 'c']:
data={
'model name':jsonfilename[0:-5]+'.pickle',
'accuracy':accuracy,
'model type':'TPOTclassification_'+modeltype,
}
elif mtype in ['regression', 'r']:
data={
'model name':jsonfilename[0:-5]+'.pickle',
'accuracy':accuracy,
'model type':'TPOTregression_'+modeltype,
}
json.dump(data,jsonfile)
jsonfile.close()
except:
print('error, please put %s in %s'%(jsonfile, data_dir))
print('note this can be done with train_audioclassify.py script')