-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy path05-origami.R
304 lines (229 loc) · 8.27 KB
/
05-origami.R
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
## ----setup--------------------------------------------------------------------
library(data.table)
library(origami)
library(knitr)
# load data set and take a peek
washb_data <- fread(
paste0(
"https://raw.githubusercontent.com/tlverse/tlverse-data/master/",
"wash-benefits/washb_data.csv"
),
stringsAsFactors = TRUE
)
## ----origami_washb_example_table1, echo=FALSE---------------------------------
n_samp <- 30
washb_data <- washb_data[seq_len(n_samp), ]
if (knitr::is_latex_output()) {
head(washb_data) %>%
kable(format = "latex")
} else if (knitr::is_html_output()) {
head(washb_data) %>%
kable() %>%
kableExtra::kable_styling(fixed_thead = TRUE) %>%
scroll_box(width = "100%", height = "300px")
}
## ----resubstitution-----------------------------------------------------------
folds <- folds_resubstitution(nrow(washb_data))
folds
## ----loo----------------------------------------------------------------------
folds <- folds_loo(nrow(washb_data))
folds[[1]]
folds[[2]]
## ----cv-----------------------------------------------------------------------
folds <- folds_vfold(nrow(washb_data), V = 2)
folds[[1]]
folds[[2]]
## ----montecarlo---------------------------------------------------------------
folds <- folds_montecarlo(nrow(washb_data), V = 2, pvalidation = 0.2)
folds[[1]]
folds[[2]]
## ----bootstrap----------------------------------------------------------------
folds <- folds_bootstrap(nrow(washb_data), V = 2)
folds[[1]]
folds[[2]]
## ----plot_airpass-------------------------------------------------------------
library(ggfortify)
data(AirPassengers)
AP <- AirPassengers
autoplot(AP) +
labs(
x = "Date",
y = "Passenger numbers (1000's)",
title = "Air Passengers from 1949 to 1961"
)
t <- length(AP)
## ---- fig.cap="Rolling origin CV", results="asis", echo=FALSE-----------------
knitr::include_graphics(path = "img/png/rolling_origin.png")
## ----rolling_origin-----------------------------------------------------------
folds <- folds_rolling_origin(
n = t,
first_window = 50, validation_size = 10, gap = 5, batch = 20
)
folds[[1]]
folds[[2]]
## ---- fig.cap="Rolling window CV", results="asis", echo=FALSE-----------------
knitr::include_graphics(path = "img/png/rolling_window.png")
## ----rolling_window-----------------------------------------------------------
folds <- folds_rolling_window(
n = t,
window_size = 50, validation_size = 10, gap = 5, batch = 20
)
folds[[1]]
folds[[2]]
## ---- fig.cap="Rolling origin V-fold CV", results="asis", echo=FALSE----------
knitr::include_graphics(path = "img/png/rolling_origin_v_fold.png")
## ---- fig.cap="Rolling window V-fold CV", results="asis", echo=FALSE----------
knitr::include_graphics(path = "img/png/rolling_window_v_fold.png")
## ----setup_ex-----------------------------------------------------------------
library(stringr)
library(dplyr)
library(tidyr)
# load data set and take a peek
washb_data <- fread(
paste0(
"https://raw.githubusercontent.com/tlverse/tlverse-data/master/",
"wash-benefits/washb_data.csv"
),
stringsAsFactors = TRUE
)
# remove missing data with drop_na(), then pick just the first 500 rows
washb_data <- washb_data %>%
drop_na() %>%
slice(1:500)
# specify the outcome and covariates as character vectors
outcome <- "whz"
covars <- colnames(washb_data)[-which(names(washb_data) == outcome)]
## ----origami_washb_example_table2, echo=FALSE---------------------------------
if (knitr::is_latex_output()) {
head(washb_data) %>%
kable(format = "latex")
} else if (knitr::is_html_output()) {
head(washb_data) %>%
kable() %>%
kableExtra::kable_styling(fixed_thead = TRUE) %>%
scroll_box(width = "100%", height = "300px")
}
## ----covariates---------------------------------------------------------------
covars
## ----linear_mod---------------------------------------------------------------
lm_mod <- lm(whz ~ ., data = washb_data)
summary(lm_mod)
## ----get_naive_mse------------------------------------------------------------
(err <- mean(resid(lm_mod)^2))
## ----define_fun_cv_lm---------------------------------------------------------
cv_lm <- function(fold, data, reg_form) {
# get name and index of outcome variable from regression formula
out_var <- as.character(unlist(str_split(reg_form, " "))[1])
out_var_ind <- as.numeric(which(colnames(data) == out_var))
# split up data into training and validation sets
train_data <- training(data)
valid_data <- validation(data)
# fit linear model on training set and predict on validation set
mod <- lm(as.formula(reg_form), data = train_data)
preds <- predict(mod, newdata = valid_data)
valid_data <- as.data.frame(valid_data)
# capture results to be returned as output
out <- list(
coef = data.frame(t(coef(mod))),
SE = (preds - valid_data[, out_var_ind])^2
)
return(out)
}
## ----cv_lm_resub--------------------------------------------------------------
# re-substitution estimate
resub <- make_folds(washb_data, fold_fun = folds_resubstitution)[[1]]
resub_results <- cv_lm(fold = resub, data = washb_data, reg_form = "whz ~ .")
mean(resub_results$SE, na.rm = TRUE)
## ----cv_lm_cross_valdate------------------------------------------------------
# cross-validated estimate
folds <- make_folds(washb_data)
cvlm_results <- cross_validate(
cv_fun = cv_lm, folds = folds, data = washb_data, reg_form = "whz ~ .",
use_future = FALSE
)
mean(cvlm_results$SE, na.rm = TRUE)
## ----cv_fun_randomForest------------------------------------------------------
# make sure to load the package!
library(randomForest)
cv_rf <- function(fold, data, reg_form) {
# get name and index of outcome variable from regression formula
out_var <- as.character(unlist(str_split(reg_form, " "))[1])
out_var_ind <- as.numeric(which(colnames(data) == out_var))
# define training and validation sets based on input object of class "folds"
train_data <- training(data)
valid_data <- validation(data)
# fit Random Forest regression on training set and predict on holdout set
mod <- randomForest(formula = as.formula(reg_form), data = train_data)
preds <- predict(mod, newdata = valid_data)
valid_data <- as.data.frame(valid_data)
# define output object to be returned as list (for flexibility)
out <- list(
coef = data.frame(mod$coefs),
SE = ((preds - valid_data[, out_var_ind])^2)
)
return(out)
}
## ----cv_fun_randomForest_run--------------------------------------------------
# now, let's cross-validate...
folds <- make_folds(washb_data)
cvrf_results <- cross_validate(
cv_fun = cv_rf, folds = folds,
data = washb_data, reg_form = "whz ~ .",
use_future = FALSE
)
mean(cvrf_results$SE)
## ----load_airpass-------------------------------------------------------------
data(AirPassengers)
print(AirPassengers)
## ----folds_airpass------------------------------------------------------------
folds <- make_folds(AirPassengers,
fold_fun = folds_rolling_origin,
first_window = 36, validation_size = 24, batch = 10
)
# How many folds where generated?
length(folds)
# Examine the first 2 folds.
folds[[1]]
folds[[2]]
## ----fit_airpass--------------------------------------------------------------
# make sure to load the package!
library(forecast)
# function to calculate cross-validated squared error
cv_forecasts <- function(fold, data) {
# Get training and validation data
train_data <- training(data)
valid_data <- validation(data)
valid_size <- length(valid_data)
train_ts <- ts(log10(train_data), frequency = 12)
# First arima model
arima_fit <- arima(train_ts, c(0, 1, 1),
seasonal = list(
order = c(0, 1, 1),
period = 12
)
)
raw_arima_pred <- predict(arima_fit, n.ahead = valid_size)
arima_pred <- 10^raw_arima_pred$pred
arima_MSE <- mean((arima_pred - valid_data)^2)
# Second arima model
arima_fit2 <- arima(train_ts, c(5, 1, 1),
seasonal = list(
order = c(0, 1, 1),
period = 12
)
)
raw_arima_pred2 <- predict(arima_fit2, n.ahead = valid_size)
arima_pred2 <- 10^raw_arima_pred2$pred
arima_MSE2 <- mean((arima_pred2 - valid_data)^2)
out <- list(mse = data.frame(
fold = fold_index(),
arima = arima_MSE, arima2 = arima_MSE2
))
return(out)
}
mses <- cross_validate(
cv_fun = cv_forecasts, folds = folds, data = AirPassengers,
use_future = FALSE
)
mses$mse
colMeans(mses$mse[, c("arima", "arima2")])