-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.Rmd
1599 lines (980 loc) · 32.4 KB
/
index.Rmd
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
---
title: "Machine Learning 101"
subtitle: "Supervised Learning in R"
author: "<br><br>Sarah Romanes `r anicon::faa('twitter', animate='float', rtext=' @sarah_romanes')`"
date: "<br>10-Oct-2018<br><br>`r anicon::faa('link', animate='vertical', rtext=' bit.ly/rladies-sydney-ML-1', color='white')`"
output:
xaringan::moon_reader:
lib_dir: libs
css: ["kunoichi", "ninjutsu", "assets/custom.css"]
seal: true
self_contained: false
nature:
ratio: "16:9"
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
options(htmltools.dir.version = FALSE)
library(ggplot2)
library(plotly)
library(dplyr)
livedemosign <- function(top, left, deg) {
htmltools::div("Live Demo!", class="faa-flash animated",
style=glue::glue("border:solid; border-color:black; position:absolute; top:{top}%; left:{left}%; font-size:36px; padding:4px; background-color:white; color:black;transform:rotate({deg}deg);")
)
}
```
layout: false
class: bg-main3 split-30 hide-slide-number
.column[
]
.column.slide-in-right[.content.vmiddle[
.sliderbox.shade_main.pad1[
.font5[Welcome!]
]
]]
---
class: split-two white
.column.bg-main1[.content.vmiddle.center[
# Overview
<br>
### This two part R-Ladies workshop is designed to give you a small taster into the large field that is known as .orange[**Machine Learning**]! Today, we will cover supervised learning techniques (explained later), and next week we will cover model performance assessment.
<br>
### For a more indepth explanation of topics covered, please read the *free* Introduction to Statistical Learning textbook (James, Witten, Hastie, and Tibshirani) [here](http://www-bcf.usc.edu/~gareth/ISL/).
]]
.column.bg-main3[.content.vmiddle.center[
<center>
<img src="images/ISLR.jpg", width="70%">
]]
---
class: middle center bg-main1
<img src="images/mlmeme.jpg", width="70%">
---
# .purple[What *is* Machine Learning?]
<br>
### Machine learning is concerned with finding functions $Y=f(X)+\epsilon$ that best **predict** outputs (responses), given data inputs (predictors).
<br>
<center>
<img src="images/ml-process.png", width="50%">
</center>
<br>
### Mathematically, Machine Learning problems are simply *optimisation* problems, in which we will use .purple[`r icon::fa("r-project", size=1)`] to help us solve!
---
# .purple[Why do Machine Learning in `r icon::fa("r-project", size=1)`?]
<br>
<center>
<img src="images/python-r-other-2016-2017.jpg", width="70%">
</center>
---
class: split-two white
.column.bg-main1[.content[
<br>
# Types of Learning
<br>
## .orange[Supervised Learning]
### - We have knowledge of class labels or values.
### - Goal: train a model using known class labels to predict class or value label for a new data point.
## .orange[Unsupervised Learning]
### - No knowledge of output class or value –data is unlabelled.
### - Goal: determine data patterns/groupings.
]]
.column[.content.vmiddle.center[
<img src="images/learning.png", width="80%">
##### .purple[Credit to Towards Data Science]
]]
---
layout: false
class: bg-main3 split-30 hide-slide-number
.column[
]
.column.slide-in-right[.content.vmiddle[
.sliderbox.shade_main.pad1[
.font5[Regression]
]
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# A simple prediction problem
### Consider the simulated dataset `Income`, which looks at the relationship between `Education` (years) and `Income` (thousands).
```{r}
data <- read.csv("data/Income.csv")
head(data)
```
### What shape is the relationship? Can we build a function to predict the value of a new data point?
]]
.column[.content.vmiddle.center[
```{r, fig.retina=4, echo=FALSE}
ggplot(data, aes(x=Education, y=Income))+geom_point(size=3, color="red") + theme(text = element_text(size=20))
```
]]
---
class: middle center bg-main1
## Linear Regression to the Rescue!
<img src="images/ols.png", width="70%">
---
class: pink-code
# .purple[What line is optimal?]
<br>
### We can use a .purple[**linear function**] to describe our data and .purple[**predict**] a new data point. The question is, what is the .purple[*optimal line*] ?
--
### One way to do this is find the slope and intercept that .purple[*minimise*] the sum of the squared residuals between the line and our data points:
<center>
<img src="images/rss.png", width="25%">
</center>
### We can visualise this optimisation process using a .purple[**Shiny App**] [here](http://43.240.99.178:3838/sample-apps/LinearRegression/).
--
### .purple[`r icon::fa("r-project", size=1)`] performs this optimisation process for us when we call the `lm` function.
###### (PS) see an alternative derivation [here](https://sarahromanes.github.io/post/gganimate/)!
---
class: split-60 white
.column.bg-main1[.content[
# We can fit a linear model in `r icon::fa("r-project", size=1)` using the `lm` function as follows:
<br>
```{r, echo=F}
data <- read.csv("data/Income.csv")
```
```{r, eval=F}
fit <- lm(data=data, #<<
Income ~ Education)
```
]]
.column.bg-main3[.content.vmiddle.center[
# This tells the `lm` function what data we are referring to.
]]
---
class: split-60 white
.column.bg-main1[.content[
# We can fit a linear model in `r icon::fa("r-project", size=1)` using the `lm` function as follows:
<br>
```{r, eval=F}
fit <- lm(data=data,
Income ~ Education) #<<
```
]]
.column.bg-main3[.content.vmiddle.center[
## This tells the `lm` function what variables we would like to regress.
### R expects the relationship in the form of `response~predictors`.
]]
---
class: split-60 white
.column.bg-main1[.content[
# We can fit a linear model in `r icon::fa("r-project", size=1)` using the `lm` function as follows:
```{r, eval=F}
fit <- lm(data=data,
Income ~ Education)
summary(fit) #<<
```
```{r, eval=F}
Call:
lm(formula = Income ~ Education, data = data)
Residuals:
Min 1Q Median 3Q Max
-13.046 -2.293 0.472 3.288 10.110
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -39.4463 4.7248 -8.349 4.4e-09 *** #<<
Education 5.5995 0.2882 19.431 < 2e-16 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 5.653 on 28 degrees of freedom
Multiple R-squared: 0.931, Adjusted R-squared: 0.9285
F-statistic: 377.6 on 1 and 28 DF, p-value: < 2.2e-16
```
]]
.column.bg-main3[.content.vmiddle.center[
## We can use the `summary` function to examine regression coefficients, and information about the residuals of our model.
]]
---
class: split-60 white
.column.bg-main1[.content[
# We can fit a linear model in `r icon::fa("r-project", size=1)` using the `lm` function as follows:
```{r, eval=F}
fit <- lm(data=data,
Income ~ Education)
summary(fit) #<<
```
```{r, eval=F}
Call:
lm(formula = Income ~ Education, data = data)
Residuals:
Min 1Q Median 3Q Max
-13.046 -2.293 0.472 3.288 10.110
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -39.4463 4.7248 -8.349 4.4e-09 ***
Education 5.5995 0.2882 19.431 < 2e-16 *** #<<
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 5.653 on 28 degrees of freedom
Multiple R-squared: 0.931, Adjusted R-squared: 0.9285
F-statistic: 377.6 on 1 and 28 DF, p-value: < 2.2e-16
```
]]
.column.bg-main3[.content.vmiddle.center[
## We can use the `summary` function to examine regression coefficients, and information about the residuals of our model.
]]
---
class: split-60 white
.column.bg-main1[.content[
# We can fit a linear model in `r icon::fa("r-project", size=1)` using the `lm` function as follows:
```{r, eval=T}
fit <- lm(data=data,
Income ~ Education)
New_Data <- data.frame(Education = c(15, 18))
predict(fit, New_Data) #<<
```
]]
.column.bg-main3[.content.vmiddle.center[
## Using the `predict` function, we can predict the `Income` of a new `Education` value (or values).
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# Modelling Binary Outcomes
<br>
### Consider the dataset `Spiders`, Suzuki et al. (2006) , from a study which looked at the relationship between `GrainSize` of sand and `Spiders` presence.
```{r}
data <- read.csv("data/Spiders.csv")
head(data,3)
```
### Can we use `lm` to predict the class for a new data point?
]]
.column[.content.vmiddle.center[
```{r, fig.retina=4, echo=FALSE}
ggplot(data, aes(x=GrainSize, y=Spiders))+geom_point(size=3, color="red")+ theme(text = element_text(size=20))
```
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
## To model **binary data**, we need to .orange[link] our **predictors** to our response using a *link function*.
<br>
### Instead of predicting the outcome directly, we instead predict the probability of being class 1, given the linear combination of predictors, as follows:
$$ p(y=1|\\beta_0 + \\beta_1 x) = \\sigma(\\beta_0 + \\beta_1 x) $$
For the logistic (`logit`) link
$$ p(y=1|\\beta_0 + \\beta_1 x) = \\frac{1}{1+ \\exp( - (\\beta_0 + \\beta_1 x))} $$
For the probit (`probit`) link
$$ p(y=1|\\beta_0 + \\beta_1 x) = \\Phi(\\beta_0 + \\beta_1 x) $$
]]
.column.white[.content.vmiddle.center[
```{r, echo=FALSE, fig.retina=4, warning=F, message=F}
x.vals <- rep(seq(-10,10, by=0.1),2)
fit.1 <- 1/(1+exp(-x.vals))
fit.2 <- pnorm(x.vals)
fit <- c(fit.1,fit.2)
Link <- c(rep("logistic", length(x.vals)),rep("probit", length(x.vals)))
library(latex2exp)
data <- data.frame(x=x.vals, y=fit, Link=Link)
ggplot(data, aes(x=x, y=y, color=Link))+geom_line(size=1.4) + xlab(TeX('$\\beta_0 + \\beta_1 x$')) + ylab(TeX('$p(y=1|\\beta_0 + \\beta_1 x) = Link(\\beta_0 + \\beta_1 x)$')) + theme(text = element_text(size=20))
```
]]
---
class: split-60 white
.column.bg-main1[.content[
# We can fit a glm in `r icon::fa("r-project", size=1)` using the `glm` function as follows:
<br>
```{r, eval=F}
fit <- glm(data=data, #<<
Spiders~GrainSize,
family=binomial(link="logit"))
```
]]
.column.bg-main3[.content.vmiddle.center[
# This tells the `glm` function what data we are referring to.
]]
---
class: split-60 white
.column.bg-main1[.content[
# We can fit a glm in `r icon::fa("r-project", size=1)` using the `glm` function as follows:
<br>
```{r, eval=F}
fit <- glm(data=data,
Spiders~GrainSize, #<<
family=binomial(link="logit"))
```
]]
.column.bg-main3[.content.vmiddle.center[
## This tells the `glm` function what variables we would like to regress.
### Just like the `lm` function, R expects the relationship in the form of `response~predictors`.
]]
---
class: split-60 white
.column.bg-main1[.content[
# We can fit a glm in `r icon::fa("r-project", size=1)` using the `glm` function as follows:
<br>
```{r, eval=F}
fit <- glm(data=data,
Spiders~GrainSize,
family=binomial(link="logit")) #<<
```
<center>
OR
</center>
```{r, eval=F}
fit <- glm(data=data,
Spiders~GrainSize,
family=binomial(link="probit")) #<<
```
<center>
OR
</center>
```{r, eval=F}
fit <- glm(data=data,
Spiders~GrainSize,
family=binomial(link="cloglog")) #<<
```
<center>
and more...
</center>
]]
.column.bg-main3[.content.vmiddle.center[
## This tells the `glm` function how we would like to model our response. For **binary** response data, we use the `binomial` family.
## Further, there are many ways we can link our linear combination of predictors to the 0,1 space.
]]
---
class: split-60 white
.column.bg-main1[.content[
# We can fit a glm in `r icon::fa("r-project", size=1)` using the `glm` function as follows:
<br>
```{r, eval=F}
fit <- glm(data=data,
Spiders~GrainSize,
family=binomial(link="logit"))
summary(fit)
```
```{r, eval=F}
Call:
glm(formula = Spiders ~ GrainSize, family = binomial(link = "logit"),
data = data)
Deviance Residuals:
Min 1Q Median 3Q Max
-1.7406 -1.0781 0.4837 0.9809 1.2582
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -1.648 1.354 -1.217 0.2237 #<<
GrainSize 5.122 3.006 1.704 0.0884 . #<<
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
```
]]
.column.bg-main3[.content.vmiddle.center[
## Similar to the `lm` function, we can use the `summary` function to examine regression coefficients.
]]
---
class: split-60 white
.column.bg-main1[.content[
# We can fit a glm in `r icon::fa("r-project", size=1)` using the `glm` function as follows:
<br>
```{r, echo=F}
data <- read.csv("data/Spiders.csv")
```
```{r, eval=T}
fit <- glm(data=data,
Spiders~GrainSize,
family=binomial(link="logit"))
New_Data <- data.frame(GrainSize = c(0.4, 0.87))
probs <- predict(fit, New_Data,type="response") #<<
probs
round(probs) #<<
```
]]
.column.bg-main3[.content.vmiddle.center[
## And we can also use the `predict` function to estimate class membership probability, as well as use the `round` command to estimate class.
]]
---
class: middle center bg-main1
## Of course, probabilities close to 0.5 are hard to classify!!
<img src="images/response.jpg", width="70%">
---
class: middle center bg-main1
`r anicon::faa('exclamation-triangle', animate='flash', size=7)`
# A warning for using GLMs!
---
class: split-two white
.column[.content[
```{r, fig.retina=4}
data.new <- read.csv("data/SpidersWarning.csv")
ggplot(data.new,
aes(x=GrainSize, y=Spiders)) +
geom_point(col="red", size=3)
```
]]
.column.bg-main3[.content.vmiddle.center[
## Suppose the scientist who collected their data thought the study would look more convincing if the data was **perfectly** sepatated, and sneakily modified their results. How would their glm look?
]]
---
class: split-60 white
.column[.content[
<br>
```{r}
fit <- glm(data=data.new,
Spiders~GrainSize,
family=binomial(link="logit"))
```
]]
.column.bg-main3[.content.vmiddle.center[
## Warnings appear when we try and fit this glm...
]]
---
class: split-60 white
.column[.content[
<br>
```{r, eval=T}
fit <- glm(data=data.new,
Spiders~GrainSize,
family=binomial(link="logit"))
```
```{r, eval=F}
summary(fit) #<<
```
```{r, eval=FALSE}
Call:
glm(formula = Spiders ~ GrainSize, family = binomial(link = "logit"),
data = data.new)
Deviance Residuals:
Min 1Q Median 3Q Max
-8.087e-05 -2.100e-08 -2.100e-08 2.100e-08 7.488e-05
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -912.4 362618.2 -0.003 0.998 #<<
GrainSize 1569.2 624478.6 0.003 0.998 #<<
```
]]
.column.bg-main3[.content.vmiddle.center[
## Warnings appear when we try and fit this glm...
## ...and, when we look at the `summary`, we can see our regression coefficients are blowing up, as well as the standard errors associated with them!
]]
---
class: middle center bg-main1
<img src="images/warning.jpg", width="70%">
---
class: split-two white
.column.bg-main1[.content[
<br>
# Multiple Regression
<br>
### Can we fit a model with more than one predictor? Of course we can! Consider the dataset `Exam`, where two exam scores are given for each student, and a Label represents whether they passed or failed the course.
```{r, fig.retina=4}
data<- read.csv("data/Exam.csv", header=T)
head(data,4)
```
]]
.column[.content.vmiddle.center[
```{r, fig.retina=4, echo=FALSE}
ggplot(data, aes(x=Exam1, y=Exam2, color=factor(Label)))+geom_point(size=4) + theme(text = element_text(size=20))
```
]]
---
class: split-60 white
.column.bg-main1[.content[
# We can fit the glm in `r icon::fa("r-project", size=1)` using the `glm` function as follows:
<br>
```{r, eval=F}
fit <- glm(data=data,
Label ~ ., #<<
family=binomial(link="logit"))
summary(fit)
```
```{r, eval=F}
Call:
glm(formula = Label ~ ., family = binomial(link = "logit"),
data = data)
Deviance Residuals:
Min 1Q Median 3Q Max
-2.19287 -0.18009 0.01577 0.19578 1.78527
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) -25.16133 5.79836 -4.339 1.43e-05 ***
Exam1 0.20623 0.04800 4.297 1.73e-05 ***
Exam2 0.20147 0.04862 4.144 3.42e-05 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
```
]]
.column.bg-main3[.content.vmiddle.center[
### The formula `Label ~ . ` tells the `glm` function to regress against all (two) predictors, `Exam1` and `Exam2`.
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# The Decision Boundary
<br>
### We can plot the **decision boundary** on our scatterplot for `Exam1` vs `Exam2` by looking at the set of points for which our classifier predicts $$p(y=1|\beta_0 + \beta_1 \text{Exam1} + \beta_2 \text{Exam2}) \geq 0.5$$
#### Given the `logit` link, this is true when
$$\beta_0 + \beta_1 \text{Exam1} + \beta_2 \text{Exam2} \geq 0$$
#### This is the **decision boundary** and can be rearranged as
$$ \text{Exam2} \geq \frac{-\beta_0}{\beta_2} + \frac{-\beta_1}{\beta_2} \text{Exam 1} $$
]]
.column[.content.vmiddle.center[
```{r, fig.retina=4, echo=FALSE}
fit <- glm(data=data,
Label ~ ., #<<
family=binomial(link="logit"))
slope <- coef(fit)[2]/(-coef(fit)[3])
intercept <- coef(fit)[1]/(-coef(fit)[3])
ggplot(data, aes(x=Exam1, y=Exam2, color=factor(Label)))+geom_point(size=4) + theme(text = element_text(size=20)) + geom_abline(slope=slope, intercept=intercept)
```
]]
---
layout: false
class: bg-main3 split-30 hide-slide-number
.column[
]
.column.slide-in-right[.content.vmiddle[
.sliderbox.shade_main.pad1[
.font5[Classification]
]
]]
---
class: middle center bg-main1
<img src="images/food.jpg", width="65%">
---
class: split-two white
.column.bg-main1[.content[
<br>
# When we can't use GLMs
<br>
### Consider the dataset `Microchips`, containing test scores `Test1` and `Test2`, and `Label` indicating whether or not the chip passed the test.
```{r, fig.retina=4}
data <- read.csv("data/Microchips.csv")
head(data,4)
```
### Why can't we use `glm` to predict the class for a new data point?
]]
.column[.content.vmiddle.center[
```{r, fig.retina=4, echo=FALSE}
ggplot(data, aes(x=Test1, y=Test2, color=factor(Label)))+geom_point(size=4) + theme(text = element_text(size=20))
```
]]
---
# .purple[Different data types require different machine learning methods]
<br>
## While we can indeed use Logistic regression to .purple[**classify**] data points, this simply isn't feasible when:
### - We have high class seperation in our data
### - We have a non-linear combination of predictors influcing our response (as in this case)
<br>
## .purple[**So, what other options do we have?**]
---
class: split-two white
.column.bg-main1[.content[
<br>
# The K-Nearest Neighbours Algorithm
<br>
## .orange[**K Nearest Neighbours (KNN)**] is a non-parametric algorithm (doesn't assume the data follows any particular shape).
<br>
## In KNN, we vote on the class of a new data point by looking at the majority class of the .orange[**K**] nearest neighbours.
]]
.column[.content.vmiddle.center[
<img src="images/knn2-Natasha-Latysheva.jpg", width="80%">
##### .purple[Credit to Natasha Latysheva]
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# KNN in `r icon::fa("r-project", size=1)`
<br>
```{r}
X <- data[,1:2]
cl <- as.factor(data[,3])
```
]]
.column.bg-main3[.content.vmiddle.center[
## First, we split our data into **predictors** (`X`), and response (`cl` for *class*),
]]
---
class: split-two white
.column.bg-main1[.content[
<br>
# KNN in `r icon::fa("r-project", size=1)`
<br>
### Next, we need to give the function new data points, as the `knn` function fits and predicts at the same time. We will use the `MASS` package to generate a grid of new points to predict the class of.
```{r, warning=FALSE, message=FALSE}
X <- data[,1:2]
cl <- as.factor(data[,3])
library(MASS)
new.X <- expand.grid(x=seq(min(X[,1]-0.5), max(X[,1]+0.5),#<<
by=0.1),#<<
y=seq(min(X[,2]-0.5), max(X[,2]+0.5), #<<
by=0.1)) #<<
```
]]
.column[.content.vmiddle.center[
```{r, fig.retina=4, echo=FALSE, warning=FALSE, message=FALSE}
require(class)
classif <- knn(X, new.X, cl, k = 3, prob=TRUE)
prob <- attr(classif, "prob")
dataf <- bind_rows(mutate(new.X,
prob=prob,
cls=1,
prob_cls=ifelse(classif==cls,
1, 0)),
mutate(new.X,
prob=prob,
cls=0,
prob_cls=ifelse(classif==cls,
1, 0)))
ggplot(dataf) +geom_point(aes(x=x, y=y), alpha=0.1)
```
]]