caret如何拆分trainControl中的数据?
How does caret split the data in trainControl?
我需要在交叉验证中按顺序拆分数据,例如:
fold-1 观察值从 1 到 10,fold-2 观察值从 11 到 20 等等...
trainControl()
和 caret
中的任何方法是否按顺序执行?我想“cv”方法以这种方式拆分数据,但插入符号的文档中没有任何明确的内容来保证这一点。
您可以使用 indexOut=
参数提供折叠。查看 help page。下面我以 iris 为例,我不能按顺序 运行 因为数据是按物种排序的,所以我先随机化它:
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.
我需要在交叉验证中按顺序拆分数据,例如:
fold-1 观察值从 1 到 10,fold-2 观察值从 11 到 20 等等...
trainControl()
和 caret
中的任何方法是否按顺序执行?我想“cv”方法以这种方式拆分数据,但插入符号的文档中没有任何明确的内容来保证这一点。
您可以使用 indexOut=
参数提供折叠。查看 help page。下面我以 iris 为例,我不能按顺序 运行 因为数据是按物种排序的,所以我先随机化它:
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.