R插入:让主题与数据子集进行交叉验证以进行培训?

时间:2016-04-19 12:21:56

标签: r subset r-caret cross-validation

我想使用R插入符号(参见this example)执行离开主题交叉验证,但仅在训练中使用数据的子集来创建CV模型。仍然,左侧的CV分区应该作为一个整体使用,因为我需要测试一个遗漏主题的所有数据(无论数百万个样本由于计算限制而无法在训练中使用)。

我使用subsetindex的{​​{1}}和caret::train参数创建了一个最小的2类分类示例来实现此目的。根据我的观察,这应该可以解决问题,但实际上我很难确保评估仍以离开主题的方式进行。也许有这方面经验的人可以对此有所了解:

caret::trainControl

情节(myRoc,main ='all')

个别科目的表现

l_ply(唯一(m3 $ pred $ Resample),. fun = function(cls){     pred_sub< - m3 $ pred [m3 $ pred $ Resample == cls,]     myRoc< - roc(predictor = pred_sub [,3],response = pred_sub $ obs)         情节(myRoc,main = cls)     })

谢谢你的时间!

1 个答案:

答案 0 :(得分:1)

同时在index中同时使用indexOutcaret::trainControl参数似乎可以解决问题(感谢Max提示in this question)。这是更新的代码:

library(plyr)
library(caret)
library(pROC)
library(ggplot2)
str(diamonds)

# with diamonds we want to predict cut and look at results for different colors = subjects
d <- diamonds
d <- d[d$cut %in% c('Premium', 'Ideal'),] # make a 2 class problem
d$cut <- factor(d$cut)
indexes_data <- c(1,5,6,8:10)
indexes_labels <- 2 

# population independent CV partitions for training and left out partitions for evaluation
indexes_populationIndependence_subjects <- 3
index <- llply(unique(d[,indexes_populationIndependence_subjects]), function(cls) c(which(d[,indexes_populationIndependence_subjects]!=cls)))
names(index) <- paste0('sub_', unique(d[,indexes_populationIndependence_subjects]))
indexOut <- llply(index, function(part) (1:nrow(d))[-part])
names(indexOut) <- paste0('sub_', unique(d[,indexes_populationIndependence_subjects]))
# subsample partitions for training
index <- llply(index, function(i) sample(i, 1000))

m3 <- train(x = d[,indexes_data], 
            y = d[,indexes_labels], 
            method = 'glm', 
            metric = 'ROC',
            trControl = trainControl(returnResamp = 'final',
                                    savePredictions = T,
                                    classProbs = T, 
                                    summaryFunction = twoClassSummary, 
                                    index = index, 
                                    indexOut = indexOut))
m3$resample # seems OK
str(m3$pred) # seems OK
myRoc <- roc(predictor = m3$pred[,3], response = m3$pred$obs)
plot(myRoc, main = 'all')
# analyze results per subject
l_ply(unique(m3$pred$Resample), .fun = function(cls) {
    pred_sub <- m3$pred[m3$pred$Resample==cls,]
    myRoc <- roc(predictor = pred_sub[,3], response = pred_sub$obs)
    plot(myRoc, main = cls)
} )

尽管如此,我并不完全确定这是否实际上是以人口独立的方式进行估算,所以如果有人知道有关详细信息,请分享您的想法!