【问题标题】:Caret returns different predictions with caret train object than it does with the extracted final modelCaret 使用插入符号训练对象返回的预测与提取的最终模型不同
【发布时间】:2018-10-28 01:21:34
【问题描述】:

我更喜欢在拟合模型时使用插入符号,因为它的相对速度和预处理能力。但是,我对它如何进行预测感到有些困惑。在比较直接从火车对象做出的预测和从提取的最终模型做出的预测时,我看到的数字非常不同。来自火车对象的预测似乎更准确。

library(caret)
library(ranger)

x1 <- rnorm(100)
x2 <- rbeta(100, 1, 1)

y <- 2*x1 + x2 + 5*x1*x2

data <- data.frame(x1, x2, y)
fitRanger <- train(y ~ x1 + x2, data = data,
                   method = 'ranger', 
                   tuneLength = 1,
                   preProcess = c('knnImpute', 'center', 'scale'))

predict.data <- data.frame(x1 = rnorm(10), x2 = rbeta(10, 1, 1))
prediction1 <- predict(fitRanger, newdata = predict.data)
prediction2 <- predict(fitRanger$finalModel, data = predict.data)$prediction

results <- data.frame(prediction1, prediction2)
results

我很肯定这与我如何预处理 train 对象中的数据有关,但即使我预处理测试数据并使用 Ranger 模型进行预测,值也是不同的

predict.data.processed <- predict.data %>% 
                             preProcess(method = c('knnImpute', 
                                                   'center', 
                                                   'scale')) %>% .$data

results3 <- predict(fitRanger$finalModel, data = predict.data.processed)$prediction

results <- cbind(results, results3)
results

我想从 ranger 模型中的每棵树中提取预测,而这在插入符号中是做不到的。有什么想法吗?

【问题讨论】:

    标签: r prediction r-caret


    【解决方案1】:

    为了从最终模型中获得与插入符号train 相同的预测,您应该以相同的方式预处理数据。将您的示例与set.seed(1) 一起使用:

    插入符号预测:

    prediction1 <- predict(fitRanger,
                           newdata = predict.data)
    

    游侠预测最终模型。插入符号预处理用于 predict.data

    prediction2 <- predict(fitRanger$finalModel,
                           data = predict(fitRanger$preProcess,
                                          predict.data))$prediction
    
    all.equal(prediction1,
              prediction2)
    #output
    TRUE
    

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 2021-01-22
      • 2018-02-06
      • 2019-04-27
      • 2016-07-08
      • 2015-03-25
      • 2021-08-11
      • 2015-12-30
      • 2019-06-21
      相关资源
      最近更新 更多