-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathch5.Rmd
490 lines (352 loc) · 18.2 KB
/
ch5.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
---
title: "Chapter 5. Resampling Methods"
output:
github_document:
md_extensions: -fancy_lists+startnum
html_notebook:
md_extensions: -fancy_lists+startnum
---
```{r setup, message=FALSE, warning=FALSE}
library(tidyverse)
library(ISLR)
library(modelr)
library(caret)
```
## Conceptual
(1) Using basic statistical properties of the variance, as well as single variable calculus, derive (5.6). In other words, prove that $α$ given by (5.6) does indeed minimize $Var(αX +(1 − α)Y)$.
![](ch5_files/exc1.png)
(2) We will now derive the probability that a given observation is part of a bootstrap sample. Suppose that we obtain a bootstrap sample from a set of $n$ observations.
(a) What is the probability that the first bootstrap observation is not the $j$th observation from the original sample? Justify your answer.
$(n-1)/n$. Because each observation in the sample has the same probability to be chosen, and the probability to pick any given observation is $1/n$.
(b) What is the probability that the second bootstrap observation is not the $j$th observation from the original sample?
The same as in (a), because we're sampling with replacement.
(c) Argue that the probability that the $j$th observation is not in the bootstrap sample is $(1 − 1/n)^n$.
Because the probability that an event (of probability $p$) happens $n$ times in a row is $p^n$, and having the $j$th observation completely left out of the bootstrap sample is the same as having the event described in (a) happening $n$ times in a row.
(d) When $n = 5$, what is the probability that the $j$th observation is in the bootstrap sample?
```{r}
1-(1-1/5)^5
```
(e) When n = 100, what is the probability that the jth observation
is in the bootstrap sample?
```{r}
1-(1-1/100)^100
```
(f) When $n = 10,000$, what is the probability that the $j$th observation is in the bootstrap sample?
```{r}
1-(1-1/10000)^10000
```
(g) Create a plot that displays, for each integer value of n from 1 to 100,000, the probability that the $j$th observation is in the bootstrap sample. Comment on what you observe.
```{r}
plot_data <-
tibble(
n = 1:100000,
prob = 1-(1-1/n)^n
)
ggplot(plot_data, aes(n, prob)) +
geom_line() +
expand_limits(y = 0) +
scale_x_log10()
```
It starts at 1, but quickly converges to 0.632.
(h) We will now investigate numerically the probability that a bootstrap sample of size n = 100 contains the jth observation. Here j = 4. We repeatedly create bootstrap samples, and each time we record whether or not the fourth observation is contained in the bootstrap sample.
```{r}
store <- rep (NA , 100000)
for (i in 1:100000) {
store[i] <- sum(sample(1:100, rep =TRUE) == 4) > 0
}
mean(store)
```
Comment on the results obtained.
The probability of having the $j$th observation in the sample is very close to the value to which the plot in (g) converges.
(3) We now review k-fold cross-validation.
(a) Explain how k-fold cross-validation is implemented.
The available data is randomly splited in k samples (or "folds") of equal size. Then the model is trained k times, leaving out a different fold each time, and using it after as test o validation data.
(b) What are the advantages and disadvantages of k-fold cross validation relative to:
i. The validation set approach?
K-fold cross validation greatly reduces the variability of the test error rate estimate, compared to using the validation set approach. Also it has less bias because we're using a higher fraction of the available data to train the model. A minor disavantage is that it slightly increases the computation cost of obtaining error rate estimates (we need to fit the model k times, not just once).
ii. LOOCV?
K-fold CV requieres less computation cost than LOOCV, because we need to fit the model k times instead of n (and most of the times k < n). Also, it has less variance in the estimation, because there is less overlap in the training data used in each iteration.
However, k-fold CV has more bias than LOOCV, since we're using less training observations for each model.
(4) Suppose that we use some statistical learning method to make a prediction for the response Y for a particular value of the predictor X. Carefully describe how we might estimate the standard deviation of our prediction.
Some statistical learning methods, like linear or logistic regression, provide us with the standard deviations of the coefficient estimates and the predictions. But other methods doesn't provide this information. In this case, we could apply a resampling method like the bootstrap. For this we need to create a function that computes the statistical of interest (in this case, the prediction) using a sample of the data. Then we pass that function to the function `boot()` (along with the original data and the number `B` of iterations) and then we get an estimation of the standard error of the predictions, obtained through repeteadly fitting the model in `B` samples (with replacement.)
## Applied
(5) In Chapter 4, we used logistic regression to predict the probability of default using `income` and `balance` on the `Default` data set. We will now estimate the test error of this logistic regression model using the validation set approach. Do not forget to set a random seed before beginning your analysis.
(a) Fit a logistic regression model that uses `income` and `balance` to predict `default`.
```{r}
glm_default <- glm(default ~ balance + income,
data = Default,
family = "binomial")
summary(glm_default)
```
(b) Using the validation set approach, estimate the test error of this model. In order to do this, you must perform the following steps:
i. Split the sample set into a training set and a validation set.
ii. Fit a multiple logistic regression model using only the training observations.
iii. Obtain a prediction of default status for each individual in the validation set by computing the posterior probability of default for that individual, and classifying the individual to the default category if the posterior probability is greater than 0.5.
iv. Compute the validation set error, which is the fraction of
the observations in the validation set that are misclassified.
```{r message = FALSE}
set.seed(1989)
train_default <-
Default %>%
sample_frac(size = 0.5)
test_default <-
Default %>%
anti_join(train_default)
glm_train_default <- glm(default ~ balance + income,
data = train_default,
family = "binomial")
test_default <- test_default %>%
add_predictions(glm_train_default, type = "response") %>%
mutate(pred_class = ifelse(
pred > 0.5, "Yes", "No"),
pred_class = factor(pred_class, levels = c("No", "Yes")))
caret::confusionMatrix(test_default[["pred_class"]],
reference = test_default[["default"]])
```
Validation set error is as follows:
```{r}
1-0.974
```
(c) Repeat the process in (b) three times, using three different splits of the observations into a training set and a validation set. Comment on the results obtained.
```{r}
estimate_error_glm_default <- function(...) {
train_default <-
Default %>%
sample_frac(size = 0.5)
test_default <-
Default %>%
anti_join(train_default,
by = c("default", "student", "balance", "income"))
glm_train_default <- glm(default ~ balance + income,
data = train_default,
family = "binomial")
test_default <- test_default %>%
add_predictions(glm_train_default, type = "response") %>%
mutate(
pred_class = ifelse(pred > 0.5, "Yes", "No"),
pred_class = factor(pred_class, levels = c("No", "Yes"))
)
conf_matrix <-
caret::confusionMatrix(test_default[["pred_class"]],
reference = test_default[["default"]])
1 - conf_matrix[["overall"]][["Accuracy"]]
}
(test_error_rates <-
map_dbl(1:3, estimate_error_glm_default))
```
```{r}
mean(test_error_rates)
```
```{r}
sd(test_error_rates)
```
The average test error rate is slightly higher than in (b), and we also see a standard eviation of 0.0011 in these three cases.
(d) Now consider a logistic regression model that predicts the probability of `default` using `income`, `balance`, and a dummy variable for `student`. Estimate the test error for this model using the validation set approach. Comment on whether or not including a dummy variable for student leads to a reduction in the test error rate.
```{r}
set.seed(1991)
train_default <-
Default %>%
sample_frac(size = 0.5)
test_default <-
Default %>%
anti_join(train_default)
glm_train_default_2 <- glm(default ~ balance + income + student,
data = train_default,
family = "binomial")
test_default <- test_default %>%
add_predictions(glm_train_default, type = "response") %>%
mutate(pred_class = ifelse(
pred > 0.5, "Yes", "No"),
pred_class = factor(pred_class, levels = c("No", "Yes")))
conf_matrix <-
caret::confusionMatrix(test_default[["pred_class"]],
reference = test_default[["default"]])
1-conf_matrix[["overall"]][["Accuracy"]]
```
The test error rate obtained is almost the same as with the simpler model, so I wouldn't say that incorporing the variable `student` improves the Accuracy.
(7) We continue to consider the use of a logistic regression model to predict the probability of `default` using `income` and `balance` on the `Default` data set.
In particular, we will now compute estimates for the standard errors of the `income` and `balance` logistic regression coefficients in two different ways: (1) using the bootstrap, and (2) using the standard formula for computing the standard errors in the `glm()` function. Do not forget to set a random seed before beginning your analysis.
(a) Using the `summary()` and `glm()` functions, determine the estimated standard errors for the coefficients associated with income and balance in a multiple logistic regression model that uses both predictors.
```{r}
summary(glm_default)
```
(b) Write a function, boot.fn(), that takes as input the Default data set as well as an index of the observations, and that outputs the coefficient estimates for income and balance in the multiple logistic regression model.
```{r}
boot.fn <- function(data, indexes) {
data <- data[indexes,]
glm(default ~ balance + income,
data = data,
family = "binomial") %>%
coefficients()
}
```
(c) Use the boot() function together with your boot.fn() function to estimate the standard errors of the logistic regression coefficients for income and balance.
```{r}
boot::boot(Default, boot.fn, 1000)
```
(d) Comment on the estimated standard errors obtained using the
`glm()` function and using your bootstrap function.
The estimated standard errors for all the coefficients are very close in the `glm()` and bootstrap functions.
(7) In Sections 5.3.2 and 5.3.3, we saw that the `cv.glm()` function can be used in order to compute the LOOCV test error estimate. Alternatively, one could compute those quantities using just the `glm()` and `predict.glm()` functions, and a `for` loop. You will now take this approach in order to compute the LOOCV error for a simple logistic regression model on the `Weekly` data set. Recall that in the context of classification problems, the LOOCV error is given in (5.4).
(a) Fit a logistic regression model that predicts `Direction` using `Lag1` and `Lag2`.
```{r}
glm(Direction ~ Lag1 + Lag2,
data = Weekly,
family = "binomial") %>%
summary()
```
(b) Fit a logistic regression model that predicts `Direction` using `Lag1` and `Lag2` using all but the first observation.
```{r}
glm_lfo <-
glm(Direction ~ Lag1 + Lag2,
data = Weekly[-1, ],
family = "binomial")
```
(c) Use the model from (b) to predict the direction of the first observation. You can do this by predicting that the first observation will go up if $P(Direction ="Up"|Lag1, Lag2) > 0.5$. Was this observation correctly classified?
```{r}
Weekly %>%
filter(row_number() == 1) %>%
add_predictions(glm_lfo, type = "response") %>%
select(Direction, pred)
```
It is incorrectly classified.
(d) Write a for loop from $i = 1$ to $i = n$, where $n$ is the number of observations in the data set, that performs each of the following steps:
i. Fit a logistic regression model using all but the $ith$ observation to predict `Direction` using `Lag1` and `Lag2`.
ii. Compute the posterior probability of the market moving up for the ith observation.
iii. Use the posterior probability for the ith observation in order to predict whether or not the market moves up.
iv. Determine whether or not an error was made in predicting the direction for the ith observation. If an error was made, then indicate this as a 1, and otherwise indicate it as a 0.
```{r}
is_error <- vector("integer", nrow(Weekly))
for(i in 1:nrow(Weekly)) {
fit_wo_i <-
glm(Direction ~ Lag1 + Lag2,
data = Weekly[-i, ],
family = "binomial")
prediction_i <-
predict(fit_wo_i, newdata = Weekly[i,], type = "response") %>%
as.numeric()
prediction_class <- ifelse(prediction_i > 0.5,
"Up",
"Down")
error <-
ifelse(
prediction_class == as.character(Weekly[i, "Direction"]),
0,
1)
is_error[[i]] <- error
}
```
(e) Take the average of the n numbers obtained in (d)iv in order to obtain the LOOCV estimate for the test error. Comment on the
results.
```{r}
mean(is_error)
```
We get 44.9% as estimate for the error rate using the LOOCV method.
(8) We will now perform cross-validation on a simulated data set.
(a) Generate a simulated data set as follows:
```{r}
set.seed(1)
simulated <-
tibble(
x = rnorm(100),
y= x - 2*x^2 + rnorm (100)
)
simulated
```
In this data set, what is n and what is p? Write out the model used to generate the data in equation form.
n is 100 and p is 2. The model used to generate the data is as follows:
$y = x - 2x^2 + e$ with $e$ as an error term with mean 0 and standard deviation 1.
(b) Create a scatterplot of X against Y. Comment on what you find.
```{r}
qplot(x, y, data = simulated)
```
The data follows a quadratic pattern (as expected, since `y` was generated from `x^2`). As `x` moves away from zero, the value of `y` goes down.
(c) Set a random seed, and then compute the LOOCV errors that result from fitting the following four models using least squares:
i. $Y = β_0 + β_1X + e$
ii. $Y = β_0 + β_1X + β_2X_2 + e$
iii. $Y = β_0 + β_1X + β_2X_2 + β_3X_3 + e$
iv. $Y = β_0 + β_1X + β_2X_2 + β_3X_3 + β_4X_4 + e$.
```{r}
models <-
list(
glm(y ~ poly(x, 1), data = simulated),
glm(y ~ poly(x, 2), data = simulated),
glm(y ~ poly(x, 3), data = simulated),
glm(y ~ poly(x, 4), data = simulated)
)
```
```{r}
set.seed(1989)
loocv_error <-
map(models, ~boot::cv.glm(data = simulated, glmfit = .))
loocv_error %>%
map("delta")
```
(d) Repeat (c) using another random seed, and report your results. Are your results the same as what you got in (c)? Why?
```{r}
set.seed(1991)
loocv_error <-
map(models, ~boot::cv.glm(data = simulated, glmfit = .))
loocv_error %>%
map("delta")
```
The results are the same because randomness doesn't influence LOOCV results (it's always the same iteration using all the observations in the data).
(e) Which of the models in (c) had the smallest LOOCV error? Is this what you expected? Explain your answer.
The second model (with `x` as a quadratic term) is the one with lowest LOOCV error. This is as expected, since `y` was generated using a quadratic function of `x`.
(f) Comment on the statistical significance of the coefficient estimates that results from fitting each of the models in (c) using least squares. Do these results agree with the conclusions drawn
based on the cross-validation results?
```{r}
map(models, summary)
```
Yes, the statistical significance results match the conclusions from the LOOCV. The terms `x^3` and `x^4` are not statistically significant in the models iii and iv, and also adding those terms doesn't reduce the LOOCV error below the one in the model ii.
9. We will now consider the `Boston` housing data set, from the `MASS` library.
(a) Based on this data set, provide an estimate for the population mean of `medv`. Call this estimate $\hat{\mu}$.
```{r}
Boston <- MASS::Boston
Boston[["medv"]] %>% mean()
```
(b) Provide an estimate of the standard error of $\hat{\mu}$. Interpret this result.
```{r}
sd_medv <- Boston[["medv"]] %>% sd()
n_obs <- nrow(Boston)
sd_medv/sqrt(n_obs)
```
(c) Now estimate the standard error of $\hat{\mu}$ using the bootstrap. How does this compare to your answer from (b)?
```{r}
get_mean_boot <- function(data, indexes) {
data[indexes] %>% mean()
}
(mean_by_boot <-
boot::boot(Boston[["medv"]], get_mean_boot, 1000))
```
The bootstrap estimate for the standard error is a bit higher than the one calculed in (b).
(d) Based on your bootstrap estimate from (c), provide a 95% confidence interval for the mean of `medv`. Compare it to the results obtained using `t.test(Boston$medv)`.
```{r}
sd_boot <- sd(mean_by_boot[["t"]])
mean_boot <- mean_by_boot[["t0"]]
c(mean_boot - 2*sd_boot, mean_boot + 2*sd_boot)
```
(e) Based on this data set, provide an estimate, $\hat{\mu}_{med}$, for the median value of `medv` in the population.
```{r}
Boston[["medv"]] %>% median()
```
(f) We now would like to estimate the standard error of $\hat{\mu}_{med}$. Unfortunately, there is no simple formula for computing the standard error of the median. Instead, estimate the standard error of the median using the bootstrap. Comment on your findings.
```{r}
get_median_boot <- function(data, indexes) {
data[indexes] %>% median()
}
(median_by_boot <-
boot::boot(Boston[["medv"]], get_median_boot, 1000))
```
The bootstrap estimate for the median itself is the same as in (e), and the estimate for standard error is lower than the estimate for the mean.
(g) Based on this data set, provide an estimate for the tenth percentile of `medv` in Boston suburbs. Call this quantity $\hat{\mu}_{0.1}$.(You can use the `quantile()` function.)
```{r}
quantile(Boston[["medv"]], 0.1)
```
(h) Use the bootstrap to estimate the standard error of $\hat{\mu}_{0.1}$.Comment on your findings.
```{r}
get_quantile10_by_boot <- function(data, indexes) {
data[indexes] %>% quantile(., 0.1)
}
boot::boot(Boston[["medv"]], get_quantile10_by_boot, 1000)
```