-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexecises-04.qmd
1375 lines (1000 loc) · 45.4 KB
/
execises-04.qmd
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
# 04 - Classification {.unnumbered}
<style>
h3, h4 {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0,0,0,0);
border: 0;
}
</style>
## Libraries
```{r}
library(ggplot2)
library(patchwork)
library(data.table)
library(tidymodels)
library(discrim)
library(klaR)
library(poissonreg)
```
## Custom functions
In this section I place the functions that were used in many code chunks across the chapter.
```{r}
rbind_list_name <- function(list.DT, new_col_name, ...){
stopifnot(is.list(list.DT))
stopifnot(all(sapply(list.DT, is.data.table)))
lapply(seq_along(list.DT),
function(tb_i){
list.DT[[tb_i]][, (new_col_name) := names(list.DT)[tb_i]] }) |>
rbindlist(...)
}
get_class_metrics <- metric_set(sens, spec)
get_class_matrix_metrics <- function(model,
split,
fit_formula,
metric_function = metric_set(sens, spec),
...){
testing_predictions <-
model |>
last_fit(as.formula(fit_formula), split = split) |>
collect_predictions()
truth_var <- sub(pattern = " *~.+$", replacement = "", x = fit_formula)
list(conf_mat = conf_mat(testing_predictions,
truth = !!truth_var,
estimate = .pred_class),
metrics = metric_function(testing_predictions,
truth = !!truth_var,
estimate = .pred_class,
...) )
}
model_knn_k <- function(k){
model <-
nearest_neighbor(neighbors = k) |>
set_mode("classification") |>
set_engine("kknn")
return(model)
}
ModelNaiveBayes <-
naive_Bayes() |>
set_mode("classification") |>
set_engine("klaR") |>
set_args(usekernel = FALSE)
evaluate_model <- function(model, recipe_list, split){
lapply(recipe_list, function(recipe, split){
workflow() |>
add_recipe(recipe) |>
add_model(model) |>
last_fit(split = split) |>
collect_metrics() |>
as.data.table() },
split = split) |>
rbind_list_name(new_col_name = "recipe")
}
```
## Conceptual
### 1
**1.** Using a little bit of algebra, prove that (4.2) is equivalent to (4.3). In other words, the logistic function representation and logit representation for the logistic regression model are equivalent.
$$
\begin{split}
p(X) &= \frac{e^{\beta_{0}+\beta_{1}X}}
{1+e^{\beta_{0}+\beta_{1}X}} \\
p(X) (1+e^{\beta_{0}+\beta_{1}X}) & = e^{\beta_{0}+\beta_{1}X} \\
p(X)+p(X) e^{\beta_{0}+\beta_{1}X} & = e^{\beta_{0}+\beta_{1}X} \\
p(X) & = e^{\beta_{0}+\beta_{1}X} - p(X) e^{\beta_{0}+\beta_{1}X} \\
p(X) & = (1 - p(X))e^{\beta_{0}+\beta_{1}X} \\
\frac{p(X)}{1 - p(X)} & = e^{\beta_{0}+\beta_{1}X}
\end{split}
$$
### 2
**2.** It was stated in the text that classifying an observation to the class for which (4.17) is largest is equivalent to classifying an observation to the class for which (4.18) is largest. Prove that this is the case. In other words, under the assumption that the observations in the *k*th class are drawn from a $N(\mu_k,\sigma^2)$ distribution, the Bayes classifier assigns an observation to the class for which the discriminant function is maximized.
- To prove that both functions would provide the same class we need to check that both functions change from one $Y$ class to other in the same $x$ value.
- If $K = 2$ and $\pi_1 = \pi_2 = \pi_c$ we can show that:
$$
\begin{split}
p_{1}(x) & = p_{2}(x) \\
\frac{\pi_c \frac{1}{\sqrt{2\pi} \sigma} e^{-\frac{1}{2\sigma^2} (x - \mu_{1})^2}}
{\sum_{l=1}^{K}
\pi_l \frac{1}{\sqrt{2\pi} \sigma} e^{-\frac{1}{2\sigma^2} (x - \mu_{l})^2}}
& =
\frac{\pi_c \frac{1}{\sqrt{2\pi} \sigma} e^{-\frac{1}{2\sigma^2} (x - \mu_{2})^2}}
{\sum_{l=1}^{K}
\pi_l \frac{1}{\sqrt{2\pi} \sigma} e^{-\frac{1}{2\sigma^2} (x - \mu_{l})^2}} \\
e^{-\frac{1}{2\sigma^2} (x - \mu_{1})^2}
& =
e^{-\frac{1}{2\sigma^2} (x - \mu_{2})^2} \\
\frac{e^{-\frac{1}{2\sigma^2} (x - \mu_{1})^2}}{e^{-\frac{1}{2\sigma^2} (x - \mu_{2})^2}}
& = 1 \\
(x - \mu_{2})^2 - (x - \mu_{1})^2
& = 0 \\
x^2 - 2x\mu_{2} + \mu_{2}^2 - (x^2 - 2x\mu_{1} + \mu_{1}^2)
& = 0 \\
2x (\mu_{1}- \mu_{2}) & = \mu_{1}^2 - \mu_{2}^2 \\
x & = \frac{\mu_{1}^2 - \mu_{2}^2}{2 (\mu_{1}- \mu_{2})} \\
x & = \frac{\mu_1 + \mu_2}{2}
\end{split}
$$
- And also:
$$
\begin{split}
\delta_{1}(x) & = \delta_{2}(x) \\
\log{(\pi_{c})}
- \frac{\mu_{1}^2}{2\sigma^2}
+ x \cdot \frac{\mu_{1}}{\sigma^2}
& =
\log{(\pi_{c})}
- \frac{\mu_{2}^2}{2\sigma^2}
+ x \cdot \frac{\mu_{2}}{\sigma^2} \\
x (\mu_{1} - \mu_{2}) & = \frac{\mu_{1}^2 - \mu_{2}^2}{2} \\
x & = \frac{\mu_{1}^2 - \mu_{2}^2}{2(\mu_{1} - \mu_{2})} \\
x & = \frac{\mu_1 + \mu_2}{2}
\end{split}
$$
- Let's see an example visually by setting as example the next values for each $Y$ class:
|$k$|$\sigma$|$\pi$|$\mu$|
|:-:|:------:|:---:|:---:|
|1|0.5|0.5|2|
|2|0.5|0.5|4|
```{r}
ldm_k_prop <- function(x,
k,
sigma = c(0.5,0.5),
pi_k = c(0.5,0.5),
mu = c(2, 4),
logit = FALSE){
if(logit){
return(x * mu[k]/sigma[k]^2 - mu[k]^2/(2*sigma[k]^2) + log(pi_k[k]))
}
denominator <-
sapply(x, \(y) sum(pi_k * (1/(sqrt(2*pi)*sigma)) * exp(-1/(2*sigma^2) * (y - mu)^2) ) )
k_numerador <-
(pi_k[k]* (sqrt(2*pi)*sigma[k])^-1 * exp(- (2*sigma[k]^2)^-1 * (x - mu[k])^2))
return(k_numerador / denominator)
}
BasePlot <-
data.frame(x = 1:5) |>
ggplot(aes(x))+
scale_x_continuous(breaks = scales::breaks_width(1))+
theme_light()+
theme(panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank())
p1 <-
BasePlot +
geom_function(fun = \(y) ldm_k_prop(x = y, k = 1), color = "blue")+
geom_function(fun = \(y) ldm_k_prop(x = y, k = 2), color = "red")
p2 <-
BasePlot +
geom_function(fun = \(y) ldm_k_prop(x = y, k = 1, logit = TRUE), color = "blue")+
geom_function(fun = \(y) ldm_k_prop(x = y, k = 2, logit = TRUE), color = "red")
(p1 / p2) +
plot_annotation(title = 'Comparing Proportion Function vs Logit Function of LDA',
theme = theme(plot.title = element_text(face = "bold")) )
```
### 3
**3.** This problem relates to the QDA model, in which the observations within each class are drawn from a normal distribution with a class specific mean vector and a class specific covariance matrix. We consider the simple case where $p = 1$; i.e. there is only one feature. Suppose that we have K classes, and that if an observation belongs to the *k*th class then X comes from a one-dimensional normal distribution, $X ∼ N(\mu_k, \sigma^2_k)$. Recall that the density function for the one-dimensional normal distribution is given in (4.16). Prove that in this case, the Bayes classifier is not linear. Argue that it is in fact quadratic.
$$
\begin{split}
p_k(x) & =
\frac{\pi_k \frac{1}{\sqrt{2\pi} \sigma_k} e^{-\frac{1}{2\sigma_k^2} (x - \mu_{1})^2}}
{\sum_{l=1}^{K}
\pi_l \frac{1}{\sqrt{2\pi} \sigma_l} e^{-\frac{1}{2\sigma_l^2} (x - \mu_{l})^2}} \\
& =
\frac{\pi_k \frac{1}{\sqrt{2\pi} \sigma_k} e^{-\frac{1}{2\sigma_k^2} (x - \mu_{1})^2}}
{\frac{1}{\sqrt{2\pi}}
\sum_{l=1}^{K}\pi_l \frac{1}{\sigma_l} e^{-\frac{1}{2\sigma_l^2} (x - \mu_{l})^2}} \\
& =
\frac{\frac{\pi_k}{\sigma_k} e^{-\frac{1}{2\sigma_k^2} (x - \mu_{1})^2}}
{\sum_{l=1}^{K} \frac{\pi_l}{\sigma_l} e^{-\frac{1}{2\sigma_l^2} (x - \mu_{l})^2}} \\
\end{split}
$$
- As the denominator is a constant for any $k$, we can define: $g(x) = \frac{1}{\sum_{l=1}^{K} \frac{\pi_l}{\sigma_l} e^{-\frac{1}{2\sigma_l^2} (x - \mu_{l})^2}}$
$$
\begin{split}
p_k(x) & = g(x) \frac{\pi_k}{\sigma_k}
e^{-\frac{1}{2\sigma_k^2} (x - \mu_{k})^2}\\
\log{(p_k(x))}& =
\log{\left( g(x) \frac{\pi_k}{\sigma_k}
e^{-\frac{1}{2\sigma_k^2} (x - \mu_{k})^2} \right)}\\
& =
\log{(g(x))} + \log{(\pi_k)} - \log{(\sigma_k)} -\frac{1}{2\sigma_k^2} (x - \mu_{k})^2 \\
& =
\log{(g(x))} + \log{(\pi_k)} - \log{(\sigma_k)} -\frac{\mu_k^2 - 2\mu_kx + x^2}{2\sigma_k^2} \\
& =
\left( \log{(g(x))} + \log{(\pi_k)} - \log{(\sigma_k)} - \frac{\mu_k^2}{2\sigma_k^2} \right)
+ \frac{\mu_k}{\sigma_k^2} \cdot x - \frac{1}{2\sigma_k^2} \cdot x^2 \\
\end{split}
$$
### 4
**4.** When the number of features *p* is large, there tends to be a deterioration in the performance of KNN and other *local* approaches that perform prediction using only observations that are near the test observation for which a prediction must be made. This phenomenon is known as the _curse of dimensionality_, and it ties into the fact that non-parametric approaches often perform poorly when p is large. We will now investigate this curse.
#### A
**(A)** Suppose that we have a set of observations, each with measurements on $p = 1$ feature, X. We assume that X is uniformly (evenly) distributed on $[0, 1]$. Associated with each observation is a response value. Suppose that we wish to predict a test observation’s response using only observations that are within 10 % of the range of $X$ closest to that test observation. For instance, in order to predict the response for a test observation with $X = 0.6$, we will use observations in the range $[0.55, 0.65]$. On average, what fraction of the available observations will we use to make the prediction?
```{r}
set.seed(123)
UnifDistVar1 <-
data.table(sample = 1:1000
)[, .(x1 = runif(1000)),
by = "sample"
][, .(prop = mean(x1 %between% c(0.6 - 0.1/2, 0.6 + 0.1/2))),
by = "sample"]
mean(UnifDistVar1$prop)
```
#### B
**(B)** Now suppose that we have a set of observations, each with measurements on $p = 2$ features, $X_1$ and $X_2$. We assume that $(X_1, X_2)$ are uniformly distributed on $[0, 1] \times [0, 1]$. We wish to predict a test observation’s response using only observations that are within 10 % of the range of X1 and within 10 % of the range of $X_2$ closest to that test observation. For instance, in order to predict the response for a test observation with $X_1 = 0.6$ and $X_2 = 0.35$, we will use observations in the range $[0.55, 0.65]$ for $X_1$ and in the range $[0.3, 0.4]$ for $X_2$. On average, what fraction of the available observations will we use to make the prediction?
```{r}
set.seed(123)
UnifDistVar2 <-
UnifDistVar1[, .(x1 = runif(1000),
x2 = runif(1000)),
by = "sample"
][ , .(prop = mean(x1 %between% c(0.6 - 0.1/2, 0.6 + 0.1/2) &
x2 %between% c(0.35 - 0.1/2, 0.35 + 0.1/2))),
by = "sample"]
mean(UnifDistVar2$prop)
```
#### C
**(C)** Now suppose that we have a set of observations on p = 100 features. Again the observations are uniformly distributed on each feature, and again each feature ranges in value from 0 to 1. We wish to predict a test observation’s response using observations within the 10 % of each feature’s range that is closest to that test observation. What fraction of the available observations will we use to make the prediction?
```{r}
0.1^100
```
#### D
**(D)** Using your answers to parts (a)–(c), argue that a drawback of KNN when *p* is large is that there are very few training observations “near” any given test observation.
- As *p* gets lager every point has more specifications to meet and the number of point which meet them decrease.
#### E (missing)
**(E)** Now suppose that we wish to make a prediction for a test observation by creating a p-dimensional hypercube centered around the test observation that contains, on average, 10% of the training observations. For $p = 1$, $2$, and $100$, what is the length of each side of the hypercube? Comment on your answer.
*Note: A hypercube is a generalization of a cube to an arbitrary number of dimensions. When *$p = 1$*, a hypercube is simply a line segment, when *$p = 2$ *it is a square, and when *$p = 100$ *it is a 100-dimensional cube.*
### 5
**5.** We now examine the differences between LDA and QDA.
#### A
**(A)** If the Bayes decision boundary is linear, do we expect LDA or QDA to perform better on the training set? On the test set?
|Type of set to test| Perform better|
|:-----------------:|:-------------:|
|training set|***QDA***, as it will model some noise|
|test set|***LDA***, as decision boundary is lineal|
#### B
**(B)** If the Bayes decision boundary is non-linear, do we expect LDA or QDA to perform better on the training set? On the test set?
|Type of set to test| Perform better|
|:-----------------:|:-------------:|
|training set|***QDA***, as it will model some noise|
|test set|***QDA***, as decision boundary is non-linear|
#### C
**(C)** In general, as the sample size n increases, do we expect the test prediction accuracy of QDA relative to LDA to improve, decline, or be unchanged? Why?
- If the Bayes decision boundary is non-linear, QDA could improve its test prediction accuracy as the sample size n increases. When the model has more examples it has less changes to overfit the data.
#### D
**(D)** True or False: Even if the Bayes decision boundary for a given problem is linear, we will probably achieve a superior test error rate using QDA rather than LDA because QDA is flexible enough to model a linear decision boundary. Justify your answer.
- **FALSE**, as QDA would model some noise that could affect the prediction accuracy.
### 6
**6.** Suppose we collect data for a group of students in a statistics class with variables $X_1$ = hours studied, $X_2$ = undergrad GPA, and Y = receive an A. We fit a logistic regression and produce estimated coefficient, $\hat{\beta}_0 = −6$, $\hat{\beta}_1 = 0.05$ and $\hat{\beta}_2 = 1$.
#### A
**(A)** Estimate the probability that a student who studies for 40 h and has an undergrad GPA of 3.5 gets an A in the class.
```{r}
LogisticCoef <- -6 + 0.05 * 40 + 1* 3.5
exp(LogisticCoef)/(1+exp(LogisticCoef))
```
#### B
**(B)** How many hours would the student in part (a) need to study to have a 50 % chance of getting an A in the class?
$$
\begin{split}
\log{ \left( \frac{p(X)}{1 - p(X)} \right)} & = \beta_{0}+\beta_{1}X_1+\beta_{2}X_2 \\
\log{ \left( \frac{0.5}{1 - 0.5} \right)} & = \beta_{0}+\beta_{1}X_1+\beta_{2}X_2 \\
0 & = \beta_{0}+\beta_{1}X_1+\beta_{2}X_2 \\
X_2 & = \frac{-\beta_0-\beta_{2}X_2}{\beta_{1}} \\
X_2 & = \frac{-(-6)-(1 \times 3.5)}{0.05} \\
X_2 & = 50 \text{ horas}
\end{split}
$$
### 7
**7.** Suppose that we wish to predict whether a given stock will issue a dividend this year (“Yes” or “No”) based on $X$, last year’s percent profit. We examine a large number of companies and discover that the mean value of X for companies that issued a dividend was $\overline{X}_y = 10$, while the mean for those that didn’t was $\overline{X}_n = 0$. In addition, the variance of X for these two sets of companies was $\hat{\sigma}^2 = 36$. Finally, *80 %* of companies issued dividends. Assuming that X follows a normal distribution, predict the probability that a company will issue a dividend this year given that its percentage profit was $x = 4$ last year.
$$
\begin{split}
p_{k}(x) & = \frac{\pi_{k} f_{k}(x)}
{\sum_{l=1}^{K} \pi_{l} f_{l}(x)} \\
p_{y}(4) & =
\frac{0.8 \times
\left(
\frac{e^{\frac{-(4-10)^2}{2 \times 36} }}{\sqrt{2 \times \pi \times 36}}
\right)}
{0.2 \times
\left(
\frac{e^{\frac{-(4-0)^2}{2 \times 36} }}{\sqrt{2 \times \pi \times 36}}
\right)
+
0.8 \times
\left(
\frac{e^{\frac{-(4-10)^2}{2 \times 36} }}{\sqrt{2 \times \pi \times 36}}
\right)
} \\
p_{k}(4) & = 0.75
\end{split}
$$
```{r}
ldm_k_prop(4,
k = 1,
sigma = c(6, 6),
pi_k = c(0.8, 0.2),
mu = c(10, 0)) |>
scales::percent(accuracy = 0.01)
```
### 8
**8.** Suppose that we take a data set, divide it into equally-sized training and test sets, and then try out two different classification procedures.
|Model|Training Error Rate|Test Error Rate|
|:---:|:-------------:|:-----:|
|Logistic regression|20%|30%|
|1-nearestbors|0%|36%|
Based on these results, which method should we prefer to use for classification of new observations? Why?
- We should use the ***Logistic Regression*** as it has a lower ***test error rate*** than the logistic regression.
### 9
**9.** This problem has to do with odds.
#### A
**(A)** On average, what fraction of people with an odds of 0.37 of defaulting on their credit card payment will in fact default?
$$
\begin{split}
\frac{p(X)}{1 - p(X)} & = Y \\
p(X) & = Y - Yp(X) \\
p(X) + Yp(X) & = Y \\
p(X) & = \frac{Y}{1+Y} = \frac{0.37}{1.37} = 0.27
\end{split}
$$
#### B
**(B)** Suppose that an individual has a 16 % chance of defaulting on her credit card payment. What are the odds that she will default?
```{r}
scales::percent(0.16/(1-0.16), accuracy = 0.01)
```
### 10 (missing)
**10.** Equation 4.32 derived an expression for $\log{ \left( \frac{\text{Pr}(Y=k|X=x)}{\text{Pr}(Y=K|X=x)} \right)}$ in the setting where $p > 1$, so that the mean for the $k$th class, $\mu_k$, is p-dimensional vector, and the shared covariance $\Sigma$ is a $p \times p$ matrix. However, in the setting with $p=1$, (4.32) takes a simpler form, since the means $\mu_1,\dots,\mu_K$ and the variance $\sigma^2$ are scalars In this simpler setting, repeat the calculation in (4.32), and provide expressions for $a_k$ and $b_{kj}$ in terms of $\pi_k$, $\pi_k$, $\mu_k$, $\mu_K$, and $\sigma^2$.
$$
\begin{split}
\log{ \left( \frac{\text{Pr}(Y=k|X=x)}{\text{Pr}(Y=K|X=x)} \right)} & =
\end{split}
$$
### 11 (missing)
**11.** Work out the detailed forms of $a_k$, $b_{kj}$ , and $b_{kjl}$ in (4.33). Your answer should involve $\pi_k$, $\pi_k$, $\mu_k$, $\mu_K$, $\Sigma_k$, and $\Sigma_K$.
### 12
**12.** Suppose that you wish to classify an observation X ∈ R into apples and oranges. You fit a logistic regression model and find that
$$
\widehat{\text{Pr}}(Y = \text{orange}|X=x) =
\frac{\exp(\hat{\beta}_0+\hat{\beta}_1x)}
{1 + \exp(\hat{\beta}_0+\hat{\beta}_1x)}
$$
Your friend fits a logistic regression model to the same data using the _softmax_ formulation in (4.13), and finds that
$$
\widehat{\text{Pr}}(Y = \text{orange}|X=x) =
\frac{\exp(\hat{\alpha}_{\text{orange}0}+
\hat{\alpha}_{\text{orange}1}x)}
{\exp(\hat{\alpha}_{\text{orange}0}+
\hat{\alpha}_{\text{orange}1}x)+
\exp(\hat{\alpha}_{\text{apple}0}+
\hat{\alpha}_{\text{apple}1}x)}
$$
#### A
**(A)** What is the log odds of orange versus apple in your model?
$$
\log{
\left(
\frac{\widehat{\text{Pr}}(Y = \text{orange}|X=x)}
{1 - \widehat{\text{Pr}}(Y = \text{orange}|X=x)}
\right)} =
\hat{\beta}_0+\hat{\beta}_1x
$$
#### B
**(B)** What is the log odds of orange versus apple in your friend’s model?
$$
\log{
\left(
\frac{\exp(\hat{\alpha}_{\text{orange}0} + \hat{\alpha}_{\text{orange}1}x)}
{\exp(\hat{\alpha}_{\text{apple}0} + \hat{\alpha}_{\text{apple}1}x)}
\right)} =
(\hat{\alpha}_{\text{orange}0} - \hat{\alpha}_{\text{apple}0}) +
(\hat{\alpha}_{\text{orange}1} - \hat{\alpha}_{\text{apple}1}) x
$$
#### C
**(C)** Suppose that in your model, $\hat{\beta}_0 = 2$ and $\hat{\beta}_1 = -1$. What are the coefficient estimates in your friend’s model? Be as specific as possible.
- $\hat{\beta}_0 = 2$ and $\hat{\beta}_1 = -1$
#### D
**(D)** Now suppose that you and your friend fit the same two models on a different data set. This time, your friend gets the coefficient estimates $\hat{\alpha}_{\text{orange}0} = 1.2$, $\hat{\alpha}_{\text{orange}1} = −2$, $\hat{\alpha}_{\text{apple}0} = 3$, $\hat{\alpha}_{\text{apple}1} = 0.6$. What are the coefficient estimates in your model?
- $\hat{\beta}_0 = 1.8$ and $\hat{\beta}_1 = -2.6$
#### E
**(E)** Finally, suppose you apply both models from (D) to a data set with 2,000 test observations. What fraction of the time do you expect the predicted class labels from your model to agree with those from your friend’s model? Explain your answer.
- Both models will predict the same class for every test observation.
## Applied
### 13
**13.** This question should be answered using the Weekly data set, which is part of the ISLR2 package. This data is similar in nature to the Smarket data from this chapter’s lab, except that it contains 1,089 weekly returns for 21 years, from the beginning of 1990 to the end of 2010.
#### A
**(A)** Produce some numerical and graphical summaries of the Weekly data. Do there appear to be any patterns?
```{r}
WeeklyDT <-
as.data.table(ISLR2::Weekly
# We want to measure the prob of going Up rather than Down
)[, Direction := factor(Direction, levels = c("Up","Down"))
][,`:=`(n_weeks = .N,
year_week = seq_len(.N)),
by = "Year"
# As 1990 has less week that the rest of year we assume that
# we are missing some weeks the beginning of the year rather than
# the end if the year
][n_weeks < 52L,
year_week := year_week + (52L - n_weeks)]
ggplot(WeeklyDT,aes(Year, Volume, color = Direction))+
geom_point(alpha = 0.3)+
geom_smooth(se = FALSE)+
scale_y_log10()+
labs(title = "Year and Volume are highly correlated",
subtitle = "So we can not use both in the same model")+
theme_classic()+
theme(legend.position = "top")
ggplot(WeeklyDT,aes(year_week, Volume, color = Direction))+
geom_point(alpha = 0.3)+
geom_smooth(se = FALSE)+
scale_y_log10()+
scale_x_continuous(breaks = scales::breaks_width(10))+
labs(title = "The volume was higher for Down Direction",
subtitle = "In the first 35 weeks",
y = "Log10(Volume)")+
theme_classic()+
theme(legend.position = "top")
melt(WeeklyDT,
measure.vars = patterns("^Lag\\d$"),
variable.name = "Lag_name",
value.name = "Lag_value") |>
ggplot(aes(Volume, Lag_value, color = Direction))+
geom_point(alpha = 0.3)+
geom_smooth(se = FALSE)+
scale_x_log10()+
facet_wrap(vars(Lag_name), scales = "free_y")+
labs(title = "There the lags can help to differenciate between Up and Down",
x = "Log10(Volume)")+
theme_classic()+
theme(legend.position = "top")
```
#### B
**(B)** Use the full data set to perform a logistic regression with Direction as the response and the five lag variables plus Volume as predictors. Use the summary function to print the results. Do any of the predictors appear to be statistically significant? If so, which ones?
```{r}
LogisticLagModelFit <-
logistic_reg() |>
fit(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume, data = WeeklyDT)
LogisticLagTrainPred <-
cbind(WeeklyDT,
predict(LogisticLagModelFit,
new_data = NULL))
summary(LogisticLagModelFit$fit)
```
- *Lag2* it's significant.
#### C
**(C)** Compute the confusion matrix and overall fraction of correct predictions. Explain what the confusion matrix is telling you about the types of mistakes made by logistic regression.
```{r}
conf_mat(LogisticLagTrainPred,
truth = "Direction",
estimate = .pred_class)
get_class_metrics(LogisticLagTrainPred,
truth = Direction,
estimate = .pred_class)
```
- By checking the specificity rate we can see that the model is making a bad job identifying when the number is going to get **Down**.
#### D
**(D)** Now fit the logistic regression model using a training data period from 1990 to 2008, with Lag2 as the only predictor. Compute the confusion matrix and the overall fraction of correct predictions for the held out data (that is, the data from 2009 and 2010).
```{r}
WeeklyYearSplit <-
WeeklyDT[, list(analysis = .I[Year <= 2008],
assessment = .I[Year > 2008]) |>
make_splits(data = .SD)]
WeeklyYearTraining <- training(WeeklyYearSplit)
WeeklyYearLogisticResults <-
logistic_reg() |>
get_class_matrix_metrics(split = WeeklyYearSplit,
fit_formula = "Direction ~ Lag2")
WeeklyYearLogisticResults
```
#### E
**(E)** Repeat (d) using LDA.
```{r}
WeeklyYearLdaResults <-
discrim_linear() |>
get_class_matrix_metrics(split = WeeklyYearSplit,
fit_formula = "Direction ~ Lag2")
WeeklyYearLdaResults
```
#### F
**(F)** Repeat (d) using QDA.
```{r}
WeeklyYearQdaResults <-
discrim_quad() |>
get_class_matrix_metrics(split = WeeklyYearSplit,
fit_formula = "Direction ~ Lag2")
WeeklyYearQdaResults
```
#### G
**(G)** Repeat (d) using KNN with K = 1.
```{r}
WeeklyYearKnnResults <-
get_class_matrix_metrics(model_knn_k(1),
split = WeeklyYearSplit,
fit_formula = "Direction ~ Lag2")
WeeklyYearKnnResults
```
#### H
**(H)** Repeat (d) using naive Bayes.
```{r}
WeeklyYearNbResults <-
get_class_matrix_metrics(ModelNaiveBayes,
split = WeeklyYearSplit,
fit_formula = "Direction ~ Lag2")
WeeklyYearNbResults
```
#### I
**(I)** Which of these methods appears to provide the best results on this data?
```{r}
list(cbind(WeeklyYearLogisticResults$metrics, model = "logistic"),
cbind(WeeklyYearLdaResults$metrics, model = "lda"),
cbind(WeeklyYearQdaResults$metrics, model = "qda"),
cbind(WeeklyYearNbResults$metrics, model = "nb")) |>
rbindlist() |>
(\(DT) DT[.metric == "spec"][order(-.estimate)])()
```
- The best models are *Logistic Regression* and the *Linear Discriminant Analysis*.
#### J
**(J)** Experiment with different combinations of predictors, including possible transformations and interactions, for each of the methods. Report the variables, method, and associated confusion matrix that appears to provide the best results on the held out data. Note that you should also experiment with values for K in the KNN classifier.
- Let's define different recipes to evaluate
```{r}
WeeklyRecipeBaseFormula <-
recipe(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume + year_week,
data = WeeklyYearTraining)
WeeklyRecipeLogVolume <-
WeeklyRecipeBaseFormula |>
step_log(Volume, base = 10)
WeeklyRecipeInteractions <-
WeeklyRecipeLogVolume |>
step_interact(~ Volume:year_week + Volume:starts_with("Lag"))
WeeklyRecipeList <-
list("BaseFormula" = WeeklyRecipeBaseFormula,
"LogVolume" = WeeklyRecipeLogVolume,
"Interactions" = WeeklyRecipeInteractions)
```
- The models to fit
```{r}
WeeklyModelList <-
c(1L, seq.int(10L, 100L, 10L)) |>
(\(x) structure(x, names = paste("knn",x)) )() |>
lapply(model_knn_k) |>
append(list("logistic" = logistic_reg(),
"lda" = discrim_linear(),
"qda" = discrim_quad(),
bayes = ModelNaiveBayes))
```
- Performing the evaluation
```{r}
#| eval: false
WeeklyEvaluationResults <-
lapply(WeeklyModelList,
FUN = evaluate_model,
recipe_list = WeeklyRecipeList,
split = WeeklyYearSplit) |>
rbind_list_name(new_col_name = "model", fill = TRUE)
WeeklyEvaluationResults[, dcast(.SD, recipe+model ~.metric,
value.var = ".estimate")
][order(-roc_auc)
][1:5]
```
```{r}
#| echo: false
fread(here::here("data/Weekly-best-recipes-models.csv"))
```
- In this case the *Logistic Regressions* has the best general results after adding interactions to the model.
```{r}
WeeklyFittedWorkFlow <-
workflow() |>
add_recipe(WeeklyRecipeInteractions) |>
add_model(logistic_reg()) |>
fit(data = WeeklyYearTraining)
WeeklyFittedWorkFlow |>
augment(new_data = testing(WeeklyYearSplit)) |>
get_class_metrics(truth = Direction,
estimate = .pred_class)
```
- The model can predict if the `Direction` would go "Up" 64 of 100 times correctly and predict "Down" correctly 54 of 100 times, that is little bit better than guessing.
```{r}
WeeklyFittedWorkFlow$fit$fit$fit |>
tidy() |>
as.data.table() |>
(\(DT) DT[order(-abs(estimate))])() |>
head(5) |>
ggplot(aes(estimate, reorder(term,estimate)))+
geom_col()+
theme_classic()
```
### 14
**14.** In this problem, you will develop a model to predict whether a given car gets high or low gas mileage based on the Auto data set.
#### A
**(A)** Create a binary variable, `mpg01`, that contains a 1 if `mpg` contains a value above its median, and a 0 if `mpg` contains a value below its median. You can compute the median using the `median()` function. Note you may find it helpful to use the `data.frame()` function to create a single data set containing both `mpg01` and the other `Auto` variables.
```{r}
AutoDT <-
as.data.table(ISLR2::Auto
)[,`:=`(mpg01 = factor(mpg > median(mpg), levels = c("TRUE","FALSE")),
origin = c("American","European","Japanese")[origin],
cylinders = factor(cylinders))]
```
#### B
**(B)** Explore the data graphically in order to investigate the association between `mpg01` and the other features. Which of the other features seem most likely to be useful in predicting `mpg01`? Scatterplots and boxplots may be useful tools to answer this question. Describe your findings.
- Exploring categorical variables
```{r}
AutoDT[, .(prob = mean(mpg01 == "TRUE")),
by = "cylinders"] |>
ggplot(aes(cylinders, prob)) +
geom_col(aes(fill = prob > 0.6), alpha = 0.8) +
labs(title = "Cars with 4 and 5 cyclinders are more efficient") +
scale_y_continuous(labels = percent_format(accuracy = 1)) +
scale_fill_manual(values = c("TRUE" = "dodgerblue3", "FALSE" = "#AAAAAA")) +
theme_classic() +
theme(legend.position = "none")
AutoDT[, .(prob = mean(mpg01 == "TRUE")),
by = "origin"] |>
ggplot(aes(origin, prob)) +
geom_col(aes(fill = prob < 0.4), alpha = 0.8) +
labs(title = "American Cars are less efficient") +
scale_y_continuous(labels = percent_format(accuracy = 1)) +
scale_fill_manual(values = c("TRUE" = "firebrick3", "FALSE" = "#AAAAAA")) +
theme_classic() +
theme(legend.position = "none")
```
- Exploring numerical variables
```{r}
AutoDT[, .(prob = mean(mpg01 == "TRUE")),
by = "year"] |>
ggplot(aes(year, prob)) +
geom_point(color = "#AAAAAA") +
geom_smooth(se = FALSE, method = "lm", color = "dodgerblue3")+
labs(title = "New cars are more efficient on average") +
scale_y_continuous(labels = percent_format(accuracy = 1)) +
scale_fill_manual(values = c("TRUE" = "firebrick3", "FALSE" = "#AAAAAA")) +
theme_classic() +
theme(legend.position = "none")
ggplot(AutoDT, aes(mpg01, displacement))+
geom_boxplot(aes(fill = mpg01), alpha = 0.6)+
scale_fill_manual(values = c("TRUE" = "dodgerblue3", "FALSE" = "#AAAAAA")) +
labs(title = "The Engine displacement is lower for efficient cars") +
theme_classic() +
theme(legend.position = "none")
ggplot(AutoDT, aes(mpg01, horsepower))+
geom_boxplot(aes(fill = mpg01), alpha = 0.6)+
scale_fill_manual(values = c("TRUE" = "dodgerblue3", "FALSE" = "#AAAAAA")) +
labs(title = "The Engine horsepower is lower for efficient cars") +
theme_classic() +
theme(legend.position = "none")
ggplot(AutoDT, aes(mpg01, weight))+
geom_boxplot(aes(fill = mpg01), alpha = 0.6)+
scale_fill_manual(values = c("TRUE" = "dodgerblue3", "FALSE" = "#AAAAAA")) +
labs(title = "The weight is lower for efficient cars") +
theme_classic() +
theme(legend.position = "none")
ggplot(AutoDT, aes(acceleration, fill = factor(mpg01,levels = c("FALSE","TRUE"))))+
geom_histogram(alpha = 0.5, position = "identity", bins = 15)+
scale_fill_manual(values = c("FALSE" = "#AAAAAA", "TRUE" = "dodgerblue3"))+
labs(title = "The acceleration is a little bit higher for efficient cars") +
theme_classic() +
theme(legend.position = "none")
```
#### C
**(C)** Split the data into a training set and a test set.
```{r}
set.seed(1224)
AutoSplit <- initial_split(AutoDT, strata = mpg01)
AutoTraining <- training(AutoSplit)
```
#### D
**(D)** Perform LDA on the training data in order to predict `mpg01` using the variables that seemed most associated with `mpg01` in (b). What is the test error of the model obtained?
```{r}
AutoRecipe <-
recipe(mpg01 ~ cylinders + origin + year + displacement + horsepower + weight + acceleration,
data = AutoTraining) |>
step_dummy(cylinders, origin) |>
# I couldn't perform QDA with a higher threshold
step_corr(all_numeric_predictors(), threshold = 0.59)
workflow() |>
add_recipe(AutoRecipe) |>
add_model(discrim_linear()) |>
last_fit(split = AutoSplit) |>
collect_predictions() |>
(\(DF) mean(DF$.pred_class != DF$mpg01) )()
```
#### E
**(E)** Perform QDA on the training data in order to predict `mpg01` using the variables that seemed most associated with `mpg01` in (b). What is the test error of the model obtained?
```{r}
workflow() |>
add_recipe(AutoRecipe) |>
add_model(discrim_quad()) |>
last_fit(split = AutoSplit) |>
collect_predictions() |>
(\(DF) mean(DF$.pred_class != DF$mpg01) )()
```
#### F
**(F)** Perform logistic regression on the training data in order to predict `mpg01` using the variables that seemed most associated with `mpg01` in (b). What is the test error of the model obtained?
```{r}
workflow() |>
add_recipe(AutoRecipe) |>
add_model(logistic_reg()) |>
last_fit(split = AutoSplit) |>
collect_predictions() |>
(\(DF) mean(DF$.pred_class != DF$mpg01) )()