-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate_screamClf.py
1349 lines (1048 loc) · 55.6 KB
/
evaluate_screamClf.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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# imports
import sys
import librosa
import librosa.display
import matplotlib.pyplot as plt
from id3 import Id3Estimator
from keras import models
from keras import layers
import numpy as np
import pandas as pd
import sklearn
from audioread import NoBackendError
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.model_selection import StratifiedKFold
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from tensorflow.python.keras.models import load_model
from tqdm import tqdm
import os
from pathlib import Path
import csv
import warnings # record warnings from librosa
from sklearn.model_selection import train_test_split
import pickle as pkl
import json
from keras.models import model_from_json
from models import get_optimised_model
from models import get_optimised_model_final
import datetime
# global objects
# todo add private/public inside class
class global_For_Clf():
def __init__(self):
self.n_mfcc = 20 # lev's initial value here was 40- this is the feature resolution- usually between 12-40
self.k_folds = 5 # amount of folds in k-fold
# inside create_csv() more columns will be added to the csv head
# TODO lev-future_improvement edit/add to get better results
self.csv_initial_head = 'filename spectral_centroid zero_crossings spectral_rolloff chroma_stft rms mel_spec'
self.data_file_path = 'csv/scream/data_experiment_3_mfcc_20.csv'
self.min_wav_duration = 0.5 # wont use shorter wav files
self.clf_label = 'scream'
self.nearMissRatio = 2 # 2 means <positives amount>/2
# which means were taking 50% from nearMiss_<clf label> for negatives
self.nearMiss_samples = -1 # -1 is initial invalid value which will be changed on relevant functions
self.nearMissLabel = "NearMiss_" + str(self.clf_label)
self.csv_to_pkl_path = "pickle/scream/combined_lower_amount.pkl"
self.path_csv_train_test_data = "csv/scream/train_test_data.csv" # chosen 1:1 ratio data, selected from data.csv
self.Kfold_testSize = 0.2
self.sampling_data_repetitions = 5 # sampling randomly the data to create 1:1 ratio
self.k_fold_repetitions: int = 5 # doing repeated k-fold for better evaluation
self.positives = -1 # -1 represents invalid value as initial value
self.negatives = -1
self.resultsPath = 'results/scream/experiments_results.csv'
self.try_lower_amount = np.inf
self.model = None # here a model will be saved- the saved model shouldn't be trained
self.finalModelsPath= 'models/final_models'
self.isTrained = False
self.userInput = ''
def getInputDim(self):
amount = len(self.csv_initial_head.split()) + self.n_mfcc - 1 # -1 because filename isnt a feature
return amount
def get_total_samples(self):
return self.positives + self.negatives
def get_model_name(self):
model_name= (type(self.model)).__name__
return model_name
class clf_Results(global_For_Clf):
def __init__(self):
global_For_Clf.__init__(self)
# exceptions
class NotEnoughPositiveSamples(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def extract_feature_to_csv(wav_path, label, data_file_path, min_wav_duration, fcc_amount):
"""
:return: writes one row to wav_path with extracted features
"""
# extract features for a wav file
wav_name = wav_path.name # 110142__ryding__scary-scream-4.wav
wav_name = wav_name.replace(" ", "_") # lev bug fix to align csv columns
# print(wav_name)
"""
# lev upgrading error tracking- know which file caused the error
try:
"""
wav_data, sampling_rate = librosa.load(wav_path, duration=5)
wav_duration = librosa.get_duration(y=wav_data, sr=sampling_rate)
# lev- dont use really short audio
if (wav_duration < min_wav_duration):
print("skipping " + wav_name + " ,duration= " + str(wav_duration))
return
with warnings.catch_warnings(record=True) as feature_warnings:
# spectral_centroid
feature_wav_spec_cent = librosa.feature.spectral_centroid(y=wav_data, sr=sampling_rate)
# print(feature_wav_spec_cent.shape) # (1, 216)
# zero crossings
zcr = librosa.feature.zero_crossing_rate(wav_data)
# print("sum "+ str(np.sum(zcr)))
# spectral_rolloff
rolloff = librosa.feature.spectral_rolloff(y=wav_data, sr=sampling_rate)
# print(rolloff.shape)
# print(rolloff[0][0:3])
# chroma_stft
chroma_stft = librosa.feature.chroma_stft(y=wav_data, sr=sampling_rate)
# print(chroma_stft.shape)
# rms and mfccs
n_mfcc = fcc_amount # resolution amount
mfccs = librosa.feature.mfcc(y=wav_data, sr=sampling_rate, n_mfcc=n_mfcc)
S, phase = librosa.magphase(mfccs)
rms = librosa.feature.rms(S=S)
# print(rms.shape)
# mel spectogram
mel_spec = librosa.feature.melspectrogram(y=wav_data, sr=sampling_rate)
# mfccs
# print(mfccs.shape)
# if there ara warnings- print and continue- for example Warning: Trying to estimate tuning from empty frequency set
# this is an OK warning- it just means that its really quiet..as in street ambient during the evenning..its a
# good negative example.
if len(feature_warnings) > 0:
for feature_warning in feature_warnings:
print("Warning: {} Triggered in:\n {}\nwith a duration of {} seconds.\n".format(
feature_warning.message, wav_path, wav_duration))
# got here - no warnings for this wav_path
# normalize what isnt normalized
to_append = f'{wav_name} {np.mean(feature_wav_spec_cent)} {np.mean(zcr)} {np.mean(rolloff)} {np.mean(chroma_stft)}' \
f' {np.mean(rms)} {np.mean(mel_spec)}'
for e in mfccs:
to_append += f' {np.mean(e)}'
to_append += f' {label}'
# save to csv (append new lines)
file = open(data_file_path, 'a', newline='')
with file:
writer = csv.writer(file)
writer.writerow(to_append.split())
# print(to_append)
def create_csv():
"""
input: uses screamGlobals for input
output: .csv file with screamGlobals.csv_initial_head columns
"""
# important variables
data_file_path = screamGlobals.data_file_path
min_wav_duration = screamGlobals.min_wav_duration
# print(data_file_path, min_wav_duration)
"""
# prevent data file over run by accident
if os.path.exists(data_file_path):
text = input(f'Press the space bar to override {data_file_path} and continue with the script')
if text != ' ':
sys.exit('User aborted script, data file saved :)')
"""
if os.path.exists(data_file_path):
# verify table fits the mfcc number- if True- return (continue with script as usuall), else- raise Error
n_mfcc_number= screamGlobals.n_mfcc
with open(data_file_path) as csvFile:
reader = csv.reader(csvFile)
field_names_list = next(reader) # read first row only (header)
mfcc_list = [x for x in field_names_list if x.startswith("mfcc")]
len_actual_mfcc_features = len(mfcc_list)
if len_actual_mfcc_features == n_mfcc_number:
print(f'OK: {len_actual_mfcc_features} == n_mfcc_number={n_mfcc_number}')
return
else:
raise Exception(f'len_actual_mfcc_features'
f'(mfcc inside {data_file_path}={len_actual_mfcc_features},'
f' but n_mfcc_number(inside globals class of this script)={n_mfcc_number},'
f' values must be equal.')
# create header for csv
header = screamGlobals.csv_initial_head
fcc_amount = screamGlobals.n_mfcc
for i in range(1, fcc_amount + 1):
header += f' mfcc_{i}'
header += ' label'
header = header.split() # split by spaces as default
file = open(data_file_path, 'w', newline='')
with file:
writer = csv.writer(file)
writer.writerow(header)
# load features from each wav file- put inside the lines below as a function
# reaching each wav file
path_train = Path("train")
for path_label in sorted(path_train.iterdir()):
print("currently in : " + str(path_label)) # train\negative
positiveOrNegative = path_label.name # negative
# print(label)
for path_class in tqdm(sorted(path_label.iterdir())):
# print info
print("currently in class: " + str(path_class))
# print amount of files in directory
onlyfiles = next(os.walk(path_class))[2] # dir is your directory path as string
wav_amount: int = len(onlyfiles)
print("wav amount= " + str(wav_amount))
# true_class= path_class.name
# print(true_class)
# print(path_class) # train\negative\scream
# print("name: "+ str(path_class.name))
# lev improvement according to coordination with mori- irrelevant since 7.8.19
if (positiveOrNegative == "positive"):
label = path_class.name # scream
else:
"""
lev- updating to differentiate near misses and far misses.
keeping if-else structure for future options
old:
print(f"switching label from {path_class.name} to <negative>") # added reporting
label = "negative"
new:
"""
label = path_class.name # NearMiss_scream
wave_file_paths = path_class.glob('**/*.wav') # <class 'generator'>
# print(type(wave_file_paths))
count = 0 # for progress tracking
print('covered WAV files: ')
for wav_path in sorted(wave_file_paths):
count += 1
if (count % 50) == 0:
fp = sys.stdout
print(str(count), end=' ')
fp.flush() # makes print flush its buffer (doesnt print without it)
# print(type(wav_path)) # <class 'pathlib.WindowsPath'>
# print(wav_path) # train\positive\scream\110142__ryding__scary-scream-4.wav
# print(wav_path.name) # 110142__ryding__scary-scream-4.wav
try:
# keeping as parameters data_file_path, min_wav_duration even though its in screamGlobals
# in order to emphasis its an inner function of create_csv()
extract_feature_to_csv(wav_path, label, data_file_path, min_wav_duration, fcc_amount)
except NoBackendError as e:
print("audioread.NoBackendError " + "for wav path " + str(wav_path))
continue # one file didnt work, continue to next one
def create_lower_bound_data_panda(csv_path, label):
"""
note(lev): because usually we will have more negatives than positives then this function
chooses randomly the negatives samples so that it will have 1:1 ratio with the true label
and within the amount of false labels, it Stratifies to keep the same ratio of
Near Misses for both train and test data.
(this has proven to increase the k-fold average accuracy from 0.45 to 0.85
"""
print(f'choosing max samples randomly while preserving 1:1 ratio for {label}:<all the rest as one group>')
# use Pandas package for reading csv
data_csv = pd.read_csv(csv_path)
# print(data_csv[data_csv.label == 'scream']) # [367 rows x 47 columns]
# print(len(data_csv[data_csv.label == 'scream'])) # 367
# find lower amount from types of labels
pos_amount = len(data_csv[data_csv.label == label])
neg_amount = len(data_csv[data_csv.label != label])
print("positives: " + str(pos_amount) + " negatives: " + str(neg_amount))
lower_amount = min(pos_amount, neg_amount, screamGlobals.try_lower_amount)
print("lower bound: " + str(lower_amount))
# take Max of 50% from NearMiss_<clf label> and then choose randomly from the rest of negatives
nearMissMaxAmount = pos_amount // screamGlobals.nearMissRatio
data_csv_negatives_nearMiss = data_csv.loc[data_csv.label == screamGlobals.nearMissLabel, :] # take all valid rows
nearMissActualAmount = len(data_csv_negatives_nearMiss)
NearMissAmountToTake = nearMissActualAmount if nearMissActualAmount < nearMissMaxAmount else nearMissMaxAmount
screamGlobals.nearMiss_samples = NearMissAmountToTake
# take near misses for this classifier
data_csv_negatives_NearMiss = data_csv_negatives_nearMiss.sample(n=NearMissAmountToTake)
# take random negatives that aren't near miss
negatives_amount_left_to_take = lower_amount - NearMissAmountToTake
assert(negatives_amount_left_to_take>0)
rest_of_negatives = data_csv.loc[
~data_csv['label'].isin([label, screamGlobals.nearMissLabel])] # take all valid rows
negatives_lower_amount_samples = data_csv_negatives_NearMiss.append(
rest_of_negatives.sample(n=negatives_amount_left_to_take))
assert (len(negatives_lower_amount_samples) == lower_amount)
# prepare for results tracking
screamGlobals.positives = lower_amount
screamGlobals.negatives = lower_amount
# positives - taking random rows
data_csv_positives = data_csv[data_csv.label == label]
# create pandas dataframe with lower_amount rows randomly
positives_lower_amount_samples = data_csv_positives.sample(n=lower_amount)
# combine
combined_lower_amount = positives_lower_amount_samples
# have to assign, returns appended datadrame
combined_lower_amount = combined_lower_amount.append(negatives_lower_amount_samples)
# print(len(combined_lower_amount)) # 734 ,when lower bound: 367
""""
dont need safe override and data analysis in evaluation process
# saving pandas dataframe to csv - for data analysis purposes
# TODO lev future - maybe build a function- you already copied this logic 3 times
if os.path.exists(screamGlobals.path_csv_train_test_data):
text = input(f'Press the space bar to override {screamGlobals.path_csv_train_test_data} and continue with the script')
if text != ' ':
sys.exit('User aborted script, pickle file saved :)')
combined_lower_amount.to_csv(screamGlobals.path_csv_train_test_data)
#TODO RETURN HERE LINES OF CODE FOR EDITING LABELS
# saving pandas dataframe to pickle - modularity
# prevent pickle file over run by accident
if os.path.exists(screamGlobals.csv_to_pkl_path):
text = input(f'Press the space bar to override {screamGlobals.csv_to_pkl_path} and continue with the script')
if text != ' ':
sys.exit('User aborted script, pickle file saved :)')
combined_lower_amount.to_pickle(screamGlobals.csv_to_pkl_path)
"""
assert (len(combined_lower_amount) == lower_amount * 2)
return combined_lower_amount
def create_default_sequential_for_mfcc_size():
"""
created this func for experiment2 due to the need of a default classifier
"""
model = models.Sequential()
# model.add(layers.Dense(256, activation='relu', input_shape=(X_train_kfold_scaled.shape[1],)))
model.add(layers.Dense(32, activation='relu', input_dim=screamGlobals.getInputDim()))
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid')) # the 1 means binary classification
model.compile(optimizer='adam'
, loss='binary_crossentropy'
, metrics=['accuracy'])
screamGlobals.model = model
screamGlobals.isTrained = False
return model
def get_stratified_results(k, X_for_k_fold, y_for_k_fold, IntPositive, screamGlobals):
"""
param: IntPositive- the integer representing our true classifiers label, for example: for scream classifier
if scream class is represented by 1 ==> so IntPositive = 1 . became necessary when wanted to return f1-score
for this class only.
"""
print("get_stratified_results() in process")
# stratified split
skf = StratifiedKFold(n_splits=k, shuffle=True)
skf.get_n_splits(X_for_k_fold, y_for_k_fold) # StratifiedKFold(n_splits=5, random_state=None, shuffle=True)
# print(skf)
scores_accuracy_k_fold = []
scores_f1_k_fold = []
scores_recall_fold = []
for train_index, test_index in skf.split(X_for_k_fold, y_for_k_fold):
X_train_kfold, X_test_kfold = X_for_k_fold[train_index], X_for_k_fold[test_index]
y_train_kfold, y_test_kfold = y_for_k_fold[train_index], y_for_k_fold[test_index]
""""
important to use scaling only after splitting the data into train/validation/test
scale on training set only, then use the returned "fit" parameters to scale validation and test
"""
# scale data
scaler = StandardScaler()
scaler.fit(X_train_kfold) # must call fit before calling transform.fitting on train, using on train+test+valid
X_train_kfold_scaled = scaler.transform(X_train_kfold)
# print(np.amax(X_train_kfold)) # 9490.310668945312
# print(np.amax(X_train_kfold_scaled)) # 8.236592246485245
X_test_kfold_scaled = scaler.transform(X_test_kfold)
# X_test_scaled = scaler.transform(X_test) # this is done in an other place. keeping for legacy
# pre-trained model
model = screamGlobals.model
# ASSUMPTION: sequential model is already trained
model_name = screamGlobals.get_model_name()
if model_name != "Sequential":
model.fit(X_train_kfold_scaled,y_train_kfold)
y_fold_predicted = model.predict(X_test_kfold_scaled)
else:
# assert (screamGlobals.isTrained is True)
if screamGlobals.isTrained is True:
y_fold_predicted = model.predict_classes(X_test_kfold_scaled)
else:
print("untrained model is being trained")
# create and train default model
# TODO take to outer function?
model = create_default_sequential_for_mfcc_size()
# train model on training set of Kfold
history = model.fit(X_train_kfold_scaled,
y_train_kfold,
epochs=20,
batch_size=128)
# save for this loop only the trained model
screamGlobals.model = model
screamGlobals.isTrained = True
y_fold_predicted = model.predict_classes(X_test_kfold_scaled)
# print("finished_predictions")
# calculate scores
# calculate global precision score
global_score = sklearn.metrics.precision_score(y_test_kfold, y_fold_predicted, average='micro')
scores_accuracy_k_fold.append(global_score)
# take f1_score only for the classifiers class
f1_score = sklearn.metrics.f1_score(y_test_kfold, y_fold_predicted, pos_label=IntPositive, average='binary')
scores_f1_k_fold.append(f1_score)
# recall for positive class
recall_score = sklearn.metrics.recall_score(y_test_kfold, y_fold_predicted, pos_label=IntPositive,
average='binary')
scores_recall_fold.append(recall_score)
mean_scores_accuracy_k_fold = np.mean(np.array(scores_accuracy_k_fold))
mean_scores_f1_k_fold = np.mean(np.array(scores_f1_k_fold))
mean_scores_recall_fold = np.mean(np.array(scores_recall_fold))
# print(mean_scores_accuracy_k_fold,mean_scores_f1_k_fold)
return mean_scores_accuracy_k_fold, mean_scores_f1_k_fold, mean_scores_recall_fold
def get_Repeated_strtfy_results(combined_lower_amount, k, repetitions):
# prepare dataFrame for stratified and for split
data_no_fileName = combined_lower_amount.drop(['filename'], axis=1)
# print(data_no_fileName.shape) # ( , ) with label column
# encode strings of labels to integers
labels_list = data_no_fileName.iloc[:, -1]
# print(labels_list.shape) # (734,)
encoder = LabelEncoder()
encoded_labels_csv = np.array(encoder.fit_transform(labels_list))
# print(encoded_labels_csv) # [0 0 0 ... 1 1 1]
# print(encoded_labels_csv.shape) # (734,)
# print(list(encoder.inverse_transform([0,1]))) # ['negative', 'scream']
# take all except labels column. important to add the dtype=float, otherwise im getting an error in the kfold.
only_features = np.array(data_no_fileName.iloc[:, :-1], dtype=float)
# print(only_features.shape) # ( , )
""""
splitting stages
"""
# split for test and k-fold
X_for_k_fold, X_test, y_for_k_fold, y_test = train_test_split \
(only_features, encoded_labels_csv, test_size=screamGlobals.Kfold_testSize, stratify=encoded_labels_csv)
# print(len(y_for_k_fold)) # 587
# print(len(y_test)) # 147
# after stratify- lets keep only binary classification (merging Near Miss and Far miss into one label
print("merging all negative labels into one label")
# find the positive label transformation
clf_label_int = encoder.transform([screamGlobals.clf_label])[0] # 0 because it returns a list
# print(clf_label_int) # 2
# give temp values in order to prevent conflicts
tempIntLabel: int = 111
IntNegative: int = 0
IntPositive: int = 1
y_for_k_fold[y_for_k_fold == clf_label_int] = tempIntLabel
y_test[y_test == clf_label_int] = tempIntLabel
y_for_k_fold[y_for_k_fold != tempIntLabel] = IntNegative
y_test[y_test != tempIntLabel] = IntNegative
# switch to binary
y_for_k_fold[y_for_k_fold == tempIntLabel] = IntPositive
y_test[y_test == tempIntLabel] = IntPositive
# now, y_test is binary, 0 represents the true label of the classifier
"""
# find models best hyper-parameters
optimised_model= get_optimised_model(X_for_k_fold, X_test, y_for_k_fold, y_test)
screamGlobals.model= optimised_model
print(f"finished optimizing our model")
"""
# important values for deciding which is the best classifier
scores_accuracy_k_fold_repeated = []
scores_f1_k_fold_repeated = []
scores_k_fold_recall = []
for repeat_number in tqdm(range(1, repetitions)):
score_mean_k_fold, f1_mean_k_fold, recall_k_fold = get_stratified_results(k, X_for_k_fold,
y_for_k_fold, IntPositive,
screamGlobals)
scores_accuracy_k_fold_repeated.append(score_mean_k_fold)
scores_f1_k_fold_repeated.append(f1_mean_k_fold)
scores_k_fold_recall.append(recall_k_fold)
mean_accuracy_k_fold_repeated = np.mean(np.array(scores_accuracy_k_fold_repeated))
mean_f1_k_fold_repeated = np.mean(np.array(scores_f1_k_fold_repeated))
mean_scores_k_fold_recall = np.mean(np.array(scores_k_fold_recall))
return mean_accuracy_k_fold_repeated, mean_f1_k_fold_repeated, mean_scores_k_fold_recall
def get_model_head():
if screamGlobals.model is None:
raise Exception("No model, supply a model please.")
model_name = screamGlobals.get_model_name()
# additional info will be in a single cell in the CSV so we seperate info by a double-underline: __
if model_name == "Sequential":
additional_info = f'model_layers={len(screamGlobals.model.layers)}'
else:
additional_info = 'None'
csv_model_head = f'model_name model_info'
csv_model_results = f'{model_name} {additional_info}'
return csv_model_head, csv_model_results
def results_to_csv(csv_results_head, csv_results):
# printing results to csv for tracking
print("results_to_csv")
csv_data_results = f'{screamGlobals.clf_label} {screamGlobals.get_total_samples()}' \
f' {screamGlobals.positives} {screamGlobals.negatives}' \
f' {screamGlobals.getInputDim()} {screamGlobals.Kfold_testSize} {screamGlobals.k_folds}' \
f' {screamGlobals.k_fold_repetitions} {screamGlobals.sampling_data_repetitions}'
csv_features_results = f'{screamGlobals.n_mfcc}'
# TODO- get_model_head() can be optimized in future versions to separate head from results
csv_model_head, csv_model_results = get_model_head()
csv_final_results = csv_results + ' ' + csv_data_results + ' ' \
+ csv_features_results + ' ' + csv_model_results + ' ' + screamGlobals.userInput
# TODO enter also model params according to moris suggestion- name, hyper params
if not os.path.exists(screamGlobals.resultsPath):
csv_data_head = f'clf_label total_samples positives negatives total_features test' \
f'_size_ratio folds kfold_repeats' \
f' sampling_repeats'
csv_features_head = f'n_mfcc_amount'
csv_final_head = csv_results_head + ' ' + csv_data_head + ' ' \
+ csv_features_head+ ' ' + csv_model_head + ' ' + 'userInput'
# save to csv (append new lines)
# file doesnt exist- lets create with header
file = open(screamGlobals.resultsPath, 'w', newline='')
with file:
writer = csv.writer(file)
writer.writerow(csv_final_head.split())
else:
# file exists with header- just add lines
file = open(screamGlobals.resultsPath, 'a', newline='')
with file:
writer = csv.writer(file)
writer.writerow(csv_final_results.split())
def experiment_data_size():
print("executing screamClf flow")
# change global definitions at the top of the file inside global_For_Clf class #todo lev maybe create config file
# screamGlobals = global_For_Clf()
create_csv() # need to create only once, but for now its already created
# lev testing parameter
# screamGlobals.try_lower_amount= lower_bound_per_class # this is used in an outer function in a different file
accuracy_sampling = [] # each iteration will append avg accuracy value
f1_sampling = []
recall_sampling = []
for sample_number in tqdm(range(1, screamGlobals.sampling_data_repetitions)):
lower_bound_data_panda = create_lower_bound_data_panda(screamGlobals.data_file_path,
screamGlobals.clf_label)
score_mean_k_fold, f1_mean_k_fold, recall_k_fold = get_Repeated_strtfy_results \
(lower_bound_data_panda, screamGlobals.k_folds, screamGlobals.k_fold_repetitions)
accuracy_sampling.append(score_mean_k_fold)
f1_sampling.append(f1_mean_k_fold)
recall_sampling.append(recall_k_fold)
mean_accuracy_sampling = np.mean(np.array(accuracy_sampling))
mean_f1_sampling = np.mean(np.array(f1_sampling))
mean_recall_sampling = np.mean(np.array(recall_sampling))
# gather results
csv_results_head = f'total_accuracy f1_{screamGlobals.clf_label} recall_{screamGlobals.clf_label}'
csv_results = f'{mean_accuracy_sampling} {mean_f1_sampling} {mean_recall_sampling}'
results_to_csv(csv_results_head, csv_results)
def different_model():
"""
goal: run with different sample sizes to understand on different models (changed manually inside the script
the models) and verified with a csv results file which direction should we take ...
in this function we run also an automated imported algorithm to find best model parameters and then ran
our algo with our custom kfold on our custom data with spesific ratio's positive:negative and
negative: nearMiss_negative to find best classifier
"""
# lower size must be > Nearmiss
for size in tqdm([100,150,200,250,300,350,400]):
screamGlobals.try_lower_amount = size
experiment_data_size()
def get_best_model_results(optimised_model, X_test, y_test, IntPositive, X_for_k_fold, y_for_k_fold):
y_fold_predicted = optimised_model.predict_classes(X_test)
print(y_fold_predicted, end='')
print(y_test, end='')
accuracy = sklearn.metrics.precision_score(y_test, y_fold_predicted, average='micro')
# take f1_score only for the classifiers class
f1 = sklearn.metrics.f1_score(y_test, y_fold_predicted, pos_label=IntPositive, average='binary')
# recall for positive class
recall = sklearn.metrics.recall_score(y_test, y_fold_predicted, pos_label=IntPositive,
average='binary')
print(f' accuracy, f1, recall: ', accuracy, f1, recall)
print("now on trained (off the record): ")
y_fold_predicted = optimised_model.predict_classes(X_for_k_fold)
print(y_fold_predicted, end='')
print(y_for_k_fold, end='')
accuracy_trained = sklearn.metrics.precision_score(y_for_k_fold, y_fold_predicted, average='micro')
# take f1_score only for the classifiers class
f1_trained = sklearn.metrics.f1_score(y_for_k_fold, y_fold_predicted, pos_label=IntPositive, average='binary')
# recall for positive class
recall_trained = sklearn.metrics.recall_score(y_for_k_fold, y_fold_predicted, pos_label=IntPositive,
average='binary')
print(f' accuracy, f1, recall: ', accuracy_trained, f1_trained, recall_trained)
return accuracy, f1, recall
def get_best_model(combined_lower_amount):
"""
first prepares data for test and train groups, then
returns best model with best hyper-parameters
"""
# prepare dataFrame for stratified and for split
data_no_fileName = combined_lower_amount.drop(['filename'], axis=1)
# print(data_no_fileName.shape) # ( , ) with label column
# encode strings of labels to integers
labels_list = data_no_fileName.iloc[:, -1]
# print(labels_list.shape) # (734,)
encoder = LabelEncoder()
encoded_labels_csv = np.array(encoder.fit_transform(labels_list))
# print(encoded_labels_csv) # [0 0 0 ... 1 1 1]
# print(encoded_labels_csv.shape) # (734,)
# print(list(encoder.inverse_transform([0,1]))) # ['negative', 'scream']
# take all except labels column. important to add the dtype=float, otherwise im getting an error in the kfold.
only_features = np.array(data_no_fileName.iloc[:, :-1], dtype=float)
# print(only_features.shape) # ( , )
""""
splitting stages
"""
# split for test and k-fold
X_for_k_fold, X_test, y_for_k_fold, y_test = train_test_split \
(only_features, encoded_labels_csv, test_size=screamGlobals.Kfold_testSize, stratify=encoded_labels_csv)
# print(len(y_for_k_fold)) # 587
# print(len(y_test)) # 147
# after stratify- lets keep only binary classification (merging Near Miss and Far miss into one label
print("merging all negative labels into one label")
# find the positive label transformation
clf_label_int = encoder.transform([screamGlobals.clf_label])[0] # 0 because it returns a list
# print(clf_label_int) # 2
# give temp values in order to prevent conflicts
tempIntLabel: int = 111
IntNegative: int = 0
IntPositive: int = 1
y_for_k_fold[y_for_k_fold == clf_label_int] = tempIntLabel
y_test[y_test == clf_label_int] = tempIntLabel
y_for_k_fold[y_for_k_fold != tempIntLabel] = IntNegative
y_test[y_test != tempIntLabel] = IntNegative
# switch to binary
y_for_k_fold[y_for_k_fold == tempIntLabel] = IntPositive
y_test[y_test == tempIntLabel] = IntPositive
# now, y_test is binary, 0 represents the true label of the classifier
# find models best hyper-parameters
optimised_model = get_optimised_model_final(X_for_k_fold, X_test, y_for_k_fold, y_test)
screamGlobals.model = optimised_model
print(f"finished optimizing our model")
accuracy, f1, recall = get_best_model_results(optimised_model,
X_test, y_test, IntPositive, X_for_k_fold, y_for_k_fold)
return optimised_model, accuracy, f1, recall
def model_results_to_csv(csv_results_head, csv_results):
# printing results to csv for tracking
print("results_to_csv")
csv_data_results = f'{screamGlobals.clf_label} {screamGlobals.get_total_samples()}' \
f' {screamGlobals.positives} {screamGlobals.negatives}' \
f' {screamGlobals.getInputDim()} {screamGlobals.Kfold_testSize} {screamGlobals.k_folds}' \
f' {screamGlobals.k_fold_repetitions} {screamGlobals.sampling_data_repetitions}'
csv_features_results = f'{screamGlobals.n_mfcc}'
# TODO- get_model_head() can be optimized in future versions to separate head from results
csv_model_head, csv_model_results = get_model_head()
csv_final_results = csv_results + ' ' + csv_data_results + ' ' + csv_features_results + ' ' + csv_model_results
# TODO enter also model params according to moris suggestion- name, hyper params
if not os.path.exists(screamGlobals.resultsPath):
csv_data_head = f'clf_label total_samples positives negatives total_features test' \
f'_size_ratio folds kfold_repeats' \
f' sampling_repeats'
csv_features_head = f'n_mfcc_amount'
csv_final_head = csv_results_head + ' ' + csv_data_head + ' ' + csv_features_head+ ' ' + csv_model_head
# save to csv (append new lines)
# file doesnt exist- lets create with header
file = open(screamGlobals.resultsPath, 'w', newline='')
with file:
writer = csv.writer(file)
writer.writerow(csv_final_head.split())
else:
# file exists with header- just add lines
file = open(screamGlobals.resultsPath, 'a', newline='')
with file:
writer = csv.writer(file)
writer.writerow(csv_final_results.split())
def save_model_and_weights(best_model):
"""
:param best_model:
new keras version allows saving a trained-model with weights in one line of code
"""
model_path = str(f'{screamGlobals.finalModelsPath}/{screamGlobals.clf_label}_clf_mfcc_{screamGlobals.n_mfcc}.h5')
print(model_path)
# new version doesnt require weights
best_model.save(model_path)
print("Saved model to disk")
def save_best_model():
"""
goal: after getting results with <different_model()> , we now have a much more limited search range in which
we will find our best model
"""
print("executing screamClf flow- save best model")
# change global definitions at the top of the file inside global_For_Clf class #todo lev maybe create config file
# screamGlobals = global_For_Clf()
create_csv() # need to create only once, but for now its already created
# lev testing parameter
# screamGlobals.try_lower_amount= lower_bound_per_class # this is used in an outer function in a different file
lower_bound_data_panda = create_lower_bound_data_panda(screamGlobals.data_file_path,
screamGlobals.clf_label)
optimised_model, accuracy, f1, recall = get_best_model(lower_bound_data_panda)
# gather results
csv_results_head = f'total_accuracy f1_{screamGlobals.clf_label} recall_{screamGlobals.clf_label}'
# csv_results = f'{mean_accuracy_sampling} {mean_f1_sampling} {mean_recall_sampling}'
csv_results = f'{accuracy} {f1} {recall}'
model_results_to_csv(csv_results_head, csv_results)
save_model_and_weights(optimised_model)
def load_bestModel():
# load model
model_path = str(f'{screamGlobals.finalModelsPath}/{screamGlobals.clf_label}_clf_mfcc_{screamGlobals.n_mfcc}.h5')
if not os.path.exists(model_path):
print(f'{model_path} doesnt exist, running save_best_model() to save best model')
save_best_model()
print("finished saving model- continue with loading")
print("loading model from {model_path}")
model= load_model(model_path)
model.summary()
screamGlobals.isTrained = True
return model
def experiment_data_size_with_model():
print("executing screamClf flow")
# change global definitions at the top of the file inside global_For_Clf class #todo lev maybe create config file
# screamGlobals = global_For_Clf()
create_csv() # need to create only once, but for now its already created
# lev testing parameter
# screamGlobals.try_lower_amount= lower_bound_per_class # this is used in an outer function in a different file
accuracy_sampling = [] # each iteration will append avg accuracy value
f1_sampling = []
recall_sampling = []
for sample_number in tqdm(range(1, screamGlobals.sampling_data_repetitions)):
lower_bound_data_panda = create_lower_bound_data_panda(screamGlobals.data_file_path,
screamGlobals.clf_label)
score_mean_k_fold, f1_mean_k_fold, recall_k_fold = get_Repeated_strtfy_results \
(lower_bound_data_panda, screamGlobals.k_folds, screamGlobals.k_fold_repetitions)
accuracy_sampling.append(score_mean_k_fold)
f1_sampling.append(f1_mean_k_fold)
recall_sampling.append(recall_k_fold)
mean_accuracy_sampling = np.mean(np.array(accuracy_sampling))
mean_f1_sampling = np.mean(np.array(f1_sampling))
mean_recall_sampling = np.mean(np.array(recall_sampling))
# gather results
csv_results_head = f'total_accuracy f1_{screamGlobals.clf_label} recall_{screamGlobals.clf_label}'
csv_results = f'{mean_accuracy_sampling} {mean_f1_sampling} {mean_recall_sampling}'
if screamGlobals.resultsPath == 'results/scream/experiment3.csv':
print("CSV for experiment3")
results_to_csv_experiment3(csv_results_head, csv_results)
else:
results_to_csv(csv_results_head, csv_results)
def evaluate_model(model):
"""
different_model() , but updated with model as input
goal: run with different sample sizes to understand on different models (changed manually inside the script
the models) and verified with a csv results file which direction should we take ...
in this function we run also an automated imported algorithm to find best model parameters and then ran
our algo with our custom kfold on our custom data with spesific ratio's positive:negative and
negative: nearMiss_negative to find best classifier
"""
# lower size must be > Nearmiss
screamGlobals.model = model # 100,150,200,250,300,350,400
# TODO can automate the process of choosing data sizes
for size in tqdm([100,150,200,250,300,350,400]):
screamGlobals.try_lower_amount = size
experiment_data_size_with_model()
def evaluate_model_different_data_size(model):
"""
different_model() , but updated with model as input
goal: run with different sample sizes to understand on different models (changed manually inside the script
the models) and verified with a csv results file which direction should we take ...
in this function we run also an automated imported algorithm to find best model parameters and then ran
our algo with our custom kfold on our custom data with spesific ratio's positive:negative and
negative: nearMiss_negative to find best classifier
"""
# lower size must be > Nearmiss
screamGlobals.model = model # 100,150,200,250,300,350,400
# TODO can automate the process of choosing data sizes
for size in tqdm([100,150,200,250,300,350,400]):
screamGlobals.try_lower_amount = size
experiment_data_size_with_model()
def evaluate_best_model():
model = load_bestModel()
evaluate_model(model)
def save_evaluate_bestModel():
save_best_model()
evaluate_best_model()
def compare_different_models():
"""
save to csv results from different models
"""
# create all the relevant models
# load best_model with best hyper parameters- this one is already trained
screamGlobals.userInput = 'compare_different_models-10%_nearmiss_instead_of_50%'
best_model = load_bestModel()
# create other models TODO - can put in different function all the creations of models
id3 = Id3Estimator()
knn = KNeighborsClassifier(3)
svc1 = SVC(kernel="linear", C=0.025)
svc2 = SVC(gamma=2, C=1)
gauss = GaussianProcessClassifier(1.0 * RBF(1.0))
decisionTrees = DecisionTreeClassifier(max_depth=25)
rand = RandomForestClassifier(max_depth=25, n_estimators=10, max_features=1)
adaboost = AdaBoostClassifier()
gaussNB = GaussianNB()
mlp = MLPClassifier(alpha=1, max_iter=100)
models_to_check = [best_model, id3, knn, svc1, svc1, svc2, gauss, decisionTrees, rand, gaussNB, adaboost, mlp]
for model in tqdm(models_to_check):
name = type(model).__name__
print(f'checking model: {name}')
evaluate_model(model)
def get_date():
"""
:return: current date with in the next format: 2019-08-21
"""
mylist = []
today = datetime.date.today()
mylist.append(today)