r - 在 caret R 包中控制交叉验证的抽样

标签 r sampling cross-validation r-caret

我有以下问题。在来自 N 个主题的数据集中,每个主题我有几个样本。我想在数据集上训练一个模型,但我想确保在每次重采样中,在训练集中没有受试者的重复。

或者,我会按主题阻止交叉验证。这可能吗?

如果没有 caret 包,我会做类似的事情(模拟代码)

subjects <- paste0("X", 1:10)
samples  <- rep(subjects, each=5)
x <- matrix(runif(50 * 10), nrow=50)
loocv <- function(x, samples) {
  for(i in 1:nrow(x)) {
     test <- x[i,]
     train <- x[ samples != samples[i],]
     # create the model from train and predict for test
  }
}

或者,或者,

looSubjCV <- function(x, samples, subjects) {
   for(i in 1:length(subjects)) {
     test <- x[ samples == subjects[i], ]
     train <- x[ samples != subjects[i], ]
     # create the model from train and predict for test
  }
}

否则,同一受试者的其他样本的存在将导致模型过拟合。

最佳答案

不是直接的,但您绝对可以使用 trainControlindexindexOut 参数来完成。这是一个使用 10 倍 CV 的示例:

library(caret)
library(nlme)

data(Orthodont)
head(Orthodont)
subjects <- as.character(unique(Orthodont$Subject))

## figure out folds at the subject level

set.seed(134)
sub_folds <- createFolds(y = subjects, list = TRUE, returnTrain = TRUE)

## now create the mappings to which *rows* are in the training set
## based on which subjects are left in or out

in_train <- holdout <- vector(mode = "list", length = length(sub_folds))

row_index <- 1:nrow(Orthodont)

for(i in seq(along = sub_folds)) {
  ## Which subjects are in fold i
  sub_in <- subjects[sub_folds[[i]]]
  ## which rows of the data correspond to those subjects
  in_train[[i]] <- row_index[Orthodont$Subject %in% sub_in]
  holdout[[i]]  <- row_index[!(Orthodont$Subject %in% sub_in)]  
}

names(in_train) <- names(holdout) <- names(sub_folds)

ctrl <- trainControl(method = "cv",
                     savePredictions = TRUE,
                     index = in_train,
                     indexOut = holdout)

mod <- train(distance ~ (age+Sex)^2, data = Orthodont,
             method = "lm", 
             trControl = ctrl)

first_fold <- subset(mod$pred, Resample == "Fold01")

## These were used to fit the model
table(Orthodont$Subject[-first_fold$rowIndex])
## These were heldout:
table(Orthodont$Subject[first_fold$rowIndex])

关于r - 在 caret R 包中控制交叉验证的抽样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31135740/

相关文章:

r - R中并行计算的stdout和stderr

r - 在 R 中使用sample.split 不正确地分割数据以及逻辑回归问题

json - 转置 JSON 字典列表以在 R 中进行分析

r - R 中两个类别的预测类别概率

java - 合成采样声音

machine-learning - 回归中的 scikit-learn 交叉验证分数

python - 如何将 GridSearchCV 中的验证集与训练集分开标准化?

python - 如何使用交叉验证模型获取系数

audio - 低频声音采样

numpy - 在 3D numpy 网格中绘制/采样球体