-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
conference.py
3691 lines (3318 loc) · 166 KB
/
conference.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
import itertools
import time
import glob as gb
import copy
import librosa
import matplotlib.pyplot as plt
import librosa.display
import pickle
import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score
import os
import soundfile as sf
import sys
import warnings
from keras.utils.vis_utils import plot_model
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
import tensorflow.keras as keras
from sklearn.svm import LinearSVC
from tensorflow.keras.layers import Input
from tensorflow.keras.regularizers import l2, l1_l2
import seaborn as sns
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from sklearn.metrics import classification_report
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import statistics
from sklearn import tree
from sklearn.dummy import DummyClassifier
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
import random
from numpy import inf
import audioread
import librosa.segment
import numpy as np
import data_utils as du
import data_utils_input as dus
from data_utils_input import normalize_image, padding_MLS, padding_SSLM, borders
from keras import backend as k
from shutil import copyfile
import fnmatch
from sklearn import preprocessing
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif
from ast import literal_eval
from sklearn.feature_selection import RFE
from skimage.transform import resize
from tensorflow.python.ops.init_ops_v2 import glorot_uniform
import lightgbm as lgb
from treegrad import TGDClassifier
from sklearn.preprocessing import MultiLabelBinarizer
import logging
# import tensorflow_decision_forests as tfdf # linux only
from tensorflow.keras.layers.experimental import RandomFourierFeatures
from XBNet.training_utils import training, predict
from XBNet.models import XBNETClassifier
from XBNet.run import run_XBNET
import autokeras as ak
from djinn import djinn
import hyperas
from hyperopt import Trials, STATUS_OK, tpe
from hyperas.distributions import choice, uniform
from os import listdir, walk, getcwd, sep
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import normalize
import math
from scipy import signal
import tensorflow.keras.layers as kl
import tensorflow.keras.applications as ka
import tensorflow.keras.optimizers as ko
import tensorflow.keras.models as km
import skimage.measure
import scipy
from scipy.spatial import distance
from tensorflow.keras.layers import Flatten, Dropout, Activation, BatchNormalization, Dense
from sklearn.model_selection import GridSearchCV
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from tensorflow.keras.optimizers import SGD
from sklearn.preprocessing import OneHotEncoder
from tensorflow.keras.layers import Conv1D, MaxPooling1D, AveragePooling1D
from tensorflow.keras.regularizers import l1
from keras.utils import np_utils
from pydub import AudioSegment
from tensorflow.keras.models import load_model
from sklearn.metrics import roc_curve, roc_auc_score, auc
import datetime
import glob
import math
import re
import pyaudio
import wave
import torch
from matplotlib.pyplot import specgram
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.metrics import multilabel_confusion_matrix
tf.get_logger().setLevel(logging.ERROR)
k.set_image_data_format('channels_last')
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
# os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
if not sys.warnoptions:
warnings.simplefilter("ignore") # ignore warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# region Directories
MASTER_DIR = 'D:/Google Drive/Resources/Dev Stuff/Python/Machine Learning/Master Thesis/'
MASTER_INPUT_DIR = 'D:/Master Thesis Input/'
MASTER_LABELPATH = os.path.join(MASTER_INPUT_DIR, 'Labels/')
WEIGHT_DIR = os.path.join(MASTER_DIR, 'Weights/')
MIDI_Data_Dir = np.array(gb.glob(os.path.join(MASTER_DIR, 'Data/MIDIs/*')))
FULL_DIR = os.path.join(MASTER_INPUT_DIR, 'Full/')
FULL_MIDI_DIR = os.path.join(FULL_DIR, 'MIDI/')
FULL_LABELPATH = os.path.join(MASTER_LABELPATH, 'Full/')
# endregion
"""=================================================================================================================="""
# region DEPRECATED
# Deprecated
Train_Data_Dir = np.array(gb.glob(os.path.join(MASTER_INPUT_DIR, 'Train/*'))) # os.path.join(MASTER_DIR, 'Data/Train/*'
Test_Data_Dir = np.array(gb.glob(os.path.join(MASTER_INPUT_DIR, 'Test/*'))) # os.path.join(MASTER_DIR, 'Data/Test/*')))
Validate_Data_Dir = np.array(gb.glob(os.path.join(MASTER_INPUT_DIR, 'Validate/*'))) # os.path.join(MASTER_DIR,'Data/Val
MLS_Data_Dir = os.path.join(MASTER_DIR, 'Images/Train/MLS/')
SSLMCOS_Data_Dir = os.path.join(MASTER_DIR, 'Images/Train/SSLMCOS/')
SSLMEUC_Data_Dir = os.path.join(MASTER_DIR, 'Images/Train/SSLMEUC/')
SSLMCRM_Data_Dir = os.path.join(MASTER_DIR, 'Images/Train/SSLMCRM/')
TRAIN_DIR = os.path.join(MASTER_INPUT_DIR, 'Train/')
TEST_DIR = os.path.join(MASTER_INPUT_DIR, 'Test/')
VAL_DIR = os.path.join(MASTER_INPUT_DIR, 'Validate/')
TRAIN_LABELPATH = os.path.join(MASTER_LABELPATH, 'Train/')
TEST_LABELPATH = os.path.join(MASTER_LABELPATH, 'Test/')
VAL_LABELPATH = os.path.join(MASTER_LABELPATH, 'Validate/')
# Deprecated
def validate_directories():
print("Validating Training Directory...")
dus.validate_folder_contents(TRAIN_LABELPATH, os.path.join(TRAIN_DIR, 'MIDI/'), os.path.join(TRAIN_DIR, 'MLS/'),
os.path.join(TRAIN_DIR, 'SSLM_CRM_COS/'), os.path.join(TRAIN_DIR, 'SSLM_CRM_EUC/'),
os.path.join(TRAIN_DIR, 'SSLM_MFCC_COS/'), os.path.join(TRAIN_DIR, 'SSLM_MFCC_EUC/'))
print("Succes.\n")
print("Validating Validation Directory...")
dus.validate_folder_contents(VAL_LABELPATH, os.path.join(VAL_DIR, 'MIDI/'), os.path.join(VAL_DIR, 'MLS/'),
os.path.join(VAL_DIR, 'SSLM_CRM_COS/'), os.path.join(VAL_DIR, 'SSLM_CRM_EUC/'),
os.path.join(VAL_DIR, 'SSLM_MFCC_COS/'), os.path.join(VAL_DIR, 'SSLM_MFCC_EUC/'))
print("Succes.\n")
print("Validating Testing Directory...")
dus.validate_folder_contents(TEST_LABELPATH, os.path.join(TEST_DIR, 'MIDI/'), os.path.join(TEST_DIR, 'MLS/'),
os.path.join(TEST_DIR, 'SSLM_CRM_COS/'), os.path.join(TEST_DIR, 'SSLM_CRM_EUC/'),
os.path.join(TEST_DIR, 'SSLM_MFCC_COS/'), os.path.join(TEST_DIR, 'SSLM_MFCC_EUC/'))
print("Succes.\n")
# Deprecated
def get_class_weights(labels, one_hot=False):
if one_hot is False:
n_classes = max(labels) + 1
else:
n_classes = len(labels[0])
class_counts = [0 for _ in range(int(n_classes))]
if one_hot is False:
for label in labels:
class_counts[label] += 1
else:
for label in labels:
class_counts[np.where(label == 1)[0][0]] += 1
return {i: (1. / class_counts[i]) * float(len(labels)) / float(n_classes) for i in range(int(n_classes))}
# Deprecated
def buildValidationSet():
cnt = 1
numtrainfiles = len(fnmatch.filter(os.listdir(os.path.join(TRAIN_DIR, "MLS/")), '*.npy'))
for file in os.listdir(os.path.join(TRAIN_DIR, "MLS/")):
numvalfiles = len(fnmatch.filter(os.listdir(os.path.join(VAL_DIR, "MLS/")), '*.npy'))
if numvalfiles >= numtrainfiles * 0.2:
print(f"Validation set >= 20% of training set: {numvalfiles}/{numtrainfiles}")
break
filename, name = file, file.split('/')[-1].split('.')[0]
print(f"\nWorking on {os.path.basename(name)}, file #" + str(cnt))
formfolder = "" # Start search for correct form to search for label
for root, dirs, files in os.walk(os.path.join(MASTER_DIR, 'Labels/')):
flag = False
for tfile in files:
if tfile.split('/')[-1].split('.')[0] == name:
formfolder = os.path.join(root, file).split('/')[-1].split('\\')[0]
flag = True
if flag:
break
path = os.path.join(os.path.join(MASTER_DIR, 'Labels/'), formfolder) + '/' + os.path.basename(name) + '.txt'
num_lines = sum(1 for _ in open(path))
if num_lines <= 2:
print("File has not been labeled with ground truth yet. Skipping...")
cnt += 1
continue
else:
src1 = os.path.join(TRAIN_DIR, "MLS/") + '/' + filename
src2 = os.path.join(TRAIN_DIR, "SSLM_CRM_COS/") + '/' + filename
src3 = os.path.join(TRAIN_DIR, "SSLM_CRM_EUC/") + '/' + filename
src4 = os.path.join(TRAIN_DIR, "SSLM_MFCC_COS/") + '/' + filename
src5 = os.path.join(TRAIN_DIR, "SSLM_MFCC_EUC/") + '/' + filename
dst1 = os.path.join(VAL_DIR, "MLS/") + '/' + filename
dst2 = os.path.join(VAL_DIR, "SSLM_CRM_COS/") + '/' + filename
dst3 = os.path.join(VAL_DIR, "SSLM_CRM_EUC/") + '/' + filename
dst4 = os.path.join(VAL_DIR, "SSLM_MFCC_COS/") + '/' + filename
dst5 = os.path.join(VAL_DIR, "SSLM_MFCC_EUC/") + '/' + filename
if os.path.exists(dst1) and os.path.exists(dst2) and os.path.exists(dst3) and os.path.exists(dst4) \
and os.path.exists(dst5):
print("File has already been prepared for training material. Skipping...")
cnt += 1
continue
else:
copyfile(src1, dst1)
copyfile(src2, dst2)
copyfile(src3, dst3)
copyfile(src4, dst4)
copyfile(src5, dst5)
cnt += 1
pass
# Deprecated
def findBestShape(mls_train, sslm_train):
dim1_mls = [i.shape[0] for i in mls_train.getImages()]
dim2_mls = [i.shape[1] for i in mls_train.getImages()]
print(dim1_mls)
print(dim2_mls)
dim1_sslm = [i.shape[0] for i in sslm_train.getImages()]
dim2_sslm = [i.shape[1] for i in sslm_train.getImages()]
print(dim1_sslm)
print(dim2_sslm)
dim1_mean = min(statistics.mean(dim1_mls), statistics.mean(dim2_sslm))
dim2_mean = min(statistics.mean(dim1_mls), statistics.mean(dim2_sslm))
dim1_median = min(statistics.median(dim1_mls), statistics.median(dim2_sslm))
dim2_median = min(statistics.median(dim1_mls), statistics.median(dim2_sslm))
dim1_mode = min(statistics.mode(dim1_mls), statistics.mode(dim2_sslm))
dim2_mode = min(statistics.mode(dim1_mls), statistics.mode(dim2_sslm))
print(f"Dimension 0:\nMean: {dim1_mean}\t\tMedian: {dim1_median}\t\tMode: {dim1_mode}")
print(f"Dimension 1:\nMean: {dim2_mean}\t\tMedian: {dim2_median}\t\tMode: {dim2_mode}")
# Deprecated WORKING FUSE MODEL
def old_formnn_fuse(output_channels=32, lrval=0.00001, numclasses=12):
cnn1_mel = formnn_mls(output_channels, lrval=lrval)
cnn1_sslm = formnn_sslm(output_channels, lrval=lrval)
combined = layers.concatenate([cnn1_mel.output, cnn1_sslm.output], axis=2)
cnn2_in = formnn_pipeline(combined, output_channels, lrval=lrval, numclasses=numclasses)
cnn2_in = layers.Dense(numclasses, activation='sigmoid')(cnn2_in)
opt = keras.optimizers.Adam(lr=lrval)
model = keras.models.Model(inputs=[cnn1_mel.input, cnn1_sslm.input], outputs=[cnn2_in])
model.compile(loss=keras.losses.BinaryCrossentropy(from_logits=True), optimizer=opt, metrics=['accuracy'])
model.summary() # Try categorical_crossentropy, metrics=[tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
if not os.path.isfile(os.path.join(MASTER_DIR, 'FormNN_Model_Diagram.png')):
plot_model(model, to_file=os.path.join(MASTER_DIR, 'FormNN_Model_Diagram.png'),
show_shapes=True, show_layer_names=True, expand_nested=True, dpi=300)
return model
# Deprecated WORKING PIPELINE MODEL
def old_formnn_pipeline(combined, output_channels=32, lrval=0.0001):
z = layers.ZeroPadding2D(padding=((1, 1), (6, 6)))(combined)
z = layers.Conv2D(filters=(output_channels * 2), kernel_size=(3, 5), strides=(1, 1),
padding='same', dilation_rate=(1, 3))(z)
z = layers.LeakyReLU(alpha=lrval)(z)
z = layers.SpatialDropout2D(rate=0.5)(z)
# z = layers.Reshape(target_shape=(-1, 1, output_channels * 152))(z)
z = layers.Conv2D(filters=output_channels * 4, kernel_size=(1, 1), strides=(1, 1), padding='same')(z)
z = layers.LeakyReLU(alpha=lrval)(z)
z = layers.SpatialDropout2D(rate=0.5)(z)
z = layers.Conv2D(filters=1, kernel_size=(1, 1), strides=(1, 1), padding='same')(z)
z = layers.GlobalMaxPooling2D()(z)
return z
# Deprecated MLS MODEL
def cnn_mls(output_channels, lrval=0.0001):
model = tf.keras.Sequential()
model.add(layers.Conv2D(filters=output_channels,
kernel_size=(5, 7), strides=(1, 1),
padding='same', # ((5 - 1) // 2, (7 - 1) // 2),
activation=layers.LeakyReLU(alpha=lrval), input_shape=(200, 1150, 4) # (1,)
))
model.add(layers.MaxPooling2D(pool_size=(5, 3), strides=(5, 1), padding='same')) # (1, 1)))
# opt = keras.optimizers.Adam(lr=lrval)
# model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
return model
# Deprecated SSLM MODEL
def cnn_sslm(output_channels, lrval=0.0001):
model = tf.keras.Sequential()
model.add(layers.Conv2D(filters=output_channels,
kernel_size=(5, 7), strides=(1, 1),
padding='same', # ((5 - 1) // 2, (7 - 1) // 2),
activation=layers.LeakyReLU(alpha=lrval), input_shape=(200, 1150, 4) # (3,)
))
model.add(layers.MaxPooling2D(pool_size=(5, 3), strides=(5, 1), padding='same')) # (1, 1)))
# opt = keras.optimizers.Adam(lr=lrval)
# model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
return model
# Deprecated PIPELINE MODEL
def cnn2(output_channels, lrval=0.0001):
model = tf.keras.Sequential()
model.add(layers.Conv2D(filters=(output_channels * 2),
kernel_size=(3, 5), strides=(1, 1),
padding='same', # ((3 - 1) // 2, (5 - 1) * 3 // 2),
dilation_rate=(1, 3),
activation=layers.LeakyReLU(alpha=lrval), input_shape=(40, 1150, 8)
))
model.add(layers.SpatialDropout2D(rate=0.5))
model.add(
layers.Conv2D(output_channels * 152, 128, (1, 1), activation=layers.LeakyReLU(alpha=lrval), padding='same'))
# *72=para 6pool, *152 para 2pool3
model.add(layers.SpatialDropout2D(rate=0.5))
model.add(layers.Conv2D(128, 1, (1, 1), padding='same')) # , padding='same'))
# x = np.reshape(x, -1, x.shape[1] * x.shape[2], 1, x.shape[3]) # reshape model?
# model = keras.layers.Reshape((-1, model.shape))(model)
# Feature maps are joined with the column dimension (frequency)
# opt = keras.optimizers.Adam(lr=lrval) # learning rate
# model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
# model.summary()
return model
# Deprecated
def fuse_model(output_channels, lrval=0.0001):
cnn1_mel = cnn_mls(output_channels, lrval=lrval)
cnn1_sslm = cnn_sslm(output_channels, lrval=lrval)
combined = keras.layers.concatenate([cnn1_mel.output, cnn1_sslm.output])
cnn2_in = cnn2(output_channels, lrval=lrval)(combined)
opt = keras.optimizers.Adam(lr=lrval) # learning rate
model = keras.models.Model(inputs=[cnn1_mel.input, cnn1_sslm.input], outputs=[cnn2_in])
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
model.summary()
model.get_layer(name='sequential_2').summary()
if not os.path.isfile(os.path.join(MASTER_DIR, 'Model_Diagram.png')):
plot_model(model, to_file=os.path.join(MASTER_DIR, 'Model_Diagram.png'),
show_shapes=True, show_layer_names=True, expand_nested=True)
# if not os.path.isfile(os.path.join(MASTER_DIR, 'Model_Diagram_Inner.png')):
# plot_model(model.get_layer(name='sequential_2'), to_file=os.path.join(MASTER_DIR, 'Model_Diagram_Inner.png'),
# show_shapes=True, show_layer_names=True, expand_nested=True)
return model
# Probably deprecated
def prepare_train_data():
"""
Retrieve analysis of the following audio data for each training file:
- Log-scaled Mel Spectrogram (MLS)
- Self-Similarity Lag Matrix (Mel-Frequency Cepstral Coefficients/MFCCs - Cosine Distance, SSLMCOS)
- Self-Similarity Lag Matrix (MFCCs - Euclidian Distance, SSLMEUC)
- Self-Similarity Matrix (Chromas, SSLMCRM)
Checks to ensure that each file has been fully analyzed/labeled with ground truth
and not yet prepared for training material.
"""
cnt = 1
for folder in MIDI_Data_Dir:
for file in os.listdir(folder):
foldername = folder.split('\\')[-1]
filename, name = file, file.split('/')[-1].split('.')[0]
print(f"\nWorking on {os.path.basename(name)}, file #" + str(cnt))
path = os.path.join(os.path.join(MASTER_DIR, 'Labels/'), foldername) + '/' + os.path.basename(name) + '.txt'
num_lines = sum(1 for _ in open(path))
if num_lines <= 2:
print("File has not been labeled with ground truth yet. Skipping...")
cnt += 1
continue
# elif os.path.basename(name) != "INSERT_DEBUG_NAME_HERE": # Debug output of specified file
else:
png1 = os.path.join(MASTER_DIR, 'Images/Train/') + "MLS/" + os.path.basename(name) + 'mls.png'
png2 = os.path.join(MASTER_DIR, 'Images/Train/') + "SSLMCOS/" + os.path.basename(name) + 'cos.png'
png3 = os.path.join(MASTER_DIR, 'Images/Train/') + "SSLMEUC/" + os.path.basename(name) + 'euc.png'
png4 = os.path.join(MASTER_DIR, 'Images/Train/') + "SSLMCRM/" + os.path.basename(name) + 'crm.png'
if os.path.exists(png1) and os.path.exists(png2) and os.path.exists(png3) and os.path.exists(png4):
print("File has already been prepared for training material. Skipping...")
cnt += 1
continue
fullfilename = folder + '/' + filename
du.create_mls_sslm(fullfilename, name, foldername)
du.peak_picking(fullfilename, name, foldername)
cnt += 1
# Deprecated
def old_prepare_train_data():
"""
Retrieve analysis of the following audio data for each training file:
- Log-scaled Mel Spectrogram (MLS)
- Self-Similarity Lag Matrix (Mel-Frequency Cepstral Coefficients/MFCCs - Cosine Distance, SSLMCOS)
- Self-Similarity Lag Matrix (MFCCs - Euclidian Distance, SSLMEUC)
- Self-Similarity Matrix (Chromas, SSLMCRM)
"""
cnt = 1
for file in Train_Data_Dir:
filename, name = file, file.split('/')[-1].split('.')[0]
print(f"\nWorking on {os.path.basename(name)}, file #" + str(cnt))
du.create_mls_sslm(filename, name)
du.create_mls_sslm2(filename, name)
cnt += 1
# Deprecated
def old_prepare_model_training_input():
"""
Read in the input data for the model, return: images [MLS, SSLMCOS, EUC, and CRM] labels (phrases), labels (seconds)
"""
mls_images = np.asarray(du.ReadImagesFromFolder(MLS_Data_Dir), dtype=np.float32)
sslmcos_images = np.asarray(du.ReadImagesFromFolder(SSLMCOS_Data_Dir), dtype=np.float32)
sslmeuc_images = np.asarray(du.ReadImagesFromFolder(SSLMEUC_Data_Dir), dtype=np.float32)
sslmcrm_images = du.ReadImagesFromFolder(SSLMCRM_Data_Dir)
lbls_seconds, lbls_phrases = du.ReadLabelSecondsPhrasesFromFolder()
# print(lbls_seconds)
# print([i for i, x in enumerate(lbls_seconds) if len(x) != 560])
# lbls_seconds = np.array(lbls_seconds).flatten()
# lbls_seconds = [item for sublist in lbls_seconds for item in sublist]
# for i in range(len(lbls_seconds)):
# lbls_seconds[i] = np.asarray(lbls_seconds[i]).flatten()
lbls_seconds = padMatrix(lbls_seconds) # matrix must not be jagged in order to convert to ndarray of float32
# print(lbls_seconds)
lbls_seconds = np.asarray(lbls_seconds, dtype=np.float32)
mdl_images = [mls_images, sslmcos_images, sslmeuc_images, sslmcrm_images]
return mdl_images, lbls_seconds, lbls_phrases
# Probably deprecated
def padMatrix(a):
b = []
width = max(len(r) for r in a)
for i in range(len(a)):
if len(a[i]) != width:
x = np.pad(a[i], (width - len(a[i]), 0), 'constant', constant_values=0)
else:
x = a[i]
b.append(x)
return b
# Probably deprecated
def debugInput(mimg, lbls, lblp):
# model_images = [0 => mls, 1 => sslmcos, 2 => sslmeuc, 3 => sslmcrm]
print("Model images:", mimg)
print("Model images length:", len(mimg))
for i in range(len(mimg)):
print("M_Imgs[" + str(i) + "] length:", len(mimg[i]))
print("Label seconds:", lbls)
print("Label phrases:", lblp)
print("Image shape:", mimg[0][0].shape) # returns (height, width, channels) := (216, 1162, 4)
# Deprecated
def old_trainModel():
model_images, labels_seconds, labels_phrases = old_prepare_model_training_input()
# debugInput(model_images, labels_seconds, labels_phrases)
# FIT MODEL AND USE CHECKPOINT TO SAVE BEST MODEL
trmodel = fuse_model(4) # (32) CNN Layer 1 Output Characteristic Maps
checkpoint = ModelCheckpoint("best_initial_model.hdf5", monitor='val_accuracy', verbose=1,
save_best_only=True, mode='max', save_freq='epoch', save_weights_only=True)
model_history = trmodel.fit((np.array([model_images[0]], dtype=np.float32),
np.array([model_images[1], model_images[2], model_images[3]], dtype=np.float32)),
# np.asarray([tf.stack(model_images[1:2]), model_images[3]],
# (np.array([model_images[1], model_images[2]], dtype=np.float32),
# np.array(model_images[3])),
np.array(labels_seconds, dtype=np.float32),
batch_size=32, epochs=2000,
validation_data=(labels_seconds,),
callbacks=[checkpoint])
print(model_history)
# PLOT MODEL HISTORY OF ACCURACY AND LOSS OVER EPOCHS
plt.plot(model_history.history['accuracy'])
plt.plot(model_history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
# plt.savefig('Initial_Model_Accuracy.png')
plt.show()
# pd.DataFrame(model_history.history).plot() # figsize=(8, 5)
# plt.show()
# summarize history for loss
plt.plot(model_history.history['loss'])
plt.plot(model_history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['train', 'test'], loc='upper left')
# plt.savefig('Initial_Model_loss.png')
plt.show()
# Probably deprecated
def combine_generator(gen1, gen2):
while True:
yield next(gen1), next(gen2)
# endregion
# region OldModelDefinition
# MIDI MODEL -- Try switching activation to ELU instead of RELU. Mimic visual/aural analysis using ensemble method
def formnn_midi(output_channels=32, numclasses=12):
inputC = layers.Input(shape=(None, 1))
w = layers.Conv1D(output_channels * 2, kernel_size=10, activation='relu', input_shape=(None, 1))(inputC)
w = layers.Conv1D(output_channels * 4, kernel_size=10, activation='relu', kernel_regularizer=l2(0.01),
bias_regularizer=l2(0.01))(w)
w = layers.MaxPooling1D(pool_size=6)(w)
w = layers.Dropout(0.4)(w)
w = layers.Conv1D(output_channels * 4, kernel_size=10, activation='relu')(w)
w = layers.MaxPooling1D(pool_size=6)(w)
w = layers.Dropout(0.4)(w)
w = layers.GlobalMaxPooling1D()(w)
w = layers.Dense(output_channels * 8, activation='relu')(w)
w = layers.Dropout(0.4)(w)
w = layers.Dense(numclasses)(w)
w = layers.Softmax()(w)
w = keras.models.Model(inputs=inputC, outputs=w)
return w
def formnn_mls2(output_channels=32):
inputA = layers.Input(batch_input_shape=(None, None, None, 1))
x = layers.Conv2D(filters=output_channels, kernel_size=(5, 7), padding='same',
kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01), activation='relu')(inputA)
x = layers.MaxPooling2D(pool_size=(5, 3), strides=(5, 1), padding='same')(x)
x = keras.models.Model(inputs=inputA, outputs=x)
return x
def formnn_sslm2(output_channels=32):
inputB = layers.Input(batch_input_shape=(None, None, None, 1)) # (None, None, None, 4)
y = layers.Conv2D(filters=output_channels, kernel_size=(5, 7), padding='same',
kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01), activation='relu')(inputB)
y = layers.MaxPooling2D(pool_size=(5, 3), strides=(5, 1), padding='same')(y)
y = layers.AveragePooling2D(pool_size=(1, 4))(y)
y = keras.models.Model(inputs=inputB, outputs=y)
return y
def formnn_pipeline2(combined, output_channels=32, numclasses=12):
z = layers.Conv2D(filters=(output_channels * 2), kernel_size=(3, 5),
padding='same', dilation_rate=(1, 3), kernel_regularizer=l2(0.01),
bias_regularizer=l2(0.01), activation='relu')(combined)
z = layers.Conv2D(filters=output_channels * 4, kernel_size=(1, 1), padding='same',
kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01), activation='relu')(z)
z = layers.MaxPooling2D(pool_size=3)(z)
z = layers.SpatialDropout2D(rate=0.3)(z)
z = layers.Conv2D(filters=output_channels * 4, kernel_size=(1, 1), padding='same',
kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01), activation='relu')(z)
z = layers.MaxPooling2D(pool_size=3)(z)
z = layers.SpatialDropout2D(rate=0.3)(z)
z = layers.GlobalMaxPooling2D()(z)
# z = layers.Dense(output_channels * 8, activation='relu')(z)
# z = layers.Dropout(rate=0.3)(z)
z = layers.Dense(numclasses)(z)
z = layers.Softmax()(z)
return z
"""=======================ORIGINAL MODEL======================="""
# MLS MODEL
def formnn_mls(output_channels=32, lrval=0.0001):
inputA = layers.Input(batch_input_shape=(None, None, None, 1))
x = layers.ZeroPadding2D(padding=((2, 2), (3, 3)))(inputA)
x = layers.Conv2D(filters=output_channels, kernel_size=(5, 7), strides=(1, 1), padding='same',
kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01))(x)
x = layers.LeakyReLU(alpha=lrval)(x)
x = layers.ZeroPadding2D(padding=((1, 1), (1, 1)))(x)
x = layers.MaxPooling2D(pool_size=(5, 3), strides=(5, 1), padding='same')(x)
x = keras.models.Model(inputs=inputA, outputs=x)
return x
# SSLM MODEL
def formnn_sslm(output_channels=32, lrval=0.0001):
inputB = layers.Input(batch_input_shape=(None, None, None, 1)) # (None, None, None, 4)
y = layers.ZeroPadding2D(padding=((2, 2), (3, 3)))(inputB)
y = layers.Conv2D(filters=output_channels, kernel_size=(5, 7), strides=(1, 1), padding='same',
kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01))(y)
y = layers.LeakyReLU(alpha=lrval)(y)
y = layers.ZeroPadding2D(padding=((1, 1), (1, 1)))(y)
y = layers.MaxPooling2D(pool_size=(5, 3), strides=(5, 1), padding='same')(y)
y = layers.AveragePooling2D(pool_size=(1, 4))(y)
y = keras.models.Model(inputs=inputB, outputs=y)
return y
# PIPELINE MODEL
def formnn_pipeline(combined, output_channels=32, lrval=0.0001, numclasses=12):
z = layers.ZeroPadding2D(padding=((1, 1), (6, 6)))(combined)
z = layers.Conv2D(filters=(output_channels * 2), kernel_size=(3, 5), strides=(1, 1),
padding='same', dilation_rate=(1, 3), kernel_regularizer=l2(0.01),
bias_regularizer=l2(0.01))(z)
z = layers.LeakyReLU(alpha=lrval)(z)
z = layers.SpatialDropout2D(rate=0.3)(z)
# z = layers.Reshape(target_shape=(-1, 1, output_channels * 152))(z)
z = layers.Conv2D(filters=output_channels * 4, kernel_size=(1, 1), strides=(1, 1), padding='same',
kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01))(z)
z = layers.LeakyReLU(alpha=lrval)(z)
# z = layers.SpatialDropout2D(rate=0.5)(z)
z = layers.Conv2D(filters=output_channels * 8, kernel_size=(1, 1), strides=(1, 1), padding='same',
kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01))(z)
z = layers.LeakyReLU(alpha=lrval)(z)
z = layers.GlobalAveragePooling2D()(z)
# z = layers.Flatten()(z)
z = layers.Dense(numclasses)(z)
z = layers.Softmax()(z)
# Softmax -> Most likely class where sum(probabilities) = 1, Sigmoid -> Multiple likely classes, sum != 1
return z
def formnn_fuse(output_channels=32, lrval=0.0001, numclasses=12):
cnn1_mel = formnn_mls(output_channels, lrval=lrval)
cnn1_sslm = formnn_sslm(output_channels, lrval=lrval)
combined = layers.concatenate([cnn1_mel.output, cnn1_sslm.output], axis=2)
cnn2_in = formnn_pipeline(combined, output_channels, lrval=lrval, numclasses=numclasses)
# opt = keras.optimizers.SGD(lr=lrval, decay=1e-6, momentum=0.9, nesterov=True)
opt = keras.optimizers.Adam(lr=lrval, epsilon=1e-6)
imgmodel = keras.models.Model(inputs=[cnn1_mel.input, cnn1_sslm.input], outputs=[cnn2_in])
midmodel = formnn_midi(output_channels, numclasses=numclasses)
averageOut = layers.Average()([imgmodel.output, midmodel.output])
model = keras.models.Model(inputs=[imgmodel.input[0], imgmodel.input[1], midmodel.input], outputs=averageOut)
model.compile(loss=['categorical_crossentropy'], optimizer=opt, metrics=['accuracy'])
# model.compile(loss=keras.losses.BinaryCrossentropy(from_logits=True), optimizer=opt, metrics=['accuracy'])
model.summary() # Try categorical_crossentropy, metrics=[tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])
if not os.path.isfile(os.path.join(MASTER_DIR, 'FormNN_Model_Diagram.png')):
plot_model(model, to_file=os.path.join(MASTER_DIR, 'FormNN_Model_Diagram.png'),
show_shapes=True, show_layer_names=True, expand_nested=True, dpi=300)
return model
def old_trainFormModel():
batch_size = 10
# region MODEL_DIRECTORIES
mls_train = dus.BuildDataloader(os.path.join(TRAIN_DIR, 'MLS/'), label_path=TRAIN_LABELPATH, # end=90,
transforms=[padding_MLS, normalize_image, borders], batch_size=batch_size)
sslm_cmcos_train = dus.BuildDataloader(os.path.join(TRAIN_DIR, 'SSLM_CRM_COS/'), label_path=TRAIN_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
sslm_cmeuc_train = dus.BuildDataloader(os.path.join(TRAIN_DIR, 'SSLM_CRM_EUC/'), label_path=TRAIN_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
sslm_mfcos_train = dus.BuildDataloader(os.path.join(TRAIN_DIR, 'SSLM_MFCC_COS/'), label_path=TRAIN_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
sslm_mfeuc_train = dus.BuildDataloader(os.path.join(TRAIN_DIR, 'SSLM_MFCC_EUC/'), label_path=TRAIN_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
midi_train = dus.BuildMIDIloader(os.path.join(TRAIN_DIR, 'MIDI/'), label_path=TRAIN_LABELPATH,
batch_size=batch_size)
mls_val = dus.BuildDataloader(os.path.join(VAL_DIR, 'MLS/'), label_path=VAL_LABELPATH,
transforms=[padding_MLS, normalize_image, borders], batch_size=batch_size)
sslm_cmcos_val = dus.BuildDataloader(os.path.join(VAL_DIR, 'SSLM_CRM_COS/'), label_path=VAL_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
sslm_cmeuc_val = dus.BuildDataloader(os.path.join(VAL_DIR, 'SSLM_CRM_EUC/'), label_path=VAL_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
sslm_mfcos_val = dus.BuildDataloader(os.path.join(VAL_DIR, 'SSLM_MFCC_COS/'), label_path=VAL_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
sslm_mfeuc_val = dus.BuildDataloader(os.path.join(VAL_DIR, 'SSLM_MFCC_EUC/'), label_path=VAL_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
midi_val = dus.BuildMIDIloader(os.path.join(VAL_DIR, 'MIDI/'), label_path=VAL_LABELPATH, batch_size=batch_size)
mls_test = dus.BuildDataloader(os.path.join(TEST_DIR, 'MLS/'), label_path=TEST_LABELPATH,
transforms=[padding_MLS, normalize_image, borders], batch_size=batch_size)
sslm_cmcos_test = dus.BuildDataloader(os.path.join(TEST_DIR, 'SSLM_CRM_COS/'), label_path=TEST_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
sslm_cmeuc_test = dus.BuildDataloader(os.path.join(TEST_DIR, 'SSLM_CRM_EUC/'), label_path=TEST_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
sslm_mfcos_test = dus.BuildDataloader(os.path.join(TEST_DIR, 'SSLM_MFCC_COS/'), label_path=TEST_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
sslm_mfeuc_test = dus.BuildDataloader(os.path.join(TEST_DIR, 'SSLM_MFCC_EUC/'), label_path=TEST_LABELPATH,
transforms=[padding_SSLM, normalize_image, borders], batch_size=batch_size)
midi_test = dus.BuildMIDIloader(os.path.join(TEST_DIR, 'MIDI/'), label_path=TEST_LABELPATH, batch_size=batch_size)
# endregion
# findBestShape(mls_train, sslm_cmcos_train)
train_datagen = multi_input_generator(mls_train, sslm_cmcos_train, sslm_cmeuc_train, sslm_mfcos_train,
sslm_mfeuc_train, midi_train)
valid_datagen = multi_input_generator(mls_val,
sslm_cmcos_val, sslm_cmeuc_val, sslm_mfcos_val, sslm_mfeuc_val, midi_val)
test_datagen = multi_input_generator(mls_test,
sslm_cmcos_test, sslm_cmeuc_test, sslm_mfcos_test, sslm_mfeuc_test, midi_test)
steps_per_epoch = len(list(mls_train)) // batch_size
steps_per_valid = len(list(mls_val)) // batch_size
label_encoder = LabelEncoder()
label_encoder.classes_ = np.load(os.path.join(WEIGHT_DIR, 'form_classes.npy'))
if mls_train.getNumClasses() != mls_val.getNumClasses() or mls_train.getNumClasses() != mls_test.getNumClasses():
print(f"Train and validation or testing datasets have differing numbers of classes: "
f"{mls_train.getNumClasses()} vs. {mls_val.getNumClasses()} vs. {mls_test.getNumClasses()}")
# classweights = get_class_weights(mls_train.getLabels().numpy().squeeze(axis=-1), one_hot=True)
"""
# Show class weights as bar graph
barx, bary = zip(*sorted(classweights.items()))
plt.figure(figsize=(12, 8))
plt.bar(label_encoder.inverse_transform(barx), bary, color='green')
for i in range(len(barx)):
plt.text(i, bary[i]//2, round(bary[i], 3), ha='center', color='white')
plt.title('Train Class Weights')
plt.ylabel('Weight')
plt.xlabel('Class')
plt.savefig('Initial_Model_Class_Weights.png')
plt.show()
"""
model = formnn_fuse(output_channels=32, lrval=0.00005, numclasses=mls_train.getNumClasses()) # Try 'val_loss'?
# model.load_weights('best_initial_model.hdf5')
early_stopping = EarlyStopping(patience=5, verbose=5, mode="auto")
checkpoint = ModelCheckpoint(os.path.join(MASTER_DIR, 'best_formNN_model.hdf5'), monitor='val_accuracy', verbose=0,
save_best_only=True, mode='max', save_freq='epoch', save_weights_only=True)
model_history = model.fit(train_datagen, epochs=100, verbose=1, validation_data=valid_datagen, shuffle=False,
callbacks=[checkpoint, early_stopping], batch_size=batch_size, # class_weight=classweight
steps_per_epoch=steps_per_epoch, validation_steps=steps_per_valid)
print("Training complete!\n")
# region LossAccuracyGraphs
plt.plot(model_history.history['loss'])
plt.plot(model_history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.savefig('Initial_Model_Loss.png')
plt.show()
plt.plot(model_history.history['accuracy'])
plt.plot(model_history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.savefig('Initial_Model_Accuracy.png')
plt.show()
pd.DataFrame(model_history.history).plot()
plt.show()
# endregion
predictions = model.predict_generator(valid_datagen, steps=1, verbose=1, workers=0)
print(predictions)
print("Prediction complete!")
inverted = label_encoder.inverse_transform([np.argmax(predictions[0, :])])
print("Predicted: ", end="")
print(inverted, end=""),
print("\tActual: ", end="")
print(label_encoder.inverse_transform([np.argmax(mls_val.getFormLabel(mls_val.getCurrentIndex() - 1))]))
print("Name: " + mls_val.getSong(mls_val.getCurrentIndex() - 1))
print("\nEvaluating...")
score = model.evaluate_generator(test_datagen, steps=len(list(mls_test)), verbose=1)
print("Evaluation complete!\nScore:")
print(f"Loss: {score[0]}\tAccuracy: {score[1]}")
# region EvaluationGraphs
predictions = model.predict(test_datagen, steps=len(list(mls_test)), verbose=1)
predictions = predictions.argmax(axis=1)
predictions = predictions.astype(int).flatten()
predictions = (label_encoder.inverse_transform(predictions))
predictions = pd.DataFrame({'Predicted Values': predictions})
actual = mls_test.getLabels().numpy().argmax(axis=1)
actual = actual.astype(int).flatten()
actual = (label_encoder.inverse_transform(actual))
actual = pd.DataFrame({'Actual Values': actual})
cm = confusion_matrix(actual, predictions)
plt.figure(figsize=(12, 10))
cm = pd.DataFrame(cm, index=[i for i in label_encoder.classes_[0:mls_test.getNumClasses()]],
columns=[i for i in label_encoder.classes_[0:mls_test.getNumClasses()]])
ax = sns.heatmap(cm, linecolor='white', cmap='Blues', linewidth=1, annot=True, fmt='')
bottom, top = ax.get_ylim()
ax.set_ylim(bottom + 0.5, top - 0.5)
plt.title('Confusion Matrix', size=20)
plt.xlabel('Predicted Labels', size=14)
plt.ylabel('Actual Labels', size=14)
plt.savefig('Initial_Model_Confusion_Matrix.png')
plt.show()
clf_report = classification_report(actual, predictions, output_dict=True,
target_names=[i for i in label_encoder.classes_[0:mls_test.getNumClasses()]])
sns.heatmap(pd.DataFrame(clf_report).iloc[:, :].T, annot=True, cmap='viridis')
plt.title('Classification Report', size=20)
plt.savefig('Initial_Model_Classification_Report.png')
plt.show()
# endregion
def formnn_cnn_mod(input_dim_1, filters=64, lrval=0.0001, numclasses=12):
model = tf.keras.Sequential()
model.add(layers.Conv1D(filters, kernel_size=10, activation='relu', input_shape=(input_dim_1, 1)))
model.add(layers.Dropout(0.4)) # ?
model.add(layers.Conv1D(filters * 2, kernel_size=10, activation='relu', kernel_regularizer=l2(0.01),
bias_regularizer=l2(0.01)))
model.add(layers.MaxPooling1D(pool_size=6))
model.add(layers.BatchNormalization())
model.add(layers.Dropout(0.4))
model.add(layers.Conv1D(filters * 2, kernel_size=10, activation='relu'))
model.add(layers.MaxPooling1D(pool_size=6))
# model.add(layers.BatchNormalization())
model.add(layers.Dropout(0.4))
model.add(layers.Flatten())
model.add(layers.Dense(filters * 4, activation='relu'))
# model.add(layers.BatchNormalization())
model.add(layers.Dropout(0.4))
model.add(layers.Dense(numclasses, activation='softmax')) # Try softmax?
opt = keras.optimizers.Adam(lr=lrval, epsilon=1e-6)
# opt = keras.optimizers.SGD(lr=lrval, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
return model
def formnn_cnn_old(input_dim_1, filters=64, lrval=0.0001, numclasses=12):
model = tf.keras.Sequential()
model.add(layers.Conv1D(filters, kernel_size=10, activation='relu', input_shape=(input_dim_1, 1)))
model.add(layers.Conv1D(filters * 2, kernel_size=10, activation='relu', kernel_regularizer=l2(0.01),
bias_regularizer=l2(0.01)))
model.add(layers.MaxPooling1D(pool_size=6))
model.add(layers.Dropout(0.4))
model.add(layers.Conv1D(filters * 2, kernel_size=10, activation='relu'))
model.add(layers.MaxPooling1D(pool_size=6))
model.add(layers.Dropout(0.4))
model.add(layers.Flatten())
model.add(layers.Dense(filters * 4, activation='relu'))
model.add(layers.Dropout(0.4))
model.add(layers.Dense(numclasses, activation='softmax')) # Try softmax?
# opt = keras.optimizers.Adam(lr=lrval, epsilon=1e-6)
opt = keras.optimizers.SGD(lr=lrval, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])
return model
# endregion
# region OldWorkingModelDefinition
def formnn_cnn(input_dim_1, filters=8, lrval=0.0001, numclasses=12, kernelsize=3, l1reg=0.01, l2reg=0.01, dropout=0.6):
np.random.seed(9)
X_input = Input(shape=(input_dim_1, 1))
X = layers.Conv1D(filters, kernel_size=kernelsize, strides=1, kernel_initializer=glorot_uniform(seed=9),
bias_regularizer=l1_l2(l1=l1reg, l2=l2reg), kernel_regularizer=l1_l2(l1=l1reg, l2=l2reg))(X_input)
X = layers.BatchNormalization(axis=2)(X)
X = layers.Activation('relu')(X)
X = layers.MaxPooling1D(numclasses, padding='same')(X)
X = layers.Dropout(dropout)(X)
# X = layers.GaussianNoise(0.1)(X)
X = layers.Conv1D(filters * 2, kernel_size=kernelsize, strides=1, kernel_initializer=glorot_uniform(seed=9),
bias_regularizer=l1_l2(l1=l1reg, l2=l2reg), kernel_regularizer=l1_l2(l1=l1reg, l2=l2reg))(X)
X = layers.BatchNormalization(axis=2)(X)
X = layers.Activation('relu')(X)
X = layers.MaxPooling1D(numclasses, padding='same')(X)
X = layers.Dropout(dropout)(X)
# X = layers.GaussianNoise(0.1)(X)
X = layers.Conv1D(filters * 4, kernel_size=kernelsize, strides=1, kernel_initializer=glorot_uniform(seed=9),
bias_regularizer=l1_l2(l1=l1reg, l2=l2reg), kernel_regularizer=l1_l2(l1=l1reg, l2=l2reg))(X)
X = layers.BatchNormalization(axis=2)(X)
X = layers.Activation('relu')(X)
X = layers.MaxPooling1D(numclasses, padding='same')(X)
X = layers.Dropout(dropout)(X)
# X = layers.GaussianNoise(0.1)(X)
X = layers.Flatten()(X)
# X = layers.Conv1D(filters * 8, kernel_size=kernelsize, strides=1, kernel_initializer=glorot_uniform(seed=9),
# bias_regularizer=l2(0.5))(X)
X = layers.Dense(filters * 8, kernel_initializer=glorot_uniform(seed=9), # 256
bias_regularizer=l1_l2(l1=l1reg, l2=l2reg), kernel_regularizer=l1_l2(l1=l1reg, l2=l2reg))(X)
X = layers.BatchNormalization(axis=-1)(X)
X = layers.Activation('relu')(X)
# X = layers.MaxPooling1D(numclasses, padding='same')(X)
X = layers.Dropout(dropout)(X)
# X = layers.GaussianNoise(0.1)(X)
# X = layers.Flatten()(X)
X = layers.Dense(numclasses, activation='sigmoid', kernel_initializer=glorot_uniform(seed=9),
bias_regularizer=l1_l2(l1=l1reg, l2=l2reg), kernel_regularizer=l1_l2(l1=l1reg, l2=l2reg))(X)
# opt = keras.optimizers.Adam(lr=lrval)
opt = keras.optimizers.SGD(lr=lrval, decay=1e-6, momentum=0.9, nesterov=True)
model = keras.models.Model(inputs=X_input, outputs=X, name='FormModel')
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
return model
def oldWorkingtrainFormModel():
# region DataPreProcessing
df = pd.read_excel(os.path.join(MASTER_DIR, 'Data/full_augmented_dataset.xlsx'))
# df = pd.read_excel(os.path.join(MASTER_DIR, 'full_dataset.xlsx'))
names = df[['piece_name', 'composer', 'filename']]
y = df['formtype']
# """
df = df.drop(columns=['sslm_chroma_cos_mean', 'sslm_chroma_cos_var', 'sslm_chroma_euc_mean', 'sslm_chroma_euc_var',
'sslm_mfcc_cos_mean', 'sslm_mfcc_cos_var', 'sslm_mfcc_euc_mean', 'sslm_mfcc_euc_var'])
# """
df.drop(columns=['spectral_bandwidth_var', 'spectral_centroid_var', 'spectral_flatness_var', 'spectral_rolloff_var',
'zero_crossing_var', 'fourier_tempo_mean', 'fourier_tempo_var'], inplace=True) # Remove useless
# nonlist = df[['duration', 'spectral_contrast_var']]
nonlist = df[['duration']]
df.drop(columns=['piece_name', 'composer', 'filename', 'duration', 'spectral_contrast_var', 'formtype'],
inplace=True)
# df = df[['ssm_log_mel_mean', 'ssm_log_mel_var', 'mel_mean', 'mel_var', 'chroma_stft_mean', 'chroma_stft_var']]
# df = df[['ssm_log_mel_mean', 'ssm_log_mel_var']]
df = df[['ssm_log_mel_mean']] # best decision tree accuracy
print("Fixing broken array cells as needed...")
def fix_broken_arr(strx):
if '[' in strx:
if ']' in strx:
return strx
else:
return strx + ']'
for col in df.columns:
df[col] = df[col].apply(lambda x: fix_broken_arr(x))
# print("Headers:", pd.concat([pd.concat([names, pd.concat([nonlist, df], axis=1)], axis=1), y], axis=1).columns)
# Headers: Index(['piece_name', 'composer', 'filename', 'duration', 'ssm_log_mel_mean', 'formtype'], dtype='object')
print("Done processing cells, building training set...")
# d = [pd.DataFrame(df[col].astype(str).apply(literal_eval).values.tolist()).add_prefix(col) for col in df.columns]
d = [pd.DataFrame(df[col].astype(str).apply(literal_eval).values.tolist()) for col in df.columns]
df = pd.concat(d, axis=1).fillna(0)
df = pd.concat([pd.concat([names, pd.concat([nonlist, df], axis=1)], axis=1), y], axis=1) # print(df)
train, test = train_test_split(df, test_size=0.169, random_state=0, stratify=df['formtype']) # test_s=.169 gave 50%
# df.to_csv(os.path.join(MASTER_DIR, 'full_modified_dataset.csv'))
X_train = train.iloc[:, 3:-1]
# X_train_names = train.iloc[:, 0:3]
y_train = train.iloc[:, -1]
print("Train shape:", X_train.shape)
X_test = test.iloc[:, 3:-1]
# X_test_names = test.iloc[:, 0:3]
y_test = test.iloc[:, -1]
print("Test shape:", X_test.shape)
# Normalize Data
"""
min_max_scaler = preprocessing.MinMaxScaler()
X_train = min_max_scaler.fit_transform(X_train) # Good for decision tree
X_test = min_max_scaler.fit_transform(X_test)
"""
# X_train = preprocessing.scale(X_train)
# X_test = preprocessing.scale(X_test)
# """
mean = np.mean(X_train, axis=0)
std = np.std(X_train, axis=0)
X_train = (X_train - mean) / std # Good for decision tree
X_test = (X_test - mean) / std
# """
print("Normalized Train shape:", X_train.shape)
print("Normalized Test shape:", X_test.shape)
# Convert to arrays for keras
X_train = np.array(X_train)
y_train = np.array(y_train)
X_test = np.array(X_test)
y_test = np.array(y_test)
label_encoder = LabelEncoder()
old_y_train = y_train
# old_y_test = y_test
int_y_train = label_encoder.fit_transform(y_train)