Newer
Older
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
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "df630e55-57dd-470a-849b-f1bc90ac719e"
}
},
"source": [
"# 1. Importing and Visualization of CIFAR-10 Dataset"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "409a1ab7-fe1d-4430-b904-7694020a6223"
}
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"# function to import CIFAR-10 data set\n",
"def unpickle(file):\n",
" import pickle\n",
" with open(file, 'rb') as fo:\n",
" dict = pickle.load(fo, encoding='bytes')\n",
" return dict\n",
"data_batch_1 = unpickle(\"./data/data_batch_1\")\n",
"data_batch_2 = unpickle(\"./data/data_batch_2\")\n",
"data_batch_3 = unpickle(\"./data/data_batch_3\")\n",
"data_batch_4 = unpickle(\"./data/data_batch_4\")\n",
"data_batch_5 = unpickle(\"./data/data_batch_5\")\n",
"test_batch = unpickle(\"./data/test_batch\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "ce2be501-0be3-4750-8207-dfc00d7db01a"
}
},
"source": [
"What is the data structure of e.g. data_batch_1 ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "f77bd9ec-de3b-4c56-b08d-4a65f0780408"
}
},
"outputs": [],
"source": [
"type(data_batch_1)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "09a5b60b-dcbb-4f97-ab57-e4611c253e2e"
}
},
"source": [
"What are the keys of e.g. data_batch_1 ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "c874a7c9-de0c-4ccd-a0f1-8f8a3265a0b6"
}
},
"outputs": [],
"source": [
"data_batch_1.keys()"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "a7f910e7-0b11-453b-84d5-df6ac88ac6dd"
}
},
"source": [
"What is the data structure of data_batch_1[b'data'] ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "fe299a35-c930-4078-97b7-c9b67f42ec42"
}
},
"outputs": [],
"source": [
"type(data_batch_1[b'data'])"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "3f978c4f-50d0-4f00-9f19-bf8744e505a3"
}
},
"source": [
"What is the data structure of data_batch_1[b'labels'] ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "46a97575-36c0-4920-a8dc-762e94239b7e"
}
},
"outputs": [],
"source": [
"type(data_batch_1[b'labels'])"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "2fd19982-c318-4303-8042-7a5a6998d175"
}
},
"source": [
"What is the shape of data_batch_1[b'data'] ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "b012720d-81f8-455d-8ce7-bfca64a842c8"
}
},
"outputs": [],
"source": [
"data_batch_1[b'data'].shape"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "378aeda2-a547-435e-b28b-09ceb0074a53"
}
},
"source": [
"What is the size of data_batch_1[b'labels'] ?\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "49c776cb-c8aa-461b-a0da-4f4d38342e2e"
}
},
"outputs": [],
"source": [
"len(data_batch_1[b'labels'])"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "02ca495c-e6d2-48d4-9bc2-2295272d5f6f"
}
},
"source": [
"What are the first 10 elements of data_batch_1[b'labels'] ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "438920f4-774e-4e94-9b7c-30a2106d163c"
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
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
}
},
"outputs": [],
"source": [
"data_batch_1[b'labels'][:10]"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "1e599fcd-a46c-4750-94f8-1cf4ad8fb342"
}
},
"source": [
"What is the data type of data_batch_1[b'data'] ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "7617a699-c3d5-434f-97a5-3443489ac9db"
}
},
"outputs": [],
"source": [
"data_batch_1[b'data'].dtype"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "067d850d-0411-4af6-8714-a79b310ca8c1"
}
},
"source": [
"Let us concatenate the batch training data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "942f351b-b771-4375-8df2-eec28391a576"
}
},
"outputs": [],
"source": [
"X_train=np.concatenate([data_batch_1[b'data'], \n",
" data_batch_2[b'data'], \n",
" data_batch_3[b'data'], \n",
" data_batch_4[b'data'], \n",
" data_batch_5[b'data']], \n",
" axis = 0)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "b289f0b9-b3ab-480b-9ae6-76a893980efe"
}
},
"source": [
"Let us concatenate the training labels"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "9b85b9a0-5f2b-4c68-a74f-82f1ec212215"
}
},
"outputs": [],
"source": [
"y_train=np.concatenate([data_batch_1[b'labels'] , \n",
" data_batch_2[b'labels'],\n",
" data_batch_3[b'labels'],\n",
" data_batch_4[b'labels'],\n",
" data_batch_5[b'labels']], \n",
" axis = 0)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "d9967582-1305-4b95-948b-e75c46fc49bb"
}
},
"source": [
"Let us define the test data as X_test"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "5c85918c-f89e-4156-8cdd-ca38d14afbb9"
}
},
"outputs": [],
"source": [
"X_test = test_batch[b'data']\n",
"X_test.shape"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "48754d72-9acd-49cf-b209-737c45047284"
}
},
"source": [
"Let us cast the test labels as ndarray"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "5f913d95-aa49-4727-8c6f-5630cbf59741"
}
},
"outputs": [],
"source": [
"y_test=np.array(test_batch[b'labels']) \n",
"y_test.shape"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "f4c3aa97-0d97-4e9c-a6b3-f2d2b1f08632"
}
},
"source": [
"What is the shape of X_train ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "a0eb7a33-19c9-46e4-b471-6f7904389177"
}
},
"outputs": [],
"source": [
"X_train.shape"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "81d3c33f-544e-44c8-8260-e89143cc6ef1"
}
},
"source": [
"What is the shape of Y_train ?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "d699e7a7-efc0-421f-bd8d-2d2b34a09516"
}
},
"outputs": [],
"source": [
"y_train.shape"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "d0a61e44-a2a9-4dff-9849-5f6a0e232290"
}
},
"source": [
"Let us visualize an image. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "d817d603-7d37-4ff2-b3d1-e95875b48f8f"
},
"scrolled": true
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"import matplotlib.pyplot as plt\n",
"\n",
"plt.imshow(X_train[20].reshape((3,32,32)).transpose((1,2,0)).astype('uint8'))\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"- By means of `reshape` we can convert an array from one shape to another without \n",
"copying any data. To do this, we pass a tuple indicating the new shape to the `reshape` array instance method. \n",
"\n",
"- By default, `NumPy` arrays are created in _row major_ order. Spatially this means, that if we have a two-dimensional array of data, the items in each row of the array are stored in adjacent memory locations. In the case of a three-dimensional array of data, the items along `axis=2` are stored in adjacent order. Since the first 32 entries of the array `X_train[0]` are the red channel values of the first row of the image, etc., we need to pass the tuple $(3,32,32)$ to `reshape`. In conclusion, when __reshaping__ the array, higher order dimensions are traversed _first_ (e.g. axis $ 2 $ before advancing on axis $ 1 $.) \n",
"\n",
"- `plt.imshow` needs for each inner list the values representing a pixel. Here, with \n",
"an RGB image, there are 3 values. We thus need to transpose the array : the RGB values need to be located along `axis=2`. \n",
"\n",
"- Using ndarray's `astype` method, we can cast an array from one `dtype` to another. `uint8` represents unsigned 8-bit integer types. Why 8 bits? Most displays can only render 8 bits per channel worth of color gradation. Why can they only render 8 bits/channel? Because that is about all the human eye can see."
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "38cf20c0-9404-4f32-91ed-a00e910832f8"
}
},
"source": [
"We visualize some examples from the dataset.\n",
"We show a few examples of training images from each class."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "ba3743b9-ea50-4201-ad99-5fa47e8b82fb"
}
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n",
"num_classes = len(classes)\n",
"samples_per_class = 7\n",
"\n",
"\n",
"\n",
"for y, cls in enumerate(classes):\n",
" idxs = np.flatnonzero(y_train == y)\n",
" idxs = np.random.choice(idxs, samples_per_class, replace=False)\n",
" for i, idx in enumerate(idxs):\n",
" plt_idx = i * num_classes + y + 1\n",
" plt.subplot(samples_per_class, num_classes, plt_idx)\n",
" plt.imshow(X_train[idx].reshape((3,32,32)).transpose((1,2,0)).astype('uint8'))\n",
" plt.axis('off')\n",
" if i == 0:\n",
" plt.title(cls)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- When iterating over a sequence we often want to keep track of the index of the \n",
"current item. Python's built-in function `enumerate` returns a sequence of $i$, value \n",
"tuples.\n",
"\n",
"- `np.flatnonzero` returns indices that are non-zero in the (flattened version of) `y_train == y`, that is, it returns the indices for the elements that are `True`.\n",
"\n",
"- `np.random.choice(..., replace=False)` generates a random sample from a given 1-D array without replacement.\n",
"\n",
"\n",
"- The `subplot()` command specifies `numrows`, `numcols`, `fignum` where `fignum` ranges from $ 1 $ to `numrows*numcols`."
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "ab168c02-9867-455d-815d-c2de707e2f87"
}
},
"source": [
"# 2. K-Nearest-Neighbour Classifier"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "36557d31-2ba4-416c-8ead-a92fb7446e85"
}
},
"source": [
" We subsample the data for more efficient code execution in this exercise."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "26316896-3b01-455b-9a0a-87278f088d83"
}
},
"outputs": [],
"source": [
"num_training = 5000\n",
"mask = range(num_training)\n",
"X_train = X_train[mask]\n",
"y_train = y_train[mask]\n",
"\n",
"num_test = 500\n",
"mask = range(num_test)\n",
"X_test = X_test[mask]\n",
"y_test = y_test[mask]"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "27db2b6f-c417-4d15-bff4-8c00d58cb808"
}
},
"source": [
"We define Class KNearestNeighbor."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "497fbf77-9a17-4b35-a0d8-375972850902"
}
},
"outputs": [],
"source": [
"class KNearestNeighbor():\n",
" \"\"\" a kNN classifier with L2 distance \"\"\"\n",
"\n",
" def __init__(self):\n",
" pass\n",
"\n",
" def train(self, X, y):\n",
" \"\"\"\n",
" Train the classifier. For k-nearest neighbors this is just \n",
" memorizing the training data.\n",
"\n",
" Inputs:\n",
" - X: A numpy array of shape (num_train, D) containing the training data\n",
" consisting of num_train samples each of dimension D.\n",
" - y: A numpy array of shape (N,) containing the training labels, where\n",
" y[i] is the label for X[i].\n",
" \"\"\"\n",
" self.X_train = X.astype('float')\n",
" self.y_train = y\n",
" \n",
" def predict(self, X, k=1, num_loops=0):\n",
" \"\"\"\n",
" Predict labels for test data using this classifier.\n",
"\n",
" Inputs:\n",
" - X: A numpy array of shape (num_test, D) containing test data consisting\n",
" of num_test samples each of dimension D.\n",
" - k: The number of nearest neighbors that vote for the predicted labels.\n",
" - num_loops: Determines which implementation to use to compute distances\n",
" between training points and testing points.\n",
"\n",
" Returns:\n",
" - y: A numpy array of shape (num_test,) containing predicted labels for the\n",
" test data, where y[i] is the predicted label for the test point X[i]. \n",
" \"\"\"\n",
" if num_loops == 0:\n",
" dists = self.compute_distances_no_loops(X)\n",
" elif num_loops == 1:\n",
" dists = self.compute_distances_one_loop(X)\n",
" elif num_loops == 2:\n",
" dists = self.compute_distances_two_loops(X)\n",
" else:\n",
" raise ValueError('Invalid value %d for num_loops' % num_loops)\n",
"\n",
" return self.predict_labels(dists, k=k)\n",
"\n",
" def compute_distances_two_loops(self, X):\n",
" \"\"\"\n",
" Compute the distance between each test point in X and each \n",
" training point in self.X_train using a nested loop over both \n",
" the training data and the test data.\n",
"\n",
" Inputs:\n",
" - X: A numpy array of shape (num_test, D) containing test data.\n",
"\n",
" Returns:\n",
" - dists: A numpy array of shape (num_test, num_train) where \n",
" dists[i, j] is the Euclidean distance between the ith test \n",
" point and the jth training point.\n",
" \"\"\"\n",
" num_test = X.shape[0]\n",
" num_train = self.X_train.shape[0]\n",
" dists = np.zeros((num_test, num_train))\n",
" X = X.astype('float')\n",
" for i in range(num_test):\n",
" for j in range(num_train):\n",
" dists[i, j] = np.sqrt(np.sum(np.square(self.X_train[j,:] - X[i,:])))\n",
" \n",
" return dists\n",
"\n",
" def compute_distances_one_loop(self, X):\n",
" \"\"\"\n",
" Compute the distance between each test point in X and each training point\n",
" in self.X_train using a single loop over the test data.\n",
"\n",
" Input / Output: Same as compute_distances_two_loops\n",
" \"\"\"\n",
" num_test = X.shape[0]\n",
" num_train = self.X_train.shape[0]\n",
" dists = np.zeros((num_test, num_train))\n",
" X = X.astype('float')\n",
" for i in range(num_test):\n",
" dists[i, :] = np.sqrt(np.sum(np.square(self.X_train - X[i,:]), axis = 1))\n",
" \n",
" \n",
" return dists\n",
"\n",
" def compute_distances_no_loops(self, X):\n",
" \"\"\"\n",
" Compute the distance between each test point in X and each training point\n",
" in self.X_train using no explicit loops.\n",
"\n",
" Input / Output: Same as compute_distances_two_loops\n",
" \"\"\"\n",
" num_test = X.shape[0]\n",
" num_train = self.X_train.shape[0]\n",
" dists = np.zeros((num_test, num_train)) \n",
" X=X.astype('float')\n",
" \n",
" # Most \"elegant\" solution leads however to memory issues\n",
" # dists = np.sqrt(np.square((self.X_train[:, np.newaxis, :] - X)).sum(axis=2)).T\n",
" # split (p-q)^2 to p^2 + q^2 - 2pq\n",
" dists = np.sqrt((X**2).sum(axis=1)[:, np.newaxis] + (self.X_train**2).sum(axis=1) - 2 * X.dot(self.X_train.T))\n",
" \n",
" \n",
" \n",
" return dists\n",
"\n",
" def predict_labels(self, dists, k=1):\n",
" \"\"\"\n",
" Given a matrix of distances between test points and training points,\n",
" predict a label for each test point.\n",
"\n",
" Inputs:\n",
" - dists: A numpy array of shape (num_test, num_train) where dists[i, j]\n",
" gives the distance betwen the ith test point and the jth training point.\n",
"\n",
" Returns:\n",
" - y: A numpy array of shape (num_test,) containing predicted labels for the\n",
" test data, where y[i] is the predicted label for the test point X[i]. \n",
" \"\"\"\n",
" num_test = dists.shape[0]\n",
" y_pred = np.zeros(num_test, dtype='float64')\n",
" for i in range(num_test):\n",
" # A list of length k storing the labels of the k nearest neighbors to\n",
" # the ith test point.\n",
" closest_y = []\n",
" # get the k indices with smallest distances\n",
" min_indices = np.argsort(dists[i,:])[:k] \n",
" closest_y = np.bincount(self.y_train[min_indices])\n",
" # predict the label of the nearest example\n",
" y_pred[i] = np.argmax(closest_y) \n",
"\n",
" return y_pred"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- Methods within a class are defined in much the same way as functions, that is, using `def`. Every defined class has a _special method_ called `__init__()` `Python` runs automatically whenever we create a new _instance_ based on the `NearestNeighbor` \n",
"class. The `self` parameter is required in the method definition, and it must come first \n",
"before the other parameters. It must be included in the definition because when `Python` \n",
"calls this `__init__` method later (to create an instance of `NearestNeighbor`), \n",
"the method call will automatically pass the `self` argument. Every method call associated with a class automatically passes `self`, which is a reference to the instance itself; \n",
"it gives the individual instance access to the attributes and methods in the class. In summary, when you invoke a class method on an object instance, `Python` \n",
"arranges for the first argument to be the invoking object instance, which is always \n",
"assigned to each method's `self` argument.\n",
"\n",
"- The two variables `self.X_train` and `self.y_train` each have the prefix `self`. Any variable prefixed with `self` is available to every method in the class, and we will also be able to access these variables through any instance created from the class. `self.X_train = X` takes the value stored in the parameter `X` and stores it in the variable `self.X_train`, which is then attached to the instance being created. The same process happens with `self.y_train = y`. \n",
"\n",
"- Variables that are accessible through instances like this are called _attributes_.\n",
"`np.zeros` produces an array of $ 0 $'s, here the size is `num_test`.\n",
"\n",
"- `np.sum` returns the sum of all elements in the array or along an axis. Zero-length \n",
"arrays have sum $ $ 0.\n",
"\n",
"- `np.argmin` returns the index of minimum element.\n",
"\n",
"- When Python reads the line `nn = NearestNeighbor()`, it calls the `__init__()` method in `NearestNeighbor()`. The `__init__()` method creates an instance representing this particular nearest neighbor classifier. The `__init__()` method has no explicit return statement, but Python automatically returns an instance representing this nearest neighbor classifier. We store that instance in the variable `nn`. The naming convention is helpful here: we can usually assume that a capitalized name like `NearestNeighbor()` refers to a class, and a lowercase name like `nn` refers to a single instance created from a class.\n",
"\n",
"\n",
"- `np.argsort` returns the indices that would sort an array.\n",
"\n",
"- `np.bincount(x)` counts the number of occurrences of each value in an array of non-negative integers. The number of bins (of size 1) is one larger than the largest value in $ x $.\n",
"\n",
"- Instead of a loop that contains a _broadcasting_ process with a 2D array \n",
"\n",
"`for i in range(num_test):\n",
" dists[i, :] = np.sqrt(np.sum(np.square(self.X_train - X[i,:]), axis = 1))`\n",
"\n",
"we can speed up this process by broadcasting with a 3D array \n",
"\n",
"`dists = np.sqrt(np.square((self.X_train[:, np.newaxis, :] - X)).sum(axis=2))`\n",
"\n",
"- The _Broadcasting rule_ states: two arrays are compatible for broadcasting if for each \n",
"_trailing dimension_ (that is, starting from the end of an array), the axis lengths match or if either of the lengths is 1. In the case of `self._train[:, np.newaxis, :]`, the trailing dimension is $2$ and the axis length $D$. The trailing dimension of `X` is 1 and has axis length $D$. Thus, they match. Broadcasting is then performed over the missing and / or length $ 1 $ dimensions. If we need to add a new axis with length $ 1 $ specifically for broadcasting purposes, `NumPy` arrays offer a special syntax for inserting new axes by indexing. We use the special `np.newaxis` attribute along with full slices to insert the new axis. We may imagine that `num_test` copies of `self.X_train` are tiled up along `axis=1` of `self.X_train[:, np.newaxis, :]`. On the other hand, `num_train` copies of `X` are tiled up on top of each other. First, the subtraction is performed along `axis=2`. Then, it is performed along `axis=1`, and finally over `axis=0`. The resulting shape of the subtraction then is (`num_train`, `num_test`, D). Since this runs into memory issues, we need to rewrite it as follows:\n",
"\n",
"`dists = np.sqrt((X**2).sum(axis=1)[:, np.newaxis] + (self.X_train**2).sum(axis=1) - 2 * X.dot(self.X_train.T))`\n",
"\n",
"which yields an array with shape (`num_test`, `num_train`, D)\n",
"\n",
"- It is important to cast the data files as `float`."
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "91c8998c-f531-4774-98ca-6c9631050fd3"
}
},
"source": [
"Create an instance nn from the class KNearestNeighbor"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "215be79c-8fe0-4e10-9587-6bea172bb33a"
}
},
"outputs": [],
"source": [
"classifier = KNearestNeighbor()"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "2f886096-8250-4739-8645-37950f408d41"
}
},
"source": [
"We call the method `train` of the `KNearestNeighbor` class."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "de24c3a8-0860-446e-b974-3e0c334feced"
}
},
"outputs": [],
"source": [
"classifier.train(X_train, y_train)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "d058a8de-3c50-4514-8405-5aff67b26398"
}
},
"source": [
"We test our implementation with two_loops"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "d87bb3a8-6338-4957-ac73-4c81b87821eb"
}
},
"outputs": [],
"source": [
"dists = classifier.compute_distances_two_loops(X_test)\n",
"dists.shape "
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "c1277b26-a267-4dec-ab9d-e44d31cdaa3e"
}
},
"source": [
"We can visualize the distance matrix: each row is a single test example and its distances to training examples"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "ae3a05a2-a3e6-4e65-a59f-0204411f57f9"
}
},
"outputs": [],
"source": [
"plt.imshow(dists, interpolation='none')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "7855beeb-d7e2-4ea7-994f-1adfa5a2c886"
}
},
"source": [
"Let us now predict labels and run the code below: We use $k = 1$ (which is Nearest Neighbor)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "219d7522-e633-4136-aa98-9abe80ca7bf3"
}
},
"outputs": [],
"source": [
"y_test_pred = classifier.predict_labels(dists, k=1)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "f083926f-4bd0-488f-8ba9-e77dc946fac8"
}
},
"source": [
"We compute and print the fraction of correctly predicted examples."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "f1ac90b4-5005-4940-9663-0bfd9574dc8c"
}
},
"outputs": [],
"source": [
"num_correct = np.sum(y_test_pred == y_test)\n",
"accuracy = float(num_correct) / num_test\n",
"print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "7a33b48c-c106-4903-ba68-769ce91ccb8b"
}
},
"source": [
" Let us now predict labels and run the code below: We use k = 10"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "7a4433f3-d7d4-4b7c-bd21-6f6d5272c837"
}
},
"outputs": [],
"source": [
"y_test_pred = classifier.predict_labels(dists, k=10)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "8cede653-c157-4396-a534-b4a8741251e2"
}
},
"source": [
"We compute and print the fraction of correctly predicted examples."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "445220c9-4974-41a0-a36c-a309d395490b"
}
},
"outputs": [],
"source": [
"num_correct = np.sum(y_test_pred == y_test)\n",
"accuracy = float(num_correct) / len(y_test_pred)\n",
"print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Confusion Matrix"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# utility function for plotting confusion matrix\n",
"import matplotlib.pyplot as plt\n",
"import seaborn as sns\n",
"from sklearn.metrics import confusion_matrix\n",
"\n",
"def plot_confmat(y_true, y_pred):\n",
" \"\"\"\n",
" Plot the confusion matrix and save to user_files dir\n",
" \"\"\"\n",
" conf_matrix = confusion_matrix(y_true, y_pred)\n",
" fig = plt.figure(figsize=(9,9))\n",
" ax = fig.add_subplot(111)\n",
" sns.heatmap(conf_matrix,\n",
" annot=True,\n",
" fmt='.0f')\n",
" plt.title('Confusion matrix')\n",
" ax.set_xticklabels( classes)\n",
" ax.set_yticklabels( classes)\n",
" plt.ylabel('True')\n",
" plt.xlabel('Predicted')\n",
" \n",
"plot_confmat(y_test, y_test_pred) "
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "df615e0b-aeeb-4074-abef-075af4118640"
}
},
"source": [
"## Algebra and Performance of Distance Matrix Computation\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "04f92811-3067-4a08-8227-ed55c42fed50"
}
},
"source": [
"To ensure that our vectorized implementation is correct, we make sure that it\n",
"agrees with the naive implementation. There are many ways to decide whether\n",
"two matrices are similar; one of the simplest is the Frobenius norm. In case\n",
"you haven't seen it before, the Frobenius norm of two matrices is the square\n",
"root of the squared sum of differences of all elements; in other words, reshape\n",
"the matrices into vectors and compute the Euclidean distance between them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "edecc2dc-bbf4-47bb-8902-6910fef3eae0"
}
},
"outputs": [],
"source": [
"dists_two = classifier.compute_distances_two_loops(X_test)\n",
"dists_one = classifier.compute_distances_one_loop(X_test)\n",
"dists_zero = classifier.compute_distances_no_loops(X_test)\n",
"\n",
"\n",
"difference_two_2_one = np.linalg.norm(dists_two - dists_one, ord='fro')\n",
"print('Difference was: %f' % (difference_two_2_one, ))\n",
"if difference_two_2_one < 0.001:\n",
" print('Good! The distance matrices are the same')\n",
"else:\n",
" print('Uh-oh! The distance matrices are different')\n",
"\n",
"difference_one_2_zero = np.linalg.norm(dists_one - dists_zero, ord='fro')\n",
"print('Difference was: %f' % (difference_one_2_zero, ))\n",
"if difference_one_2_zero < 0.001:\n",
" print('Good! The distance matrices are the same')\n",
"else:\n",
" print('Uh-oh! The distance matrices are different')"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "94c6dacb-929f-4378-b80f-4859256bd7f4"
}
},
"source": [
"Let's compare how fast the implementations are"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "1d3c6b0c-9a33-4f71-b283-0b1eb8061e77"
}
},
"outputs": [],
"source": [
"def time_function(f, *args):\n",
" \"\"\"\n",
" Call a function f with args and return the time (in seconds) that it took to execute.\n",
" \"\"\"\n",
" import time\n",
" tic = time.time()\n",
" f(*args)\n",
" toc = time.time()\n",
" return toc - tic\n",
"\n",
"two_loop_time = time_function(classifier.compute_distances_two_loops, X_test)\n",
"print('Two loop version took %f seconds' % two_loop_time)\n",
"\n",
"one_loop_time = time_function(classifier.compute_distances_one_loop, X_test)\n",
"print('One loop version took %f seconds' % one_loop_time)\n",
"\n",
"no_loop_time = time_function(classifier.compute_distances_no_loops, X_test)\n",
"print('No loop version took %f seconds' % no_loop_time)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "e55a0c49-3d30-47b3-bbfc-2ba53025a0eb"
}
},
"source": [
"# 3. k-fold cross validation\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "48a7d639-21bd-4b58-892d-c54a818111aa"
}
},
"outputs": [],
"source": [
"num_folds = 5\n",
"\n",
"k_choices = [1, 3, 5, 7, 9, 10, 12, 15, 18, 20, 50, 100]\n",
"\n",
"X_train_folds = []\n",
"y_train_folds = []"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "8b1aa44f-7099-4511-8b20-168c0f37edb9"
}
},
"source": [
"Split up the training data into folds. After splitting, `X_train_folds` and \n",
"`y_train_folds` should each be lists of length `num_folds`, where \n",
"`y_train_folds[i]` is the label vector for the points in `X_train_folds[i]`. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "ee7f2e26-fa37-45b0-af4c-c225369eedc2"
}
},
"outputs": [],
"source": [
"num_train = X_train.shape[0]\n",
"fold_size = np.ceil(num_train/num_folds).astype('int')"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "235c4927-a8f9-475f-83c4-54fb4b1de699"
}
},
"source": [
"In the case of `num_train = 5000` and 5 folds, we obtain \n",
"`X_train_folds = np.split(X_train, [1000, 2000, 3000, 4000])`\n",
"`y_train_folds = np.split(y_train, [1000, 2000, 3000, 4000])`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "dd9d3e91-fb0d-4ea1-8e37-6282e1eea5f5"
}
},
"outputs": [],
"source": [
"X_train_folds = np.split(X_train, [(i + 1)*fold_size for i in np.arange(num_folds)])\n",
"y_train_folds = np.split(y_train, [(i + 1)*fold_size for i in np.arange(num_folds)])\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"X_train_folds[1].shape"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "99d20b22-bc30-49c6-85a1-86f153b21fe0"
}
},
"source": [
"A dictionary holding the accuracies for different values of $k$ that we find\n",
"when running cross-validation. After running cross-validation,\n",
"`k_to_accuracies[k]` should be a list of length `num_folds` giving the different\n",
"accuracy values that we found when using that value of $k$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "a14b3164-b63a-49eb-980e-57c74b2304db"
}
},
"outputs": [],
"source": [
"k_to_accuracies = {}"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "369cc408-fb92-4899-9e37-92c02a9ef4c1"
}
},
"source": [
"We perform $k$-fold cross validation to find the best value of $k$. For each \n",
"possible value of $k$, run the $k$-nearest-neighbor algorithm `num_folds` times, \n",
"where in each case you use all but one of the folds as training data and the \n",
"last fold as a validation set. Store the accuracies for all fold and all \n",
"values of k in the `k_to_accuracies` dictionary. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "6c869757-5e74-48cc-b7ef-14246b832a99"
}
},
"outputs": [],
"source": [
"for k in k_choices:\n",
" \n",
" k_to_accuracies[k] = []\n",
" classifier = KNearestNeighbor()\n",
" for i in range(num_folds):\n",
" X_cv_training = np.concatenate([x for k, x in enumerate(X_train_folds) if k!=i], axis=0)\n",
" y_cv_training = np.concatenate([x for k, x in enumerate(y_train_folds) if k!=i], axis=0)\n",
" classifier.train(X_cv_training, y_cv_training)\n",
" dists = classifier.compute_distances_no_loops(X_train_folds[i])\n",
" y_test_pred = classifier.predict_labels(dists, k=k)\n",
" k_to_accuracies[k].append(np.mean(y_train_folds[i] == y_test_pred))\n",
" \n"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "c10d6b24-607c-470b-bffd-614c8fa0be2c"
}
},
"source": [
"We print out the computed accuracies."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "d7c42393-850e-4329-91db-5c052fe247e0"
}
},
"outputs": [],
"source": [
"for k in sorted(k_to_accuracies):\n",
" for accuracy in k_to_accuracies[k]:\n",
" print('k = %d, accuracy = %f' % (k, accuracy))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We plot the raw observations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "e81573f1-9d05-44e2-a581-ffa01100b7af"
}
},
"outputs": [],
"source": [
"for k in k_choices:\n",
" accuracies = k_to_accuracies[k]\n",
" plt.scatter([k] * len(accuracies), accuracies)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "21f79bed-12f0-4e15-abdd-1105b4467cf0"
}
},
"source": [
" We plot the trend line with error bars that correspond to standard deviation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "c9af79e8-2cfa-42ed-84fe-efbdadcf65fd"
}
},
"outputs": [],
"source": [
"accuracies_mean = np.array([np.mean(v) for k,v in sorted(k_to_accuracies.items())])\n",
"accuracies_std = np.array([np.std(v) for k,v in sorted(k_to_accuracies.items())])\n",
"plt.errorbar(k_choices, accuracies_mean, yerr=accuracies_std)\n",
"plt.title('Cross-validation on k')\n",
"plt.xlabel('k')\n",
"plt.ylabel('Cross-validation accuracy')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "301c698f-4817-4bc5-8e35-ee37caebacba"
}
},
"source": [
" # K-Nearest Neighbor with L1 distance"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "ce60718f-a584-4026-8071-292b5943eca4"
}
},
"outputs": [],
"source": [
"class KNearestNeighbor_L1(KNearestNeighbor):\n",
" \"\"\" a kNN classifier with L1 distance \"\"\"\n",
"\n",
" def __init__(self):\n",
" super().__init__()\n",
" \n",
"\n",
" def compute_distances_one_loop(self, X):\n",
" \"\"\"\n",
" We overwrite the compute_distance_one_loop method of the parent class \n",
" KNearestNeighbor. \n",
" Compute the distance between each test point in X and each training point\n",
" in self.X_train using one loop and the L1 distance measure.\n",
"\n",
" Input / Output: Same as compute_distances_two_loops\n",
" \"\"\"\n",
" num_test = X.shape[0]\n",
" num_train = self.X_train.shape[0]\n",
" dists = np.zeros((num_test, num_train))\n",
" X = X.astype('float')\n",
" for i in range(num_test):\n",
" dists[i, :] = (np.sum(np.abs(self.X_train - X[i,:]), axis = 1))\n",
" return dists \n",
" \n",
" def compute_distances_two_loops(self, X):\n",
" \"\"\"\n",
" Compute the distance between each test point in X and each \n",
" training point in self.X_train using a nested loop over both \n",
" the training data and the test data.\n",
"\n",
" Inputs:\n",
" - X: A numpy array of shape (num_test, D) containing test data.\n",
"\n",
" Returns:\n",
" - dists: A numpy array of shape (num_test, num_train) where \n",
" dists[i, j] is the L1 distance between the ith test \n",
" point and the jth training point.\n",
" \"\"\"\n",
" num_test = X.shape[0]\n",
" num_train = self.X_train.shape[0]\n",
" dists = np.zeros((num_test, num_train))\n",
" X = X.astype('float')\n",
" for i in range(num_test):\n",
" for j in range(num_train):\n",
" dists[i, j] = np.sum(np.abs(self.X_train[j,:] - X[i,:]))\n",
" \n",
" \n",
" \n",
" return dists\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "d5745a61-1071-4704-8b71-6c0d175de9fc"
}
},
"source": [
"We create an instance nn form the class `KNearestNeighbor_L1`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "235c3d13-a428-4dae-a286-6ea912f8a0b2"
}
},
"outputs": [],
"source": [
"classifier = KNearestNeighbor_L1()"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "94df5594-5eff-4354-bc83-889aca850336"
}
},
"source": [
"Call the method train of the `KNearestNeighbor` class"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "627b4ca8-b0df-473d-8e53-3bcc2e31acd8"
}
},
"outputs": [],
"source": [
"classifier.train(X_train, y_train)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "b96d32ad-0526-4a52-a91e-dffb4a9e634a"
}
},
"source": [
"We test our implementation with one loop."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "f6ecd69e-e8b4-44a5-8ec1-8aeb47fbc5b5"
}
},
"outputs": [],
"source": [
"dists = classifier.compute_distances_one_loop(X_test)\n",
"dists.shape "
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "cd4c75ed-d9f1-4f3f-8990-2259f4f2f0d5"
}
},
"source": [
" Let us now predict labels and run the code below: We use $k = 10$"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "606e2720-6672-45f3-ae46-761df5c2066d"
}
},
"outputs": [],
"source": [
"y_test_pred = classifier.predict_labels(dists, k=10)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "3408b28c-0781-4186-b1cc-f8d0040ecf8f"
}
},
"source": [
"We compute and print the fraction of correctly predicted examples."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "1919eb5a-988f-4bee-a646-d110372bbca6"
}
},
"outputs": [],
"source": [
"num_correct = np.sum(y_test_pred == y_test)\n",
"accuracy = float(num_correct) / len(y_test_pred)\n",
"print('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy)) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The confusion matrix looks as follows:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# utility function for plotting confusion matrix\n",
"import matplotlib.pyplot as plt\n",
"import seaborn as sns\n",
"from sklearn.metrics import confusion_matrix\n",
"\n",
"def plot_confmat(y_true, y_pred):\n",
" \"\"\"\n",
" Plot the confusion matrix and save to user_files dir\n",
" \"\"\"\n",
" conf_matrix = confusion_matrix(y_true, y_pred)\n",
" fig = plt.figure(figsize=(9,9))\n",
" ax = fig.add_subplot(111)\n",
" sns.heatmap(conf_matrix,\n",
" annot=True,\n",
" fmt='.0f')\n",
" plt.title('Confusion matrix')\n",
" ax.set_xticklabels( classes)\n",
" ax.set_yticklabels( classes)\n",
" plt.ylabel('True')\n",
" plt.xlabel('Predicted')\n",
" \n",
"plot_confmat(y_test, y_test_pred) "
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "09892b80-b73f-41f3-8671-04ebc8f58ece"
}
},
"source": [
"# k-fold cross validation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "4d4d5599-4959-4aa9-8250-7ccd99c0eef6"
}
},
"outputs": [],
"source": [
"num_folds = 5\n",
"\n",
"k_choices = [1, 3, 5, 7, 9, 10, 12, 15, 18, 20, 50, 100]\n",
"\n",
"X_train_folds = []\n",
"y_train_folds = []"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "eeb5aeda-0ce5-4581-9fbe-e7605376384a"
}
},
"source": [
"We Split up the training data into folds. After splitting, `X_train_folds` and \n",
"`y_train_folds` should each be lists of length `num_folds`, where \n",
"`y_train_folds[i]` is the label vector for the points in `X_train_folds[i]` "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "50f9138b-3378-411f-96a1-5e3fe013e396"
}
},
"outputs": [],
"source": [
"num_train = X_train.shape[0]\n",
"fold_size = np.ceil(num_train/num_folds).astype('int')"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "267d72f8-6485-4abd-a1d7-d26b4be5a6cc"
}
},
"source": [
" In the case of `num_train = 5000` and 5 folds, we obtain \n",
"`X_train_folds = np.split(X_train, [1000, 2000, 3000, 4000])`\n",
"`y_train_folds = np.split(y_train, [1000, 2000, 3000, 4000])`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "ca3a1d8c-4b8a-42d6-94e7-793e87cebdea"
}
},
"outputs": [],
"source": [
"X_train_folds = np.split(X_train, [(i + 1)*fold_size for i in np.arange(num_folds)])\n",
"y_train_folds = np.split(y_train, [(i + 1)*fold_size for i in np.arange(num_folds)])\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "e1be1d21-0776-4587-9b88-d38e804eab71"
}
},
"source": [
"A dictionary holding the accuracies for different values of $k$ that we find\n",
"when running cross-validation. After running cross-validation,\n",
"`k_to_accuracies[k]` should be a list of length num_folds giving the different\n",
"accuracy values that we found when using that value of $k$."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "05e1ac10-1a25-4740-a21b-8b067116fd69"
}
},
"outputs": [],
"source": [
"k_to_accuracies = {}"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "f97b560b-929b-4a1f-90ee-3cf17ecef7e6"
}
},
"source": [
"We perform $k$-fold cross validation to find the best value of $k$. For each \n",
"possible value of $k$, run the $k$-nearest-neighbor algorithm `num_folds` times, \n",
"where in each case you use all but one of the folds as training data and the \n",
"last fold as a validation set. Store the accuracies for all fold and all \n",
"values of $k$ in the `k_to_accuracies` dictionary. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "bc2a21b5-4387-4bfc-8851-abcf62acaafc"
}
},
"outputs": [],
"source": [
"for k in k_choices:\n",
" \n",
" k_to_accuracies[k] = []\n",
" classifier = KNearestNeighbor_L1()\n",
" for i in range(num_folds):\n",
" X_cv_training = np.concatenate([x for k, x in enumerate(X_train_folds) if k!=i], axis=0)\n",
" y_cv_training = np.concatenate([x for k, x in enumerate(y_train_folds) if k!=i], axis=0)\n",
" classifier.train(X_cv_training, y_cv_training)\n",
" dists = classifier.compute_distances_two_loops(X_train_folds[i])\n",
" y_test_pred = classifier.predict_labels(dists, k=k)\n",
" k_to_accuracies[k].append(np.mean(y_train_folds[i] == y_test_pred))\n",
" \n"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "c24db8cd-04a8-45a6-b15e-24194bb42248"
}
},
"source": [
"We print out the computed accuracies."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "972c66f2-03ea-4de0-8ac6-a564c3365f50"
}
},
"outputs": [],
"source": [
"for k in sorted(k_to_accuracies):\n",
" for accuracy in k_to_accuracies[k]:\n",
" print('k = %d, accuracy = %f' % (k, accuracy))\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "57f5291f-1e32-456f-b84f-76eba7b40d44"
}
},
"source": [
"We plot the raw observations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "a028040f-a7a6-4b61-904d-48090dcbbe8d"
}
},
"outputs": [],
"source": [
"for k in k_choices:\n",
" accuracies = k_to_accuracies[k]\n",
" plt.scatter([k] * len(accuracies), accuracies)"
]
},
{
"cell_type": "markdown",
"metadata": {
"nbpresent": {
"id": "6a867f1e-9207-4d0d-adf9-7884532ed06e"
}
},
"source": [
"We plot the trend line with error bars that correspond to standard deviation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbpresent": {
"id": "caf9f446-5155-42db-a69b-46f1d7f06322"
}
},
"outputs": [],
"source": [
"accuracies_mean = np.array([np.mean(v) for k,v in sorted(k_to_accuracies.items())])\n",
"accuracies_std = np.array([np.std(v) for k,v in sorted(k_to_accuracies.items())])\n",
"plt.errorbar(k_choices, accuracies_mean, yerr=accuracies_std)\n",
"plt.title('Cross-validation on k')\n",
"plt.xlabel('k')\n",
"plt.ylabel('Cross-validation accuracy')\n",
"plt.show()"
]
}
],
"metadata": {
"anaconda-cloud": {},
"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.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}