-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCh05_Resampling_R.Rmd
805 lines (489 loc) · 14.8 KB
/
Ch05_Resampling_R.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
---
title: "Resampling"
author: "Your Name Here"
date: "2022-12-30"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE,message=FALSE,fig.align="center",fig.width=7,fig.height=2.5)
pacman::p_load(
car
, ggplot2
, ggExtra
, reshape2
, corrplot
, RColorBrewer
, lubridate
, AmesHousing
)
```
```{css}
.btn {
border-width: 0 0px 0px 0px;
font-weight: normal;
text-transform: ;
}
.btn-default {
color: #2ecc71;
background-color: #ffffff;
border-color: #ffffff;
}
```
```{r,echo=FALSE}
# Global parameter
show_code <- TRUE
```
# Class Workbook {.tabset .tabset-fade .tabset-pills}
## In class activity
### Ames House Data
```{r,echo=show_code}
library(AmesHousing)
?ames_raw
```
Let's revisit the AmesHousing data. As we did in the previous class, I will split the data into before 2008 and after. The data up to 2008 will be the training data and after 2008 will be the testing data.
```{r,echo=show_code}
ames_raw_2008=ames_raw[ames_raw$`Yr Sold`<2008,]
ames_raw_2009=ames_raw[ames_raw$`Yr Sold`>=2008,]
```
* For the regression model fit, use bootstrap to compare the standard error estimates to the model based estimates.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
* Use cross validation to decide which model has a good predictive accuracy. Does the result hold true for the prediction of future data?
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
* Using `knn.reg` fit KNN regression model. Use cross validation to decide which K to use.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
* Which model performs better on your training data? Which model performs better in your future prediction?
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
## Problem Set
### Bootstrap
We will 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.
Here is the code to get you going
```{r,echo =TRUE,eval=FALSE}
store <- rep(NA, 10000)
for(i in 1:10000){
store[i] <- sum(sample (1:100 , rep=TRUE) == 4) > 0
}
mean(store)
```
Comment on the results obtained.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
### CV
We will now perform cross-validation on a simulated data set.
(a) Generate a simulated data set as follows:
```{r,eval=FALSE, echo =TRUE}
set.seed (1)
x <- rnorm (100)
y <- x - 2 * x^2 + rnorm (100)
```
In this data set, what is n and what is p? Write out the model
used to generate the data in equation form.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(b) Create a scatterplot of X against Y . Comment on what you find.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(c) Set a random seed, and then compute the LOOCV errors that result from fitting the following four models using least squares:
i. $Y = \beta_0 + \beta_1X + \epsilon$
ii. $Y = \beta_0 + \beta_1X + \beta_2X^2 + \epsilon$
iii. $Y = \beta_0 + \beta_1X + \beta_2X^2 + \beta_3X^3 + \epsilon$
iv. $Y = \beta_0 + \beta_1X + \beta_2X^2 + \beta_3X^3 + \beta_4X^4 + \epsilon$.
Note you may find it helpful to use the `data.frame()` function
to create a single data set containing both $X$ and $Y$ .
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(d) Repeat (c) using another random seed, and report your results.
Are your results the same as what you got in (c)? Why?
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(e) Which of the models in (c) had the smallest LOOCV error? Is this what you expected? Explain your answer.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(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?
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
### Default 1
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.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(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.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
ii. Fit a multiple logistic regression model using only the training observations.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
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.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
iv. Compute the validation set error, which is the fraction of the observations in the validation set that are misclassified.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(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.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(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.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
### Default 2
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.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(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.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(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.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(d) Comment on the estimated standard errors obtained using the glm() function and using your bootstrap function.
Your answer:
~~~
Please write your answer in full sentences.
~~~
### Boston housing data set
We will now consider the Boston housing data set, from the ISLR2 library.
(a) Based on this data set, provide an estimate for the population mean of medv. Call this estimate $\hat{\mu}$.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(b) Provide an estimate of the standard error of $\hat{\mu}$. Interpret this result.
Hint: We can compute the standard error of the sample mean by dividing the sample standard deviation by the square root of the number of observations.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(c) Now estimate the standard error of $\hat{\mu}$ using the bootstrap. How does this compare to your answer from (b)?
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(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).
Hint: You can approximate a 95% confidence interval using the formula $[\hat{\mu} − 2SE(\hat{\mu}), \hat{\mu} + 2SE(\hat{\mu})]$.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(e) Based on this data set, provide an estimate, $\hat{\mu}_{med}$, for the median value of medv in the population.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(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.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(g) Based on this data set, provide an estimate for the tenth percentile of medv in Boston census tracts. Call this quantity $\hat{\mu}_{0.1}$. (You can use the quantile() function.)
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
(h) Use the bootstrap to estimate the standard error of $\hat{\mu}_{0.1}$. Comment on your findings.
Your code:
```{r,echo=TRUE}
#
#
```
Your answer:
~~~
Please write your answer in full sentences.
~~~
## Additional Material
### Predictive Modeling Platforms in R
There are few platforms in R that does predictive modeling.
These platforms are wrappers around other packages that makes it easy to do routine tasks.
- mlr3 (https://mlr3book.mlr-org.com)
- tidymodels (https://www.tidymodels.org/)
- caret (https://topepo.github.io/caret/)
- h2o (https://docs.h2o.ai/h2o/latest-stable/h2o-r/docs/index.html)
```{r,echo=show_code}
# split the data
index <- sample(1:nrow(ames_raw), 0.7*nrow(ames_raw))
vars <- c("SalePrice","Lot Area","Gr Liv Area","Full Bath")
train <- ames_raw[ index, vars]
test <- ames_raw[-index, vars]
colnames(train) <- make.names(colnames(train))
colnames(test) <- make.names(colnames(test))
# mlr3 TaskRegr
train$SalePrice <- log(train$SalePrice)
```
#### Resampling using [mlr3](https://mlr3book.mlr-org.com)
In MLR3 resampling for CV is
```{r,eval=FALSE,echo=TRUE}
mlr_resamplings$get("cv")
rsmp("cv")
```
resampling for bootstrap is
```{r,eval=FALSE,echo=TRUE}
mlr_resamplings$get("bootstrap")
rsmp("bootstrap")
```
They are called using `resample` function
```{r,echo=show_code}
# load packages and data
library(mlr3)
library(mlr3learners)
# fit a model
task <- as_task_regr(train, target ="SalePrice",id = "ames_raw")
learner <- lrn("regr.lm", predict_type = "response")
resampler = rsmp("cv")
# Explicitly instantiate the resampling for this task for reproduciblity
set.seed(123)
resampler$instantiate(task)
rr = resample(task, learner, resampler)
rr$aggregate()
pred = rr$prediction()
# Repeat resampling with featureless learner
rr_featureless = resample(task, lrn("regr.featureless"), resampler)
# Convert results to BenchmarkResult, then combine them
bmr1 = as_benchmark_result(rr)
bmr2 = as_benchmark_result(rr_featureless)
bmr1$aggregate()
```
#### Resampling using [tidymodels](https://www.tidymodels.org/)
```{r,echo=show_code}
# load packages and data
library(tidymodels)
library(dotwhisker)
# Setup the model
rec <- recipe(SalePrice ~ ., data = train)
clf <- linear_reg()
folds <- vfold_cv(train, v = 10)
control <- control_resamples(save_pred = TRUE)
wflow <- workflow() %>%
add_recipe(rec) %>%
add_model(clf)
# fit the models
lm_fit_rsmpl <- wflow %>% fit_resamples(folds,control=control)
collect_metrics(lm_fit_rsmpl)
prediction=collect_predictions(lm_fit_rsmpl)
```
#### Resampling using caret
```{r,echo=show_code}
# load packages and data
library(caret)
# fit the models
cv <- trainControl(method = "cv", number = 5)
lm_model <- train(SalePrice ~ ., data = train, method = "lm", trControl = cv)
prediction=predict(lm_model,newdata = test)
```
#### Resampling using h2o
#### Starting H2O
To use H2O you need to instantiate it.
```{r,echo=show_code,eval=FALSE}
library("h2o")
# nthreads specifies number of threads. -1 means use all the CPU cores.
# max_mem_size specifies the maximum amount of RAM to use.
localH2O <- h2o.init(nthreads = -1, max_mem_size="4g")
```
#### Serving the data to H2O
Since H2O is not in R, you need to tell it to use your data.
```{r,echo=show_code,eval=FALSE}
train_hf <- as.h2o(train)
test_hf <- as.h2o(test)
```
##### Cross validation
You can use K fold cross validation by specifying an integer to nfolds option. With cross-validated model building, H2O builds K+1 models: K cross-validated model and 1 overarching model over all of the training data.
Fitting GLM using 10 fold cross validation.
```{r,echo=show_code,eval=FALSE}
gaussian.fit.cv = h2o.glm(y = "SalePrice", #response variable
x = c("SalePrice","Lot.Area","Gr.Liv.Area","Full.Bath"),
training_frame = train_hf, family = "gaussian",lambda = 0, nfolds = 10)
gaussian.fit.cv
```
The plot shows the variability of each coefficient among the 10 folds. The red x is the final estimate.
```{r,echo=show_code,eval=FALSE}
boxplot(t(sapply(sapply(gaussian.fit.cv@model$cross_validation_models, `[[`, "name"), function(x) h2o.coef(h2o.getModel(x)))),
names = NULL)
points(1:4, coef(gaussian.fit.cv@model), pch = "X", col = "red")
abline(h = 0, col = "blue")
```