【发布时间】:2020-12-29 22:22:42
【问题描述】:
我需要将数据拆分成一个顺序结构化的交叉验证,比如:
fold-1 的观测值从 1 到 10,fold-2 的观测值的索引从 11 到 20 等等...
caret 中的trainControl() 中的任何方法是否按顺序执行?我想“cv”方法以这种方式拆分数据,但插入符号的文档中没有很清楚的保证。
【问题讨论】:
标签: r split cross-validation r-caret sampling
我需要将数据拆分成一个顺序结构化的交叉验证,比如:
fold-1 的观测值从 1 到 10,fold-2 的观测值的索引从 11 到 20 等等...
caret 中的trainControl() 中的任何方法是否按顺序执行?我想“cv”方法以这种方式拆分数据,但插入符号的文档中没有很清楚的保证。
【问题讨论】:
标签: r split cross-validation r-caret sampling
您可以使用indexOut= 参数提供折叠。查看help page。下面我以 iris 为例,由于数据是按 Species 排序的,所以不能顺序运行,所以我先随机化:
library(caret)
dat = iris[sample(nrow(iris)),]
我创建了折叠,下面是基于 10 折叠交叉验证,所以每个折叠占总行数的 1/10:
idx = (1:nrow(dat) - 1) %/% (nrow(dat) / 10)
Folds = split(1:nrow(dat),idx)
我们可以看看索引的分配:
Folds[[1]]
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Folds[[2]]
[1] 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
然后用这个运行train():
model = train(Species ~.,method="rf",data=dat,
trControl=trainControl(method="cv",indexOut=Folds))
model
Random Forest
150 samples
4 predictor
3 classes: 'setosa', 'versicolor', 'virginica'
No pre-processing
Resampling: Cross-Validated (10 fold)
Summary of sample sizes: 135, 135, 135, 135, 135, 135, ...
Resampling results across tuning parameters:
mtry Accuracy Kappa
2 1.0000000 1.0000000
3 1.0000000 1.0000000
4 0.9933333 0.9895833
Accuracy was used to select the optimal model using the largest value.
The final value used for the model was mtry = 2.
【讨论】: