我有如下数据集
set.seed(503)
foo <- data.table(group = rep(LETTERS[1:6], 150),
y = rnorm(n = 6 * 150, mean = 5, sd = 2),
x1 = rnorm(n = 6 * 150, mean = 5, sd = 10),
x2 = rnorm(n = 6 * 150, mean = 25, sd = 10),
x3 = rnorm(n = 6 * 150, mean = 50, sd = 10),
x4 = rnorm(n = 6 * 150, mean = 0.5, sd = 10),
x5 = sample(c(1, 0), size = 6 * 150, replace = T))
foo[, period := 1:.N, by = group]
问题:我想使用变量y
对每个group
预测x1, ..., x5
提前一步>
我想在caret
中运行一些模型来决定使用哪个模型。
到目前为止,我正在使用时间片在循环中运行它
window.length <- 115 timecontrol <- trainControl(method = 'timeslice', initialWindow = window.length, horizon = 1, selectionFunction = "best", fixedWindow = TRUE, savePredictions = 'final') model_list <- list() for(g in unique(foo$group)){ for(model in c("xgbTree", "earth", "cubist")){ dat <- foo[group == g][, c('group', 'period') := NULL] model_list[[g]][[model]] <- train(y ~ . - 1, data = dat, method = model, trControl = timecontrol) } }
但是,我想同时运行所有组,使用虚拟变量来标识每个组,例如
dat <- cbind(foo, model.matrix(~ group- 1, foo)) y x1 x2 x3 x4 x5 period groupA groupB groupC groupD groupE groupF 1: 5.710250 11.9615460 22.62916 31.04790 -4.821331e-04 1 1 1 0 0 0 0 0 2: 3.442213 8.6558983 32.41881 45.70801 3.255423e-01 1 1 0 1 0 0 0 0 3: 3.485286 7.7295448 21.99022 56.42133 8.668391e+00 1 1 0 0 1 0 0 0 4: 9.659601 0.9166456 30.34609 55.72661 -7.666063e+00 1 1 0 0 0 1 0 0 5: 5.567950 3.0306864 22.07813 52.21099 5.377153e-01 1 1 0 0 0 0 1 0
但是仍然使用
timeslice
以正确的时间顺序运行时间序列。
[是否有一种方法可以在time
中声明trainControl
变量,所以在这种情况下,我的one step ahead
预测每轮使用另外六个观察值,而删除前六个观察值?
我可以通过对数据进行排序并与horizon
自变量(给定n
组,按时间变量进行排序并放入horizon = n
)来做到这一点,但是如果组数更改,则必须更改。并且initial.window
必须为time * n_groups
timecontrol <- trainControl(method = 'timeslice', initialWindow = window.length * length(unique(foo$group)), horizon = length(unique(foo$group)), selectionFunction = "best", fixedWindow = TRUE, savePredictions = 'final')
还有其他方法吗?
我有一个像下面的set.seed(503)foo
我将嵌套组并使用purrr
函数来解决此问题。这种方法更加灵活,如果您喜欢使用furrr
,则可以并行运行所有内容。