假设我有一个多类数据集(例如,iris)。我要执行分层的10折CV以测试模型性能。我在包splitstackchange
中找到了一个名为stratified
的函数,该函数根据我想要的数据的比例对我进行分层折叠。因此,如果我想要测试折痕,那将是数据行的0.1。
#One Fold
library(splitstackchange)
stratified(iris,c("Species"),0.1)
我想知道如何在10折循环中实现此功能或任何其他形式的分层简历。我无法破解其背后的逻辑。在这里,我提供了一个可重现的示例。
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折简历。我建议插入符号上的this非常有用的链接。
您发现以下解决方案很有用。
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.
)