-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFMML_Aug22-M1Lab3- (Terms&Metrics.ipynb)
2320 lines (2320 loc) · 122 KB
/
FMML_Aug22-M1Lab3- (Terms&Metrics.ipynb)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": [],
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/github/lakshmilikithabonthu/Fmml/blob/main/FMML_Aug22-M1Lab3-%20(Terms%26Metrics.ipynb)\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3Eu9VZbF01eq"
},
"source": [
"# Machine learning terms and metrics\n",
"\n",
"FMML Module 1, Lab 3<br>\n",
"Module Coordinator: Amit Pandey [email protected] <br>\n",
"<br>\n",
"\n",
" In this lab, we will show a part of the ML pipeline by extracting features, training and testing. We will also explore how data augmentation affects accuracy."
]
},
{
"cell_type": "code",
"metadata": {
"id": "8qBvyEem0vLi"
},
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn import datasets\n",
"# set randomseed\n",
"rng = np.random.default_rng(seed=42)"
],
"execution_count": 1,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "u3t59g5s1HfC"
},
"source": [
"In this lab, we will use the California Housing dataset. There are 20640 samples, each with 8 attributes like income of the block, age of the houses per district etc. The task is to predict the cost of the houses per district. \n",
"\n",
"Let us download and examine the dataset. "
]
},
{
"cell_type": "code",
"metadata": {
"id": "8LpqjN991GGJ",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "33ad2a83-dbb7-4407-e0d8-515f675e581f"
},
"source": [
" dataset = datasets.fetch_california_housing()\n",
" # print(dataset.DESCR) # uncomment this if you want to know more about this dataset\n",
" # print(dataset.keys()) # if you want to know what else is there in this dataset\n",
" dataset.target = dataset.target.astype(np.int) # so that we can classify\n",
" print(dataset.data.shape)\n",
" print(dataset.target.shape)"
],
"execution_count": 2,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"(20640, 8)\n",
"(20640,)\n"
]
},
{
"output_type": "stream",
"name": "stderr",
"text": [
"<ipython-input-2-60ae2e9a125e>:4: DeprecationWarning: `np.int` is a deprecated alias for the builtin `int`. To silence this warning, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.\n",
"Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations\n",
" dataset.target = dataset.target.astype(np.int) # so that we can classify\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "iNx4174W5xRg"
},
"source": [
"Here is a function for calculating the 1-nearest neighbours"
]
},
{
"cell_type": "code",
"source": [
"type(dataset), dataset.DESCR"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ut5lj4HsaTfp",
"outputId": "4fee797d-b08a-4a0a-ebb4-1f5e8be30e08"
},
"execution_count": 3,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"(sklearn.utils._bunch.Bunch,\n",
" '.. _california_housing_dataset:\\n\\nCalifornia Housing dataset\\n--------------------------\\n\\n**Data Set Characteristics:**\\n\\n :Number of Instances: 20640\\n\\n :Number of Attributes: 8 numeric, predictive attributes and the target\\n\\n :Attribute Information:\\n - MedInc median income in block group\\n - HouseAge median house age in block group\\n - AveRooms average number of rooms per household\\n - AveBedrms average number of bedrooms per household\\n - Population block group population\\n - AveOccup average number of household members\\n - Latitude block group latitude\\n - Longitude block group longitude\\n\\n :Missing Attribute Values: None\\n\\nThis dataset was obtained from the StatLib repository.\\nhttps://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html\\n\\nThe target variable is the median house value for California districts,\\nexpressed in hundreds of thousands of dollars ($100,000).\\n\\nThis dataset was derived from the 1990 U.S. census, using one row per census\\nblock group. A block group is the smallest geographical unit for which the U.S.\\nCensus Bureau publishes sample data (a block group typically has a population\\nof 600 to 3,000 people).\\n\\nAn household is a group of people residing within a home. Since the average\\nnumber of rooms and bedrooms in this dataset are provided per household, these\\ncolumns may take surpinsingly large values for block groups with few households\\nand many empty houses, such as vacation resorts.\\n\\nIt can be downloaded/loaded using the\\n:func:`sklearn.datasets.fetch_california_housing` function.\\n\\n.. topic:: References\\n\\n - Pace, R. Kelley and Ronald Barry, Sparse Spatial Autoregressions,\\n Statistics and Probability Letters, 33 (1997) 291-297\\n')"
]
},
"metadata": {},
"execution_count": 3
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "07zpydQj1hIQ",
"outputId": "1ca34dc2-6ede-4630-c9d9-f7b918ee6cae",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"source": [
"def NN1(traindata, trainlabel, query):\n",
" diff = traindata - query # find the difference between features. Numpy automatically takes care of the size here \n",
" sq = diff*diff # square the differences\n",
" dist = sq.sum(1) # add up the squares\n",
" label = trainlabel[np.argmin(dist)] # our predicted label is the label of the training data which has the least distance from the query\n",
" return label\n",
"\n",
"def NN(traindata, trainlabel, testdata):\n",
" # we will run nearest neighbour for each sample in the test data \n",
" # and collect the predicted classes in an array using list comprehension\n",
" predlabel = np.array([NN1(traindata, trainlabel, i) for i in testdata])\n",
" return predlabel\n",
"\n",
"\n",
"\n",
"5,5\n",
"6,6\n",
"8,9\n",
"\n",
"\n",
"0,0"
],
"execution_count": 4,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"(0, 0)"
]
},
"metadata": {},
"execution_count": 4
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "03JktkfIGaje"
},
"source": [
"We will also define a 'random classifier', which randomly allots labels to each sample"
]
},
{
"cell_type": "code",
"metadata": {
"id": "fogWAtjyGhAH"
},
"source": [
"def RandomClassifier(traindata, trainlabel, testdata):\n",
" # in reality, we don't need these arguments\n",
"\n",
" classes = np.unique(trainlabel)\n",
" rints = rng.integers(low=0, high=len(classes), size=len(testdata))\n",
" predlabel = classes[rints]\n",
" return predlabel"
],
"execution_count": 5,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "1Hjf1KHs7fU5"
},
"source": [
"Let us define a metric 'Accuracy' to see how good our learning algorithm is. Accuracy is the ratio of the number of correctly classified samples to the total number of samples. The higher the accuracy, the better the algorithm. "
]
},
{
"cell_type": "code",
"metadata": {
"id": "ouuCqWU07bz-"
},
"source": [
"def Accuracy(gtlabel, predlabel):\n",
" assert len(gtlabel)==len(predlabel), \"Length of the groundtruth labels and predicted labels should be the same\"\n",
" correct = (gtlabel==predlabel).sum() # count the number of times the groundtruth label is equal to the predicted label.\n",
" return correct/len(gtlabel)"
],
"execution_count": 6,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "4vJFwBFa9Klw"
},
"source": [
"Let us make a function to split the dataset with the desired probability."
]
},
{
"cell_type": "code",
"metadata": {
"id": "Ko0VzpSM2Tdi"
},
"source": [
"def split(data, label, percent):\n",
" # generate a random number for each sample\n",
" rnd = rng.random(len(label))\n",
" split1 = rnd<percent\n",
" split2 = rnd>=percent\n",
" split1data = data[split1,:]\n",
" split1label = label[split1]\n",
" split2data = data[split2,:]\n",
" split2label = label[split2]\n",
" return split1data, split1label, split2data, split2label"
],
"execution_count": 7,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "AcK3LEAJ_LGC"
},
"source": [
"We will reserve 20% of our dataset as the test set. We will not change this portion throughout our experiments"
]
},
{
"cell_type": "code",
"metadata": {
"id": "bBZkHBLJ1iU-",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "1bb8d458-d87a-400d-cdba-533fac553162"
},
"source": [
"testdata, testlabel, alltraindata, alltrainlabel = split(dataset.data, dataset.target, 20/100)\n",
"print('Number of test samples = ', len(testlabel))\n",
"print('Number of other samples = ', len(alltrainlabel))\n",
"print('Percent of test data = ', len(testlabel)*100/len(dataset.target),'%')"
],
"execution_count": 8,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Number of test samples = 4144\n",
"Number of other samples = 16496\n",
"Percent of test data = 20.07751937984496 %\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a6Ss0Z6IAGNV"
},
"source": [
"## Experiments with splits\n",
"\n",
"Let us reserve some of our train data as a validation set"
]
},
{
"cell_type": "code",
"metadata": {
"id": "WFew2iry_7W7"
},
"source": [
"traindata, trainlabel, valdata, vallabel = split(alltraindata, alltrainlabel, 75/100)"
],
"execution_count": 9,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "60hiu4clFN1i"
},
"source": [
"What is the accuracy of our classifiers on the train dataset?"
]
},
{
"cell_type": "markdown",
"source": [
"Accuracy= TP+TN/(TP+TN+FP+FN)\n",
"Where TP = True Positives, TN = True Negatives, FP = False Positives, and FN = False Negatives."
],
"metadata": {
"id": "VWuTAjE37Cor"
}
},
{
"cell_type": "code",
"metadata": {
"id": "DBlZDTHUFTZx",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "b00cdabf-12ab-41ba-9cb3-fae32c208291"
},
"source": [
"trainpred = NN(traindata, trainlabel, traindata)\n",
"trainAccuracy = Accuracy(trainlabel, trainpred)\n",
"print(\"Train accuracy using nearest neighbour is \", trainAccuracy)\n",
"\n",
"trainpred = RandomClassifier(traindata, trainlabel, traindata)\n",
"trainAccuracy = Accuracy(trainlabel, trainpred)\n",
"print(\"Train accuracy using random classifier is \", trainAccuracy)"
],
"execution_count": 10,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Train accuracy using nearest neighbour is 1.0\n",
"Train accuracy using random classifier is 0.164375808538163\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"A,B,C=5,6,7\n",
"6,6 -B\n",
"7,7 -C\n",
"\n",
"\n",
"\n",
"8,8 - A | C\n",
"0,0 -B | A - 0\n",
"\n",
"\n",
"10,10 -A\n",
"15,15 -C"
],
"metadata": {
"id": "jnMblJyaXKZZ",
"outputId": "c46ea456-3aaa-4a0c-c6f8-14c608e30a4d",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"execution_count": 11,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"(15, 8)"
]
},
"metadata": {},
"execution_count": 11
}
]
},
{
"cell_type": "markdown",
"source": [
"## Interesting: See how train accuracy of nearest neighbour is 1 i.e. 100%. Ponder and Explain."
],
"metadata": {
"id": "tW_I-YuhbQqA"
}
},
{
"cell_type": "markdown",
"metadata": {
"id": "7h08-9gJDtSy"
},
"source": [
"For nearest neighbour, the train accuracy is always 1. The accuracy of the random classifier is close to 1/(number of classes) which is 0.1666 in our case.\n",
"\n",
"Let us predict the labels for our validation set and get the accuracy"
]
},
{
"cell_type": "code",
"metadata": {
"id": "4h7bXoW_2H3v",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "05cfa358-b43f-42ed-9dae-8b90b14eb498"
},
"source": [
"valpred = NN(traindata, trainlabel, valdata)\n",
"valAccuracy = Accuracy(vallabel, valpred)\n",
"print(\"Validation accuracy using nearest neighbour is \", valAccuracy)\n",
"\n",
"valpred = RandomClassifier(traindata, trainlabel, valdata)\n",
"valAccuracy = Accuracy(vallabel, valpred)\n",
"print(\"Validation accuracy using random classifier is \", valAccuracy)"
],
"execution_count": 12,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Validation accuracy using nearest neighbour is 0.34108527131782945\n",
"Validation accuracy using random classifier is 0.1688468992248062\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "py9bLguFEjfg"
},
"source": [
"Validation accuracy of nearest neighbour is considerably less than its train accuracy while the validation accuracy of random classifier is the same. However, the validation accuracy of nearest neighbour is twice that of the random classifier. \n",
"\n",
"Now let us try another random split and check the validation accuracy"
]
},
{
"cell_type": "code",
"metadata": {
"id": "ujm3cyYzEntE",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "6a5dda41-2a43-457d-8897-b8a57646c3ba"
},
"source": [
"traindata, trainlabel, valdata, vallabel = split(alltraindata, alltrainlabel, 75/100)\n",
"valpred = NN(traindata, trainlabel, valdata)\n",
"valAccuracy = Accuracy(vallabel, valpred)\n",
"print(\"Validation accuracy of nearest neighbour is \", valAccuracy)"
],
"execution_count": 13,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Validation accuracy of nearest neighbour is 0.34048257372654156\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "oSOx7U83EKie"
},
"source": [
"You can run the above cell multiple times to try with different random splits. \n",
"We notice that the accuracy is different for each run, but close together. \n",
"\n",
"Now let us compare it with the accuracy we get on the test dataset. "
]
},
{
"cell_type": "code",
"metadata": {
"id": "PNEZ5ToYBEDW",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "5066a3cd-6af6-41a3-f93e-0fb0490d7713"
},
"source": [
"testpred = NN(alltraindata, alltrainlabel, testdata)\n",
"testAccuracy = Accuracy(testlabel, testpred)\n",
"print('Test accuracy is ', testAccuracy)"
],
"execution_count": 14,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Test accuracy is 0.34917953667953666\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "w3dGD531K3gH"
},
"source": [
"### Try it out for yourself and answer:\n",
"1. How is the accuracy of the validation set affected if we increase the percentage of validation set? What happens when we reduce it?\n",
"2. How does the size of the train and validation set affect how well we can predict the accuracy on the test set using the validation set?\n",
"3. What do you think is a good percentage to reserve for the validation set so that thest two factors are balanced? \n",
"\n",
"Answer for both nearest neighbour and random classifier. You can note down the values for your experiments and plot a graph using <a href=https://matplotlib.org/stable/gallery/lines_bars_and_markers/step_demo.html#sphx-glr-gallery-lines-bars-and-markers-step-demo-py>plt.plot<href>. Check also for extreme values for splits, like 99.9% or 0.1%"
]
},
{
"cell_type": "markdown",
"source": [
"***Answer-1*** If we increase the percentage of validation set, it will not show any effect on accuracy, whereas if we decrease the percentage of validation set we don't get the best accuracy.bold "
],
"metadata": {
"id": "QIcSpVKA7NtF"
}
},
{
"cell_type": "markdown",
"source": [
"***Answer-2*** The training set should not small.If the validation set is too small, there will be a large variance in the evaluation metrics like accuracy, precision, F score and it will no lead to the proper training of the model."
],
"metadata": {
"id": "We9oYmjV7S5N"
}
},
{
"cell_type": "markdown",
"source": [
"***Answer-3*** Train set depends on factor such as structure of model,dimension of data.Normally putting 80% of the data in training set,10% in the validation set,and 10% in the test set is a good to start."
],
"metadata": {
"id": "0Ysdecc47WYt"
}
},
{
"cell_type": "markdown",
"metadata": {
"id": "PnYvkAZLQY7h"
},
"source": [
"## Multiple Splits\n",
"\n",
"One way to get more accurate estimates for the test accuracy is by using <b>crossvalidation</b>. Here, we will try a simple version, where we do multiple train/val splits and take the average of validation accuracies as the test accuracy estimation. Here is a function for doing this. Note that this function will take a long time to execute. "
]
},
{
"cell_type": "code",
"source": [
"100 --- 80 --- 75|5, 12345, 1234|5, 2345|1, 1345|2"
],
"metadata": {
"id": "k-HGXSovYQ1v",
"outputId": "5b0e7511-bc82-4584-b8f1-cc3110f4f05f",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"execution_count": 15,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"(-51, 12345, 1239, 2345, 1347)"
]
},
"metadata": {},
"execution_count": 15
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "E4nGCUQXBTzo"
},
"source": [
"# you can use this function for random classifier also\n",
"def AverageAccuracy(alldata, alllabel, splitpercent, iterations, classifier=NN):\n",
" accuracy = 0\n",
" for ii in range(iterations):\n",
" traindata, trainlabel, valdata, vallabel = split(alldata, alllabel, splitpercent)\n",
" valpred = classifier(traindata, trainlabel, valdata)\n",
" accuracy += Accuracy(vallabel, valpred)\n",
" return accuracy/iterations # average of all accuracies"
],
"execution_count": 16,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "H3qtNar7Bbik",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "8cd5c602-679c-4f4c-83bc-0905c81c5f26"
},
"source": [
"print('Average validation accuracy is ', AverageAccuracy(alltraindata, alltrainlabel, 75/100, 10, classifier=NN))\n",
"testpred = NN(alltraindata, alltrainlabel, testdata)\n",
"print('test accuracy is ',Accuracy(testlabel, testpred) )"
],
"execution_count": 17,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Average validation accuracy is 0.33584635395170215\n",
"test accuracy is 0.34917953667953666\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "33GIn4x5VH-d"
},
"source": [
"This is a very simple way of doing cross-validation. There are many well-known algorithms for cross-validation, like k-fold cross-validation, leave-one-out etc. This will be covered in detail in a later module. For more information about cross-validation, check <a href=https://en.wikipedia.org/wiki/Cross-validation_(statistics)>Cross-validatioin (Wikipedia)</a>\n",
"\n",
"### Questions\n",
"1. Does averaging the validation accuracy across multiple splits give more consistent results?\n",
"2. Does it give more accurate estimate of test accuracy?\n",
"3. What is the effect of the number of iterations on the estimate? Do we get a better estimate with higher iterations?\n",
"4. Consider the results you got for the previous questions. Can we deal with a very small train dataset or validation dataset by increasing the iterations?\n"
]
},
{
"cell_type": "markdown",
"source": [
"***Answer-1*** Yes,averaging the validation accuracy across multiple splits gives more consistent results."
],
"metadata": {
"id": "hE1RJOna7cq1"
}
},
{
"cell_type": "markdown",
"source": [
"***Answer-2*** Cross validation is easy to understand and implement making it go to method for comparing the predictive capabilities of different models and choosing best.It is useful for building more accurate machine learning models and evaluating how will they work on an independent test dataset."
],
"metadata": {
"id": "zfiUTqAr7efE"
}
},
{
"cell_type": "markdown",
"source": [
"***Answer-3*** There is no effect of the number of iterations on estimate. Yes,We get a better estimate when the iteration rate is higher."
],
"metadata": {
"id": "q1qORwrq7hM9"
}
},
{
"cell_type": "markdown",
"source": [
"***Answer-4*** By increasing the number of iterations we can deal with very small train dataset or validation dataset."
],
"metadata": {
"id": "FxesED6r7lLn"
}
},
{
"cell_type": "markdown",
"source": [
"## Now let us see how augmentation affects accuracy. We will pick components from what we studied in the last module"
],
"metadata": {
"id": "UUft9G1acwlB"
}
},
{
"cell_type": "markdown",
"source": [
"we will experiment with MNIST dataset\n"
],
"metadata": {
"id": "XtU3AfVDkkYM"
}
},
{
"cell_type": "code",
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from keras.datasets import mnist\n",
"# set randomseed\n",
"rng = np.random.default_rng(seed=42)\n",
"from sklearn.utils.extmath import cartesian\n",
"from skimage.transform import rotate, AffineTransform, warp\n",
"import math\n",
"\n",
"#loading the dataset\n",
"(train_X, train_y), (test_X, test_y) = mnist.load_data()\n",
"\n",
"print(train_X[0].shape,train_y[0])\n",
"\n"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "47HIwFsMkebm",
"outputId": "840db721-79c5-4e71-936b-45872811cc82"
},
"execution_count": 18,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz\n",
"11490434/11490434 [==============================] - 1s 0us/step\n",
"(28, 28) 5\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"train_X = train_X/255\n",
"test_X = test_X/255\n",
"\n",
"#train_X[0].shape, train_X[0]"
],
"metadata": {
"id": "WW6ZGBcTkyXB"
},
"execution_count": 19,
"outputs": []
},
{
"cell_type": "code",
"source": [
"train_X = train_X[::1200,:,:].copy() # subsample. Otherwise it will take too long!\n",
"train_y = train_y[::1200].copy() # do the same to the labels"
],
"metadata": {
"id": "64ATS9mtk_mA"
},
"execution_count": 20,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "1WileBUqC404"
},
"source": [
"## Augmentation functions:\n",
"\n",
"\n",
"\n",
"def augRotate(sample, angleconstraint):\n",
" if angleconstraint==0:\n",
" return sample\n",
"\n",
" print(\"shape of sample before is:\", sample.shape)\n",
" print(\"len(sample.shape)\", len(sample.shape))\n",
" if len(sample.shape)==2:\n",
" sample = np.expand_dims(sample, 0) # make sure the sample is 3 dimensional\n",
" print(\"shape of sample is:\", sample.shape)\n",
" angle = rng.random(len(sample)) # generate random numbers for angles\n",
" print(\"angle is:\", angle)\n",
" angle = (angle-0.5)*angleconstraint # make the random angle constrained\n",
" print(\"angle with constraint is:\", angle)\n",
" nsample = sample.copy() # preallocate the augmented array to make it faster\n",
" for ii in range(len(sample)):\n",
" nsample[ii] = rotate(sample[ii], angle[ii])\n",
" return np.squeeze(nsample) # take care if the input had only one sample.\n",
"\n",
"\n",
"def NN1(traindata, trainlabel, query):\n",
" diff = traindata - query # find the difference between features. Numpy automatically takes care of the size here \n",
" sq = diff*diff # square the differences\n",
" dist = sq.sum(1) # add up the squares\n",
" label = trainlabel[np.argmin(dist)] # our predicted label is the label of the training data which has the least distance from the query\n",
" return label\n",
"\n",
"def NN(traindata, trainlabel, testdata):\n",
" # we will run nearest neighbour for each sample in the test data \n",
" # and collect the predicted classes in an array using list comprehension\n",
" traindata = traindata.reshape(-1, 28*28)\n",
" testdata = testdata.reshape(-1,28*28)\n",
" predlabel = np.array([NN1(traindata, trainlabel, i) for i in testdata])\n",
" return predlabel\n",
"\n",
"def Accuracy(gtlabel, predlabel):\n",
" assert len(gtlabel)==len(predlabel), \"Length of the groundtruth labels and predicted labels should be the same\"\n",
" correct = (gtlabel==predlabel).sum() # count the number of times the groundtruth label is equal to the predicted label.\n",
" return correct/len(gtlabel)"
],
"execution_count": 21,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def shear(sample, amount):\n",
" tform = AffineTransform(shear = amount) # create the shear transform\n",
" img = warp(sample, tform) # apply the shear\n",
" # this makes the digit off-center. Since all the images in the test set are centralized, we will do the same here\n",
" col = img.sum(0).nonzero()[0]\n",
" row = img.sum(1).nonzero()[0]\n",
" if len(col)>0 and len(row)>0:\n",
" xshift = int(sample.shape[0]/2 - (row[0]+row[-1])/2)\n",
" yshift = int(sample.shape[1]/2 - (col[0]+col[-1])/2)\n",
" img = np.roll(img, (xshift, yshift),(0,1))\n",
" return img\n",
"\n",
"def augShear(sample, shearconstraint):\n",
" if shearconstraint==0:\n",
" return sample\n",
" if len(sample.shape)==2:\n",
" sample = np.expand_dims(sample, 0) # make sure the sample is 3 dimensional\n",
" amt = rng.random(len(sample)) # generate random numbers for shear\n",
" amt = (amt-0.5)*shearconstraint # make the random shear constrained\n",
" nsample = sample.copy() # preallocate the augmented array to make it faster\n",
" for ii in range(len(sample)):\n",
" nsample[ii] = shear(sample[ii], amt[ii])\n",
" return np.squeeze(nsample) # take care if the input had only one sample.\n",
"\n",
"\n"
],
"metadata": {
"id": "BIsZ_Q5LqWEs"
},
"execution_count": 22,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"In this lab, we will use the image pixels themselves as features, instead of extracting features. Each image has 28*28 pixels, so we will flatten them to 784 pixels to use as features. Note that this is very compute intensive and will take a long time.\n",
"\n",
"Let us check the baseline accuracy on the test set without any augmentations. We hope that adding augmentations will help us to get better results."
],
"metadata": {
"id": "vAFpOzQFj-2r"
}
},
{
"cell_type": "code",
"source": [
"testpred = NN(train_X, train_y, test_X)\n",
"print('Baseline accuracy without augmentation is ', Accuracy(test_y, testpred))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "dPNdNyFVj4pX",
"outputId": "22b0b149-9a06-4993-d2a4-5b15cdb91386"
},
"execution_count": 23,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Baseline accuracy without augmentation is 0.6472\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"Let us try to improve this accuracy using augmentations. When we create augmentations, we have to make sure that the changes reflect what will naturally occur in the dataset. For example, we should not add colour to our samples as an augmentation because they do not naturally occur. We should not also flip the images in MNIST, because flipped images have different meanings for digits."
],
"metadata": {
"id": "MckdgpPflSYh"
}
},
{
"cell_type": "markdown",
"source": [
"Let us augment the whole dataset and see if this improves the test accuracy"
],
"metadata": {
"id": "7aWfHHggmqu7"
}
},
{
"cell_type": "code",
"source": [
"# hyperparameters\n",
"angleconstraint = 60\n",
"naugmentations = 5\n",
"\n",
"# augment\n",
"augdata = train_X # we include the original images also in the augmented dataset\n",
"auglabel = train_y\n",
"for ii in range(naugmentations):\n",
" augdata = np.concatenate((augdata, augRotate(train_X, angleconstraint))) # concatenate the augmented data to the set\n",
" auglabel = np.concatenate((auglabel, train_y)) # the labels don't change when we augment\n",
"\n",
"# check the test accuracy\n",
"testpred = NN(augdata, auglabel, test_X)\n",
"print('Accuracy after rotation augmentation is ', Accuracy(test_y, testpred))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Kdn0TZ_tlMg3",
"outputId": "6c6c344e-f51f-4e33-fb1e-69e3c675cbc7"
},
"execution_count": 24,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"shape of sample before is: (50, 28, 28)\n",
"len(sample.shape) 3\n",
"angle is: [0.77395605 0.43887844 0.85859792 0.69736803 0.09417735 0.97562235\n",
" 0.7611397 0.78606431 0.12811363 0.45038594 0.37079802 0.92676499\n",
" 0.64386512 0.82276161 0.4434142 0.22723872 0.55458479 0.06381726\n",
" 0.82763117 0.6316644 0.75808774 0.35452597 0.97069802 0.89312112\n",
" 0.7783835 0.19463871 0.466721 0.04380377 0.15428949 0.68304895\n",
" 0.74476216 0.96750973 0.32582536 0.37045971 0.46955581 0.18947136\n",
" 0.12992151 0.47570493 0.22690935 0.66981399 0.43715192 0.8326782\n",
" 0.7002651 0.31236664 0.8322598 0.80476436 0.38747838 0.2883281\n",
" 0.6824955 0.13975248]\n",
"angle with constraint is: [ 16.43736291 -3.66729361 21.51587519 11.84208174 -24.34935913\n",
" 28.5373411 15.66838212 17.16385832 -22.31318204 -2.97684373\n",
" -7.75211855 25.60589933 8.6319072 19.3656968 -3.39514807\n",
" -16.36567669 3.27508722 -26.17096463 19.65787032 7.89986395\n",
" 15.48526441 -8.72844191 28.24188146 23.58726728 16.70300982\n",
" -18.32167753 -1.99673978 -27.37177405 -20.74263048 10.98293719\n",
" 14.68572935 28.05058395 -10.45047851 -7.77241764 -1.82665132\n",
" -18.63171845 -22.20470968 -1.45770443 -16.38543906 10.18883968\n",
" -3.77088487 19.96069176 12.01590612 -11.25800152 19.93558808\n",
" 18.28586145 -6.75129726 -12.70031376 10.94973024 -21.61485098]\n",
"shape of sample before is: (50, 28, 28)\n",
"len(sample.shape) 3\n",
"angle is: [0.1999082 0.00736227 0.78692438 0.66485086 0.70516538 0.78072903\n",
" 0.45891578 0.5687412 0.139797 0.11453007 0.66840296 0.47109621\n",
" 0.56523611 0.76499886 0.63471832 0.5535794 0.55920716 0.3039501\n",
" 0.03081783 0.43671739 0.21458467 0.40852864 0.85340307 0.23393949\n",
" 0.05830274 0.28138389 0.29359376 0.66191651 0.55703215 0.78389821\n",
" 0.66431354 0.40638686 0.81402038 0.16697292 0.02271207 0.09004786\n",
" 0.72235935 0.46187723 0.16127178 0.50104478 0.1523121 0.69632038\n",
" 0.44615628 0.38102123 0.30151209 0.63028259 0.36181261 0.08764992\n",
" 0.1180059 0.96189766]\n",
"angle with constraint is: [-18.00550785 -29.55826381 17.21546265 9.8910514 12.30992272\n",
" 16.84374186 -2.46505347 4.12447176 -21.61218011 -23.12819559\n",
" 10.10417771 -1.73422763 3.91416639 15.89993144 8.0830992\n",
" 3.21476404 3.55242964 -11.76299412 -28.15092993 -3.79695665\n",
" -17.12491963 -5.48828138 21.2041844 -15.96363085 -26.5018355\n",
" -13.11696648 -12.38437453 9.71499088 3.42192914 17.03389255\n",
" 9.85881242 -5.61678831 18.84122308 -19.98162481 -28.63727561\n",