首页 > 解决方案 > Caret 包的置信区间

问题描述

我正在使用 Caret 包进行一些回归分析。我在网上看过,但现在已经找到了解决方案。我的代码如下。有没有办法计算这个模型的置信区间?

set.seed(123)
# Set up repeated k-fold cross-validation
train.control <- trainControl(method = "cv", number = 10,
                              predictionBounds = c(0, NA), verboseIter = TRUE)
# Train the model
step.model <- train(`likes` ~., data = reduced_Data,
                    method = "leapSeq", 
                    tuneGrid = data.frame(nvmax = 1:13),
                    trControl = train.control)


step.model$results

step.model$bestTune

summary(step.model$finalModel)

coef(step.model$finalModel, 2)

我曾尝试使用基础包中的预测功能,但没有运气

predict(step.model$finalModel, my_data, interval = "confidence")

标签: rregression

解决方案


您拥有的是一个 regsubset 类,有来自不同术语子集的结果,您需要一个标准来选择哪个是最佳模型,重新拟合模型并进行预测,例如:

library(caret)
train.control <- trainControl(method = "cv",number=3)
step.model <- train(mpg ~., data = mtcars,
method = "leapSeq",trControl = train.control)

假设我们使用具有最大 r 平方的模型:

res = summary(step.model$finalModel)
bestm = which.max(res$adjr2)
terms_to_use = names(which(res$which[bestm,]))[-1]
terms_to_use
1] "cyl" "hp"  "wt"

拟合最终模型:

final_form = as.formula(paste("mpg ~",paste(terms_to_use,collapse="+")))
fit = lm(final_form,data=mtcars)

要获得合适的 se:

predict(fit,se=TRUE)

要获得 95 ci 的系数:

confint(fit)
                 2.5 %       97.5 %
(Intercept) 35.0915623 42.412012412
cyl         -2.0701179  0.186884238
hp          -0.0423655  0.006289293
wt          -4.6839740 -1.649972191

推荐阅读