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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# What is Music?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the first lesson of Popular Music History lecture, a professor came and asked us \"What is Music?\". We all had different answers. Music is a song made by instruments. Music is the expression of feelings. Music is singing. Music is what takes us to other worlds. The answers were all correct. However, the professor said there was a more general definition. Music is a set of sounds that harmonize with each other. It is harmony that distinguishes music from noise.\n",
    "\n",
    "Popular Music History was one of the elective courses I took during my engineering degree. After many years, I never forgot this answer from the professor. It was very reasonable. Above all, musical notes we hear from different instruments are just sound waves. They have mathematical expressions in both the time and frequency domain. Some waves go well with each other. Some just don't get along and make noise.\n",
    "\n",
    "Recently, I was searching for datasets about music in Kaggle and came across [Deep Contractor's](https://www.kaggle.com/deepcontractor) dataset \"[Musical Instrument Chord Classification (Audio)](https://www.kaggle.com/deepcontractor/musical-instrument-chord-classification)\". The dataset contains audio files which are chord recordings from either a piano or guitar. Chords are labeled as Major or Minor, so the data is suitable for a classification problem. I thought why not give it a try and started.\n",
    "\n",
    "In the first section, I explained the mathematics behind the music as much as I can. There will be a bit of music theory, a bit of math, and a bit of digital signal processing. Using the knowledge from section 1, I created a DataFrame from all the audio files in section 2. In section 3, I explored data and applied some feature engineering to make it ready for machine learning. Finally, I build a model and make predictions in section 4. \n",
    "\n",
    "**Index**\n",
    "\n",
    "1. [Understanding Math Behind Music](#1.-Understanding-Math-Behind-Music)\n",
    "\n",
    " 1.1. [Notes and Chords](#1.1.-Notes-and-Chords)\n",
    " \n",
    " 1.2. [Time and Frequency Domain Representations](#1.2.-Time-and-Frequency-Domain-Representations)\n",
    " \n",
    " 1.3. [Spectrogram](#1.3.-Spectrogram)\n",
    " \n",
    " 1.4. [Detection of Harmonic Frequencies](#1.4.-Detection-of-Harmonic-Frequencies)\n",
    "\n",
    "2. [Importing Dataset](#2.-Importing-Dataset)\n",
    "\n",
    "3. [Data Exploration](#3.-Data-Exploration)\n",
    "\n",
    " 3.1. [Min and Max Harmonics](#3.1.-Min-and-Max-Harmonics)\n",
    " \n",
    " 3.2. [Number of Harmonics](#3.2.-Number-of-Harmonics)\n",
    " \n",
    " 3.3. [Feature Engineering on Harmonics](#3.3.-Feature-Engineering-on-Harmonics)\n",
    "\n",
    "4. [Model Building](#4.-Model-Building)\n",
    "\n",
    " 4.1. [Preprocessing Data](#4.1.-Preprocessing-Data)\n",
    " \n",
    " 4.2. [Model Selection](#4.2.-Model-Selection)\n",
    " \n",
    " 4.3. [Model Training and Prediction](#4.3.-Model-Training-and-Prediction)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1. Understanding Math Behind Music"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "_cell_guid": "b1076dfc-b9ad-4769-8c92-a6c4dae69d19",
    "_uuid": "8f2839f25d086af736a60e9eeb907d3b93b6e0e5",
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:50.439036Z",
     "iopub.status.busy": "2023-04-24T19:47:50.438637Z",
     "iopub.status.idle": "2023-04-24T19:47:51.679073Z",
     "shell.execute_reply": "2023-04-24T19:47:51.678228Z",
     "shell.execute_reply.started": "2023-04-24T19:47:50.438964Z"
    }
   },
   "outputs": [],
   "source": [
    "# importing necessary packages for the section\n",
    "import os\n",
    "import IPython\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from scipy.io import wavfile\n",
    "from scipy.fft import fft, fftfreq\n",
    "from scipy.signal import spectrogram, find_peaks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.1. Notes and Chords"
   ]
  },
  {
   "attachments": {
    "b6f37314-e253-479a-b37c-9296e4ca19b8.png": {
     "image/png": "iVBORw0KGgoAAAANSUhEUgAABJoAAAFfCAYAAAAGdKYmAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAFiUAABYlAUlSJPAAACrISURBVHhe7d0JvF3TvQfwFWJWlBqLkqjEUFNFayo1K6+eDoZSLaq84rXhqakorT5DS5DSR7Q8UTWU57VPgtKkMfUh5jZFzDE8YoiYidf/zrrJzc2lyb3rnpNz9/f7+ZxP9lrk5N5z9973rN9Z67/6jBkz5v0EAAAAAN00V/4TAAAAALpF0AQAAABAEYImAAAAAIoQNAEAAABQhKAJAAAAgCIETQAAAAAUIWgCAAAAoAhBEwAAAABFCJoAAAAAKELQBAAAAEARgiYAAAAAihA0AQAAAFCEoAkAAACAIgRNAAAAABQhaAIAAACgCEETAAAAAEUImgAAAAAoQtAEAAAAQBGCJgAAAACKEDQBAAAAUISgCQAAAIAiBE0AAAAAFCFoAgAAAKAIQRMAAAAARQiaAAAAAChC0AQAAABAEYImAAAAAIoQNAEAAABQhKAJAAAAgCIETQAAAAAUIWgCAAAAoAhBEwAAAABFCJoAAAAAKELQBAAAAEARgiYAAAAAihA0AQAAAFBEnzFjxryfj2GaTTfdNB8BAADQ3t/H0fkI6EjQRKeee+65fNQ4d999dzr11FPTXHM1Z6Jd/Ls//OEP08orr5x7GmPy5Mnp5z//eZoyZUruaazXX389feUrX0lrr7127mmsK664Io0cOTLNN998uaex+vTpU513CyywQO5pDU8++WQaPHhwdXzCCSdUf7aSp59+Op133nnp/feb8yso/t241r/5zW/mnsb57W9/m+69997q3GuG+N532223tNpqq+We1jBx4sR0xhlnpBVXXDF961vfyr2t4bXXXks//elP03vvvZd7Gm+hhRZKhx9+eG41zvDhw9Njjz2W5p577tzTOPF7NX637LPPPmnxxRfPvY3zxBNPpF/+8pe51Xhxrffv3z/ttddeuad1HHvssdWfw4YNS6usskp13EqGDh2a/vjHPzbtvc28885bnXvNeE8dv1fffPPN3Gqst99+O22wwQbpiCOOyD09qxn3NWgVgibmGPFGfPfdd08vvfRS7mms5ZdfPl199dVpvfXWyz2N8eKLL6Z11lmnCg6aJQZAhx56aG411imnnNKUwU+beBM+duzYtMgii+Se1jBkyJBpQdP48eNTv379quNWceedd6aNNtqoelPYLJtssklTPo3cb7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qr+t6bYbfddkvXXHNNmm+++XLP7Inz5s0330xLLLFE7pk977//fnXutNrAe8iQIdM+MR0/fnzq169fddwq7rzzzrTBBhukPn365J5ZFz+zuNbj73b1DW38/XXWWSeNHTs29zTOnnvumX796193eeD/3nvvVa9B3759c8/sib/729/+tuU+9X3wwQfTgAED0sYbb5xuuumm3Nsann/++bTWWmulZ599Nvc0Xgx+J02alFuNs9hii6VXXnkltxov7hFnnnlmOvDAA3NP45x44onpmGOO6dJ9LsS1Go/4+129V8Z5d/fdd+ee1nDPPfdU9+cwbNiwtO+++1bHreTggw9Ol112WZp//vlzz6x7+eWX0+TJk9Pyyy+fe2ZfhC3jxo1rSsAc51y8N+uKeC/+xBNPpKWWWqpL44E33ngjbb/99mnvvffOPUCzCJroNU455ZTqTfSoUaNyT2t466230i9+8YsuDxpvueWWatB66qmnpgUWWCD3zrp33nkn7brrrmnZZZfNPY316quvVm8quur0009PV155Zfr7vSz3zL411lgjH7WOVg+awiWXXJKPZs9TTz2Vvv/971ehw3HHHZd7Z99qq602bTDTSM8991x64IEHcmv2xRvouGYiLIpBfFdsscUW+ah1tHLQFOJe/ac//Sm3Zs/o0aPTyJEj084771wFtF11xBFH5KPG2W+//dJdd93VpaAkfj/ed999aaGFFqqu166IgG3EiBFd/jCju2688cZ8NPsiCD/ssMPSlltumY466qjcO3uWW265NHDgwNxqDb0haIpQOT5I7Ir4/X755Zenm2++Ofd0zeqrr56PGmvChAn5aPY988wzadCgQenss89OX/ziF3Pv7Hv00UfzEdAsgiZ6jVYNmror3oTFG/mXXnqpy4POVnbkkUdWr0HMGKiT3hA0dVWENGuuuWbaZJNNuhUwtqoYPPz1r3+tAqv41LcuWj1o6o6TTz65ConOOeecdMABB+Te3u+hhx6qZvyuv/766fbbb8+99fGHP/whbb311mmPPfZIw4cPz729X28ImrojQsVzzz03vfDCC7mnPuKDpBVWWKH6IKo7M7qA5lOjCQAAAIAiBE0AAAAAFCFoAgAAAKAIQRMAAAAARQiaAAAAAChC0A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zQMPPJCuvfba9IlPfCIdeeSR1ZKv2Xnsueee+ZmmizCtboXh55577rTjjjumZZddNvdMFb9bLr/88vTGG2/kHgDqQtAEUBOxtKFjAdsQg8/YaYieEa9vR7FsLgrqQk+IoKmzZWCxjHPSpEm5VW8xwypm2zzzzDNVjaHjjjsuHX744bP1OPjgg2cKV26++eb0t7/9LbfqI+o1dZzVFu677z4bTgDUkKAJoCbiU/vOBgLjx49PL774Ym5RUgxmY7v8jqIeTAzMoCdEkLnuuuvm1nSPPvpop/XC6ijqVY0YMaI63nLLLdN8881XHc+OCO9jB7r2Irj6/e9/X7tZolG3Kn7HdBRBU7wmANSLoAmgJhZddNGZBkUhBgKdzbop6emnn06f//zn08UXX5x76iF22HrkkUdya7oNN9ywVrsARuD23//939WuXDTG5z73uZlm28SA/+GHH86terv//vurukxxTxw0aFDunT0R6G222Wa5Nd11111Xu9p3888/f1pmmWVyazpLswHqSdAEUCPbbLNNNZumvRgI/O///m9u9Yw77rgjjRo1KrfqIwab8b23F7MgonBu1DWpi5dffjldcMEF6d5778099LSBAwembbfdNremi3phdR/4x05oMesodDf03WKLLWa6p0ZR8Lvuuiu36mHKlCnp7bffzi0A6k7QBFAjK664YlWPpKPYlrunCtjGoO6GG27IrXq57bbbZlo6t/POO8/yNuq9Rczqitcizj8aI5Yy7b333jPNarr99ttrXzPnscceS6NHj65emyhi3Z3QN3aq6xg0hd/97nfVrnZ1ESFTZ0uwoy5gzPwCoF4ETQA1EgOq3XffPW288ca5Z6qeLGAbS/Ouvvrq3KqPKLzccalYDEi/+c1vpr59++aeeohZXeq0NF6cb1/72tdya6qYbfOXv/wlt+opioDHzK64Dw4YMCD3dk3UdoqwqqPYzS52tauL2M2wsyXY/fv3r8I4AOpF0ARQMyuttFI66KCDZviUOUKAyy67rJp9VFI8329+85v0+OOP5576uOaaa9JVV12VW1PruXzve9/rdOe/3ixmdcRsJhovQpD9999/hhk3dd9yPmZujhw5sjrebrvtqtp13bXmmmt2WhQ8Aq2oT1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UyAT0rQqS4pju71mO5WaNCJgCgdQmaAAAAAChC0AQAAABAEYImAAAAAIoQNAEAAABQhKAJAAAAgCIETQAAAAAUIWgCAAAAoAhBEwAAAABFCJoAAAAAKELQBAAAAEARgiYAAAAAihA0AQAAAFCEoAkAAACAIgRNAAAAABQhaAIAAACgCEETAAAAAEUImgAAAAAoQtAEAAAAQBGCJgAAAACKEDQBAAAAUISgCQAAAIAiBE0AAAAAFCFoAgAAAKAIQRMAAAAARQiaAAAAAChC0AQAAABAEYImAAAAAIoQNAEAAABQhKAJAAAAgCIETQAAAAAUIWgCAAAAoAhBEwAAAABFCJoAAAAAKELQBAAAAEARfcaMGfN+PoZpJk2alI9ax/HHH5/eeOONdNJJJ+Weerj22mvTmWeemS677LK00EIL5d76uOCCC6rX4JJLLsk99fDggw+mwYMHV8eHHHJI9WddTJw4MV144YXp4x//eNp1111zb33E9/7qq6+mffbZJy244IK5t/d76aWX0q9+9au03HLLpd122y331sPtt9+e/v5+LW211VZprbXWyr29X9vPfOmll0577LFH7q2PJ554Il1xxRVp4MCB6Qtf+ELurYfTTjut+nPYsGGpb9++1XFdxM981KhRaejQobmnPuKaP++889Jmm22WPvOZz+TeOVf//v3zEdCRoIlObbrppvkIAACA9uIDAKBzgiYAAAAAilCjCQAAAIAiBE0AAAAAFCFoAgAAAKAIQRMAAAAARQiaAAAAAChC0AQAAABAEYImAAAAAIoQNAEAAABQhKAJAAAAgCIETQAAAAAUIWgCAAAAoAhBEwAAAABFCJoAAAAAKELQBAAAAEARgiYAAAAAihA0AQAAAFCEoAkAAACAIgRNAAAAABQhaAIAAACgCEETAAAAAEUImgAAAAAoQtAEAAAAQBGCJgAAAACKEDQBAAAAUISgCQAAAIAiBE0AAAAAFCFoAgAAAKAIQRMAAAAARQiaAAAAAChC0AQAAABAEYImAAAAAIoQNAEAAABQhKAJAAAAgCIETQAAAAAUIWgCAAAAoAhBEwAAAABFCJoAAAAAKELQBAAAAEARgiYAAAAACkjp/wHVrqc7xhYS7wAAAABJRU5ErkJggg=="
    }
   },
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Notes.png](attachment:b6f37314-e253-479a-b37c-9296e4ca19b8.png)\n",
    "\n",
    "Notes are the smallest building blocks of music. In western music, there are 7 natural notes which are represented with letters as A, B, C, D, E, F, G. These natural notes are the white keys of a piano. Except for 2 cases, the interval between two natural notes is a whole step. Since the smallest interval is half step, there are also other notes between natural notes which are black keys of a piano. For example, we can call the note between A and B as A Sharp (A#) or B flat (Bb). The two exception cases are, there are no notes between B&C and E&F. After placing all the notes in between, all the consecutive intervals are half steps and there are 12 notes in total as:\n",
    "\n",
    "A A# B C C# D D# E F F# G G#\n",
    "\n",
    "One of the most important properties of a note is frequency. By knowing the rules, all the note frequencies in western music can be calculated.\n",
    "1. You can use reference note as **A** with frequency **440** Hz.\n",
    "2. If you **double frequency** of a note, you again obtain the **same note** in one octave higher.\n",
    "3. All the intervals between consecutive notes are **equal** in **logarithmic** scale.\n",
    "\n",
    "Let's make some calculations. Using the first two rules, I know that if 440 Hz is \"A\", 880 Hz is also \"A\". The reverse is also true, 440 is the double of 220, so 220 Hz is \"A\" too. Be careful, 660 Hz is **not** \"A\". What about other notes? The third rule says that intervals are equal on a logarithmic scale. Since there are 12 notes, all I have to do is multiply by 2^(1/12) to go to the next note. For example starting from \"A\", ( 440 \\* 2^(1/12) ) is \"A#\", (440 \\* 2^(1/12) \\* 2^(1/12) ) is \"B\", and goes on. After 12 steps, resulting frequency is ( 440 \\* 2^(12/12) ) = 880 Hz which is again \"A\". Cool, right? Enough calculation for us, let's leave the remaining to Python."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:51.681028Z",
     "iopub.status.busy": "2023-04-24T19:47:51.680796Z",
     "iopub.status.idle": "2023-04-24T19:47:51.725237Z",
     "shell.execute_reply": "2023-04-24T19:47:51.724264Z",
     "shell.execute_reply.started": "2023-04-24T19:47:51.681000Z"
    }
   },
   "outputs": [],
   "source": [
    "# Our hearing range is commonly 20 Hz to 20 kHz\n",
    "# Starting with 55 Hz which is \"A\" (I divided 440 by 2 three times)\n",
    "curr_freq = 55\n",
    "freq_list = []\n",
    "\n",
    "# I want to calculate 8 octaves of notes. Each octave has 12 notes. Looping for 96 steps:\n",
    "for i in range(96): \n",
    "    freq_list.append(curr_freq)\n",
    "    curr_freq *= np.power(2, 1/12) # Multiplying by 2^(1/12)\n",
    "\n",
    "#reshaping and creating dataframe\n",
    "freq_array = np.reshape(np.round(freq_list,1), (8, 12))\n",
    "cols = [\"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\"]\n",
    "df_note_freqs = pd.DataFrame(freq_array, columns=cols)\n",
    "print(\"NOTE FREQUENCIES IN WESTERN MUSIC\")\n",
    "df_note_freqs.head(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can either play the notes in sequence to create a melody or play several notes at the same time to form a chord. In music, a chord is three or more different notes that sounded simultaneously. The most common types of chords are Major chords and Minor chords which both have three notes. To form a Major chord, we first choose a root note, then move 2 whole steps to find the second note, and finally move 1.5 steps to find the third note. For C Major chord, root note is \"C\", second note is \"E\" and third note is \"G\".\n",
    "\n",
    "Forming a Minor chord is also similar, the difference is steps. In Minor chord, we first move 1.5 steps and later move 2 whole steps. Example from the same note \"C\", C Minor chord is formed of \"C\", \"Eb\" and \"G\". (Reminder: Eb and D# have same frequencies)\n",
    "\n",
    "The dataset contains different Major and Minor chord recordings in wav format. Since the project is about distinguishing Major and Minor, the steps between the notes are important for us. We will not be interested in the notes of the chord. Now let's listen to some chord examples. Using the IPython package, audio can be displayed and listened to in the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:51.726809Z",
     "iopub.status.busy": "2023-04-24T19:47:51.726556Z",
     "iopub.status.idle": "2023-04-24T19:47:51.765691Z",
     "shell.execute_reply": "2023-04-24T19:47:51.764972Z",
     "shell.execute_reply.started": "2023-04-24T19:47:51.726777Z"
    }
   },
   "outputs": [],
   "source": [
    "path_1 = \"data_small/Major/Major_0.wav\"\n",
    "path_2 = \"data_small/Minor/Minor_169.wav\"\n",
    "path_3 = \"data_small/Major/Major_111.wav\"\n",
    "IPython.display.Audio(path_1, rate = 44100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:51.767471Z",
     "iopub.status.busy": "2023-04-24T19:47:51.767246Z",
     "iopub.status.idle": "2023-04-24T19:47:51.790127Z",
     "shell.execute_reply": "2023-04-24T19:47:51.789295Z",
     "shell.execute_reply.started": "2023-04-24T19:47:51.767443Z"
    }
   },
   "outputs": [],
   "source": [
    "IPython.display.Audio(path_2, rate = 44100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:51.792128Z",
     "iopub.status.busy": "2023-04-24T19:47:51.791643Z",
     "iopub.status.idle": "2023-04-24T19:47:51.815896Z",
     "shell.execute_reply": "2023-04-24T19:47:51.815239Z",
     "shell.execute_reply.started": "2023-04-24T19:47:51.792083Z"
    }
   },
   "outputs": [],
   "source": [
    "IPython.display.Audio(path_3, rate = 44100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.2. Time and Frequency Domain Representations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the previous section, we have seen that notes have frequencies that describe themselves. A sound wave with 220 Hz frequency is an \"A\" note. Here comes the fun part. In nature, musical sound waves never vibrate at a single frequency. When we play a note with an instrument, harmonics of the note occur at the integer multiples of the base note. Playing \"A\" note with 220 Hz also creates waves at 440 Hz, 660 Hz, 880 Hz, 1100 Hz and goes on. We know that 220 Hz, 440 Hz and 880 Hz are all \"A\" notes. But if you look at the table we created, 660 Hz is the \"E\" note and 1000 Hz is somewhere between \"C\" and \"C#\". That's the reason why we love music. That's the reason for harmony. That's the reason why playing some notes together forms a chord and sounds beautiful. All notes contain other notes within themselves.\n",
    "\n",
    "I would like to create a computer-made note to show the concept of harmonics better. To represent a wave at a single frequency, I can define a sine wave as A\\*sin(2\\*pi\\*f\\*t). A is amplitude, f is frequency and t is time. For a sound wave with harmonics, I will first create a sine wave with fundamental frequency and then add its harmonics using a loop. Another important variable in this cell will be the sampling rate. Sound waves are analog signals and to save on a computer, it has to be converted to a digital signal. The sampling rate determines how many numbers we will save in each second. Using 44100 as a sampling rate is very common in practice.\n",
    "\n",
    "The signal I defined will be in time domain. After creating the signal, I will also apply Fourier Transform to convert it into frequency domain. Scipy fft package can be used for this transform. Fft method gives us both positive and negative frequency terms, I only need positive terms. For detailed information about FFT, [Scipy fft documentation](https://docs.scipy.org/doc/scipy/tutorial/fft.html) can be viewed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:51.817739Z",
     "iopub.status.busy": "2023-04-24T19:47:51.817316Z",
     "iopub.status.idle": "2023-04-24T19:47:52.154151Z",
     "shell.execute_reply": "2023-04-24T19:47:52.153315Z",
     "shell.execute_reply.started": "2023-04-24T19:47:51.817696Z"
    }
   },
   "outputs": [],
   "source": [
    "freq = 220 # note frequency\n",
    "fs = 44100 # sampling rate\n",
    "duration = 1 # duration of a signal [seconds]\n",
    "time = np.linspace(0, duration, fs*duration, endpoint=False) # array for time stamps\n",
    "\n",
    "# Creating signal in time domain\n",
    "np.random.seed(42)\n",
    "signal = np.zeros(len(time))\n",
    "for i in range(1,12):\n",
    "    amp = np.random.randint(0,10) # using random numbers for amplitudes\n",
    "    current_freq = i*freq # current harmonic\n",
    "    signal += amp*np.sin(2 * np.pi * current_freq * time)\n",
    "\n",
    "# Fourier Transform\n",
    "N = len(signal)\n",
    "y_freq = fftfreq(N, 1/fs)[:N//2]  # array for frequency stamps\n",
    "signal_f = fft(signal) # Signal in frequency domain\n",
    "signal_f_onesided = 2.0/N * np.abs(signal_f[0:N//2]) # taking positive terms\n",
    "\n",
    "# Displaying audio\n",
    "IPython.display.display(IPython.display.Audio(data=signal, rate=44100))\n",
    "\n",
    "# Plotting signal in time and frequency domains\n",
    "fig, axes = plt.subplots(1, 2, figsize=(12, 3))\n",
    "axes[0].plot(time[:480], signal[:480])\n",
    "axes[0].set_title(\"Sound Wave in Time Domain (Zoomed)\")\n",
    "axes[0].set(xlabel='Time [sec]')\n",
    "axes[1].plot(y_freq[:3000], signal_f_onesided[:3000])\n",
    "axes[1].set_title(\"Sound Wave in Frequency Domain (Zoomed)\")\n",
    "axes[1].set(xlabel='Frequency [Hz]')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Listening to the audio that I created, it's pretty clear it's a computer-generated sound, not a natural one. Still, it is aa \"A\" note, and the frequency plot gives us really valuable information. We can see at what frequencies our signal has values. We can see the harmonic structure of a musical wave. We can find frequencies and determine which note it is.\n",
    "\n",
    "It's time to analyze our real recordings. Wav files are Major and Minor chords that contain at least three notes. So, I expect to see a more complicated frequency plot after the Fourier transform. It will be like the three plots are overlapped. Intervals between harmonics will not be equal. This is great because I am planning to build my classification model on the relationship of harmonics."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:52.155717Z",
     "iopub.status.busy": "2023-04-24T19:47:52.155468Z",
     "iopub.status.idle": "2023-04-24T19:47:52.756749Z",
     "shell.execute_reply": "2023-04-24T19:47:52.755868Z",
     "shell.execute_reply.started": "2023-04-24T19:47:52.155687Z"
    }
   },
   "outputs": [],
   "source": [
    "path = \"data_small/Major/Major_0.wav\"\n",
    "fs, signal = wavfile.read(path)\n",
    "N = len(signal)\n",
    "time = np.linspace(0., N/fs, N)\n",
    "\n",
    "# Fourier Transform\n",
    "y_freq = fftfreq(N, 1/fs)[:N//2]  # array for frequency stamps\n",
    "signal_f = fft(signal) # Signal in frequency domain\n",
    "signal_f_onesided = 2.0/N * np.abs(signal_f[0:N//2]) # taking positive terms\n",
    "\n",
    "# Plotting signal in time and frequency domains\n",
    "fig, axes = plt.subplots(2, 2, figsize=(12, 7))\n",
    "axes[0,0].plot(time, signal)\n",
    "axes[0,0].set_title(\"Sound Wave in Time Domain (No Zoom)\")\n",
    "axes[0,0].set(xlabel='Time [sec]')\n",
    "axes[0,1].plot(y_freq, signal_f_onesided)\n",
    "axes[0,1].set_title(\"Sound Wave in Frequency Domain (No Zoom)\")\n",
    "axes[0,1].set(xlabel='Frequency [Hz]')\n",
    "axes[1,0].plot(time[(N//2):(N//2+480)], signal[(N//2):(N//2+480)])\n",
    "axes[1,0].set_title(\"Sound Wave in Time Domain (Zoomed)\")\n",
    "axes[1,0].set(xlabel='Time [sec]')\n",
    "axes[1,1].plot(y_freq[:5000], signal_f_onesided[:5000])\n",
    "axes[1,1].set_title(\"Sound Wave in Frequency Domain (Zoomed)\")\n",
    "axes[1,1].set(xlabel='Frequency [Hz]')\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.3. Spectrogram"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the previous section, we have seen the time and frequency plots of a sound wave. Now, I also want to plot the spectrogram of the signal. A spectrogram is a powerful way to visualize a signal over time at various frequencies. It is calculated by splitting the signal into small pieces in time and later applying Fourier transform. As a result, a 2D matrix is obtained and can be plotted. Good news: Scipy has a method for spectrogram, so we don't have to do calculations from the scratch. Documentation of the spectrogram method can be found [here](https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:52.758210Z",
     "iopub.status.busy": "2023-04-24T19:47:52.757936Z",
     "iopub.status.idle": "2023-04-24T19:47:53.333378Z",
     "shell.execute_reply": "2023-04-24T19:47:53.332551Z",
     "shell.execute_reply.started": "2023-04-24T19:47:52.758177Z"
    }
   },
   "outputs": [],
   "source": [
    "# applying spectrogram\n",
    "f, t, Sxx = spectrogram(signal, fs, nperseg=10000, nfft = 50000)\n",
    "\n",
    "# Plots\n",
    "fig, axes = plt.subplots(1, 2, figsize=(12, 5))\n",
    "axes[0].pcolormesh(t, f, np.log(Sxx), cmap=\"jet\")\n",
    "axes[0].set_title(\"Spectogram (No Zoom)\")\n",
    "axes[0].set(xlabel='Time [sec]', ylabel='Frequency [Hz]')\n",
    "axes[1].pcolormesh(t, f[:1500], np.log(Sxx)[:1500,:], cmap=\"jet\")\n",
    "axes[1].set_title(\"Spectogram (Zoomed)\")\n",
    "axes[1].set(xlabel='Time [sec]', ylabel='Frequency [Hz]')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.4. Detection of Harmonic Frequencies"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To summarize what we have done so far, we can read a wav file and save it in an array that is in the time domain. By applying the Fourier transform, we can obtain an array in the frequency domain. Also, Spectrogram is applied to obtain a 2D matrix that has both time and frequency information. The time-domain array is not suitable to use in this project. I will not use the Spectrogram matrix too, because our recordings contain only one chord, so frequency information doesn't change with time. For example, if we had a recording that changes chords every second, we would see in the visualization that harmonics are changing every second.\n",
    "\n",
    "In this project, I will continue with the frequency array. There are peak values in the frequency plot which are harmonics. I believe that if I can find at which frequencies peaks occur, I can use that data to build a model. To do this, I will use find_peaks method from Scipy which returns the indices of peaks. When I plug these indices into the frequency stamp array, I will obtain harmonic frequencies. \n",
    "\n",
    "Update: In some files, I have seen a peak at a really small value like 2 Hz. If there is a peak less than 50 Hz, I will ignore that value, because it is most likely noise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:53.335316Z",
     "iopub.status.busy": "2023-04-24T19:47:53.334823Z",
     "iopub.status.idle": "2023-04-24T19:47:53.553388Z",
     "shell.execute_reply": "2023-04-24T19:47:53.552523Z",
     "shell.execute_reply.started": "2023-04-24T19:47:53.335271Z"
    }
   },
   "outputs": [],
   "source": [
    "# h: height threshold. I defined as %5 of max value\n",
    "h = signal_f_onesided.max()*5/100\n",
    "peaks, _ = find_peaks(signal_f_onesided, distance=10, height = h)\n",
    "\n",
    "freq_50_index = np.abs(y_freq - 50).argmin() # finding index for 50 Hz\n",
    "peaks = peaks[peaks>freq_50_index] # filtering peaks less than 50 Hz\n",
    "harmonics = y_freq[peaks]\n",
    "print(\"Harmonics: {}\".format(np.round(harmonics)))\n",
    "\n",
    "# Plot\n",
    "i = peaks.max() + 100\n",
    "plt.plot(y_freq[:i], signal_f_onesided[:i])\n",
    "plt.plot(y_freq[peaks], signal_f_onesided[peaks], \"x\")\n",
    "plt.xlabel('Frequency [Hz]')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:53.556508Z",
     "iopub.status.busy": "2023-04-24T19:47:53.556254Z",
     "iopub.status.idle": "2023-04-24T19:47:53.565359Z",
     "shell.execute_reply": "2023-04-24T19:47:53.564273Z",
     "shell.execute_reply.started": "2023-04-24T19:47:53.556471Z"
    }
   },
   "outputs": [],
   "source": [
    "# I would like to create a method so that I can use in the next section\n",
    "# The method will read sound file, apply Fourier, find peak frequencies and return\n",
    "# Input: path of the sound file\n",
    "# Output: Frequency peaks\n",
    "# print_peaks = true to plot peaks\n",
    "\n",
    "def find_harmonics(path, print_peaks=False):\n",
    "    fs, X = wavfile.read(path)\n",
    "    N = len(X)\n",
    "    X_F = fft(X)\n",
    "    X_F_onesided = 2.0/N * np.abs(X_F[0:N//2])\n",
    "    freqs = fftfreq(N, 1/fs)[:N//2]\n",
    "    freqs_50_index = np.abs(freqs - 50).argmin()\n",
    "    \n",
    "    h = X_F_onesided.max()*5/100\n",
    "    peaks, _ = find_peaks(X_F_onesided, distance=10, height = h)\n",
    "    peaks = peaks[peaks>freqs_50_index]\n",
    "    harmonics = np.round(freqs[peaks],2)\n",
    "    \n",
    "    if print_peaks:\n",
    "        i = peaks.max() + 100\n",
    "        plt.plot(freqs[:i], X_F_onesided[:i])\n",
    "        plt.plot(freqs[peaks], X_F_onesided[peaks], \"x\")\n",
    "        plt.xlabel('Frequency [Hz]')\n",
    "        plt.show()\n",
    "    return harmonics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:53.567293Z",
     "iopub.status.busy": "2023-04-24T19:47:53.566571Z",
     "iopub.status.idle": "2023-04-24T19:47:53.781998Z",
     "shell.execute_reply": "2023-04-24T19:47:53.781085Z",
     "shell.execute_reply.started": "2023-04-24T19:47:53.567231Z"
    }
   },
   "outputs": [],
   "source": [
    "# Another example to check if method is working correctly\n",
    "path = \"data_small/Minor/Minor_169.wav\"\n",
    "\n",
    "harmonics_2 = find_harmonics(path, print_peaks=True)\n",
    "print(\"Harmonics: {}\".format(np.round(harmonics_2)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2. Importing Dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this section, I will create a DataFrame so that I can analyze all the sound data together. There are more than 800 wav files. First, I will loop through all the files and find harmonics. I will save chord type, file name and all harmonics for each file. I will also save minimum & maximum harmonics and the number of harmonics for easier analysis. After the loop, I will convert it to a DataFrame."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:53.783599Z",
     "iopub.status.busy": "2023-04-24T19:47:53.783316Z",
     "iopub.status.idle": "2023-04-24T19:47:55.420646Z",
     "shell.execute_reply": "2023-04-24T19:47:55.419466Z",
     "shell.execute_reply.started": "2023-04-24T19:47:53.783562Z"
    }
   },
   "outputs": [],
   "source": [
    "import librosa\n",
    "import statistics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:47:55.423308Z",
     "iopub.status.busy": "2023-04-24T19:47:55.422905Z",
     "iopub.status.idle": "2023-04-24T19:49:35.307759Z",
     "shell.execute_reply": "2023-04-24T19:49:35.306802Z",
     "shell.execute_reply.started": "2023-04-24T19:47:55.423265Z"
    }
   },
   "outputs": [],
   "source": [
    "path = \"data\"\n",
    "data = []\n",
    "max_harm_length = 0 # i will keep track of max harmonic length for naming columns\n",
    "\n",
    "for dirname, _, filenames in os.walk(path):\n",
    "    for filename in filenames:\n",
    "        foldername = os.path.basename(dirname)\n",
    "        full_path = os.path.join(dirname, filename)\n",
    "        y, sr = librosa.load(full_path)\n",
    "        centroids =  librosa.feature.spectral_centroid(y = y, sr=sr)\n",
    "        \n",
    "        cenmean = [np.mean(np.nan_to_num(centroids))]\n",
    "        cenmin = [np.min(centroids)]\n",
    "        cenmax = [np.max(centroids)]\n",
    "        \n",
    "        \n",
    "        max_harm_length = max(max_harm_length, len(centroids))\n",
    "        \n",
    "        cur_data = [foldername, filename]\n",
    "        #cur_data.extend([freq_peaks.min(), freq_peaks.max(), len(freq_peaks)])\n",
    "        cur_data.extend(centroids[0,:])\n",
    "        cur_data.extend(cenmean)\n",
    "        cur_data.extend(cenmin)\n",
    "        cur_data.extend(cenmax)\n",
    "        \n",
    "        data.append(cur_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-03-20T19:51:51.162210Z",
     "iopub.status.busy": "2023-03-20T19:51:51.161544Z",
     "iopub.status.idle": "2023-03-20T19:51:57.987658Z",
     "shell.execute_reply": "2023-03-20T19:51:57.986892Z",
     "shell.execute_reply.started": "2023-03-20T19:51:51.162163Z"
    }
   },
   "source": [
    "path = \"/kaggle/input/musical-instrument-chord-classification/Audio_Files\"\n",
    "data = []\n",
    "max_harm_length = 0 # i will keep track of max harmonic length for naming columns\n",
    "\n",
    "for dirname, _, filenames in os.walk(path):\n",
    "    for filename in filenames:\n",
    "        foldername = os.path.basename(dirname)\n",
    "        full_path = os.path.join(dirname, filename)\n",
    "        freq_peaks = find_harmonics(full_path)\n",
    "        \n",
    "        max_harm_length = max(max_harm_length, len(freq_peaks))\n",
    "        \n",
    "        cur_data = [foldername, filename]\n",
    "        cur_data.extend([freq_peaks.min(), freq_peaks.max(), len(freq_peaks)])\n",
    "        cur_data.extend(freq_peaks)\n",
    "        \n",
    "        data.append(cur_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.309798Z",
     "iopub.status.busy": "2023-04-24T19:49:35.309383Z",
     "iopub.status.idle": "2023-04-24T19:49:35.368852Z",
     "shell.execute_reply": "2023-04-24T19:49:35.368236Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.309765Z"
    }
   },
   "outputs": [],
   "source": [
    "# Column Names for DataFrame:\n",
    "cols = [\"Chord Type\", \"File Name\"]\n",
    "for i in range(100):\n",
    "    cols.append(\"Centroids {}\".format(i+1))\n",
    "    \n",
    "cols.append(\"CenMean\")\n",
    "cols.append(\"CenMin\")\n",
    "cols.append(\"CenMax\")\n",
    "\n",
    "# Creating DataFrame\n",
    "df = pd.DataFrame(data, columns=cols)\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.370585Z",
     "iopub.status.busy": "2023-04-24T19:49:35.370212Z",
     "iopub.status.idle": "2023-04-24T19:49:35.378619Z",
     "shell.execute_reply": "2023-04-24T19:49:35.377618Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.370553Z"
    }
   },
   "outputs": [],
   "source": [
    "#Se guarda en nandata las columnas donde hay hay algún dato de tipo NaN\n",
    "nandata = df.columns[df.isna().any()].tolist()\n",
    "\n",
    "print(\"Las columnas con datos faltantes son:\",nandata)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.380600Z",
     "iopub.status.busy": "2023-04-24T19:49:35.380362Z",
     "iopub.status.idle": "2023-04-24T19:49:35.409888Z",
     "shell.execute_reply": "2023-04-24T19:49:35.409133Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.380572Z"
    }
   },
   "outputs": [],
   "source": [
    "#Preprocesamiento\n",
    "from sklearn.impute import SimpleImputer #Herramienta para lidiar con datos faltantes\n",
    "#Se corrigen datos faltantes con SimpleImputer\n",
    "imputer = SimpleImputer(missing_values=np.nan, strategy = \"mean\")\n",
    "if nandata != []:\n",
    "  df[nandata] = imputer.fit_transform(df[nandata])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.412207Z",
     "iopub.status.busy": "2023-04-24T19:49:35.411297Z",
     "iopub.status.idle": "2023-04-24T19:49:35.422802Z",
     "shell.execute_reply": "2023-04-24T19:49:35.421819Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.412135Z"
    }
   },
   "outputs": [],
   "source": [
    "#Se guarda en nandata las columnas donde hay hay algún dato de tipo NaN\n",
    "nandata = df.columns[df.isna().any()].tolist()\n",
    "\n",
    "print(\"Las columnas con datos faltantes son:\",nandata)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.424399Z",
     "iopub.status.busy": "2023-04-24T19:49:35.424095Z",
     "iopub.status.idle": "2023-04-24T19:49:35.434862Z",
     "shell.execute_reply": "2023-04-24T19:49:35.433920Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.424365Z"
    }
   },
   "outputs": [],
   "source": [
    "# Se obtienen las columnas con variables categóticas\n",
    "cols = df.columns\n",
    "num_cols = df._get_numeric_data().columns\n",
    "catvar = list(set(cols) - set(num_cols))\n",
    "print(\"Las columnas categóricas son:\",catvar)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.436310Z",
     "iopub.status.busy": "2023-04-24T19:49:35.436041Z",
     "iopub.status.idle": "2023-04-24T19:49:35.471835Z",
     "shell.execute_reply": "2023-04-24T19:49:35.470456Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.436278Z"
    }
   },
   "outputs": [],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.474056Z",
     "iopub.status.busy": "2023-04-24T19:49:35.473605Z",
     "iopub.status.idle": "2023-04-24T19:49:35.588019Z",
     "shell.execute_reply": "2023-04-24T19:49:35.586920Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.473999Z"
    }
   },
   "outputs": [],
   "source": [
    "y, sr = librosa.load(\"data_small/Major/Major_0.wav\")\n",
    "cent = librosa.feature.spectral_centroid(y=y, sr=sr)\n",
    "np.mean(cent)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.589458Z",
     "iopub.status.busy": "2023-04-24T19:49:35.589224Z",
     "iopub.status.idle": "2023-04-24T19:49:35.595258Z",
     "shell.execute_reply": "2023-04-24T19:49:35.594655Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.589429Z"
    }
   },
   "outputs": [],
   "source": [
    "cent.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.596906Z",
     "iopub.status.busy": "2023-04-24T19:49:35.596598Z",
     "iopub.status.idle": "2023-04-24T19:49:35.623867Z",
     "shell.execute_reply": "2023-04-24T19:49:35.622704Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.596873Z"
    }
   },
   "outputs": [],
   "source": [
    "S, phase = librosa.magphase(librosa.stft(y=y))\n",
    "librosa.feature.spectral_centroid(S=S)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.625724Z",
     "iopub.status.busy": "2023-04-24T19:49:35.625388Z",
     "iopub.status.idle": "2023-04-24T19:49:35.651682Z",
     "shell.execute_reply": "2023-04-24T19:49:35.650652Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.625681Z"
    }
   },
   "outputs": [],
   "source": [
    "freqs, times, D = librosa.reassigned_spectrogram(y, fill_nan=True)\n",
    "librosa.feature.spectral_centroid(S=np.abs(D), freq=freqs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:35.653647Z",
     "iopub.status.busy": "2023-04-24T19:49:35.653285Z",
     "iopub.status.idle": "2023-04-24T19:49:36.069415Z",
     "shell.execute_reply": "2023-04-24T19:49:36.068711Z",
     "shell.execute_reply.started": "2023-04-24T19:49:35.653600Z"
    }
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from librosa import display\n",
    "times = librosa.times_like(cent)\n",
    "fig, ax = plt.subplots()\n",
    "librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max),\n",
    "                         y_axis='log', x_axis='time', ax=ax)\n",
    "ax.plot(times, cent.T, label='Spectral centroid', color='w')\n",
    "ax.legend(loc='upper right')\n",
    "ax.set(title='log Power spectrogram')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3. Data Exploration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we have a nice DataFrame to make some exploration. The first column, Chord Type, is the value that we will predict. It is a categorical column consisting of 2 categories: Major and Minor. By printing value counts of Chord Type, it seems that most of the chords are Major. We have 502 Major chords and 357 Minor chords. \n",
    "\n",
    "The second column is the file name that the row is created from. We will not need this column for model building, I just keep it in case I want to analyze a specific row deeper."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:36.071369Z",
     "iopub.status.busy": "2023-04-24T19:49:36.070728Z",
     "iopub.status.idle": "2023-04-24T19:49:36.084567Z",
     "shell.execute_reply": "2023-04-24T19:49:36.083616Z",
     "shell.execute_reply.started": "2023-04-24T19:49:36.071329Z"
    }
   },
   "outputs": [],
   "source": [
    "df[\"Chord Type\"].value_counts()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.1. Min and Max Harmonics"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this part, I have plotted distributions of Min Harmonics and Max Harmonics. By setting hue as Chord Type, I can see if chord type affects distribution. As I expected, the distribution of Min Harmonics for Major and Minor chords is extremely close. This is because the min harmonic determines the note of the chord. For example for 110 Hz, we will have either \"A Major\" or \"A Minor\" chord. We cannot determine what chord it is just by the first note. The difference between Major and Minor chords is in the intervals between harmonics.\n",
    "\n",
    "By looking at the distribution of Max harmonics, Major and Minor chords have again a similar behavior. There is a slight difference that I will ignore for now. I decided not to use \"Min Harmonic\" and \"Max Harmonic\" columns in my model building."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:36.086371Z",
     "iopub.status.busy": "2023-04-24T19:49:36.086050Z",
     "iopub.status.idle": "2023-04-24T19:49:36.964775Z",
     "shell.execute_reply": "2023-04-24T19:49:36.963833Z",
     "shell.execute_reply.started": "2023-04-24T19:49:36.086336Z"
    }
   },
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(1, 3, figsize=(15, 5))\n",
    "sns.kdeplot(ax=axes[0], data=df, x=\"CenMin\", hue=\"Chord Type\", shade=True)\n",
    "sns.kdeplot(ax=axes[1], data=df, x=\"CenMax\", hue=\"Chord Type\", shade=True)\n",
    "sns.scatterplot(ax=axes[2], data=df, x=\"CenMin\", y=\"CenMax\",hue=\"Chord Type\")\n",
    "axes[0].set_title(\"Distribution of Min Centroids\")\n",
    "axes[1].set_title(\"Distribution of Max Centroids\")\n",
    "axes[2].set_title(\"Scatter Plot Min vs. Max Centroids\")\n",
    "fig.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.2. Number of Harmonics"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the column \"# of Harmonics\", I have information that how many harmonic values are not null in that row. For example if \"# of Harmonics\" is 12, that row will have values from \"Harmonic 1\" to \"Harmonic 12\", but after \"Harmonic 13\" we will see NaN values. This \"# of Harmonics\" column will not be directly related to my classification model but will make it easier to analyze other columns.\n",
    "\n",
    "Using describe method on \"# of harmonics\", I see that\n",
    "* min is 8 --> every row at least 8 harmonics value\n",
    "* max is 38 --> last column will be \"Harmonic 38\"\n",
    "* starting with column \"Harmonic 9\", there will be NaN values\n",
    "* since harmonics are ordered, missing values will increase with each column\n",
    "* the mean value for the number of harmonics is 20\n",
    "\n",
    "Looking at the number of missing values, I know that I will drop most of the columns. Harmonics bigger than 20 are gone. The first 8 harmonics are absolutely important. But I am not sure about the harmonics in between. I have to make more exploration to decide for them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:36.966442Z",
     "iopub.status.busy": "2023-04-24T19:49:36.966141Z",
     "iopub.status.idle": "2023-04-24T19:49:36.977673Z",
     "shell.execute_reply": "2023-04-24T19:49:36.976727Z",
     "shell.execute_reply.started": "2023-04-24T19:49:36.966380Z"
    }
   },
   "outputs": [],
   "source": [
    "df[\"CenMean\"].describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 4. Model Building"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:36.982438Z",
     "iopub.status.busy": "2023-04-24T19:49:36.982143Z",
     "iopub.status.idle": "2023-04-24T19:49:37.025135Z",
     "shell.execute_reply": "2023-04-24T19:49:37.024304Z",
     "shell.execute_reply.started": "2023-04-24T19:49:36.982405Z"
    }
   },
   "outputs": [],
   "source": [
    "# importing packages\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.model_selection import cross_val_score\n",
    "from sklearn.metrics import confusion_matrix, accuracy_score\n",
    "\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.naive_bayes import GaussianNB\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "import librosa\n",
    "import numpy as np\n",
    "\n",
    "import sklearn\n",
    "import sklearn.cluster\n",
    "import sklearn.pipeline\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.1. Preprocessing Data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There is just one step left before training the classification model. Since the Chord Type column is categorical and consists of strings, I will replace \"Major\" with 1 and \"Minor\" with 0. Finally, select columns that I will use in training and split the data into training and validation sets. I used test size as %40."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:37.026790Z",
     "iopub.status.busy": "2023-04-24T19:49:37.026356Z",
     "iopub.status.idle": "2023-04-24T19:49:37.053920Z",
     "shell.execute_reply": "2023-04-24T19:49:37.052910Z",
     "shell.execute_reply.started": "2023-04-24T19:49:37.026748Z"
    }
   },
   "outputs": [],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:37.055624Z",
     "iopub.status.busy": "2023-04-24T19:49:37.055362Z",
     "iopub.status.idle": "2023-04-24T19:49:37.074865Z",
     "shell.execute_reply": "2023-04-24T19:49:37.073879Z",
     "shell.execute_reply.started": "2023-04-24T19:49:37.055591Z"
    }
   },
   "outputs": [],
   "source": [
    "dfarray = np.array(df)\n",
    "dfarray = dfarray[:,2:].astype('float64')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T19:49:37.076407Z",
     "iopub.status.busy": "2023-04-24T19:49:37.076148Z",
     "iopub.status.idle": "2023-04-24T19:49:37.090662Z",
     "shell.execute_reply": "2023-04-24T19:49:37.089723Z",
     "shell.execute_reply.started": "2023-04-24T19:49:37.076378Z"
    }
   },
   "outputs": [],
   "source": [
    "df[\"Chord Type\"] = df[\"Chord Type\"].replace(\"Major\", 1)\n",
    "df[\"Chord Type\"] = df[\"Chord Type\"].replace(\"Minor\", 0)\n",
    "\n",
    "#columns = [3::]\n",
    "#columns.extend([\"Interval 4_1\", \"Interval 5_1\", \"Interval 6_1\"])\n",
    "train_X, val_X, train_y, val_y = train_test_split(dfarray, df[\"Chord Type\"], test_size=0.2, random_state=0)\n",
    "\n",
    "train_X"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.2. Model Selection"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In order to select a classification model, I will try 6 different models in this section and compare their cross validation score."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T20:58:21.049696Z",
     "iopub.status.busy": "2023-04-24T20:58:21.049336Z",
     "iopub.status.idle": "2023-04-24T20:58:21.059399Z",
     "shell.execute_reply": "2023-04-24T20:58:21.058245Z",
     "shell.execute_reply.started": "2023-04-24T20:58:21.049661Z"
    }
   },
   "outputs": [],
   "source": [
    "path = \"data_small/\"\n",
    "def FeatureExtractor(path, n_mels, fmax=20000, fmin=20):\n",
    "\n",
    "    data = []\n",
    "    max_harm_length = 0 # i will keep track of max harmonic length for naming columns\n",
    "    \n",
    "    for dirname, _, filenames in os.walk(path):\n",
    "        for filename in filenames:\n",
    "            foldername = os.path.basename(dirname)\n",
    "            full_path = os.path.join(dirname, filename)\n",
    "            \n",
    "            y, sr = librosa.load(full_path)\n",
    "            mel = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=n_mels, fmax=fmax, fmin=fmin)\n",
    "            logam = librosa.power_to_db(mel)            \n",
    "            data.append(logam)\n",
    "            \n",
    "            max_harm_length = max(max_harm_length, logam.shape[1])  # fix First step: Track longest frame length\n",
    "            \n",
    "    # fix: Second step: Pad all spectrograms to max_frames\n",
    "    data = [librosa.util.fix_length(mel, size=max_harm_length, axis=1) for mel in data]\n",
    "    \n",
    "    data = np.array(data)        \n",
    "    return data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-04-24T20:58:21.745520Z",
     "iopub.status.busy": "2023-04-24T20:58:21.745139Z",
     "iopub.status.idle": "2023-04-24T21:00:46.199809Z",
     "shell.execute_reply": "2023-04-24T21:00:46.197963Z",
     "shell.execute_reply.started": "2023-04-24T20:58:21.745487Z"
    }
   },
   "outputs": [],
   "source": [
    "NX = FeatureExtractor(path, n_mels = 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2023-04-24T20:38:49.411615Z",
     "iopub.status.idle": "2023-04-24T20:38:49.412493Z",
     "shell.execute_reply": "2023-04-24T20:38:49.412093Z",
     "shell.execute_reply.started": "2023-04-24T20:38:49.412053Z"
    }
   },
   "outputs": [],
   "source": [
    "plt.figure(figsize=(25, 10))\n",
    "librosa.display.specshow(NX[1], \n",
    "                         x_axis=\"time\",\n",
    "                         y_axis=\"mel\", \n",
    "                         sr=sr)\n",
    "plt.colorbar(format=\"%+2.f\")\n",
    "\n",
    "plt.show()  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2023-04-24T20:38:49.427002Z",
     "iopub.status.idle": "2023-04-24T20:38:49.432746Z",
     "shell.execute_reply": "2023-04-24T20:38:49.432226Z",
     "shell.execute_reply.started": "2023-04-24T20:38:49.432137Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "21"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(NX)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2023-04-24T20:38:49.435465Z",
     "iopub.status.idle": "2023-04-24T20:38:49.436620Z",
     "shell.execute_reply": "2023-04-24T20:38:49.436267Z",
     "shell.execute_reply.started": "2023-04-24T20:38:49.436224Z"
    }
   },
   "outputs": [],
   "source": [
    "NX[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Itera a través de cada archivo de audio en la carpeta\n",
    "for filename in os.listdir(path):\n",
    "    i=0        \n",
    "    data_min=np.zeros((357,10,80))\n",
    "\n",
    "    if filename.endswith('.wav'): #Solo lea archivos .wav\n",
    "\n",
    "\n",
    "        # Cargar archivo de audio\n",
    "        audio_file = os.path.join(path_audio, filename)\n",
    "        y, sr = librosa.load(audio_file)\n",
    "        \n",
    "        # Calcular espectrograma\n",
    "        spec = librosa.feature.melspectrogram(y=y, sr=sr, n_mels =10)\n",
    "        spec_flat = spec.reshape(-1)\n",
    "        mel = librosa.power_to_db(spec, ref=np.max)\n",
    "        \n",
    "        data_min[i]=mel[:,0:80]\n",
    "        i=i+1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2023-04-24T20:38:49.448700Z",
     "iopub.status.idle": "2023-04-24T20:38:49.450385Z",
     "shell.execute_reply": "2023-04-24T20:38:49.449941Z",
     "shell.execute_reply.started": "2023-04-24T20:38:49.449892Z"
    }
   },
   "outputs": [],
   "source": [
    "# Now, build a learning object.  We'll use mini-batch k-means with default parameters.\n",
    "C = sklearn.cluster.MiniBatchKMeans()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2023-04-24T20:38:49.452940Z",
     "iopub.status.idle": "2023-04-24T20:38:49.454051Z",
     "shell.execute_reply": "2023-04-24T20:38:49.453701Z",
     "shell.execute_reply.started": "2023-04-24T20:38:49.453659Z"
    }
   },
   "outputs": [],
   "source": [
    "# Now, chain them all together into a pipeline\n",
    "ClusterPipe = sklearn.pipeline.Pipeline([('Cluster', C)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2023-04-24T20:38:49.456367Z",
     "iopub.status.idle": "2023-04-24T20:38:49.457469Z",
     "shell.execute_reply": "2023-04-24T20:38:49.457100Z",
     "shell.execute_reply.started": "2023-04-24T20:38:49.457059Z"
    }
   },
   "outputs": [],
   "source": [
    "# Let's build a model using just the first 20 seconds of the example track\n",
    "\n",
    "y_train, sr = librosa.load(train_X, duration=20, offset=0.0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2023-04-24T20:38:49.459994Z",
     "iopub.status.idle": "2023-04-24T20:38:49.460508Z",
     "shell.execute_reply": "2023-04-24T20:38:49.460333Z",
     "shell.execute_reply.started": "2023-04-24T20:38:49.460311Z"
    }
   },
   "outputs": [],
   "source": [
    "lr = LogisticRegression(random_state=0,solver='liblinear')\n",
    "knn = KNeighborsClassifier()\n",
    "svc = SVC(random_state=0)\n",
    "gnb = GaussianNB()\n",
    "dtc = DecisionTreeClassifier(random_state=0)\n",
    "rfc = RandomForestClassifier(random_state=0)\n",
    "\n",
    "score_lr = cross_val_score(lr, train_X, train_y, cv=10).mean()\n",
    "score_knn = cross_val_score(knn, train_X, train_y, cv=10).mean()\n",
    "score_svc = cross_val_score(svc, train_X, train_y, cv=10).mean()\n",
    "score_gnb = cross_val_score(gnb, train_X, train_y, cv=10).mean()\n",
    "score_dtc = cross_val_score(dtc, train_X, train_y, cv=10).mean()\n",
    "score_rfc = cross_val_score(rfc, train_X, train_y, cv=10).mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2023-04-24T19:52:01.993036Z",
     "iopub.status.idle": "2023-04-24T19:52:01.993385Z",
     "shell.execute_reply": "2023-04-24T19:52:01.993229Z",
     "shell.execute_reply.started": "2023-04-24T19:52:01.993208Z"
    }
   },
   "outputs": [],
   "source": [
    "print(\"Cross Val Score for Logistic Regression: {:.2f}\".format(score_lr))\n",
    "print(\"Cross Val Score for KNeighbors Classifier: {:.2f}\".format(score_knn))\n",
    "print(\"Cross Val Score for SVC: {:.2f}\".format(score_svc))\n",
    "print(\"Cross Val Score for Gaussian NB: {:.2f}\".format(score_gnb))\n",
    "print(\"Cross Val Score for Decision Tree Classifier: {:.2f}\".format(score_dtc))\n",
    "print(\"Cross Val Score for Random Forest Classifier: {:.2f}\".format(score_rfc))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.3. Model Training and Prediction"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the previous section, I tried 6 different models and Random Forest Classifier works really well with my dataset. I obtained 0.92 success rate with this model. After Random Forest Classifier, Decision Tree Classifier obtained %90 and KNeighbors Classifier obtained %83 success rate. \n",
    "\n",
    "Now, I will continue with Random Forest Classifier. First, I will train my model with the training dataset and then make a prediction on the validation dataset to see the accuracy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2023-04-24T19:52:01.995535Z",
     "iopub.status.idle": "2023-04-24T19:52:01.996087Z",
     "shell.execute_reply": "2023-04-24T19:52:01.995900Z",
     "shell.execute_reply.started": "2023-04-24T19:52:01.995878Z"
    }
   },
   "outputs": [],
   "source": [
    "# defining my classifier\n",
    "classifier = RandomForestClassifier(random_state=0)\n",
    "\n",
    "classifier.fit(train_X, train_y) # training classifier\n",
    "pred_y = classifier.predict(val_X) # making prediction on validation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2023-04-24T19:52:01.997139Z",
     "iopub.status.idle": "2023-04-24T19:52:01.997695Z",
     "shell.execute_reply": "2023-04-24T19:52:01.997531Z",
     "shell.execute_reply.started": "2023-04-24T19:52:01.997510Z"
    }
   },
   "outputs": [],
   "source": [
    "cm = confusion_matrix(val_y, pred_y)\n",
    "acc = accuracy_score(val_y, pred_y)\n",
    "\n",
    "print(\"Confusion Matrix:\")\n",
    "print(cm)\n",
    "\n",
    "print(\"Accuracy Score: {:.2f}\".format(acc))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-03-20T20:43:13.066373Z",
     "iopub.status.busy": "2023-03-20T20:43:13.065493Z",
     "iopub.status.idle": "2023-03-20T20:43:13.072982Z",
     "shell.execute_reply": "2023-03-20T20:43:13.071743Z",
     "shell.execute_reply.started": "2023-03-20T20:43:13.066294Z"
    }
   },
   "source": [
    "For the validation set, I obtained an even better score, %94 success rate.\n",
    "\n",
    "So, I guess this is the final cell in this notebook. Thank you very much for your interest in this project :)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}