forked from business-science/modeltime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodeltime-recursive.R
712 lines (586 loc) · 19.2 KB
/
modeltime-recursive.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
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
# RECURSIVE ----
#' Create a Recursive Time Series Model from a Parsnip or Workflow Regression Model
#'
#' @param object An object of `model_fit` or a fitted `workflow` class
#' @param transform A transformation performed on `new_data` after
#' each step of recursive algorithm.
#'
#' * __Transformation Function:__ Must have one argument `data` (see examples)
#'
#' @param train_tail A tibble with tail of training data set.
#' In most cases it'll be required to create some variables
#' based on dependent variable.
#' @param ... Not currently used.
#' @param id (Optional) An identifier that can be provided to perform a panel forecast.
#' A single quoted column name (e.g. `id = "id"`).
#'
#' @return An object with added `recursive` class
#'
#' @details
#'
#' __What is a Recursive Model?__
#'
#' A _recursive model_ uses predictions to generate
#' new values for independent features. These features are typically
#' lags used in autoregressive models. It's important to understand that
#' a recursive model is only needed when the __Lag Size < Forecast Horizon.__
#'
#'
#' __Why is Recursive needed for Autoregressive Models with Lag Size < Forecast Horizon?__
#'
#' When the lag length is less than the forecast horizon,
#' a problem exists were missing values (`NA`) are
#' generated in the future data. A solution that `recursive()` implements
#' is to iteratively fill these missing values in with values generated
#' from predictions.
#'
#' __Recursive Process__
#'
#' When producing forecast, the following steps are performed:
#'
#' 1. Computing forecast for first row of new data.
#' The first row cannot contain NA in any required column.
#' 2. Filling i-th place of the dependent variable column with
#' already computed forecast.
#' 3. Computing missing features for next step, based on
#' already calculated prediction. These features are computed
#' with on a tibble object made from binded `train_tail` (i.e. tail of
#' training data set) and `new_data` (which is an argument of predict function).
#' 4. Jumping into point 2., and repeating rest of steps till the for-loop is ended.
#'
#' __Recursion for Panel Data__
#'
#' Panel data is time series data with multiple groups identified by an ID column.
#' The `recursive()` function can be used for Panel Data with the following modifications:
#'
#' 1. Supply an `id` column as a quoted column name
#'
#' 2. Replace [tail()] with [panel_tail()] to use tails for each time series group.
#'
#' @seealso
#' - [panel_tail()] - Used to generate tails for multiple time series groups.
#'
#' @examples
#' # Libraries & Setup ----
#' library(modeltime)
#' library(tidymodels)
#' library(tidyverse)
#' library(lubridate)
#' library(timetk)
#' library(slider)
#'
#' # ---- SINGLE TIME SERIES (NON-PANEL) -----
#'
#' m750
#'
#' FORECAST_HORIZON <- 24
#'
#' m750_extended <- m750 %>%
#' group_by(id) %>%
#' future_frame(
#' .length_out = FORECAST_HORIZON,
#' .bind_data = TRUE
#' ) %>%
#' ungroup()
#'
#' # TRANSFORM FUNCTION ----
#' # - Function runs recursively that updates the forecasted dataset
#' lag_roll_transformer <- function(data){
#' data %>%
#' # Lags
#' tk_augment_lags(value, .lags = 1:12) %>%
#' # Rolling Features
#' mutate(rolling_mean_12 = lag(slide_dbl(
#' value, .f = mean, .before = 12, .complete = FALSE
#' ), 1))
#' }
#'
#' # Data Preparation
#' m750_rolling <- m750_extended %>%
#' lag_roll_transformer() %>%
#' select(-id)
#'
#' train_data <- m750_rolling %>%
#' drop_na()
#'
#' future_data <- m750_rolling %>%
#' filter(is.na(value))
#'
#' # Modeling
#'
#' # Straight-Line Forecast
#' model_fit_lm <- linear_reg() %>%
#' set_engine("lm") %>%
#' # Use only date feature as regressor
#' fit(value ~ date, data = train_data)
#'
#' # Autoregressive Forecast
#' model_fit_lm_recursive <- linear_reg() %>%
#' set_engine("lm") %>%
#' # Use date plus all lagged features
#' fit(value ~ ., data = train_data) %>%
#' # Add recursive() w/ transformer and train_tail
#' recursive(
#' transform = lag_roll_transformer,
#' train_tail = tail(train_data, FORECAST_HORIZON)
#' )
#'
#' model_fit_lm_recursive
#'
#' # Forecasting
#' modeltime_table(
#' model_fit_lm,
#' model_fit_lm_recursive
#' ) %>%
#' update_model_description(2, "LM - Lag Roll") %>%
#' modeltime_forecast(
#' new_data = future_data,
#' actual_data = m750
#' ) %>%
#' plot_modeltime_forecast(
#' .interactive = FALSE,
#' .conf_interval_show = FALSE
#' )
#'
#' # MULTIPLE TIME SERIES (PANEL DATA) -----
#'
#' m4_monthly
#'
#' FORECAST_HORIZON <- 24
#'
#' m4_extended <- m4_monthly %>%
#' group_by(id) %>%
#' future_frame(
#' .length_out = FORECAST_HORIZON,
#' .bind_data = TRUE
#' ) %>%
#' ungroup()
#'
#' # TRANSFORM FUNCTION ----
#' # - NOTE - We create lags by group
#' lag_transformer_grouped <- function(data){
#' data %>%
#' group_by(id) %>%
#' tk_augment_lags(value, .lags = 1:FORECAST_HORIZON) %>%
#' ungroup()
#' }
#'
#' m4_lags <- m4_extended %>%
#' lag_transformer_grouped()
#'
#' train_data <- m4_lags %>%
#' drop_na()
#'
#' future_data <- m4_lags %>%
#' filter(is.na(value))
#'
#' # Modeling Autoregressive Panel Data
#' model_fit_lm_recursive <- linear_reg() %>%
#' set_engine("lm") %>%
#' fit(value ~ ., data = train_data) %>%
#' recursive(
#' id = "id", # We add an id = "id" to specify the groups
#' transform = lag_transformer_grouped,
#' # We use panel_tail() to grab tail by groups
#' train_tail = panel_tail(train_data, id, FORECAST_HORIZON)
#' )
#'
#' modeltime_table(
#' model_fit_lm_recursive
#' ) %>%
#' modeltime_forecast(
#' new_data = future_data,
#' actual_data = m4_monthly,
#' keep_data = TRUE
#' ) %>%
#' group_by(id) %>%
#' plot_modeltime_forecast(
#' .interactive = FALSE,
#' .conf_interval_show = FALSE
#' )
#'
#'
#' @export
recursive <- function(object, transform, train_tail, id = NULL, ...){
UseMethod("recursive")
}
#' @export
recursive.model_fit <- function(object, transform, train_tail, id = NULL, ...) {
dot_list <- list(...)
.class_obj <- if(!is.null(id)){"recursive_panel"} else {"recursive"}
object$spec[["forecast"]] <- .class_obj
object$spec[["transform"]] <- if(!is.null(id)){.prepare_panel_transform(transform)} else {.prepare_transform(transform)}
object$spec[["train_tail"]] <- train_tail
object$spec[["id"]] <- id
# Workflow: Need to pass in the y_var
object$spec[["y_var"]] <- dot_list$y_var # Could be NULL or provided by workflow
.class <- class(object)
class(object) <- c(.class[1], .class_obj, .class[2])
object
}
#' @export
recursive.workflow <- function(object, transform, train_tail, id = NULL, ...) {
# object$fit$fit$fit$spec[["forecast"]] <- "recursive"
# object$fit$fit$fit$spec[["transform"]] <- .prepare_transform(transform)
# object$fit$fit$fit$spec[["train_tail"]] <- train_tail
mld <- object %>% workflows::pull_workflow_mold()
y_var <- names(mld$outcomes)
if (is.null(id)){
object$fit$fit <- recursive(
object = object$fit$fit,
transform = transform,
train_tail = train_tail,
y_var = y_var
)
.class <- class(object)
class(object) <- c("recursive", .class)
} else {
object$fit$fit <- recursive(
object = object$fit$fit,
transform = transform,
train_tail = train_tail,
y_var = y_var,
id = id
)
.class <- class(object)
class(object) <- c("recursive_panel", .class)
}
object
}
#' @export
print.recursive <- function(x, ...) {
if (inherits(x, "model_fit")) {
cat("Recursive [parsnip model]\n\n")
} else if (inherits(x, "workflow")) {
cat("Recursive [workflow]\n\n")
} else {
cat("Recursive [modeltime ensemble]\n\n")
}
y <- x
class(y) <- class(y)[class(y) %>% stringr::str_detect("recursive", negate = TRUE)]
print(y)
invisible(x)
}
#' @export
print.recursive_panel <- function(x, ...) {
if (inherits(x, "model_fit")) {
cat("Recursive [parsnip model]\n\n")
} else if (inherits(x, "workflow")) {
cat("Recursive [workflow]\n\n")
} else {
cat("Recursive [modeltime ensemble]\n\n")
}
y <- x
class(y) <- class(y)[class(y) %>% stringr::str_detect("recursive_panel", negate = TRUE)]
print(y)
invisible(x)
}
#' Recursive Model Predictions
#'
#' Make predictions from a recursive model.
#'
#' @inheritParams parsnip::predict.model_fit
#'
#' @details
#'
#' Refer to [recursive()] for further details and examples.
#'
#' @return
#' Numeric values for the recursive panel prediction
#'
#' @export
predict.recursive <- function(object, new_data, type = NULL, opts = list(), ...) {
if (inherits(object, "model_fit")) {
# print("Recursive Model fit")
ret <- predict_recursive_model_fit(object, new_data, type = NULL, opts = list(), ...)
}
if (inherits(object, "workflow")) {
# print("Recursive Workflow")
ret <- predict_recursive_workflow(object, new_data, type = NULL, opts = list(), ...)
}
return(ret)
}
#' Recursive Model Predictions
#'
#' Make predictions from a recursive model.
#'
#' @inheritParams parsnip::predict.model_fit
#'
#' @details
#'
#' Refer to [recursive()] for further details and examples.
#'
#' @return
#' Numeric values for the recursive panel prediction
#'
#' @export
predict.recursive_panel <- function(object, new_data, type = NULL, opts = list(), ...) {
if (inherits(object, "model_fit")) {
# print("Recursive Model fit")
ret <- predict_recursive_panel_model_fit(object, new_data, type = NULL, opts = list(), ...)
}
if (inherits(object, "workflow")) {
# print("Recursive Workflow")
ret <- predict_recursive_panel_workflow(object, new_data, type = NULL, opts = list(), ...)
}
return(ret)
}
# SINGLE TIME SERIES DISPATCH ----
predict_recursive_model_fit <- function(object, new_data, type = NULL, opts = list(), ...) {
# SETUP ----
y_var <- object$spec$y_var
if (is.null(y_var)) {
y_var <- object$preproc$y_var
}
pred_fun <- parsnip::predict.model_fit
.transform <- object$spec[["transform"]]
train_tail <- object$spec$train_tail
# print({
# list(
# object,
# y_var,
# class(object),
# new_data,
# train_tail
# )
# })
# LOOP LOGIC ----
.preds <- tibble::tibble(.pred = numeric(nrow(new_data)))
.first_slice <- new_data %>%
dplyr::slice_head(n = 1)
.preds[1,] <- new_data[1, y_var] <-
pred_fun(
object,
new_data = .first_slice,
type = type,
opts = opts,
...
)
for (i in 2:nrow(.preds)) {
.temp_new_data <- dplyr::bind_rows(
train_tail,
new_data
)
.nth_slice <- .transform(.temp_new_data, nrow(new_data), i)
.preds[i,] <- new_data[i, y_var] <- pred_fun(
object, new_data = .nth_slice[names(.first_slice)],
type = type, opts = opts, ...
)
}
return(.preds)
}
predict_recursive_workflow <- function(object, new_data, type = NULL, opts = list(), ...) {
workflow <- object
if (!workflow$trained) {
rlang::abort("Workflow has not yet been trained. Do you need to call `fit()`?")
}
blueprint <- workflow$pre$mold$blueprint
forged <- hardhat::forge(new_data, blueprint)
new_data <- forged$predictors
fit <- workflow$fit$fit
# print(fit)
predict.recursive(fit, new_data, type = type, opts = opts, ...)
}
# PANEL DISPATCH ----
predict_recursive_panel_model_fit <- function(object, new_data, type = NULL, opts = list(), ...) {
# SETUP ----
y_var <- object$spec$y_var
if (is.null(y_var)) {
y_var <- object$preproc$y_var
}
pred_fun <- parsnip::predict.model_fit
.transform <- object$spec[["transform"]]
train_tail <- object$spec$train_tail
id <- object$spec$id
.id <- dplyr::ensym(id)
# # Comment this out ----
# print("here")
# obj <<- object
# print({
# list(
# object,
# y_var,
# class(object),
# new_data,
# train_tail
# )
# })
# LOOP LOGIC ----
.preds <- tibble::tibble(.id = new_data %>% dplyr::select(!! .id) %>% purrr::as_vector(),
.pred = numeric(nrow(new_data))) %>%
dplyr::group_by(.id) %>%
dplyr::mutate(rowid.. = dplyr::row_number()) %>%
dplyr::ungroup()
new_data <- new_data %>%
dplyr::group_by(!! .id) %>%
dplyr::mutate(rowid.. = dplyr::row_number()) %>%
dplyr::ungroup()
.first_slice <- new_data %>%
dplyr::group_by(!! .id) %>%
dplyr::slice_head(n = 1) %>%
dplyr::ungroup()
# Fix - When ID is dummied
if (!is.null(object$spec$remove_id)) {
if (object$spec$remove_id) {
.first_slice <- .first_slice %>%
dplyr::select(-(!! .id))
}
}
if ("rowid.." %in% names(.first_slice)) {
.first_slice <- .first_slice %>% dplyr::select(-rowid..)
}
.preds[.preds$rowid.. == 1, 2] <- new_data[new_data$rowid.. == 1, y_var] <- pred_fun(object,
new_data = .first_slice,
type = type,
opts = opts,
...)
.groups <- new_data %>%
dplyr::group_by(!! .id) %>%
dplyr::count(!! .id) %>%
dim() %>%
.[1]
new_data_size <- nrow(.preds)/.groups
for (i in 2:new_data_size) {
.temp_new_data <- dplyr::bind_rows(train_tail, new_data)
.nth_slice <- .transform(.temp_new_data, new_data_size, i, id)
# Fix - When ID is dummied
if (!is.null(object$spec$remove_id)) {
if (object$spec$remove_id) {
.nth_slice <- .nth_slice %>%
dplyr::select(-(!! .id))
}
}
if ("rowid.." %in% names(.nth_slice)) {
.nth_slice <- .nth_slice %>% dplyr::select(-rowid..)
}
.nth_slice <- .nth_slice[names(.first_slice)]
.preds[.preds$rowid.. == i, 2] <- new_data[new_data$rowid.. == i, y_var] <- pred_fun(object,
new_data = .nth_slice,
type = type,
opts = opts,
...)
}
return(.preds[,2])
}
predict_recursive_panel_workflow <- function(object, new_data, type = NULL, opts = list(), ...) {
workflow <- object
# Fix - When ID is dummied
id <- workflow$fit$fit$spec$id
df_id = new_data %>% dplyr::select(dplyr::all_of(id))
if (!workflow$trained) {
rlang::abort("Workflow has not yet been trained. Do you need to call `fit()`?")
}
blueprint <- workflow$pre$mold$blueprint
forged <- hardhat::forge(new_data, blueprint)
new_data <- forged$predictors
# Fix - When ID is dummied
if (!is.null(id)) {
if (!id %in% names(new_data)) {
new_data <- new_data %>%
dplyr::bind_cols(df_id)
workflow$fit$fit$spec$remove_id <- TRUE
}
}
# print(new_data)
fit <- workflow$fit$fit
# print(fit)
predict.recursive_panel(fit, new_data, type = type, opts = opts, ...)
}
# PANEL TAIL ----
#' Filter the last N rows (Tail) for multiple time series
#'
#' @param data A data frame
#' @param id An "id" feature indicating which column differentiates the time series panels
#' @param n The number of rows to filter
#'
#' @return
#' A data frame
#'
#' @seealso
#' - [recursive()] - used to generate recursive autoregressive models
#'
#' @examples
#' library(timetk)
#'
#' # Get the last 6 observations from each group
#' m4_monthly %>%
#' panel_tail(id = id, n = 6)
#'
#' @export
panel_tail <- function(data, id, n){
id <- dplyr::ensym(id)
ret <- data %>%
tibble::rowid_to_column(var = "..row_id") %>%
dplyr::group_by(!! id) %>%
dplyr::slice_tail(n = n) %>%
dplyr::ungroup() %>%
dplyr::arrange(..row_id) %>%
dplyr::select(-..row_id)
return(ret)
}
# HELPERS ----
#' Prepare Recursive Transformations
#'
#' @param .transform A transformation function
#'
#' @return A function that applies a recursive transformation
#'
#' @rdname dot_prepare_transform
#' @export
.prepare_transform <- function(.transform) {
if (inherits(.transform, "recipe")) {
.recipe <- .transform
if (!is_prepped_recipe(.recipe)) {
.recipe <- recipes::prep(.recipe)
}
.derived_features <- .recipe$term_info %>%
dplyr::filter(source == "derived") %>%
.$variable
.transform_fun <- function(temp_new_data, new_data_size, slice_idx){
temp_new_data <- temp_new_data %>%
dplyr::select(-!!.derived_features)
recipes::bake(.recipe, new_data = temp_new_data) %>%
dplyr::slice_tail(n = new_data_size) %>%
.[slice_idx, ]
}
} else if (inherits(.transform, "function")){
.transform_fun <- function(temp_new_data, new_data_size, slice_idx){
.transform(temp_new_data) %>%
dplyr::slice_tail(n = new_data_size) %>%
.[slice_idx, ]
}
}
.transform_fun
}
#' @rdname dot_prepare_transform
#' @export
.prepare_panel_transform <- function(.transform) {
if (inherits(.transform, "function")) {
.transform_fun <- function(temp_new_data, new_data_size, slice_idx, id) {
id_chr <- as.character(id)
..id <- dplyr::ensym(id_chr)
# print(.transform(temp_new_data))
.transform(temp_new_data) %>%
tibble::rowid_to_column(var = "..row_id") %>%
dplyr::group_by(!! ..id) %>%
dplyr::group_split() %>%
purrr::map(function(x){
dplyr::slice_tail(x, n = new_data_size) %>%
.[slice_idx, ]
}) %>%
dplyr::bind_rows() %>%
dplyr::arrange(..row_id) %>%
dplyr::select(-..row_id)
}
} else if (inherits(.transform, "recipe")) {
rlang::abort("Recursive Panel Data cannot use a recipe. Please use a transform function.")
}
.transform_fun
}
is_prepped_recipe <- function(recipe) {
is_prepped <- FALSE
if ("orig_lvls" %in% names(recipe)) {
is_prepped <- TRUE
}
return(is_prepped)
}