-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSTM09_sklearn_classifiers.py
633 lines (555 loc) · 22.4 KB
/
STM09_sklearn_classifiers.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 2 12:11:23 2024
"""
import numpy as np
import pandas as pd
import datetime
import sys
import os
import json
from joblib import dump
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import make_pipeline
from sklearn.metrics import roc_auc_score, classification_report, confusion_matrix
from sklearn.kernel_approximation import RBFSampler
from bayes_opt import BayesianOptimization
from bayes_opt.logger import JSONLogger
from bayes_opt.event import Events
# %% prepData
def prepData():
corpus_speech_list = ['BibleTTS/akuapem-twi',
'BibleTTS/asante-twi',
'BibleTTS/ewe',
'BibleTTS/hausa',
'BibleTTS/lingala',
'BibleTTS/yoruba',
'Buckeye',
'EUROM',
'HiltonMoser2022_speech',
'LibriSpeech',
# 'LibriVox',
'MediaSpeech/AR',
'MediaSpeech/ES',
'MediaSpeech/FR',
'MediaSpeech/TR',
'MozillaCommonVoice/ab',
'MozillaCommonVoice/ar',
'MozillaCommonVoice/ba',
'MozillaCommonVoice/be',
'MozillaCommonVoice/bg',
'MozillaCommonVoice/bn',
'MozillaCommonVoice/br',
'MozillaCommonVoice/ca',
'MozillaCommonVoice/ckb',
'MozillaCommonVoice/cnh',
'MozillaCommonVoice/cs',
'MozillaCommonVoice/cv',
'MozillaCommonVoice/cy',
'MozillaCommonVoice/da',
'MozillaCommonVoice/de',
'MozillaCommonVoice/dv',
'MozillaCommonVoice/el',
'MozillaCommonVoice/en',
'MozillaCommonVoice/eo',
'MozillaCommonVoice/es',
'MozillaCommonVoice/et',
'MozillaCommonVoice/eu',
'MozillaCommonVoice/fa',
'MozillaCommonVoice/fi',
'MozillaCommonVoice/fr',
'MozillaCommonVoice/fy-NL',
'MozillaCommonVoice/ga-IE',
'MozillaCommonVoice/gl',
'MozillaCommonVoice/gn',
'MozillaCommonVoice/hi',
'MozillaCommonVoice/hu',
'MozillaCommonVoice/hy-AM',
'MozillaCommonVoice/id',
'MozillaCommonVoice/ig',
'MozillaCommonVoice/it',
'MozillaCommonVoice/ja',
'MozillaCommonVoice/ka',
'MozillaCommonVoice/kab',
'MozillaCommonVoice/kk',
'MozillaCommonVoice/kmr',
'MozillaCommonVoice/ky',
'MozillaCommonVoice/lg',
'MozillaCommonVoice/lt',
'MozillaCommonVoice/ltg',
'MozillaCommonVoice/lv',
'MozillaCommonVoice/mhr',
'MozillaCommonVoice/ml',
'MozillaCommonVoice/mn',
'MozillaCommonVoice/mt',
'MozillaCommonVoice/nan-tw',
'MozillaCommonVoice/nl',
'MozillaCommonVoice/oc',
'MozillaCommonVoice/or',
'MozillaCommonVoice/pl',
'MozillaCommonVoice/pt',
'MozillaCommonVoice/ro',
'MozillaCommonVoice/ru',
'MozillaCommonVoice/rw',
'MozillaCommonVoice/sr',
'MozillaCommonVoice/sv-SE',
'MozillaCommonVoice/sw',
'MozillaCommonVoice/ta',
'MozillaCommonVoice/th',
'MozillaCommonVoice/tr',
'MozillaCommonVoice/tt',
'MozillaCommonVoice/ug',
'MozillaCommonVoice/uk',
'MozillaCommonVoice/ur',
'MozillaCommonVoice/uz',
'MozillaCommonVoice/vi',
'MozillaCommonVoice/yo',
'MozillaCommonVoice/yue',
'MozillaCommonVoice/zh-CN',
'MozillaCommonVoice/zh-TW',
'primewords_chinese',
'room_reader',
'SpeechClarity',
'TAT-Vol2',
'thchs30',
'TIMIT',
'TTS_Javanese',
'zeroth_korean'
]
corpus_music_list = [
'IRMAS',
'Albouy2020Science',
'CD',
'GarlandEncyclopedia',
'fma_large',
'ismir04_genre',
'MTG-Jamendo',
'HiltonMoser2022_song',
'NHS2',
'MagnaTagATune'
]
corpus_env_list = ['SONYC', 'SONYC_augmented']
# sort the corpora lists to make sure the order is replicable
corpus_speech_list.sort()
corpus_music_list.sort()
corpus_env_list.sort()
corpus_list_all = corpus_speech_list+corpus_music_list+corpus_env_list
# %% load STM data
for corp in corpus_list_all:
filename = 'STM_output/corpSTMnpy/'+corp.replace('/', '-')+'_STMall.npy'
if 'STM_all' not in locals():
STM_all = np.load(filename)
else:
STM_all = np.vstack((STM_all, np.load(filename)))
if corp == 'SONYC_augmented':
SONYC_aug_len = np.load(filename).shape[0]
print(filename)
# %% load meta data
speech_corp_df1 = pd.read_csv('train_test_split/speech1_10folds_speakerGroupFold.csv',index_col=0)
speech_corp_df2 = pd.read_csv('train_test_split/speech2_10folds_speakerGroupFold.csv',index_col=0)
music_corp_df = pd.read_csv('train_test_split/music_10folds_speakerGroupFold.csv',index_col=0)
df_SONYC = pd.read_csv('train_test_split/env_10folds_speakerGroupFold.csv',index_col=0)
all_corp_df = pd.concat([speech_corp_df1, speech_corp_df2, music_corp_df, df_SONYC], ignore_index=True)
# %% split data
target = pd.concat([all_corp_df['corpus_type'], pd.Series(['env'] * SONYC_aug_len)],
ignore_index=True)
target.replace({
'speech: non-tonal':0,
'speech: tonal':1,
'music: vocal':2,
'music: non-vocal':3,
'env':4,
},
inplace=True)
data_split = pd.concat([all_corp_df['10fold_labels'], pd.Series([1] * SONYC_aug_len)],
ignore_index=True)
train_ind = data_split<8
val_ind = data_split==8
test_ind = data_split==9
X_train = STM_all[train_ind,:]
X_val = STM_all[val_ind,:]
X_test = STM_all[test_ind,:]
y_train = target[train_ind]
y_val = target[val_ind]
y_test = target[test_ind]
return X_train, X_val, X_test, y_train, y_val, y_test
# %% SGDClassifier (linear SVC)
def params_SGDClinearSVC(alpha_power):
params = {
"loss":"hinge",
"penalty":"l2",
"alpha":10**alpha_power,
"shuffle":True,
"n_jobs":-1,
"class_weight":"balanced",
"random_state":23,
"verbose":1
}
return params
def run_SGDClinearSVC(X_train, X_val, X_test, y_train, y_val, y_test):
def bo_tune_SGDClinearSVC(alpha_power):
params = params_SGDClinearSVC(alpha_power)
clf = make_pipeline(StandardScaler(), SGDClassifier(**params))
clf.fit(X_train, y_train)
y_val_encoded = OneHotEncoder(sparse_output=False).fit_transform(pd.DataFrame(y_val))
return roc_auc_score(y_val_encoded, clf.decision_function(X_val), multi_class='ovr')
bo_SGDClinearSVC = BayesianOptimization(
bo_tune_SGDClinearSVC,
pbounds={
"alpha_power": (-5, -3),
},
random_state=23
)
jogger_path = 'model/STM/sklearn_corpora_categories/SGDClinearSVM/'+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")+'/'
os.makedirs(jogger_path)
jogger_file=jogger_path+'logs.json'
logger = JSONLogger(path=jogger_file)
bo_SGDClinearSVC.subscribe(Events.OPTIMIZATION_STEP, logger)
bo_SGDClinearSVC.maximize(n_iter=27, init_points=3)
best_param_dict = get_best_params(jogger_file) # this is a dict of the best parameters
# fit the model again with best parameters and combined X_train X_val data
X = np.concatenate((X_train, X_val), axis=0)
y = np.concatenate((y_train, y_val), axis=0)
params = params_SGDClinearSVC(best_param_dict['alpha_power'])
clf = make_pipeline(StandardScaler(), SGDClassifier(**params))
clf.fit(X, y)
dump(clf, jogger_path+'clf.joblib')
# print test performances
print_performances(clf, X_test, y_test, use_prob=False, save_path=jogger_path)
# %% SGDClassifier (rbf SVC)
def params_SGDCrbfSVC(alpha_power):
params = {
"loss":"hinge",
"penalty":"l2",
"alpha":10**alpha_power,
"shuffle":True,
"n_jobs":-1,
"class_weight":"balanced",
"random_state":23,
"verbose":1
}
return params
def params_RBFSampler(gamma_power, n_components):
params_rbf = {
"gamma":10**gamma_power,
"n_components":int(n_components)*100,
"random_state":23,
}
return params_rbf
def run_SGDCrbfSVC(X_train, X_val, X_test, y_train, y_val, y_test):
def bo_tune_SGDCrbfSVC(alpha_power, gamma_power, n_components):
params = params_SGDClinearSVC(alpha_power)
params_rbf = params_RBFSampler(gamma_power, n_components)
clf = make_pipeline(StandardScaler(), RBFSampler(**params_rbf), SGDClassifier(**params))
clf.fit(X_train, y_train)
y_val_encoded = OneHotEncoder(sparse_output=False).fit_transform(pd.DataFrame(y_val))
return roc_auc_score(y_val_encoded, clf.decision_function(X_val), multi_class='ovr')
bo_SGDCrbfSVC = BayesianOptimization(
bo_tune_SGDCrbfSVC,
pbounds={
"alpha_power": (-10, -6),
"gamma_power": (-8, -4),
"n_components": (10, 16) # times 100
},
random_state=23
)
jogger_path = 'model/STM/sklearn_corpora_categories/SGDCrbfSVM/'+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")+'/'
os.makedirs(jogger_path)
jogger_file=jogger_path+'logs.json'
logger = JSONLogger(path=jogger_file)
bo_SGDCrbfSVC.subscribe(Events.OPTIMIZATION_STEP, logger)
bo_SGDCrbfSVC.maximize(n_iter=81, init_points=9)
best_param_dict = get_best_params(jogger_file) # this is a dict of the best parameters
# fit the model again with best parameters and combined X_train X_val data
X = np.concatenate((X_train, X_val), axis=0)
y = np.concatenate((y_train, y_val), axis=0)
params = params_SGDCrbfSVC(best_param_dict['alpha_power'])
params_rbf = params_RBFSampler(best_param_dict['gamma_power'], best_param_dict['n_components'])
clf = make_pipeline(StandardScaler(), RBFSampler(**params_rbf), SGDClassifier(**params))
clf.fit(X, y)
dump(clf, jogger_path+'clf.joblib')
# print test performances
print_performances(clf, X_test, y_test, use_prob=False, save_path=jogger_path)
# %% SGDClassifier (Logistic Regression)
def params_SGDClogReg(alpha_power, l1_ratio):
params = {
"loss":"log_loss",
"penalty":"elasticnet",
"l1_ratio":l1_ratio,
"alpha":10**alpha_power,
"shuffle":True,
"n_jobs":-1,
"class_weight":"balanced",
"random_state":23,
"verbose":1,
"max_iter":50
}
return params
def run_SGDClogReg(X_train, X_val, X_test, y_train, y_val, y_test):
def bo_tune_SGDClogReg(alpha_power, l1_ratio):
params = params_SGDClogReg(alpha_power, l1_ratio)
clf = make_pipeline(StandardScaler(), SGDClassifier(**params))
clf.fit(X_train, y_train)
return roc_auc_score(y_val, clf.predict_proba(X_val), multi_class='ovr')
bo_SGDClogReg = BayesianOptimization(
bo_tune_SGDClogReg,
pbounds={
"alpha_power": (-8, -4),
"l1_ratio": (0, 1)
},
random_state=23
)
jogger_path = 'model/STM/sklearn_corpora_categories/SGDClogReg/'+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")+'/'
os.makedirs(jogger_path)
jogger_file=jogger_path+'logs.json'
logger = JSONLogger(path=jogger_file)
bo_SGDClogReg.subscribe(Events.OPTIMIZATION_STEP, logger)
bo_SGDClogReg.maximize(n_iter=54, init_points=6)
best_param_dict = get_best_params(jogger_file) # this is a dict of the best parameters
# fit the model again with best parameters and combined X_train X_val data
X = np.concatenate((X_train, X_val), axis=0)
y = np.concatenate((y_train, y_val), axis=0)
params = params_SGDClogReg(best_param_dict['alpha_power'], best_param_dict['l1_ratio'])
clf = make_pipeline(StandardScaler(), SGDClassifier(**params))
clf.fit(X, y)
dump(clf, jogger_path+'clf.joblib')
# print test performances
print_performances(clf, X_test, y_test, use_prob=True, save_path=jogger_path)
# %% linearSVC
def params_linearSVC(C_power):
params = {
"kernel":"linear",
"C":10**C_power,
"probability":True,
"class_weight":"balanced",
"decision_function_shape":"ovr",
"random_state":23,
"verbose":1
}
return params
def run_linearSVC(X_train, X_val, X_test, y_train, y_val, y_test):
def bo_tune_linearSVC(C_power):
params = params_linearSVC(C_power)
clf = make_pipeline(StandardScaler(), SVC(**params))
clf.fit(X_train, y_train)
return roc_auc_score(y_val, clf.predict_proba(X_val), multi_class='ovr')
bo_linearSVC = BayesianOptimization(
bo_tune_linearSVC,
pbounds={
"C_power": (-6, 6),
},
random_state=23
)
jogger_path = 'model/STM/sklearn_corpora_categories/linearSVM/'+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")+'/'
os.makedirs(jogger_path)
jogger_file=jogger_path+'logs.json'
logger = JSONLogger(path=jogger_file)
bo_linearSVC.subscribe(Events.OPTIMIZATION_STEP, logger)
bo_linearSVC.maximize(n_iter=200, init_points=25)
best_param_dict = get_best_params(jogger_file) # this is a dict of the best parameters
# fit the model again with best parameters and combined X_train X_val data
X = np.concatenate((X_train, X_val), axis=0)
y = np.concatenate((y_train, y_val), axis=0)
params = params_linearSVC(best_param_dict['C_power'])
clf = make_pipeline(StandardScaler(), SVC(**params))
clf.fit(X, y)
dump(clf, jogger_path+'clf.joblib')
# print test performances
print_performances(clf, X_test, y_test, use_prob=True, save_path=jogger_path)
# %% rbfSVC
def params_rbfSVC(C_power, gamma_power):
params = {
"kernel":"rbf",
"C":10**C_power,
"gamma":10**gamma_power,
"probability":True,
"class_weight":"balanced",
"decision_function_shape":"ovr",
"random_state":23,
"verbose":1
}
return params
def run_rbfSVC(X_train, X_val, X_test, y_train, y_val, y_test):
def bo_tune_rbfSVC(C_power, gamma_power):
params = params_rbfSVC(C_power, gamma_power)
clf = make_pipeline(StandardScaler(), SVC(**params))
clf.fit(X_train, y_train)
return roc_auc_score(y_val, clf.predict_proba(X_val), multi_class='ovr')
bo_rbfSVC = BayesianOptimization(
bo_tune_rbfSVC,
pbounds={
"C_power": (-6, 6),
"gamma_power": (-6, 0),
},
random_state=23
)
jogger_path = 'model/STM/sklearn_corpora_categories/rbfSVM/'+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")+'/'
os.makedirs(jogger_path)
jogger_file=jogger_path+'logs.json'
logger = JSONLogger(path=jogger_file)
bo_rbfSVC.subscribe(Events.OPTIMIZATION_STEP, logger)
bo_rbfSVC.maximize(n_iter=200, init_points=25)
best_param_dict = get_best_params(jogger_file) # this is a dict of the best parameters
# fit the model again with best parameters and combined X_train X_val data
X = np.concatenate((X_train, X_val), axis=0)
y = np.concatenate((y_train, y_val), axis=0)
params = params_rbfSVC(best_param_dict['C_power'], best_param_dict['gamma_power'])
clf = make_pipeline(StandardScaler(), SVC(**params))
clf.fit(X, y)
dump(clf, jogger_path+'clf.joblib')
# print test performances
print_performances(clf, X_test, y_test, use_prob=True, save_path=jogger_path)
# %% Logistic Regression
def params_LogReg(C_power, l1_ratio):
params = {
"penalty":"elasticnet",
"C":10**C_power,
"l1_ratio":l1_ratio,
"solver":"saga",
"n_jobs":-1,
"class_weight":"balanced",
"multi_class":"ovr",
"random_state":23,
"verbose":1
}
return params
def run_LogReg(X_train, X_val, X_test, y_train, y_val, y_test):
def bo_tune_LogReg(C_power, l1_ratio):
params = params_LogReg(C_power, l1_ratio)
clf = make_pipeline(StandardScaler(), LogisticRegression(**params))
clf.fit(X_train, y_train)
return roc_auc_score(y_val, clf.predict_proba(X_val), multi_class='ovr')
bo_LogReg = BayesianOptimization(
bo_tune_LogReg,
pbounds={
"C_power": (-6, 6),
"l1_ratio": (0, 1),
},
random_state=23
)
jogger_path = 'model/STM/sklearn_corpora_categories/logReg/'+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")+'/'
os.makedirs(jogger_path)
jogger_file=jogger_path+'logs.json'
logger = JSONLogger(path=jogger_file)
bo_LogReg.subscribe(Events.OPTIMIZATION_STEP, logger)
bo_LogReg.maximize(n_iter=200, init_points=25)
best_param_dict = get_best_params(jogger_file) # this is a dict of the best parameters
# fit the model again with best parameters and combined X_train X_val data
X = np.concatenate((X_train, X_val), axis=0)
y = np.concatenate((y_train, y_val), axis=0)
params = params_LogReg(best_param_dict['C_power'], best_param_dict['l1_ratio'])
clf = make_pipeline(StandardScaler(), LogisticRegression(**params))
clf.fit(X, y)
dump(clf, jogger_path+'clf.joblib')
# print test performances
print_performances(clf, X_test, y_test, use_prob=True, save_path=jogger_path)
# %% Random Forest Classifier
def params_RFC(n_estimators, max_depth, min_samples_leaf, min_samples_split, max_samples):
params = {
"n_estimators":int(n_estimators),
"max_depth":int(max_depth),
"min_samples_leaf":int(min_samples_leaf),
"min_samples_split":int(min_samples_split),
"max_samples":max_samples,
"n_jobs":-1,
"class_weight":"balanced",
"random_state":23,
"verbose":1
}
return params
def run_RFC(X_train, X_val, X_test, y_train, y_val, y_test):
def bo_tune_RFC(n_estimators, max_depth, min_samples_leaf, min_samples_split, max_samples):
params = params_RFC(n_estimators, max_depth, min_samples_leaf, min_samples_split, max_samples)
clf = make_pipeline(StandardScaler(), RandomForestClassifier(**params))
clf.fit(X_train, y_train)
return roc_auc_score(y_val, clf.predict_proba(X_val), multi_class='ovr')
bo_RFC = BayesianOptimization(
bo_tune_RFC,
pbounds={
"n_estimators": (100,1000),
"max_depth": (8, 50),
"min_samples_leaf": (1, 5),
"min_samples_split": (2, 10),
"max_samples": (1e-3,1)
},
random_state=23
)
jogger_path = 'model/STM/sklearn_corpora_categories/randomForest/'+datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")+'/'
os.makedirs(jogger_path)
jogger_file=jogger_path+'logs.json'
logger = JSONLogger(path=jogger_file)
bo_RFC.subscribe(Events.OPTIMIZATION_STEP, logger)
bo_RFC.maximize(n_iter=100, init_points=25)
best_param_dict = get_best_params(jogger_file) # this is a dict of the best parameters
# fit the model again with best parameters and combined X_train X_val data
X = np.concatenate((X_train, X_val), axis=0)
y = np.concatenate((y_train, y_val), axis=0)
params = params_RFC(best_param_dict['n_estimators'],
best_param_dict['max_depth'],
best_param_dict['min_samples_leaf'],
best_param_dict['min_samples_split'],
best_param_dict['max_samples'])
clf = make_pipeline(StandardScaler(), RandomForestClassifier(**params))
clf.fit(X, y)
dump(clf, jogger_path+'clf.joblib')
# print test performances
print_performances(clf, X_test, y_test, use_prob=True, save_path=jogger_path)
# %% return the best parameters
def get_best_params(json_path):
list_bayesOpt = [json_path]
opt_best_df = pd.DataFrame()
for jsonFile in list_bayesOpt:
with open(jsonFile) as f:
optList = []
for jsonObj in f:
optDict = json.loads(jsonObj)
optList.append(optDict)
opt_df = pd.DataFrame(optList)
opt_df = pd.concat([opt_df.drop(['params','datetime'], axis=1), opt_df['params'].apply(pd.Series), opt_df['datetime'].apply(pd.Series)], axis=1)
opt_best_df = pd.concat([opt_best_df,opt_df.sort_values('target',ascending=False).iloc[:10]])
opt_best_df = opt_best_df.sort_values(['target', 'delta'],ascending=[False, True]) # Highest AUC, lowest training time
print(opt_best_df)
return dict(opt_best_df.iloc[0])
# %% print test performances
def print_performances(clf, X_test, y_test, use_prob, save_path):
y_test_pred = clf.predict(X_test)
cm = confusion_matrix(y_test, y_test_pred, normalize='true')
if use_prob==True:
auc = roc_auc_score(y_test, clf.predict_proba(X_test), multi_class='ovr')
else:
y_test_encoded = OneHotEncoder(sparse_output=False).fit_transform(pd.DataFrame(y_test))
auc = roc_auc_score(y_test_encoded, clf.decision_function(X_test), multi_class='ovr')
with open(save_path+'test_performance.txt', 'w') as f:
print(classification_report(y_test, y_test_pred), file=f)
print("Confusion matrix", file=f)
print(cm, file=f)
print("ROC AUC: "+str(auc), file=f)
# %% main
if __name__ == "__main__":
# Check if the correct number of arguments are provided
if len(sys.argv) != 2:
print("Usage: python script.py arg1")
sys.exit(1)
X_train, X_val, X_test, y_train, y_val, y_test = prepData()
clf_type = sys.argv[1]
if clf_type=='0':
run_linearSVC(X_train, X_val, X_test, y_train, y_val, y_test)
elif clf_type=='1':
run_rbfSVC(X_train, X_val, X_test, y_train, y_val, y_test)
elif clf_type=='2':
run_LogReg(X_train, X_val, X_test, y_train, y_val, y_test)
elif clf_type=='3':
run_RFC(X_train, X_val, X_test, y_train, y_val, y_test)
elif clf_type=='4':
run_SGDClinearSVC(X_train, X_val, X_test, y_train, y_val, y_test)
elif clf_type=='5':
run_SGDClogReg(X_train, X_val, X_test, y_train, y_val, y_test)
elif clf_type=='6':
run_SGDCrbfSVC(X_train, X_val, X_test, y_train, y_val, y_test)
else:
print("choose a classifer: {0: linearSVC, 1: rbfSVC, 2: LogReg, 3: RFC, 4: SGDClinearSVC, 5: SGDClogReg, 6: SGDCrbfSVC]")
print("All Done!")