【问题标题】:Obtaining predictions on test datasets for k-fold cross validation in caret获取测试数据集的预测以在插入符号中进行 k 折交叉验证
【发布时间】:2016-04-08 19:57:27
【问题描述】:

我有点困惑 caret 如何在 k-fold 交叉验证中对测试折叠进行评分。

我想生成一个数据框或矩阵,其中包含十个测试数据集在 10 倍交叉验证中的得分记录。

例如,使用 iris 数据集训练决策树模型:

install.packages("caret", dependencies=TRUE) 

library(caret)

data(iris)

train_control <- trainControl(method="cv", number=10, savePredictions = TRUE), 

model <- train(Species ~ ., data=iris, trControl=train_control, method="rpart")

model$pred

model$pred 命令列出了 450 条记录中十折的预测。

这似乎不对 - model$pred 不应该为十个测试折叠中的 150 条记录 生成预测(每个测试折叠 1/10 * 150 = 15 条记录)? 450条记录是如何产生的?

【问题讨论】:

    标签: r prediction r-caret cross-validation


    【解决方案1】:

    默认情况下,train 会遍历 rpart 的复杂度参数 cp 的三个值(参见 ?rpart.control):

    library(caret)
    data(iris)
    train_control <- trainControl(method="cv", number=10, savePredictions = TRUE) 
    
    model <- train(Species ~ ., 
                   data=iris, 
                   trControl=train_control, 
                   method="rpart")
    nrow(model$pred)
    # [1] 450
    length(unique(model$pred$cp))
    # [1] 3
    

    您可以通过显式指定cp=0.05 来更改它:

    model <- train(Species ~ ., 
                   data=iris, 
                   trControl=train_control, 
                   method="rpart", 
                   tuneGrid = data.frame(cp = 0.05))
    nrow(model$pred)
    # [1] 150
    length(unique(model$pred$cp))
    # [1] 1
    

    或使用tuneLength=1 代替默认的3

    model <- train(Species ~ ., 
                   data=iris, 
                   trControl=train_control, 
                   method="rpart", 
                   tuneLength = 1)
    nrow(model$pred)
    # [1] 150
    length(unique(model$pred$cp))
    # [1] 1
    

    【讨论】:

    • 谢谢卢克A!我需要注意为每个过程指定调整参数。
    • 替代,可以指定参数savePredictions="final"
    猜你喜欢
    • 2018-03-20
    • 2016-05-12
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2020-11-07
    相关资源
    最近更新 更多