Skip to main content
 首页 » 编程设计

R逻辑回归舍入误差

2024年11月24日72JeffreyZhao

我刚刚学习 R 中的逻辑回归,并且遇到了一些令人困惑的事情。我有一个包含两个预测变量的大型数据集,我用它们来训练 logit 模型。

> model <- glm(as.factor(traintrain$loss)~.,data=traintrain[,-ncol(traintrain),with=FALSE],family=binomial) 
Warning message: 
glm.fit: fitted probabilities numerically 0 or 1 occurred  
> traintest$pred <- predict(model, traintest[,!"loss",with=FALSE],type="response") 

这是我的模型的输出

> model 
 
Call:  glm(formula = as.factor(traintrain$loss) ~ ., family = binomial,  
    data = traintrain[, -ncol(traintrain), with = FALSE]) 
 
Coefficients: 
(Intercept)         f527         f528   
 -2.4123661   -0.0001938    0.0001938   
 
Degrees of Freedom: 53804 Total (i.e. Null);  53802 Residual 
Null Deviance:      34540  
Residual Deviance: 32740    AIC: 32750 

这是我的测试数据集的样子

> traintest 
             f527      f528 loss       pred 
    1:  512556.00  512690.3    0 0.08359656 
    2:  516634.38  516635.0    0 0.08162884 
    3: 7261975.82 7262170.0    0 0.07658846 
    4: 1289936.09 1290091.5    0 0.08297042 
    5:  474396.88  476308.0    0 0.11410204 
   ---                                      
23056:  362651.53  362950.3    0 0.08625780 
23057: 1590119.98 1590853.3    0 0.09150362 
23058:  124814.17  125030.8    0 0.08530484 
23059:  346397.91  346536.2    0 0.08385799 
23060:   85503.97   85504.0    0 0.08213298 

如您所见,该模型在我的第一个测试数据点上的成功概率为 0.08359。作为健全性检查,我想将模型系数插入 logistic function以及我的第一次测试观察,并确保我得到相同的结果。这就是我得到的

> 1/(1+exp(-(-2.4123661-0.0001938*512556.00+0.0001938*512690.3))) 
[1] 0.08422038 

误差约 0.001。我注意到许多其他的差异看起来有点像这样。这只是舍入错误还是我犯了一个根本性错误?谢谢

请您参考如下方法:

试试这个:

sum( c(1, 512556.00, 512690.3) * coef(model) )  

感谢您的复选标记,但即使我在第一篇文章中提出了建议,下一个建议也可能行不通。有两个原因。第一个是 traintest 的输出看起来来自 data.table 对象,因为它不包含表示基线乘以(截距) 所需的“1” coef() 返回值。

sum( traintest[1, ] * coef(model) )