r - R中的分层k-fold交叉验证
问题描述
假设我有一个多类数据集(例如 iris)。我想执行分层的 10 倍 CV 来测试模型性能。splitstackchange
我在包中找到了一个名为的函数,stratified
它根据我想要的数据的比例给我一个分层的折叠。因此,如果我想要一个测试折叠,它将是 0.1 个数据行。
#One Fold
library(splitstackchange)
stratified(iris,c("Species"),0.1)
我想知道如何在 10 倍循环中实现此功能或任何其他形式的分层 cv。我无法破解它背后的逻辑。这里我包括一个可重现的例子。
library(splitstackshape)
data=iris
names(data)[ncol(data)]=c("Y")
nFolds=10
for (i in 1:nFolds){
testing=stratified(data,c("Y"),0.1,keep.rownames=TRUE)
rn=testing$rn
testing=testing[,-"rn"]
row.names(testing)=rn
trainingRows=setdiff(1:nrow(data),as.numeric(row.names(testing)))
training=data[trainingRows,]
names(training)[ncol(training)]="Y"
}
解决方案
对 n-fold cv使用caret包。我建议在插入符号上提供这个非常有用的链接。
许多人发现以下解决方案很有用。
library(tidyverse)
library(splitstackshape)
library(caret)
library(randomForest)
data=iris
## split data into train and test using stratified sampling
d <- rownames_to_column(data, var = "id") %>% mutate_at(vars(id), as.integer)
training <- d %>% stratified(., group = "Species", size = 0.90)
dim(training)
## proportion check
prop.table(table(training$Species))
testing <- d[-training$id, ]
dim(testing)
prop.table(table(testing$Species))
## Modelling
set.seed(123)
tControl <- trainControl(
method = "cv", #cross validation
number = 10, #10 folds
search = "random" #auto hyperparameter selection
)
trRf <- train(
Species ~ ., #formulae
data = training[,-1], #data without id field
method = "rf", # random forest model
trControl = tControl # train control from previous step.
)
推荐阅读
- javascript - 正则表达式 Javascript - 无效的正则表达式:没有重复的数字输入
- ios - UITableViewDelegate:通过添加默认实现来减少重复代码,有更好的主意吗?
- swift - 是否可以在运行时使用 AutoLayout 根据屏幕高度或屏幕宽度中的最大值来制作 1:1 的纵横比?
- php - 如何将 Wordpress 文件从 localhost 传输到 azure
- javascript - Dojo:浮动窗格在关闭和重新打开时抛出错误
- html - HTML表格中的标签内允许有多少个标签?
- mysql - 如何优化sql select语句?
- swift - 如何在 AVQueuePlayer 中的项目之间插入暂停?
- python - 在列表中查找大于给定值的最小元素
- vue.js - 如何从url获取参数并在vue中显示