如何将R中的一次交叉验证转换为K次交叉验证



我有一个GAM模型,我想通过R中5倍的交叉验证来计算AUC、TSS(真技能统计(和RMSE。不幸的是,插入符号包不支持GAM,因此无法使用。由于我没有找到任何替代方案,我尝试自己构建交叉验证的代码,它运行得很好,唯一的问题是它只有一次交叉验证。有人能帮我做这个5倍的吗?很抱歉,如果这是一个初级问题,我是R.的新手

sample <- sample(c(TRUE, FALSE), nrow(DF), replace=TRUE, prob=c(0.8,0.2))
train <- DF[sample, ]
test <- DF[!sample, ] 
predicted <- predict(GAM, test, type="response")
# Calculating RMSE
RMSE(test$Y, predicted)
# Calculating AUC
auc(test$Y, predicted)
GAM_TSS <- gam(Y ~ X1 + X2 + X3 + X4 + s(X5, k = 3), train, family = "binomial")
test$pred <- predict(GAM_TSS, type="response", newdata=test)
roc.curve <- roc(test$Y, test$pred, ci=T)
plot(roc.curve)
threshold <- 0.1
CM <- confusionMatrix(factor(test$pred>threshold), factor(test$P_A==1), positive="TRUE")
CM <- CM$byClass
Sensitivity <- CM[['Sensitivity']]
Specificity <- CM[['Specificity']]
# Calculating TSS
TSS = Sensitivity + Specificity - 1
TSS

我过去在GAM中遇到过这个问题。我的方法是创建一个向量,将数据随机拆分为大小尽可能相等的部分,然后按如下方式循环折叠ID:

k <- 5
FoldID <- rep(1:k, ceiling(nrow(modelData)/k))
length(FoldID) <- nrow(modelData)
FoldID <- sample(FoldID, replace = FALSE)
for(fold in 1:k){
train_data <- modelData[FoldID != fold, ]
val_data <- modelData[FoldID == fold, ]
# Create training model and predictions
# Calculate RMSE data etc.
# Add a line with fold validation results to a dataframe
}
# Calculate column means of your validation results frame

我会让你填补空白,以满足你自己的要求。为重复添加一个外循环(在FoldID创建之外(也是一个好主意。

最新更新