【问题标题】:Python Sklearn Logistic Regression Model Incorrect FitPython Sklearn 逻辑回归模型拟合不正确
【发布时间】:2023-04-03 12:14:01
【问题描述】:

对于逻辑回归,我试图从 Wikipedia logistic regression 页面重现结果。所以,我的代码如下所示:

import numpy as np
from sklearn.linear_model import LogisticRegression

x = np.array([0.5, 0.75, 1, 1.25, 1.5, 1.75, 1.75, 2, 2.25, 2.5, 2.75, 3, 3.25, 3.5, 4, 4.25, 4.5, 4.75, 5, 5.5])
y = np.array([0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1])

logistic = LogisticRegression()
logistic.fit(x[:, None], y)

但是如何获得拟合模型的摘要,具体如下:

            Coefficient  Std.Error  z-value  P-value (Wald)
Intercept   −4.0777      1.7610     −2.316    0.0206
Hours        1.5046      0.6287      2.393    0.0167

这是 Wikipedia 页面对拟合模型的内容。如果我尝试使用打印系数和截距,我会收到如下信息:

print(logistic.coef_)
print(logistic.intercept_)

[[ 0.61126347]]

[-1.36550178]

这显然是不同的。

问题是,为什么我的结果与在 Wikipedia 页面上获得的结果不同?

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    wikipedia 示例不包括模型参数上的正则化,但 sklearn 的LogisticRegression 默认使用 L2 正则化。 Set the inverse regularization strength, C, to a very high value to use no regularization,例如,

    logistic = LogisticRegression(penalty='l2', C=1e4)
    logistic.fit(x[:, None],y)
    
    print(logistic.coef_)
    print(logistic.intercept_)
    
    # [[ 1.50459727]]
    # [-4.07757136]
    

    【讨论】:

      【解决方案2】:

      sklearn中不存在R类型总结报告。

      对于分类任务,有一个函数:sklearn.metrics.classification_report,它计算几种类型的(预测)分数。

      要获得 R 风格的摘要报告,请查看 statsmodels 库。

      【讨论】:

        猜你喜欢
        • 2022-10-04
        • 2016-03-06
        • 2014-02-20
        • 2013-12-24
        • 2018-05-01
        • 2016-12-24
        • 2018-11-29
        • 2015-05-04
        • 2014-01-20
        相关资源
        最近更新 更多