/
US8K-Binary Visualization, Training & Predictions.ipynb
1276 lines (1276 loc) · 911 KB
/
US8K-Binary Visualization, Training & Predictions.ipynb
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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction \n",
"## Dataset Details\n",
" - UrbanSound8K was extended by adding 2400 gunshot files to it from AudioSet & MIVIA audio events data set. \n",
" \n",
" - \"UrbanSound8K.csv\" was modified accordingly.\n",
"\n",
"- 74 more gunshots were added which were downloaded from:\n",
"http://soundbible.com/tags-gun.html\n",
"\n",
" - \"UrbanSound8K-modified.csv\" was created for latest version of dataset.\n",
" - \"US8K-Binary\" refers to new dataset\n",
"\n",
"\n",
"- Moreover, UrbanSound8K was changed for binary classification with new classes: \n",
" - no_gun_shot (8358 files, which is 3 times when compared with other class.)\n",
" - gun_shot (2848)\n",
" - Total files are 11206.\n",
"- Lastly, folds were increased from 10 to 40."
]
},
{
"cell_type": "markdown",
"metadata": {
"_uuid": "a590fa9d11ca366b1d47725556fe9d87ec8c25c9"
},
"source": [
"# Retriving and Visualizing the Dataset\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Once deleted, variables cannot be recovered. Proceed (y/[n])? y\n"
]
}
],
"source": [
"%reset\n",
"import matplotlib.pyplot as plt\n",
"import librosa\n",
"import pandas as pd\n",
"import numpy as np\n",
"import sys\n",
"import os\n",
"\n",
"# for visualization\n",
"import scipy\n",
"from scipy import signal\n",
"import IPython.display as ipd"
]
},
{
"cell_type": "markdown",
"metadata": {
"_uuid": "4c04bec9acd76c91b2d381c618a9fc41acc16e75"
},
"source": [
"## Get the classes\n",
"Reading all class names along with their numeric labels from csv file."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"_uuid": "f43a73f31fade7c9caaac6d1d166455c82277fb9"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'0': 'no_gun_shot', '1': 'gun_shot'}\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\G3NZ\\Anaconda3\\envs\\tf-2.0\\lib\\site-packages\\ipykernel_launcher.py:6: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.\n",
" \n"
]
}
],
"source": [
"dataset_dir = r\".\\UrbanSound8K-binary\"\n",
"metadata_csv = r\".\\UrbanSound8K-binary\\metadata\\UrbanSound8K-modified.csv\"\n",
"audio_dir = r\".\\UrbanSound8K-binary\\audio\"\n",
"metadata = pd.read_csv(metadata_csv)\n",
"df = pd.DataFrame(metadata)\n",
"classes = df[['classID', 'class']].as_matrix().tolist()\n",
"classes = set(['{} {}'.format(c[0], c[1]) for c in classes])\n",
"classes = np.array([c.split(' ') for c in classes])\n",
"classes = {k: v for k, v in classes}\n",
"print(classes)"
]
},
{
"cell_type": "markdown",
"metadata": {
"_uuid": "9334c05e526244f76c7af594629bf0c3e489a16a"
},
"source": [
"## Visualizing Dataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Select files for visualization"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"from tkinter import*\n",
"# Create Tk root\n",
"root = Tk()\n",
"# Hide the main window\n",
"root.withdraw()\n",
"root.call('wm', 'attributes', '.', '-topmost', True)\n",
"\n",
"from tkinter import filedialog\n",
"selected_files = filedialog.askopenfilename(multiple=True)\n",
"\n",
"%gui tk"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"# use this cell to paste file addresses manually\n",
"# selected_files = [\"xyz.mp3\", \"D://abc.mp3\"]"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"from librosa import display\n",
"for file in selected_files:\n",
" # sr = sample rate\n",
" x, sr = librosa.load(file, sr=44100)\n",
" print(type(x), type(sr))\n",
" print(x.shape, sr)\n",
" plt.figure(figsize=(14, 5))\n",
" librosa.display.waveplot(x, sr=sr)\n",
" print(file.split(\"/\")[-1])\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {
"_uuid": "db2cac259491bda373b4a23c5016594cc04d8a62"
},
"source": [
"# Extracting Features of Audio Files"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [],
"source": [
"import struct\n",
"\n",
"class WavFileHelper():\n",
" \n",
" def read_file_properties(self, filename):\n",
" wave_file = open(filename,\"rb\")\n",
" \n",
" riff = wave_file.read(12)\n",
" fmt = wave_file.read(36)\n",
" \n",
" num_channels_string = fmt[10:12]\n",
" num_channels = struct.unpack('<H', num_channels_string)[0]\n",
"\n",
" sample_rate_string = fmt[12:16]\n",
" sample_rate = struct.unpack(\"<I\",sample_rate_string)[0]\n",
" \n",
" bit_depth_string = fmt[22:24]\n",
" bit_depth = struct.unpack(\"<H\",bit_depth_string)[0]\n",
"\n",
" return (num_channels, sample_rate, bit_depth)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"# Load various imports \n",
"import pandas as pd\n",
"import os\n",
"import librosa\n",
"import librosa.display\n",
"\n",
"wavfilehelper = WavFileHelper()\n",
"\n",
"audiodata = []\n",
"for index, row in metadata.iterrows():\n",
" file_name = os.path.join(audio_dir, 'fold'+str(row[\"fold\"])+'\\\\', str(row[\"file_name\"]))\n",
" data = wavfilehelper.read_file_properties(file_name)\n",
" audiodata.append(data)\n",
"\n",
"# Convert into a Panda dataframe\n",
"audiodf = pd.DataFrame(audiodata, columns=['num_channels','sample_rate','bit_depth'])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Checking Audio Properties"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 0.71802\n",
"1 0.28198\n",
"Name: num_channels, dtype: float64\n",
"16 0.732842\n",
"24 0.247305\n",
"32 0.015181\n",
"8 0.003863\n",
"4 0.000808\n",
"Name: bit_depth, dtype: float64\n",
"44100 0.482393\n",
"48000 0.224757\n",
"32000 0.215954\n",
"96000 0.054797\n",
"24000 0.007366\n",
"16000 0.004042\n",
"22050 0.003953\n",
"11025 0.003503\n",
"192000 0.001527\n",
"8000 0.001078\n",
"11024 0.000629\n",
"Name: sample_rate, dtype: float64\n"
]
}
],
"source": [
"print(audiodf.num_channels.value_counts(normalize=True))\n",
"print(audiodf.bit_depth.value_counts(normalize=True))\n",
"print(audiodf.sample_rate.value_counts(normalize=True))"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(2, 44100, 16)"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"audiodata[0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Preprocessing with Librosa for better results"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def extract_features(file_name):\n",
" \n",
" try:\n",
" audio, sample_rate = librosa.load(file_name, res_type='kaiser_fast') \n",
"# print(audio.dtype)\n",
"# print(type(audio))\n",
"# print(len(audio))\n",
"# print(audio)\n",
" mfccs = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40)\n",
" mfccsscaled = np.mean(mfccs.T,axis=0)\n",
" \n",
" except Exception as e:\n",
" print(\"Error encountered while parsing file: \", file)\n",
" return None \n",
" \n",
" return mfccsscaled\n",
"\n",
"def extract_features_arr(audio_arr, sample_rate):\n",
" \n",
" mfccs = librosa.feature.mfcc(y=audio_arr, sr=sample_rate, n_mfcc=40)\n",
" mfccsscaled = np.mean(mfccs.T,axis=0)\n",
" \n",
" return mfccsscaled"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Set the path to the full UrbanSound dataset \n",
"features = []\n",
"\n",
"# Iterate through each sound file and extract the features \n",
"for index, row in metadata.iterrows():\n",
" \n",
" file_name = os.path.join(audio_dir,'fold'+str(row[\"fold\"])+'\\\\',str(row[\"file_name\"]))\n",
" class_label = row[\"classID\"]\n",
" data = extract_features(file_name)\n",
" features.append([data, class_label])\n",
"\n",
"# Convert into a Panda dataframe \n",
"featuresdf = pd.DataFrame(features, columns=['feature','class_label'])\n",
"\n",
"print('Finished feature extraction from ', len(featuresdf), ' files')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Use this cell to train data on specific set of files only**\n",
"I used it to better fit on specific files before training on whole dataset. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"\n",
"Use this cell to train data on specific set of files only \n",
"\n",
"\"\"\"\n",
"# # Set the path to the full UrbanSound dataset \n",
"# features_custom = []\n",
"\n",
"# path_to_files = r\"D:\\ML\\Datasets\\Sound\\Downloaded Gunshots\\renamedfiles\"\n",
"# # Iterate through each sound file and extract the features \n",
"# for file in os.listdir(path_to_files):\n",
"# file_name = os.path.join(path_to_files, file)\n",
"# class_label = 1\n",
"# data = extract_features(file_name)\n",
"# features_custom.append([data, class_label])\n",
"\n",
"# # Convert into a Panda dataframe \n",
"# featuresdf_custom = pd.DataFrame(features_custom, columns=['feature','class_label'])\n",
"\n",
"# print('Finished feature extraction from ', len(featuresdf_custom), ' files')\n",
"\n",
"# del featuresdf\n",
"# featuresdf = featuresdf_custom"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(40,)"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"featuresdf[\"feature\"][0].shape"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Saving & Loading Features Dataframe "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Instead of generating features each time, use this cell to save/load features dataframe."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"# using HDFStore for high speed data reading\n",
"backup = pd.HDFStore('Backups//dataframes_backup.h5', 'r+')\n",
"\n",
"# uncomment to store featuresdf again\n",
"# backup[\"featuresdf\"] = featuresdf\n",
"# backup[\"featuresdf_custom\"] = featuresdf_custom\n",
"\n",
"# loading from featuresdf from .h5 file\n",
"featuresdf = backup[\"featuresdf\"]\n",
"backup.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Splitting Dataset, Defining Model, Training & Evaluation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## One-hot Encoding and Splitting of Dataset"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Using TensorFlow backend.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"(11132, 40)\n",
"(11132,)\n"
]
}
],
"source": [
"from sklearn.preprocessing import LabelEncoder\n",
"from keras.utils import to_categorical\n",
"\n",
"# Convert features and corresponding classification labels into numpy arrays\n",
"X = np.array(featuresdf.feature.tolist())\n",
"y = np.array(featuresdf.class_label.tolist())\n",
"print(X.shape)\n",
"print(y.shape)\n",
"\n",
"# Encode the classification labels\n",
"le = LabelEncoder()\n",
"yy = to_categorical(le.fit_transform(y)) \n",
"\n",
"# split the dataset \n",
"from sklearn.model_selection import train_test_split \n",
"\n",
"x_train, x_test, y_train, y_test = train_test_split(X, yy, test_size=.01, random_state = 42)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Defining CNN Model"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import tensorflow as tf\n",
"from tensorflow.keras.models import Sequential\n",
"from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\n",
"from tensorflow.keras.layers import Convolution2D, Conv2D, MaxPooling2D, GlobalAveragePooling2D\n",
"from tensorflow.keras.optimizers import Adam\n",
"from keras.utils import np_utils\n",
"from sklearn import metrics "
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"num_rows = 4\n",
"num_columns = 10\n",
"num_channels = 1"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"x_train = x_train.reshape(x_train.shape[0], num_rows, num_columns, num_channels)\n",
"x_test = x_test.reshape(x_test.shape[0], num_rows, num_columns, num_channels)\n",
"\n",
"num_labels = yy.shape[1]\n",
"filter_size = 2"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"# Construct model \n",
"model = Sequential()\n",
"model.add(Conv2D(filters=16, kernel_size=2, padding=\"same\", input_shape=(num_rows, num_columns, num_channels), activation='relu'))\n",
"model.add(MaxPooling2D(pool_size=1))\n",
"model.add(Dropout(0.2))\n",
"\n",
"model.add(Conv2D(filters=32, kernel_size=2, padding=\"same\", activation='relu'))\n",
"model.add(MaxPooling2D(pool_size=1))\n",
"model.add(Dropout(0.2))\n",
"\n",
"model.add(Conv2D(filters=64, kernel_size=2, padding=\"same\", activation='relu'))\n",
"model.add(MaxPooling2D(pool_size=1))\n",
"model.add(Dropout(0.2))\n",
"\n",
"model.add(Conv2D(filters=128, kernel_size=2, padding=\"same\", activation='relu'))\n",
"model.add(MaxPooling2D(pool_size=1))\n",
"model.add(Dropout(0.2))\n",
"model.add(GlobalAveragePooling2D())\n",
"\n",
"model.add(Dense(num_labels, activation='sigmoid'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Model Compilation"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Model: \"sequential\"\n",
"_________________________________________________________________\n",
"Layer (type) Output Shape Param # \n",
"=================================================================\n",
"conv2d (Conv2D) (None, 4, 10, 16) 80 \n",
"_________________________________________________________________\n",
"max_pooling2d (MaxPooling2D) (None, 4, 10, 16) 0 \n",
"_________________________________________________________________\n",
"dropout (Dropout) (None, 4, 10, 16) 0 \n",
"_________________________________________________________________\n",
"conv2d_1 (Conv2D) (None, 4, 10, 32) 2080 \n",
"_________________________________________________________________\n",
"max_pooling2d_1 (MaxPooling2 (None, 4, 10, 32) 0 \n",
"_________________________________________________________________\n",
"dropout_1 (Dropout) (None, 4, 10, 32) 0 \n",
"_________________________________________________________________\n",
"conv2d_2 (Conv2D) (None, 4, 10, 64) 8256 \n",
"_________________________________________________________________\n",
"max_pooling2d_2 (MaxPooling2 (None, 4, 10, 64) 0 \n",
"_________________________________________________________________\n",
"dropout_2 (Dropout) (None, 4, 10, 64) 0 \n",
"_________________________________________________________________\n",
"conv2d_3 (Conv2D) (None, 4, 10, 128) 32896 \n",
"_________________________________________________________________\n",
"max_pooling2d_3 (MaxPooling2 (None, 4, 10, 128) 0 \n",
"_________________________________________________________________\n",
"dropout_3 (Dropout) (None, 4, 10, 128) 0 \n",
"_________________________________________________________________\n",
"global_average_pooling2d (Gl (None, 128) 0 \n",
"_________________________________________________________________\n",
"dense (Dense) (None, 2) 258 \n",
"=================================================================\n",
"Total params: 43,570\n",
"Trainable params: 43,570\n",
"Non-trainable params: 0\n",
"_________________________________________________________________\n",
"112/112 [==============================] - 4s 32ms/sample - loss: 0.6858 - accuracy: 0.6161\n",
"Pre-training accuracy: 61.6071%\n"
]
}
],
"source": [
"# Compile the model\n",
"model.compile(loss='binary_crossentropy', metrics=['accuracy'], optimizer='adam')\n",
"\n",
"# Display model architecture summary \n",
"model.summary()\n",
"\n",
"# Calculate pre-training accuracy \n",
"score = model.evaluate(x_test, y_test, verbose=1)\n",
"accuracy = 100*score[1]\n",
"\n",
"print(\"Pre-training accuracy: %.4f%%\" % accuracy) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Training & Saving Checkpoints with Best Validation Accuracy"
]
},
{
"cell_type": "code",
"execution_count": 101,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"WARNING: Logging before flag parsing goes to stderr.\n",
"W0811 18:58:30.735896 17032 deprecation.py:323] From C:\\Users\\G3NZ\\Anaconda3\\envs\\tf-2.0\\lib\\site-packages\\tensorflow\\python\\ops\\math_grad.py:1250: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
"Instructions for updating:\n",
"Use tf.where in 2.0, which has the same broadcast rule as np.where\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Train on 11020 samples, validate on 112 samples\n",
"Epoch 1/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.3462 - accuracy: 0.8515 ETA: 0s - loss: 0.3592 - accuracy: \n",
"Epoch 00001: val_loss improved from inf to 0.18600, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 3s 258us/sample - loss: 0.3462 - accuracy: 0.8517 - val_loss: 0.1860 - val_accuracy: 0.9643\n",
"Epoch 2/50\n",
"10900/11020 [============================>.] - ETA: 0s - loss: 0.1834 - accuracy: 0.9309\n",
"Epoch 00002: val_loss improved from 0.18600 to 0.13655, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 2s 213us/sample - loss: 0.1835 - accuracy: 0.9310 - val_loss: 0.1365 - val_accuracy: 0.9643\n",
"Epoch 3/50\n",
"10900/11020 [============================>.] - ETA: 0s - loss: 0.1459 - accuracy: 0.9450\n",
"Epoch 00003: val_loss improved from 0.13655 to 0.11366, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 2s 217us/sample - loss: 0.1454 - accuracy: 0.9453 - val_loss: 0.1137 - val_accuracy: 0.9732\n",
"Epoch 4/50\n",
"10750/11020 [============================>.] - ETA: 0s - loss: 0.1333 - accuracy: 0.9511\n",
"Epoch 00004: val_loss improved from 0.11366 to 0.10313, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 2s 212us/sample - loss: 0.1325 - accuracy: 0.9516 - val_loss: 0.1031 - val_accuracy: 0.9732\n",
"Epoch 5/50\n",
"10850/11020 [============================>.] - ETA: 0s - loss: 0.1186 - accuracy: 0.9562\n",
"Epoch 00005: val_loss did not improve from 0.10313\n",
"11020/11020 [==============================] - 3s 233us/sample - loss: 0.1181 - accuracy: 0.9563 - val_loss: 0.1585 - val_accuracy: 0.9464\n",
"Epoch 6/50\n",
"10900/11020 [============================>.] - ETA: 0s - loss: 0.1053 - accuracy: 0.9628\n",
"Epoch 00006: val_loss did not improve from 0.10313\n",
"11020/11020 [==============================] - 2s 211us/sample - loss: 0.1056 - accuracy: 0.9629 - val_loss: 0.1126 - val_accuracy: 0.9643\n",
"Epoch 7/50\n",
"10850/11020 [============================>.] - ETA: 0s - loss: 0.1026 - accuracy: 0.9629\n",
"Epoch 00007: val_loss did not improve from 0.10313\n",
"11020/11020 [==============================] - 2s 213us/sample - loss: 0.1030 - accuracy: 0.9629 - val_loss: 0.1493 - val_accuracy: 0.9554\n",
"Epoch 8/50\n",
"10900/11020 [============================>.] - ETA: 0s - loss: 0.0946 - accuracy: 0.9663\n",
"Epoch 00008: val_loss did not improve from 0.10313\n",
"11020/11020 [==============================] - 2s 222us/sample - loss: 0.0947 - accuracy: 0.9663 - val_loss: 0.1343 - val_accuracy: 0.9643\n",
"Epoch 9/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0878 - accuracy: 0.9695\n",
"Epoch 00009: val_loss did not improve from 0.10313\n",
"11020/11020 [==============================] - 2s 207us/sample - loss: 0.0878 - accuracy: 0.9694 - val_loss: 0.1105 - val_accuracy: 0.9643\n",
"Epoch 10/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0838 - accuracy: 0.9709\n",
"Epoch 00010: val_loss improved from 0.10313 to 0.09442, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 2s 207us/sample - loss: 0.0842 - accuracy: 0.9708 - val_loss: 0.0944 - val_accuracy: 0.9643\n",
"Epoch 11/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0817 - accuracy: 0.9724\n",
"Epoch 00011: val_loss improved from 0.09442 to 0.08939, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 3s 230us/sample - loss: 0.0817 - accuracy: 0.9722 - val_loss: 0.0894 - val_accuracy: 0.9821\n",
"Epoch 12/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0830 - accuracy: 0.9731\n",
"Epoch 00012: val_loss did not improve from 0.08939\n",
"11020/11020 [==============================] - 3s 234us/sample - loss: 0.0829 - accuracy: 0.9731 - val_loss: 0.0991 - val_accuracy: 0.9732\n",
"Epoch 13/50\n",
"10900/11020 [============================>.] - ETA: 0s - loss: 0.0718 - accuracy: 0.9746\n",
"Epoch 00013: val_loss did not improve from 0.08939\n",
"11020/11020 [==============================] - 2s 220us/sample - loss: 0.0719 - accuracy: 0.9745 - val_loss: 0.1254 - val_accuracy: 0.9643\n",
"Epoch 14/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0737 - accuracy: 0.9754\n",
"Epoch 00014: val_loss did not improve from 0.08939\n",
"11020/11020 [==============================] - 3s 228us/sample - loss: 0.0736 - accuracy: 0.9755 - val_loss: 0.0919 - val_accuracy: 0.9732\n",
"Epoch 15/50\n",
"10850/11020 [============================>.] - ETA: 0s - loss: 0.0687 - accuracy: 0.9763\n",
"Epoch 00015: val_loss did not improve from 0.08939\n",
"11020/11020 [==============================] - 3s 252us/sample - loss: 0.0695 - accuracy: 0.9760 - val_loss: 0.1194 - val_accuracy: 0.9643\n",
"Epoch 16/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0720 - accuracy: 0.9757\n",
"Epoch 00016: val_loss did not improve from 0.08939\n",
"11020/11020 [==============================] - 3s 236us/sample - loss: 0.0718 - accuracy: 0.9758 - val_loss: 0.1359 - val_accuracy: 0.9554\n",
"Epoch 17/50\n",
"10900/11020 [============================>.] - ETA: 0s - loss: 0.0684 - accuracy: 0.9757\n",
"Epoch 00017: val_loss did not improve from 0.08939\n",
"11020/11020 [==============================] - 3s 288us/sample - loss: 0.0680 - accuracy: 0.9758 - val_loss: 0.1079 - val_accuracy: 0.9464\n",
"Epoch 18/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0653 - accuracy: 0.9779\n",
"Epoch 00018: val_loss improved from 0.08939 to 0.08464, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 3s 264us/sample - loss: 0.0652 - accuracy: 0.9779 - val_loss: 0.0846 - val_accuracy: 0.9821\n",
"Epoch 19/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0641 - accuracy: 0.9777\n",
"Epoch 00019: val_loss improved from 0.08464 to 0.07915, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 3s 231us/sample - loss: 0.0640 - accuracy: 0.9778 - val_loss: 0.0791 - val_accuracy: 0.9821\n",
"Epoch 20/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0607 - accuracy: 0.9779\n",
"Epoch 00020: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 3s 228us/sample - loss: 0.0606 - accuracy: 0.9779 - val_loss: 0.1104 - val_accuracy: 0.9554\n",
"Epoch 21/50\n",
"10850/11020 [============================>.] - ETA: 0s - loss: 0.0583 - accuracy: 0.9799\n",
"Epoch 00021: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 3s 288us/sample - loss: 0.0588 - accuracy: 0.9799 - val_loss: 0.0853 - val_accuracy: 0.9732\n",
"Epoch 22/50\n",
"10850/11020 [============================>.] - ETA: 0s - loss: 0.0585 - accuracy: 0.9785\n",
"Epoch 00022: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 3s 230us/sample - loss: 0.0588 - accuracy: 0.9784 - val_loss: 0.1043 - val_accuracy: 0.9688\n",
"Epoch 23/50\n",
"10850/11020 [============================>.] - ETA: 0s - loss: 0.0579 - accuracy: 0.9810\n",
"Epoch 00023: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 3s 232us/sample - loss: 0.0573 - accuracy: 0.9812 - val_loss: 0.0862 - val_accuracy: 0.9732\n",
"Epoch 24/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0577 - accuracy: 0.9800\n",
"Epoch 00024: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 4s 336us/sample - loss: 0.0575 - accuracy: 0.9800 - val_loss: 0.0939 - val_accuracy: 0.9643\n",
"Epoch 25/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0514 - accuracy: 0.9815\n",
"Epoch 00025: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 6s 508us/sample - loss: 0.0515 - accuracy: 0.9814 - val_loss: 0.0951 - val_accuracy: 0.9732\n",
"Epoch 26/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0565 - accuracy: 0.9807\n",
"Epoch 00026: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 6s 571us/sample - loss: 0.0562 - accuracy: 0.9809 - val_loss: 0.0814 - val_accuracy: 0.9732\n",
"Epoch 27/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0521 - accuracy: 0.9831\n",
"Epoch 00027: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 6s 519us/sample - loss: 0.0519 - accuracy: 0.9831 - val_loss: 0.1102 - val_accuracy: 0.9643\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 28/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0526 - accuracy: 0.9809\n",
"Epoch 00028: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 5s 480us/sample - loss: 0.0526 - accuracy: 0.9809 - val_loss: 0.0890 - val_accuracy: 0.9732\n",
"Epoch 29/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0518 - accuracy: 0.9813\n",
"Epoch 00029: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 6s 517us/sample - loss: 0.0517 - accuracy: 0.9813 - val_loss: 0.1366 - val_accuracy: 0.9464\n",
"Epoch 30/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0509 - accuracy: 0.9841\n",
"Epoch 00030: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 7s 593us/sample - loss: 0.0510 - accuracy: 0.9840 - val_loss: 0.0897 - val_accuracy: 0.9643\n",
"Epoch 31/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0492 - accuracy: 0.9829 ETA\n",
"Epoch 00031: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 7s 592us/sample - loss: 0.0490 - accuracy: 0.9830 - val_loss: 0.0893 - val_accuracy: 0.9732\n",
"Epoch 32/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0463 - accuracy: 0.9846\n",
"Epoch 00032: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 6s 568us/sample - loss: 0.0462 - accuracy: 0.9846 - val_loss: 0.0890 - val_accuracy: 0.9732\n",
"Epoch 33/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0450 - accuracy: 0.9851\n",
"Epoch 00033: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 6s 529us/sample - loss: 0.0449 - accuracy: 0.9852 - val_loss: 0.1011 - val_accuracy: 0.9554\n",
"Epoch 34/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0459 - accuracy: 0.9847\n",
"Epoch 00034: val_loss did not improve from 0.07915\n",
"11020/11020 [==============================] - 6s 563us/sample - loss: 0.0457 - accuracy: 0.9847 - val_loss: 0.0880 - val_accuracy: 0.9732\n",
"Epoch 35/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0457 - accuracy: 0.9844\n",
"Epoch 00035: val_loss improved from 0.07915 to 0.07434, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 9s 809us/sample - loss: 0.0458 - accuracy: 0.9844 - val_loss: 0.0743 - val_accuracy: 0.9732\n",
"Epoch 36/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0449 - accuracy: 0.9850\n",
"Epoch 00036: val_loss did not improve from 0.07434\n",
"11020/11020 [==============================] - 12s 1ms/sample - loss: 0.0450 - accuracy: 0.9850 - val_loss: 0.0765 - val_accuracy: 0.9821\n",
"Epoch 37/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0422 - accuracy: 0.9855\n",
"Epoch 00037: val_loss improved from 0.07434 to 0.07366, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 10s 947us/sample - loss: 0.0421 - accuracy: 0.9855 - val_loss: 0.0737 - val_accuracy: 0.9821\n",
"Epoch 38/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0447 - accuracy: 0.9843\n",
"Epoch 00038: val_loss improved from 0.07366 to 0.07210, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 11s 999us/sample - loss: 0.0447 - accuracy: 0.9842 - val_loss: 0.0721 - val_accuracy: 0.9732\n",
"Epoch 39/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0443 - accuracy: 0.9851\n",
"Epoch 00039: val_loss improved from 0.07210 to 0.06468, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 11s 1ms/sample - loss: 0.0441 - accuracy: 0.9852 - val_loss: 0.0647 - val_accuracy: 0.9821\n",
"Epoch 40/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0409 - accuracy: 0.9856\n",
"Epoch 00040: val_loss did not improve from 0.06468\n",
"11020/11020 [==============================] - 11s 1ms/sample - loss: 0.0408 - accuracy: 0.9856 - val_loss: 0.0680 - val_accuracy: 0.9821\n",
"Epoch 41/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0437 - accuracy: 0.98 - ETA: 0s - loss: 0.0438 - accuracy: 0.9860\n",
"Epoch 00041: val_loss improved from 0.06468 to 0.06443, saving model to best_weights_temp.hdf5\n",
"11020/11020 [==============================] - 11s 1ms/sample - loss: 0.0437 - accuracy: 0.9860 - val_loss: 0.0644 - val_accuracy: 0.9732\n",
"Epoch 42/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0404 - accuracy: 0.9863\n",
"Epoch 00042: val_loss did not improve from 0.06443\n",
"11020/11020 [==============================] - 10s 921us/sample - loss: 0.0404 - accuracy: 0.9863 - val_loss: 0.0704 - val_accuracy: 0.9821\n",
"Epoch 43/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0390 - accuracy: 0.9874\n",
"Epoch 00043: val_loss did not improve from 0.06443\n",
"11020/11020 [==============================] - 12s 1ms/sample - loss: 0.0390 - accuracy: 0.9874 - val_loss: 0.0683 - val_accuracy: 0.9821\n",
"Epoch 44/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0392 - accuracy: 0.9873\n",
"Epoch 00044: val_loss did not improve from 0.06443\n",
"11020/11020 [==============================] - 10s 936us/sample - loss: 0.0392 - accuracy: 0.9873 - val_loss: 0.0724 - val_accuracy: 0.9821\n",
"Epoch 45/50\n",
"10950/11020 [============================>.] - ETA: 0s - loss: 0.0385 - accuracy: 0.9877\n",
"Epoch 00045: val_loss did not improve from 0.06443\n",
"11020/11020 [==============================] - 10s 925us/sample - loss: 0.0384 - accuracy: 0.9877 - val_loss: 0.1042 - val_accuracy: 0.9643\n",
"Epoch 46/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0400 - accuracy: 0.9867\n",
"Epoch 00046: val_loss did not improve from 0.06443\n",
"11020/11020 [==============================] - 11s 980us/sample - loss: 0.0399 - accuracy: 0.9868 - val_loss: 0.0680 - val_accuracy: 0.9821\n",
"Epoch 47/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0424 - accuracy: 0.9863\n",
"Epoch 00047: val_loss did not improve from 0.06443\n",
"11020/11020 [==============================] - 11s 1ms/sample - loss: 0.0423 - accuracy: 0.9863 - val_loss: 0.0701 - val_accuracy: 0.9821\n",
"Epoch 48/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0333 - accuracy: 0.9879\n",
"Epoch 00048: val_loss did not improve from 0.06443\n",
"11020/11020 [==============================] - 9s 855us/sample - loss: 0.0332 - accuracy: 0.9879 - val_loss: 0.0819 - val_accuracy: 0.9643\n",
"Epoch 49/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0354 - accuracy: 0.9874\n",
"Epoch 00049: val_loss did not improve from 0.06443\n",
"11020/11020 [==============================] - 10s 921us/sample - loss: 0.0354 - accuracy: 0.9874 - val_loss: 0.0702 - val_accuracy: 0.9821\n",
"Epoch 50/50\n",
"11000/11020 [============================>.] - ETA: 0s - loss: 0.0356 - accuracy: 0.9881\n",
"Epoch 00050: val_loss did not improve from 0.06443\n",
"11020/11020 [==============================] - 9s 860us/sample - loss: 0.0355 - accuracy: 0.9881 - val_loss: 0.0720 - val_accuracy: 0.9821\n",
"Training completed in time: 0:04:53.609231\n"
]
}
],
"source": [
"from tensorflow.keras.callbacks import ModelCheckpoint \n",
"from datetime import datetime \n",
"\n",
"num_epochs = 50\n",
"num_batch_size = 50\n",
"\n",
"checkpointer = ModelCheckpoint(filepath='best_weights_temp.hdf5', \n",
" verbose=1, save_best_only=True)\n",
"start = datetime.now()\n",
"\n",
"model.fit(x_train, y_train, batch_size=num_batch_size, epochs=num_epochs, validation_data=(x_test, y_test), callbacks=[checkpointer], verbose=1)\n",
"\n",
"\n",
"duration = datetime.now() - start\n",
"print(\"Training completed in time: \", duration)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evaluation"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Training Accuracy: 99.30%\n",
"Test Accuracy: 97.32%\n"
]
}
],
"source": [
"# Evaluating the model on the training and testing set\n",
"score = model.evaluate(x_train, y_train, verbose=0)\n",
"print(\"Training Accuracy: {0:.2f}\".format(score[1] * 100) + \"%\")\n",
"\n",
"score = model.evaluate(x_test, y_test, verbose=0)\n",
"print(\"Test Accuracy: {0:.2f}\".format(score[1] * 100) + \"%\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Making Predictions"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"# load model\n",
"model.load_weights(\"Backups//best_weights_temp.hdf5\")"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"def predict_class(featuresdf):\n",
" pred_index_tensor=tf.argmax(model.predict(featuresdf.reshape(1, x_train.shape[1], x_train.shape[2], x_train.shape[3])), axis=1)\n",
" pred_index_arr = pred_index_tensor.numpy()\n",
" pred_index = str(pred_index_arr[0])\n",
" pred_class = classes[pred_index]\n",
" return (pred_index, pred_class)\n",
"\n",
"def index_to_class(index):\n",
" return classes[str(index)]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Make prediction on test set"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enter test set file index (total test files are 112):\n",
"50\n",
"\n",
"Predicted Class: 1\n",
"Predicted Class Name: gun_shot\n",
"\n",
"Actual Class: gun_shot\n"
]
}
],
"source": [
"# make prediction on test set file\n",
"index = int(input(\"Enter test set file index (total test files are \" + str(len(x_test)) + \"):\\n\"))\n",
"print()\n",