python - 使用 statsmodels 与 scikit-learn 的逻辑回归 : large difference in predictions

标签 python scikit-learn statsmodels

我使用 Python 库 statsmodels 和 scikit-learn 进行逻辑回归和预测。类别概率预测结果差异很大。我知道解决方案是用数字计算的,但是,我希望结果只会略有不同。我的期望是默认情况下两者都使用 logistic 函数 - 这是正确的还是我需要设置任何选项?

这是我的统计模型代码:

import numpy as np
from sklearn.linear_model import LogisticRegression
x = np.array([1,2,3,4,5]).reshape((-1, 1))
y = np.array([0,0,1,1,1])
model = LogisticRegression()
model.fit(x, y)
model.predict_proba(np.array([2.5, 7]).reshape(-1,1))
Out:  array([[0.47910045, 0.52089955],
       [0.00820326, 0.99179674]])

即1 类的预测值为 0.521 和 0.992。

如果我改用 scikit-learn,我会得到 0.730 和 0.942:

import statsmodels.api as sm
x = [1, 2, 3, 4, 5]
y = [0,0,1,1,1]
model = sm.Logit(y, x)
results = model.fit()
results.summary()
results.predict([2.5, 7])
Out: array([0.73000205, 0.94185834])

(作为旁注:如果我使用 R 而不是 Python,则预测为 0.480 和 1.000,即它们再次完全不同。)

我怀疑这些差异不是数值上的,而是背后有分析数学原因,例如使用的不同功能。有人可以帮忙吗?

谢谢!

最佳答案

我现在找到了解决方案。有两个原因:

(1) scikit-learn 默认使用正则化,需要关闭。这是通过将 scikit-learn 代码中的第 5 行更改为:

model = LogisticRegression(penalty='none')

(2) Yati Raj 提到的那个 - 感谢您的提示! Statsmodels 不会自动拟合截距。这可以通过添加行来更改

x = sm.add_constant(x)

在 statsmodels 代码中。

关于python - 使用 statsmodels 与 scikit-learn 的逻辑回归 : large difference in predictions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63225847/

相关文章:

python - GRPC。测试上下文

Python:TIFFReadDirectory 警告:带有标签的未知字段

python - PIL 剪贴板图像到 Base64 字符串

python - python 的哪个统计模块支持单向方差分析和事后测试(Tukey、Scheffe 或其他)?

python - pandas dataframe将函数应用于具有nans的列

python - 为什么打开 jupyter notebook 会得到 "' outputs' were unexpected"错误?

python - 使用 XGBoost 进行超参数网格搜索 - 评分函数与评估指标

python - 对象相似性 Pandas 和 Scikit Learn

pandas - 使用 Graphviz 绘制决策树时出现“特征名称长度与特征数量不匹配”错误

Python ARIMA 预测返回 NaN