R中的分层k倍交叉验证

时间:2020-04-17 01:41:03

标签: r data-mining cross-validation sampling multiclass-classification

假设我有一个多类数据集(例如,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"
    }

2 个答案:

答案 0 :(得分:0)

使用插入符软件包进行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.
)

答案 1 :(得分:0)

很晚了,但我希望我能帮助别人。 示例代码对我有帮助:

library(splitstackshape)


dat1 <- data.frame(ID = 1:100,
              A = sample(c("AA", "BB", "CC", "DD", "EE"), 100, replace = TRUE),
              B = rnorm(100), C = abs(round(rnorm(100), digits=1)),
              D = sample(c("CA", "NY", "TX"), 100, replace = TRUE),
              E = sample(c("M", "F"), 100, replace = TRUE))



flds=list()
dat=dat1

for(i in 1:10){
  j=10-(i-1)
  if(j>1){
  a=stratified(dat, c("E", "D"), size = 1/j)
  flds[[i]]=a$ID
  dat=dat%>%filter(ID %in% setdiff(dat$ID,a$ID))
  } else{
  flds[[i]]=dat$ID  
  }
}