【问题标题】:R: compute the bootstrap estimate using rms:bootcov on caret model and glm modelR:在插入符号模型和 glm 模型上使用 rms:bootcov 计算引导估计
【发布时间】:2019-12-21 01:50:31
【问题描述】:

如何使用 rms 包中的函数 bootcov 计算回归系数的引导估计值?我使用示例数据集尝试了以下操作,但出现错误:

library(mlbench)
data(PimaIndiansDiabetes)

library(caret)
trControl <- trainControl(method = "repeatedcv",
                          repeats = 3,
                          classProbs = TRUE,
                          number = 10, 
                          savePredictions = TRUE,
                          summaryFunction = twoClassSummary)

caret_model <- train(diabetes~., 
                     data=PimaIndiansDiabetes, 
                     method="glm", 
                     trControl=trControl)

library(rms)
set.seed(1234)
reduced_model_bootcov <- bootcov(caret_model$finalModel, B=100)

错误是:

bootcov(caret_model$finalModel, B = 100) 中的错误:你没有 在 fit 中指定 x=TRUE 和 y=TRUE

如果我使用函数glm 来构建模型,我会这样做:

model <- glm(diabetes~., 
             data=PimaIndiansDiabetes, 
             family=binomial,
             x=TRUE, y=TRUE)
model_bootcov <- bootcov(model, B=100)

但我又遇到了另一个错误:

bootcov 中的错误(模型,B = 100):fitter 无效

【问题讨论】:

  • 嘿,bootcov 不能接受 glm 对象,根据它的小插图,它用于“来自 ols、lrm、cph、psm、Rq 和任何其他拟合的回归系数集合,其中 x=真,y=真"
  • 我猜你可以使用包 boot 来计算回归系数的引导估计?
  • @StupidWolf。感谢您的答复。我是这种技术的新手。你能在我的数据集PimaIndiansDiabetes 上发布一个工作示例吗?
  • 当然没问题。

标签: r logistic-regression statistics-bootstrap


【解决方案1】:

原来在rms中有一个叫做glm的拟合函数,它是glm的一个包装器,但是如果你对使用bootcov感兴趣,也可以使用它。所以要让 bootcov 工作:

library(mlbench)
library(rms)
data(PimaIndiansDiabetes)

model <- rms::Glm(diabetes~., 
             data=PimaIndiansDiabetes, 
             family=binomial,
             x=TRUE, y=TRUE)
model_bootcov <- bootcov(model, B=1000)

使用引导:

library(boot)
glm.fun <- function(dat, inds){
  fit <- glm(diabetes~.,family=binomial,data=dat[inds,])
      coef(fit)
     }
model_boot <- boot(PimaIndiansDiabetes, glm.fun, R = 1000)

我们可以比较两个不同的模型是如何引导的,当然种子是不同的,很可能你需要先设置相似的种子:

library(tidyr)
library(dplyr)
library(ggplot2)

melt_matrix = function(mat,NAMES,X){
colnames(mat) = NAMES
data.frame(mat) %>% 
tibble::rownames_to_column("B") %>% 
pivot_longer(-B) %>%
mutate(type=X)
}

VAR = names(coef(model))

plotdf = rbind(
melt_matrix(model_boot$t,VAR,"boot"),
melt_matrix(model_bootcov$boot.Coef,VAR,"bootcov")
)

ggplot(plotdf,aes(x=type,y=value))+ geom_violin() + facet_wrap(~name,scale="free_y")

【讨论】:

  • 是否可以使用来自caret 的模型?因为我想在使用caret 构建时利用trainControl (特别是,我想要重复的K-fold 交叉验证,就像我的问题的第一部分一样)。谢谢
  • 您使用交叉验证来获取拟合参数。最后,数据适合整个数据集,请参阅 length(caret_model$finalModel$y) 示例
  • 结果和只拟合一个glm是一样的,因为glm没有训练超参数?我建议只使用 glm fit。
  • 我还想绘制包含在 caret$pred 中的 AUC。我想是因为我想用一种方法完成很多事情......
  • 一旦有了预测和概率来绘制 AUC,就可以使用包 ROCR
猜你喜欢
  • 1970-01-01
  • 2021-08-14
  • 2020-11-24
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 2016-04-07
  • 2015-04-06
  • 2019-05-02
相关资源
最近更新 更多