使用插入符号指定交叉验证折叠

时间:2015-08-18 16:34:54

标签: r neural-network cross-validation r-caret nnet

您好,并提前致谢。我正在使用caret来交叉验证nnet包中的神经网络。在method函数的train.Control参数中,我可以指定交叉验证类型,但所有这些都会随机选择观察结果以进行交叉验证。无论如何,我可以使用插入符号通过ID或硬编码参数来交叉验证我的数据中的特定观察结果吗?例如,这是我当前的代码:

library(nnet) 
library(caret) 
library(datasets) 

data(iris) 

train.control <- trainControl( 
    method = "repeatedcv" 
    , number = 4 
    , repeats = 10 
    , verboseIter = T 
    , returnData = T 
    , savePredictions = T 
    ) 

tune.grid <- expand.grid( 
    size = c(2,4,6,8)
    ,decay = 2^(-3:1) 
    ) 

nnet.train <- train( 
    x = iris[,1:4] 
    , y = iris[,5] 
    , method = "nnet" 
    , preProcess = c("center","scale")  
    , metric = "Accuracy" 
    , trControl = train.control 
    , tuneGrid = tune.grid 
    ) 
nnet.train 
plot(nnet.train)

假设我想在CV_GROUP数据框中添加另一个列iris,我希望在该列的1值的观察值上交叉验证神经网络:

iris$CV_GROUP <- c(rep.int(0,times=nrow(iris)-20), rep.int(1,times=20))

这可以用caret吗?

1 个答案:

答案 0 :(得分:5)

使用indexindexOut控制选项。我编写了一种实现此方法的方法,让您选择所需的重复和折叠次数:

library(nnet)
library(caret)
library(datasets)
library(data.table)
library(e1071)

r <- 2 # number of repeats
k <- 5 # number of folds
data(iris)
iris <- data.table(iris)

# Create folds and repeats here - you could create your own if you want #
set.seed(343)
for (i in 1:r) {
    newcol <- paste('fold.num',i,sep='')
    iris <- iris[,eval(newcol):=sample(1:k, size=dim(iris)[1], replace=TRUE)]
}

folds.list.out <- list()
folds.list <- list()
list.counter <- 1
for (y in 1:r) {
    newcol <- paste('fold.num', y, sep='')
    for (z in 1:k) {
        folds.list.out[[list.counter]] <- which(iris[,newcol,with=FALSE]==z)
        folds.list[[list.counter]] <- which(iris[,newcol,with=FALSE]!=z)
        list.counter <- list.counter + 1
    }
    iris <- iris[,!newcol,with=FALSE]
}

tune.grid <- expand.grid( 
    size = c(2,4,6,8)
    ,decay = 2^(-3:1) 
    ) 

train.control <- trainControl( 
    index=folds.list
    , indexOut=folds.list.out
    , verboseIter = T 
    , returnData = T 
    , savePredictions = T 
    ) 

iris <- data.frame(iris)

nnet.train <- train( 
    x = iris[,1:4] 
    , y = iris[,5] 
    , method = "nnet" 
    , preProcess = c("center","scale")  
    , metric = "Accuracy" 
    , trControl = train.control 
    , tuneGrid = tune.grid 
    ) 

nnet.train
plot(nnet.train)