首页 > 解决方案 > 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"
    }

标签: rdata-miningcross-validationsamplingmulticlass-classification

解决方案


对 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.
)

推荐阅读