我有一个类似下面的数据集:
问题:我想要为每个组使用变量 x1,...,x5,预测 y 一步;我想在 caret 中运行几个模型以决定要使用哪一个。目前,我正在使用 timeslice 循环来运行它。
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]
问题:我想要为每个组使用变量 x1,...,x5,预测 y 一步;我想在 caret 中运行几个模型以决定要使用哪一个。目前,我正在使用 timeslice 循环来运行它。
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
以正确的时间顺序运行时间序列。
是否有一种方法可以在trainControl
中声明time
变量,使得我的one step ahead
预测在每个回合中使用六个更多观测值,并删除前6个观测值?
我可以通过对数据进行排序并操纵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')
还有其他的方法吗?
initialWindow
和horizon
取决于组大小吗?你在问题结尾提供的代码是否已经给出了你期望的结果? - Giovanni ColittitrainControl
对象时,存在一些信息泄漏,因为在第一个训练/测试集中,你使用了115 * 6个obs来预测接下来的6个obs,而默认情况下,训练集仅添加下一个观察值。所以现在你正在预测A组的117期和B-F组的116期,其中A组的116期已经被添加到训练集中。所以你在训练和测试集中使用了相同的期间?这就是你的意思吗? - Giovanni ColittitrainControl()
函数中的skip
参数。请查看我的最新回答。 - Giovanni Colitti