predict.rpart 和 predict.glm 之间的输出差异

Difference in output between predict.rpart and predict.glm

我将数据集拆分为训练样本和测试样本。然后我在训练数据上拟合一个 Logit 模型来预测测试样本的结果。我可以通过两种方式做到这一点:

使用 Tidyverse:

logit_mod <- logistic_reg() %>% 
 set_mode("classification") %>% 
 set_engine("glm") %>%
 fit(y ~ x + z, data=train)
res <- predict(logit_mod, new_data = test, type="prob")

或者使用 GLM class:

logit_mod <- glm(y ~ x + z, data=train, family='logit')
res <- predict(logit_mod, newdata=test, type="response")

两种方法都给我不同的输出(y 的概率)。虽然模型应该是相同的。提取 logit_mod[["fit"]] 得到的系数与使用 GLM 得到的 logit_mod 相同。

为什么第二种方法给出不同的预测概率?

如果您对 glm 二项式回归执行 predict,您将得到正数 class 的概率,并且 tidymodels 的概率会向上舍入。

例如,响应为 0/1 的简单回归,1 为正 class :

library(tidymodels)
set.seed(111)
df = data.frame(y = factor(rbinom(50,1,0.5)),x=runif(50),z=runif(50))
train = df[1:40,]
test = df[41:50,]

logit_mod <- logistic_reg() %>% 
 set_mode("classification") %>% 
 set_engine("glm") %>%
 fit(y ~ x + z, data=train)
res <- predict(logit_mod, new_data = test, type="prob")

这是 class 1 的预测:

res$.pred_1
       41        42        43        44        45        46        47        48 
0.3186626 0.3931925 0.4259043 0.3651420 0.6670263 0.6732433 0.5844562 0.5584770 
       49        50 
0.6791727 0.7567285

做glm,你可以看到它完全一样:

fit <- glm(y ~ x + z, data=train, family=binomial)
res2 <- predict(fit, newdata=test, type="response")

res2
       41        42        43        44        45        46        47        48 
0.3186626 0.3931925 0.4259043 0.3651420 0.6670263 0.6732433 0.5844562 0.5584770 
       49        50 
0.6791727 0.7567285