Repository navigation
Expand file tree
/
Copy pathweek12-13_ML.html
More file actions
2542 lines (2359 loc) · 176 KB
/
Copy pathweek12-13_ML.html
File metadata and controls
2542 lines (2359 loc) · 176 KB
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
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.18.1: http://docutils.sourceforge.net/" />
<title>Chapter 9: Machine Learning — Python Programming for Geospatial Data Analysis</title>
<script data-cfasync="false">
document.documentElement.dataset.mode = localStorage.getItem("mode") || "";
document.documentElement.dataset.theme = localStorage.getItem("theme") || "light";
</script>
<!-- Loaded before other Sphinx assets -->
<link href="_static/styles/theme.css?digest=e353d410970836974a52" rel="stylesheet" />
<link href="_static/styles/bootstrap.css?digest=e353d410970836974a52" rel="stylesheet" />
<link href="_static/styles/pydata-sphinx-theme.css?digest=e353d410970836974a52" rel="stylesheet" />
<link href="_static/vendor/fontawesome/6.1.2/css/all.min.css?digest=e353d410970836974a52" rel="stylesheet" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.1.2/webfonts/fa-solid-900.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.1.2/webfonts/fa-brands-400.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="_static/vendor/fontawesome/6.1.2/webfonts/fa-regular-400.woff2" />
<link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" href="_static/styles/sphinx-book-theme.css?digest=14f4ca6b54d191a8c7657f6c759bf11a5fb86285" type="text/css" />
<link rel="stylesheet" type="text/css" href="_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/mystnb.4510f1fc1dee50b3e5859aac5469c37c29e427902b24a333a5f9fcb2f0b3ac41.css" />
<link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="_static/design-style.4045f2051d55cab465a707391d5b2007.min.css" />
<!-- Pre-loaded scripts that we'll load fully later -->
<link rel="preload" as="script" href="_static/scripts/bootstrap.js?digest=e353d410970836974a52" />
<link rel="preload" as="script" href="_static/scripts/pydata-sphinx-theme.js?digest=e353d410970836974a52" />
<script data-url_root="./" id="documentation_options" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
<script src="_static/_sphinx_javascript_frameworks_compat.js"></script>
<script src="_static/doctools.js"></script>
<script src="_static/clipboard.min.js"></script>
<script src="_static/copybutton.js"></script>
<script src="_static/scripts/sphinx-book-theme.js?digest=5a5c038af52cf7bc1a1ec88eea08e6366ee68824"></script>
<script>let toggleHintShow = 'Click to show';</script>
<script>let toggleHintHide = 'Click to hide';</script>
<script>let toggleOpenOnPrint = 'true';</script>
<script src="_static/togglebutton.js"></script>
<script>var togglebuttonSelector = '.toggle, .admonition.dropdown';</script>
<script src="_static/design-tabs.js"></script>
<script>const THEBE_JS_URL = "https://unpkg.com/thebe@0.8.2/lib/index.js"
const thebe_selector = ".thebe,.cell"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output, .cell_output"
</script>
<script async="async" src="_static/sphinx-thebe.js"></script>
<script>window.MathJax = {"options": {"processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<script defer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>DOCUMENTATION_OPTIONS.pagename = 'week12-13_ML';</script>
<link rel="index" title="Index" href="genindex.html" />
<link rel="search" title="Search" href="search.html" />
<link rel="prev" title="Chapter 8: GeoPandas Python Library" href="week11_GeoPandas.html" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="docsearch:language" content="en"/>
</head>
<body data-bs-spy="scroll" data-bs-target=".bd-toc-nav" data-offset="180" data-bs-root-margin="0px 0px -60%" data-default-mode="">
<a class="skip-link" href="#main-content">Skip to main content</a>
<input type="checkbox"
class="sidebar-toggle"
name="__primary"
id="__primary"/>
<label class="overlay overlay-primary" for="__primary"></label>
<input type="checkbox"
class="sidebar-toggle"
name="__secondary"
id="__secondary"/>
<label class="overlay overlay-secondary" for="__secondary"></label>
<div class="search-button__wrapper">
<div class="search-button__overlay"></div>
<div class="search-button__search-container">
<form class="bd-search d-flex align-items-center"
action="search.html"
method="get">
<i class="fa-solid fa-magnifying-glass"></i>
<input type="search"
class="form-control"
name="q"
id="search-input"
placeholder="Search this book..."
aria-label="Search this book..."
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"/>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd>K</kbd></span>
</form></div>
</div>
<nav class="bd-header navbar navbar-expand-lg bd-navbar">
</nav>
<div class="bd-container">
<div class="bd-container__inner bd-page-width">
<div class="bd-sidebar-primary bd-sidebar">
<div class="sidebar-header-items sidebar-primary__section">
</div>
<div class="sidebar-primary-items__start sidebar-primary__section">
<div class="sidebar-primary-item">
<a class="navbar-brand logo" href="intro.html">
<p class="title logo__title">Python Programming for Geospatial Data Analysis</p>
</a></div>
<div class="sidebar-primary-item"><nav class="bd-links" id="bd-docs-nav" aria-label="Main">
<div class="bd-toc-item navbar-nav active">
<ul class="nav bd-sidenav bd-sidenav__home-link">
<li class="toctree-l1">
<a class="reference internal" href="intro.html">
Python Programming for Geospatial Data Analysis
</a>
</li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Python Programming Basics</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="week1.html">Chapter 1: An Introductory Guide to Python</a></li>
<li class="toctree-l1"><a class="reference internal" href="week2.html">Chapter 2: Python Fundamentals</a></li>
<li class="toctree-l1"><a class="reference internal" href="week3.html">Chapter 3: Control Flow</a></li>
<li class="toctree-l1"><a class="reference internal" href="week4.html">Chapter 4: Errors and Exceptions in Python</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Data Visualization and Numpy</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="week8.html">Chapter 5: Python Plotting using Matplotlib</a></li>
<li class="toctree-l1"><a class="reference internal" href="week9_Numpy.html">Chapter 6: Numpy and Rasterio</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Pandas and GeoPandas</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="week10_Pandas.html">Chapter 7: Pandas</a></li>
<li class="toctree-l1"><a class="reference internal" href="week11_GeoPandas.html">Chapter 8: GeoPandas Python Library</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Applications</span></p>
<ul class="current nav bd-sidenav">
<li class="toctree-l1 current active"><a class="current reference internal" href="#">Chapter 9: Machine Learning</a></li>
</ul>
</div>
</nav></div>
</div>
<div class="sidebar-primary-items__end sidebar-primary__section">
</div>
<div id="rtd-footer-container"></div>
</div>
<main id="main-content" class="bd-main">
<div class="sbt-scroll-pixel-helper"></div>
<div class="bd-content">
<div class="bd-article-container">
<div class="bd-header-article">
<div class="header-article-items header-article__inner">
<div class="header-article-items__start">
<div class="header-article-item"><label class="sidebar-toggle primary-toggle btn btn-sm" for="__primary" title="Toggle primary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-bars"></span>
</label></div>
</div>
<div class="header-article-items__end">
<div class="header-article-item">
<div class="article-header-buttons">
<div class="dropdown dropdown-source-buttons">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Source repositories">
<i class="fab fa-github"></i>
</button>
<ul class="dropdown-menu">
<li><a href="https://github.com/subornaa/Python-Programming-for-Geospatial-Data-Analysis/tree/gh-pages" target="_blank"
class="btn btn-sm btn-source-repository-button dropdown-item"
title="Source repository"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fab fa-github"></i>
</span>
<span class="btn__text-container">Repository</span>
</a>
</li>
<li><a href="https://github.com/subornaa/Python-Programming-for-Geospatial-Data-Analysis/tree/gh-pages/issues/new?title=Issue%20on%20page%20%2Fweek12-13_ML.html&body=Your%20issue%20content%20here." target="_blank"
class="btn btn-sm btn-source-issues-button dropdown-item"
title="Open an issue"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-lightbulb"></i>
</span>
<span class="btn__text-container">Open issue</span>
</a>
</li>
</ul>
</div>
<div class="dropdown dropdown-download-buttons">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Download this page">
<i class="fas fa-download"></i>
</button>
<ul class="dropdown-menu">
<li><a href="_sources/week12-13_ML.ipynb" target="_blank"
class="btn btn-sm btn-download-source-button dropdown-item"
title="Download source file"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-file"></i>
</span>
<span class="btn__text-container">.ipynb</span>
</a>
</li>
<li>
<button onclick="window.print()"
class="btn btn-sm btn-download-pdf-button dropdown-item"
title="Print to PDF"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-file-pdf"></i>
</span>
<span class="btn__text-container">.pdf</span>
</button>
</li>
</ul>
</div>
<button onclick="toggleFullScreen()"
class="btn btn-sm btn-fullscreen-button"
title="Fullscreen mode"
data-bs-placement="bottom" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-expand"></i>
</span>
</button>
<script>
document.write(`
<button class="theme-switch-button btn btn-sm btn-outline-primary navbar-btn rounded-circle" title="light/dark" aria-label="light/dark" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="theme-switch" data-mode="light"><i class="fa-solid fa-sun"></i></span>
<span class="theme-switch" data-mode="dark"><i class="fa-solid fa-moon"></i></span>
<span class="theme-switch" data-mode="auto"><i class="fa-solid fa-circle-half-stroke"></i></span>
</button>
`);
</script>
<script>
document.write(`
<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass"></i>
</button>
`);
</script>
<label class="sidebar-toggle secondary-toggle btn btn-sm" for="__secondary"title="Toggle secondary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-list"></span>
</label>
</div></div>
</div>
</div>
</div>
<div id="jb-print-docs-body" class="onlyprint">
<h1>Chapter 9: Machine Learning</h1>
<!-- Table of contents -->
<div id="print-main-content">
<div id="jb-print-toc">
<div>
<h2> Contents </h2>
</div>
<nav aria-label="Page">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#machine-learning-application-in-geospatial-data">Machine Learning Application in Geospatial Data</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#span-style-color-blue-learning-objectives-span"><span style="color:blue"> Learning Objectives:</span></a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#what-is-machine-learning">1. What is Machine Learning?</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#general-characteristics">1.1. General Characteristics:</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#terminologies">1.2.Terminologies:</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#why-use-ml-in-remote-sensing-gis">2. Why Use ML in Remote Sensing/GIS?</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#scikit-learn">3. scikit-learn</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#setup-the-environment">4. Setup the Environment</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#the-famous-iris-dataset">4.1. The Famous Iris Dataset</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#objects-in-the-iris-data">4.2. Objects in the Iris Data</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#overfitting-and-underfitting-models">4.3. Overfitting and Underfitting Models</a><ul class="nav section-nav flex-column">
<li class="toc-h4 nav-item toc-entry"><a class="reference internal nav-link" href="#different-approaches-to-reduce-overfitting">4.3.1.Different Approaches to Reduce Overfitting</a></li>
<li class="toc-h4 nav-item toc-entry"><a class="reference internal nav-link" href="#different-approaches-to-reduce-underfitting">4.3.2. Different Approaches to Reduce Underfitting</a></li>
</ul>
</li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#training-validation-and-test-data">4.4. Training, Validation, and Test data</a><ul class="nav section-nav flex-column">
<li class="toc-h4 nav-item toc-entry"><a class="reference internal nav-link" href="#separate-iris-data-into-train-and-test-data">4.4.1. Separate Iris Data into Train and Test Data</a></li>
</ul>
</li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#types-of-algorithms">5. Types of Algorithms</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#supervised-algorithms">5.1. Supervised Algorithms</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#unsupervised-algorithms">5.2. Unsupervised Algorithms</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#popular-supervised-algorithms-linear-regression">5.3. Popular Supervised Algorithms – Linear Regression</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#popular-algorithms-k-nearest-neighbors">5.4. Popular Algorithms: k-Nearest Neighbors</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#popular-algorithms-cart">5.5. Popular Algorithms: CART</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#random-forest">5.6. Random Forest</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#training-a-ml-model">5.7 Training a ML Model</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#assessing-the-model-accuracy">5.8. Assessing the Model Accuracy</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#confusion-matrix">5.9. Confusion Matrix</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#kappa-coefficient">5.10. Kappa Coefficient</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#problem-solving-framework">6. Problem-Solving Framework</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#working-process">Working Process</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#train-a-cart-and-make-predictions">Train a CART and Make Predictions</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#visualize-the-results">Visualize the Results</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#concern-and-application-plan">Concern and Application Plan</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#debriefing-the-results">Debriefing the Results</a></li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#further-resources">Further Resources</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#solution">Solution</a><ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#k-nearest-neighbors-knn-application">K-Nearest Neighbors (KNN) Application</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#id1">Random Forest</a></li>
<li class="toc-h3 nav-item toc-entry"><a class="reference internal nav-link" href="#compare-model-evaluation">Compare Model Evaluation:</a></li>
</ul>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div id="searchbox"></div>
<article class="bd-article" role="main">
<section class="tex2jax_ignore mathjax_ignore" id="chapter-9-machine-learning">
<h1>Chapter 9: Machine Learning<a class="headerlink" href="#chapter-9-machine-learning" title="Permalink to this heading">#</a></h1>
<section id="machine-learning-application-in-geospatial-data">
<h2>Machine Learning Application in Geospatial Data<a class="headerlink" href="#machine-learning-application-in-geospatial-data" title="Permalink to this heading">#</a></h2>
<p><strong>Author: Dr. Suborna Ahmed</strong></p>
<p>In Machine Learning, Python is widely used and many Python libraries are built for analyzing geodata. You have applied many Python modules on Geospatial data already. Now, you will apply some of those modules (i.e., NumPy, Matplotlib) along with a few more new modules that are built for application of Machine Learning techniques for prediction. We will also apply some methods that you have learned in the Linear Regression course (i.e., developing statistical models and checking assumptions).</p>
</section>
<section id="span-style-color-blue-learning-objectives-span">
<h2><span style="color:blue"> Learning Objectives:</span><a class="headerlink" href="#span-style-color-blue-learning-objectives-span" title="Permalink to this heading">#</a></h2>
<ul class="simple">
<li><p>What is Machine Learning</p>
<ul>
<li><p>General Characteristics</p></li>
<li><p>Terminologies</p></li>
</ul>
</li>
<li><p>Why Use ML in Remote Sensing/GIS?</p></li>
<li><p>scikit-learn</p></li>
<li><p>Load and Analyze Iris dataset</p></li>
<li><p>Fitting Models</p></li>
<li><p>Overfitting Models</p></li>
<li><p>Setup the environment</p>
<ul>
<li><p>Activate Libraries</p></li>
<li><p>Load dataset</p></li>
</ul>
</li>
<li><p>Different Approaches to Reduce Overfitting</p></li>
<li><p>Training, Validation, and Test data</p></li>
<li><p>Types of Algorithms</p>
<ul>
<li><p>Supervised algorithms</p></li>
<li><p>Unsupervised algorithms</p></li>
</ul>
</li>
<li><p>Popular Algorithms:</p>
<ul>
<li><p>k-Nearest Neighbors</p></li>
<li><p>Popular Algorithms: CART</p></li>
<li><p>Random Forest</p></li>
</ul>
</li>
<li><p>Analyze a Real Data and Assessing the Model Accuracy</p></li>
</ul>
</section>
<section id="what-is-machine-learning">
<h2>1. What is Machine Learning?<a class="headerlink" href="#what-is-machine-learning" title="Permalink to this heading">#</a></h2>
<ul class="simple">
<li><p>Machine learning (ML) is the process by which a computer solves a task that it was not explicitly programmed to do. In Machine Learning algorithm statistical methodologies are combined with computer science technologies to train algorithms to learn the pattern in the training data and apply them onto an untrained dataset. For example we can use ML techniques to:</p></li>
</ul>
<blockquote>
<div><p>Predict a classification for a new image <br>
Identify an email as spam <br>
Forecast storm movement <br></p>
</div></blockquote>
<ul class="simple">
<li><p>Machine learning is a subset of artificial intelligence (AI).</p></li>
<li><p>Artificial intelligence is a computer’s ability to “learn” and make decisions.</p></li>
</ul>
<p>References: <a href="https://github.com/ageron/handson-ml" target="_blank">More information can be found here</a>.</p>
<section id="general-characteristics">
<h3>1.1. General Characteristics:<a class="headerlink" href="#general-characteristics" title="Permalink to this heading">#</a></h3>
<ul class="simple">
<li><p>Prioritizes predictive accuracy</p></li>
<li><p>Less focus on inference/hypothesis testing</p></li>
<li><p>Handles big-data:</p>
<ul>
<li><p>Large number of observations? <br></p></li>
<li><p>Large number of independent variables?</p></li>
</ul>
</li>
</ul>
</section>
<section id="terminologies">
<h3>1.2.Terminologies:<a class="headerlink" href="#terminologies" title="Permalink to this heading">#</a></h3>
<ul class="simple">
<li><p>Independent variables:</p>
<ul>
<li><p>Attribute</p></li>
<li><p>Feature</p></li>
<li><p>Predictor</p></li>
<li><p>Field</p></li>
</ul>
</li>
<li><p>Outcome or Result or Predicted Values</p></li>
<li><p>Error Estimate: Mean squared error (MSE) (in Statistics)</p>
<ul>
<li><p>Loss Function</p></li>
</ul>
</li>
<li><p>Dimensionality</p></li>
</ul>
</section>
</section>
<section id="why-use-ml-in-remote-sensing-gis">
<h2>2. Why Use ML in Remote Sensing/GIS?<a class="headerlink" href="#why-use-ml-in-remote-sensing-gis" title="Permalink to this heading">#</a></h2>
<p>In spatial analysis, ML is a popular component and the algorithm is applied on geoprocessing tools.</p>
<ol class="arabic simple">
<li><p>Classification <span class="math notranslate nohighlight">\(\Rightarrow\)</span> create land-cover classification layer</p></li>
<li><p>Clustering <span class="math notranslate nohighlight">\(\Rightarrow\)</span> process a large data and identify probable clusters</p></li>
<li><p>Prediction <span class="math notranslate nohighlight">\(\Rightarrow\)</span> predictive modelling through weighted regression</p></li>
</ol>
<p>Reference: <a href="https://www.esri.com/about/newsroom/arcwatch/where-deep-learning-meets-gis/" target="_blank">More information can be found here</a>.</p>
<p>Further, many other interesting tasks require (or benefit from) machine learning:</p>
<ul class="simple">
<li><p>Imputing missing information</p></li>
<li><p>Transforming spectral information</p></li>
<li><p>Masking clouds</p></li>
<li><p>Forecasting crop growth</p></li>
<li><p>ML models can scale in a way that humans cannot</p></li>
</ul>
</section>
<section id="scikit-learn">
<h2>3. scikit-learn<a class="headerlink" href="#scikit-learn" title="Permalink to this heading">#</a></h2>
<ul class="simple">
<li><p>Arguably the most popular language for ML</p></li>
<li><p>By the far the most popular module is scikit-learn</p></li>
<li><p>So popular that it comes prepackaged with Anaconda!</p></li>
<li><p>scikit-learn is built on top of NumPy, SciPy, and matplotlib</p></li>
<li><p>Open source with a very active community</p></li>
<li><p>Tons of tools and algorithms ready to go</p></li>
<li><p>Built-in sample datasets to practice and explore!</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">sklearn</span></code> is an alias for scikit-learn.</p></li>
</ul>
<p><strong>References:</strong></p>
<ul class="simple">
<li><p><a href= "https://machinelearningmastery.com/a-gentle-introduction-to-scikit-learn-a-python-machine-learning-library/"> A brief history, basic functionality and quick learining references can be found on this site.</a></p></li>
<li><p><a href ="https://www.digitalocean.com/community/tutorials/how-to-build-a-machine-learning-classifier-in-python-with-scikit-learn"> Read this webpage for learing to build a ML Classifier in Python with Scikit-learn</a></p></li>
<li><p><a href= "https://scikit-learn.org/stable/index.html"> Detail guidelines of main features of scikit-learn can be found on this site. </a></p></li>
</ul>
<p><img alt="sci-kit.PNG" src="_images/sklearn.png" /></p>
</section>
<section id="setup-the-environment">
<h2>4. Setup the Environment<a class="headerlink" href="#setup-the-environment" title="Permalink to this heading">#</a></h2>
<p>Prepare your Notebook to apply main features of sci-kit learn.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># load here or from Command Prompt</span>
<span class="o">!</span>pip install -U scikit-learn
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Requirement already satisfied: scikit-learn in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (1.3.0)
</pre></div>
</div>
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Requirement already satisfied: numpy>=1.17.3 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from scikit-learn) (1.24.2)
Requirement already satisfied: scipy>=1.5.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from scikit-learn) (1.11.2)
Requirement already satisfied: joblib>=1.1.1 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from scikit-learn) (1.3.2)
Requirement already satisfied: threadpoolctl>=2.0.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from scikit-learn) (3.2.0)
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Load Libraries</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="kn">import</span> <span class="nn">sklearn</span>
<span class="kn">import</span> <span class="nn">rasterio</span>
</pre></div>
</div>
</div>
</div>
<section id="the-famous-iris-dataset">
<h3>4.1. The Famous Iris Dataset<a class="headerlink" href="#the-famous-iris-dataset" title="Permalink to this heading">#</a></h3>
<ul class="simple">
<li><p>One of the most famous datasets in ML.</p></li>
<li><p>Empirical measurements of 150 iris flowers.</p></li>
<li><p>Features:</p></li>
</ul>
<blockquote>
<div><p>petal length <br>
petal width <br>
sepal length <br>
sepal width <br></p>
</div></blockquote>
<ul class="simple">
<li><p>Target:</p></li>
</ul>
<blockquote>
<div><p>Can we predict its species?</p>
</div></blockquote>
<ul class="simple">
<li><p>It’s essential to familiarize ourselves with the data before diving into analysis or modeling. Take some time to explore its structure, contents, and nuances.</p></li>
<li><p>Upon initial observation, you’ll notice that the data predominantly resembles numpy arrays.</p></li>
</ul>
<img src="https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Machine+Learning+R/iris-machinelearning.png">
<p>Reference: <a class="reference external" href="http://www.lac.inpe.br/~rafael.santos/Docs/CAP394/WholeStory-Iris.html">http://www.lac.inpe.br/~rafael.santos/Docs/CAP394/WholeStory-Iris.html</a></p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Load iris data</span>
<span class="kn">from</span> <span class="nn">sklearn.datasets</span> <span class="kn">import</span> <span class="n">load_iris</span> <span class="c1"># import the dataset</span>
<span class="n">iris_dataset</span> <span class="o">=</span> <span class="n">load_iris</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
</section>
<section id="objects-in-the-iris-data">
<h3>4.2. Objects in the Iris Data<a class="headerlink" href="#objects-in-the-iris-data" title="Permalink to this heading">#</a></h3>
<p><strong>Keys</strong> – all the different aspects of our dataset that we can call.<br>
<strong>Feature_names</strong> – the names of the measurements that we will use to try to predict classification.<br>
<strong>Data</strong> – the actual measurements from feature_names. Does not include the targets!<br>
<strong>Target</strong> – the classifications we are trying to predict.</p>
<p><strong>View the different attributes (or keys) of our dataset object:</strong></p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="s2">"attributes of iris_dataset: </span><span class="se">\n</span><span class="s2">"</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">iris_dataset</span><span class="o">.</span><span class="n">keys</span><span class="p">()))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>attributes of iris_dataset:
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename', 'data_module'])
</pre></div>
</div>
</div>
</div>
<p><strong>View the different features (attributes or characteristics):</strong></p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="s2">"features: </span><span class="se">\n</span><span class="s2">"</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">iris_dataset</span><span class="o">.</span><span class="n">feature_names</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>features:
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
</pre></div>
</div>
</div>
</div>
<p><strong>View the names of the <em>target classes</em> in the dataset:</strong></p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="s2">"targets: </span><span class="se">\n</span><span class="s2">"</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">iris_dataset</span><span class="o">.</span><span class="n">target_names</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>targets:
['setosa' 'versicolor' 'virginica']
</pre></div>
</div>
</div>
</div>
<p><strong>View the shape (dimensions) of the dataset’s main data: this will give the number of samples (flowers) and the number of features (measurements).</strong></p>
<ul class="simple">
<li><p>The <code class="docutils literal notranslate"><span class="pre">.shape</span></code> attribute is a tuple indicating the dimensions of a numpy array.</p></li>
</ul>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="s2">"dataset dimensions: </span><span class="se">\n</span><span class="s2">"</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">iris_dataset</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">shape</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>dataset dimensions:
(150, 4)
</pre></div>
</div>
</div>
</div>
<p><strong>View the shape (dimensions) of the target data.</strong></p>
<ul class="simple">
<li><p>The <em>target data</em> usually has one dimension, indicating the number of samples.</p></li>
</ul>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="s2">"target data dimensions: </span><span class="se">\n</span><span class="s2">"</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">iris_dataset</span><span class="o">.</span><span class="n">target</span><span class="o">.</span><span class="n">shape</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>target data dimensions:
(150,)
</pre></div>
</div>
</div>
</div>
<p><strong>Have a look at the some of the data and the keys:</strong></p>
<ul class="simple">
<li><p>select the first 10 rows and all columns (4 measurements:) of the data:</p></li>
</ul>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="n">iris_dataset</span><span class="o">.</span><span class="n">data</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="mi">10</span><span class="p">,</span> <span class="p">:])</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[[5.1 3.5 1.4 0.2]
[4.9 3. 1.4 0.2]
[4.7 3.2 1.3 0.2]
[4.6 3.1 1.5 0.2]
[5. 3.6 1.4 0.2]
[5.4 3.9 1.7 0.4]
[4.6 3.4 1.4 0.3]
[5. 3.4 1.5 0.2]
[4.4 2.9 1.4 0.2]
[4.9 3.1 1.5 0.1]]
</pre></div>
</div>
</div>
</div>
<ul class="simple">
<li><p>prints the <strong>target values (species labels)</strong> for the first 10 flowers in the dataset: in the context of the Iris dataset, this would typically show all <code class="docutils literal notranslate"><span class="pre">setosa</span></code> since the dataset is ordered by species.</p></li>
</ul>
<blockquote>
<div><p>“0” typically corresponds to the species ‘setosa’.<br>
“1” would correspond to ‘versicolor’.<br>
“2” would correspond to ‘virginica’.<br></p>
</div></blockquote>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="n">iris_dataset</span><span class="o">.</span><span class="n">target</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="mi">10</span><span class="p">])</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[0 0 0 0 0 0 0 0 0 0]
</pre></div>
</div>
</div>
</div>
</section>
<section id="overfitting-and-underfitting-models">
<h3>4.3. Overfitting and Underfitting Models<a class="headerlink" href="#overfitting-and-underfitting-models" title="Permalink to this heading">#</a></h3>
<div class="tip admonition">
<p class="admonition-title">Overfitting</p>
<p>Overfitting is one of the most common pitfalls in machine learning. When a model is overfitted, it means it has <strong>learned the training data exceptionally well</strong>, including its noise and outliers, to the point where it <strong>performs poorly on new, unseen data.</strong></p>
</div>
<blockquote>
<p><strong>Characteristics of Overfitting:</strong></p>
<ul class="simple">
<li><p>The model performs exceptionally well on the training data: might pass through almost <strong>every</strong> single data point, including any noise or anomalies.</p></li>
<li><p>The model performs poorly on the test data or new, unseen data.</p></li>
<li><p>The model is too complex, with too many parameters (a high-degree polynomial).</p></li>
</ul>
</blockquote><div class="tip admonition">
<p class="admonition-title">Underfitting</p>
<p>Underfitting occurs when a machine learning model is <strong>too simplistic to capture the underlying structure or pattern of the data</strong>.</p>
</div>
<blockquote>
<p><strong>Characteristics of Underfitting:</strong></p>
<ul class="simple">
<li><p>The model performs poorly on both the training data and the test data.</p></li>
<li><p>The model is too simple, might not have enough parameters.</p></li>
<li><p>Eg: a linear model, which can only produce straight lines, is too simplistic to capture the sinusoidal nature of a sine curve.</p></li>
</ul>
</blockquote><div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Generate sample data based on a sine curve</span>
<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># set seed for reproductivity</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="mi">2</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">pi</span> <span class="o">*</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">rand</span><span class="p">(</span><span class="mi">80</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># Generating data points between [0, 2π]</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sin</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">ravel</span><span class="p">()</span> <span class="o">+</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">normal</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="c1"># sine curve with added noise</span>
<span class="c1"># Overfitting model (using KNeighborsRegressor with n_neighbors=1)</span>
<span class="kn">from</span> <span class="nn">sklearn.neighbors</span> <span class="kn">import</span> <span class="n">KNeighborsRegressor</span>
<span class="n">model1</span> <span class="o">=</span> <span class="n">KNeighborsRegressor</span><span class="p">(</span><span class="n">n_neighbors</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="c1"># Underfitting model (fit a linear regression model)</span>
<span class="kn">from</span> <span class="nn">sklearn.linear_model</span> <span class="kn">import</span> <span class="n">LinearRegression</span>
<span class="n">model2</span> <span class="o">=</span> <span class="n">LinearRegression</span><span class="p">()</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="c1"># Plot</span>
<span class="n">plt</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">color</span><span class="o">=</span><span class="s1">'black'</span><span class="p">,</span> <span class="n">s</span><span class="o">=</span><span class="mi">30</span><span class="p">,</span> <span class="n">marker</span><span class="o">=</span><span class="s1">'o'</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s2">"training points"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">model1</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">x</span><span class="p">),</span> <span class="n">color</span><span class="o">=</span><span class="s1">'red'</span><span class="p">,</span> <span class="n">linewidth</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s2">"model1: Overfitting"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">model2</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">x</span><span class="p">),</span> <span class="n">color</span><span class="o">=</span><span class="s1">'green'</span><span class="p">,</span> <span class="n">linewidth</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s2">"model2: Underfitting"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">legend</span><span class="p">(</span><span class="n">loc</span><span class="o">=</span><span class="s1">'upper right'</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s2">"x"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s2">"y"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="_images/13d914537a7abc4c6e150a80640403d75e52d09f71873aa4f61c7191e4e400ed.png" src="_images/13d914537a7abc4c6e150a80640403d75e52d09f71873aa4f61c7191e4e400ed.png" />
</div>
</div>
<p><strong>Questions to Consider:</strong></p>
<blockquote>
<div><p>Which model would be more successful at predicting new, “unseen” data? <br>
Red (model 1) or green (model 2)?</p>
</div></blockquote>
<p>The plot aims to demonstrate two different models and how they relate to the training data, illustrating the concepts of overfitting, underfitting.</p>
<ul class="simple">
<li><p>Black points are measured data: they seem to follow a pattern but have some random noise associated.</p></li>
</ul>
<p>Let’s pretend I created two different ML models, red and green, and their predictions are shown here. If we added more data to the right, which of these two models would be more successful at getting the trend correct?</p>
<ul class="simple">
<li><p>Model1: Overfitting:<br>
This model is represented by the red line. It’s an instance of extreme overfitting. Since it tries to pass through every training point, it also captures the noise, which is not ideal. <br>
In a real-world scenario, this model would likely perform poorly on new, unseen data because it’s too closely tailored to the training data. <br>
For unseen data points that fall very close to the original training data, the predictions might be reasonable. However, for data points that fall between two training points or outside the range of the training data, the predictions can be erratic. Since the model is influenced heavily by noise, it might predict sharp jumps or falls where the actual function might be smooth. Additionally, if the new data points don’t contain the same noise as the training data, the overfit model’s predictions would be inaccurate.</p></li>
<li><p>Model2: Underfitting:<br>
Represented by the green line, this is a simple linear regression model. Given that the underlying data is based on a sine curve, a straight line is too simple to capture the data’s inherent patterns. Hence, the model underperforms both on training and, likely, on unseen data, fails to capture the underlying structure of the data.<br>
Given that this model is too simplistic, it would consistently predict values along a straight line regardless of the inputs. It won’t be able to capture the oscillating behavior of the sine curve.</p></li>
</ul>
<section id="different-approaches-to-reduce-overfitting">
<h4>4.3.1.Different Approaches to Reduce Overfitting<a class="headerlink" href="#different-approaches-to-reduce-overfitting" title="Permalink to this heading">#</a></h4>
<ul class="simple">
<li><p>Reduce the number of training epochs (aka ‘runs’)
<a class="reference external" href="https://towardsdatascience.com/epoch-vs-iterations-vs-batch-size-4dfb9c7ce9c9">Reference to learn epochs.</a></p></li>
<li><p>Limit the number of parameters</p></li>
<li><p>Penalize large values for fitting parameters (‘regularization’)</p>
<ul>
<li><p>Tends to smooth results</p></li>
</ul>
</li>
<li><p>Ensemble models</p>
<ul>
<li><p>Train many different models, then take the average of their predictions</p></li>
<li><p>Extremely common!</p></li>
</ul>
</li>
<li><p>Separate training, test, and validation data</p></li>
</ul>
</section>
<section id="different-approaches-to-reduce-underfitting">
<h4>4.3.2. Different Approaches to Reduce Underfitting<a class="headerlink" href="#different-approaches-to-reduce-underfitting" title="Permalink to this heading">#</a></h4>
<ul class="simple">
<li><p>Increase Model Complexity:</p>
<ul>
<li><p>Simple models are more likely to underfit. Adding complexity, like additional layers in neural networks or higher-degree features in polynomial regression, can help.</p></li>
</ul>
</li>
<li><p>Add More Features:</p>
<ul>
<li><p>Sometimes, the model might not have enough information to make accurate predictions. Consider engineering new features or using more available features.</p></li>
</ul>
</li>
<li><p>Reduce Regularization</p></li>
<li><p>Ensemble Methods</p></li>
<li><p>Cross-validation</p></li>
</ul>
<p><img alt="model_complexity.png" src="_images/model_complexity.png" /></p>
<p><a class="reference external" href="https://towardsai.net/p/machine-learning/underfitting-overfitting%E2%80%8A-%E2%80%8Athe-thwarts-of-machine-learning-models%E2%80%8Baccuracy">Figure Reference</a></p>
<ul class="simple">
<li><p>Rare to see models that are NOT ensembled!</p></li>
<li><p>It’s crucial to continuously monitor and diagnose model performance.</p></li>
<li><p>Identifying underfitting early on can save valuable resources and guide you to adjust the model or training process accordingly.</p></li>
<li><p>We don’t want to get too far into this though, so we’ll just focus on the most inescapable: our dataset.</p></li>
<li><p>Very important to consider overtraining whenever you do any ML task.</p></li>
</ul>
<p><a class="reference external" href="https://medium.com/@itbodhi/overfitting-and-underfitting-in-machine-learning-models-76cb60dbdaf6">Reference on overfirrintg and underfitting</a></p>
<p>The figure above is a typical visualization in machine learning called the <strong>“Bias-Variance Tradeoff” or “Model Complexity vs. Generalization Error” curve</strong>.</p>
<p>The plot typically shows the relationship between the <strong>complexity of a model</strong> (e.g., depth of a decision tree, degree of a polynomial in regression) and its performance on both training data and validation/test data.</p>
<ul class="simple">
<li><p>Training Error is the error that you get when you test your model on the data that you trained on. It represents how well the model has learned the training data.</p></li>
<li><p>Generalization Error is the error that you get when you test your model on new, <strong>unseen</strong> data. It represents how well the model can generalize its knowledge from the training data to new data.</p></li>
</ul>
<p>In this figure:</p>
<blockquote>
<div><p>Underfitting: When the model is too simple, it may not capture the underlying patterns in the data. This leads to poor performance on both training and test datasets. This is the left side of the plot.<br></p>
</div></blockquote>
<blockquote>
<div><p>Overfitting: If the model becomes too complex, it might start to fit the noise in the training data, thinking it’s a pattern. While it will have a very high accuracy on the training data, its performance on unseen (test) data will decrease. This is the right side of the plot.<br></p>
</div></blockquote>
<blockquote>
<div><p>Sweet Spot: As the model becomes more complex, its performance on the training data improves. More importantly, its performance on the test data also improves, but only up to a certain point. This point, where the test performance is optimal, is often called the “sweet spot” because it represents a good balance between bias (error due to overly simplistic models) and variance (error due to overly complex models that are too sensitive to the training data).</p>
</div></blockquote>
</section>
</section>
<section id="training-validation-and-test-data">
<h3>4.4. Training, Validation, and Test data<a class="headerlink" href="#training-validation-and-test-data" title="Permalink to this heading">#</a></h3>
<ol class="arabic simple">
<li><p><strong>Training data</strong>: the data that your model uses to “learn”.</p></li>
<li><p><strong>Validation data</strong>: “unseen” data points that are used to assess how well the model learned</p>
<ul class="simple">
<li><p>We consider models that are more successful at predicting the test data to be more predictive, i.e. “better”</p></li>
<li><p>Used repeatedly during training to assess the model fit</p></li>
</ul>
</li>
<li><p><strong>Test data</strong>: additional “unseen” data that is used to assess the final model</p>
<ul class="simple">
<li><p>These are held out until the very, very end</p></li>
</ul>
</li>
</ol>
<p><a class="reference external" href="https://towardsdatascience.com/train-validation-and-test-sets-72cb40cba9e7">Reference on training, test and validation data.</a>
<br>
<br>
Sometimes we just have two sets of data. In this case, there is no difference between the test and the validation. In that case, we usually just call it test data. Mostly only separate validation and test data when we are bootstrapping and ensembling models.</p>
<ul class="simple">
<li><p>Test and validation data only need to be separated during more advanced techniques!</p></li>
<li><p>We will not distinguish between test and validation data here.</p></li>
</ul>
<section id="separate-iris-data-into-train-and-test-data">
<h4>4.4.1. Separate Iris Data into Train and Test Data<a class="headerlink" href="#separate-iris-data-into-train-and-test-data" title="Permalink to this heading">#</a></h4>
<p>Set aside some of the data for training and some for testing.
<br>
This code demonstrates how to split the iris dataset into <code class="docutils literal notranslate"><span class="pre">training</span></code> and <code class="docutils literal notranslate"><span class="pre">testing</span></code> sets using the <code class="docutils literal notranslate"><span class="pre">train_test_split</span> <span class="pre">function</span></code> from <code class="docutils literal notranslate"><span class="pre">sklearn</span> <span class="pre">module</span></code>. The training set will be used to train a machine learning model, while the testing set will be used to evaluate the model’s performance on data it hasn’t seen during training.</p>
<ul class="simple">
<li><p>By default, this function splits the data in a 75% (training) to 25% (testing) ratio.</p></li>
</ul>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sklearn</span> <span class="kn">import</span> <span class="n">model_selection</span>
<span class="c1"># x represents the features that we have (petal and sepal characteristics)</span>
<span class="c1"># y represents the targets that we are trying to predict</span>
<span class="c1"># train_test_split separates the data into matching test and train sets</span>
<span class="n">x_train</span><span class="p">,</span> <span class="n">x_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">model_selection</span><span class="o">.</span><span class="n">train_test_split</span><span class="p">(</span><span class="n">iris_dataset</span><span class="o">.</span><span class="n">data</span><span class="p">,</span> <span class="n">iris_dataset</span><span class="o">.</span><span class="n">target</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span><span class="p">(</span><span class="s2">"x_train dimensions:"</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">x_train</span><span class="o">.</span><span class="n">shape</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"x_test dimensions: "</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">x_test</span><span class="o">.</span><span class="n">shape</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"y_train dimensions: "</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">y_train</span><span class="o">.</span><span class="n">shape</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"y_test dimensions: "</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">y_test</span><span class="o">.</span><span class="n">shape</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>x_train dimensions:(112, 4)
x_test dimensions: (38, 4)
y_train dimensions: (112,)
y_test dimensions: (38,)
</pre></div>
</div>
</div>
</div>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">iris_dataset.data</span></code>: contains the features (e.g., petal and sepal lengths and widths) of the iris dataset.</p></li>
</ul>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">iris_dataset</span><span class="o">.</span><span class="n">data</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>array([[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
[4.6, 3.1, 1.5, 0.2],
[5. , 3.6, 1.4, 0.2],
[5.4, 3.9, 1.7, 0.4],
[4.6, 3.4, 1.4, 0.3],
[5. , 3.4, 1.5, 0.2],
[4.4, 2.9, 1.4, 0.2],
[4.9, 3.1, 1.5, 0.1],
[5.4, 3.7, 1.5, 0.2],
[4.8, 3.4, 1.6, 0.2],
[4.8, 3. , 1.4, 0.1],
[4.3, 3. , 1.1, 0.1],
[5.8, 4. , 1.2, 0.2],
[5.7, 4.4, 1.5, 0.4],
[5.4, 3.9, 1.3, 0.4],
[5.1, 3.5, 1.4, 0.3],
[5.7, 3.8, 1.7, 0.3],
[5.1, 3.8, 1.5, 0.3],
[5.4, 3.4, 1.7, 0.2],
[5.1, 3.7, 1.5, 0.4],
[4.6, 3.6, 1. , 0.2],
[5.1, 3.3, 1.7, 0.5],
[4.8, 3.4, 1.9, 0.2],
[5. , 3. , 1.6, 0.2],
[5. , 3.4, 1.6, 0.4],
[5.2, 3.5, 1.5, 0.2],
[5.2, 3.4, 1.4, 0.2],
[4.7, 3.2, 1.6, 0.2],
[4.8, 3.1, 1.6, 0.2],
[5.4, 3.4, 1.5, 0.4],
[5.2, 4.1, 1.5, 0.1],
[5.5, 4.2, 1.4, 0.2],
[4.9, 3.1, 1.5, 0.2],