逻辑回归 scikit-learn 与 statsmodels 的系数

Coefficients for Logistic Regression scikit-learn vs statsmodels

当使用两个 API 执行逻辑回归时,它们给出不同的系数。 即使是这个简单的例子,它在系数方面也不会产生相同的结果。我遵循关于同一主题的旧建议的建议,例如在 sklearn 中为参数 C 设置一个大值,因为它使惩罚几乎消失(或设置 penalty="none")。

import pandas as pd
import numpy as np
import sklearn as sk
from sklearn.linear_model import LogisticRegression
import statsmodels.api as sm

n = 200

x = np.random.randint(0, 2, size=n)
y = (x > (0.5 + np.random.normal(0, 0.5, n))).astype(int)

display(pd.crosstab( y, x ))


max_iter = 100

#### Statsmodels
res_sm = sm.Logit(y, x).fit(method="ncg", maxiter=max_iter)
print(res_sm.params)

#### Scikit-Learn
res_sk = LogisticRegression( solver='newton-cg', multi_class='multinomial', max_iter=max_iter, fit_intercept=True, C=1e8 )
res_sk.fit( x.reshape(n, 1), y )
print(res_sk.coef_)

例如,我只是 运行 上面的代码,得到 statsmodels 的 1.72276655 和 sklearn 的 1.86324749。当 运行 多次时,它总是给出不同的系数(有时比其他系数更接近,但无论如何)。

因此,即使在那个玩具示例中,两个 API 给出了不同的系数(因此优势比),并且对于真实数据(此处未显示),它几乎得到 "out of control"...

我错过了什么吗?我怎样才能产生相似的系数,例如逗号后至少一两个数字?

您的代码存在一些问题。

首先,您在此处显示的两个模型 不是 等效的:尽管您将 scikit-learn LogisticRegressionfit_intercept=True 相匹配(这是默认设置),你不会用你的 statsmodels 一个;来自统计模型 docs:

An intercept is not included by default and should be added by the user. See statsmodels.tools.add_constant.

这似乎是一个常见的混淆点 - 例如参见 [​​=27=](以及自己的答案)。

另一个问题是,尽管您处于二元分类设置中,但您在 LogisticRegression 中要求 multi_class='multinomial',这不应该是这种情况。

第三个问题是,如相关交叉验证线程中所述Logistic Regression: Scikit Learn vs Statsmodels

There is no way to switch off regularization in scikit-learn, but you can make it ineffective by setting the tuning parameter C to a large number.

这使得这两个模型在原则上再次不可比,但您已通过设置 C=1e8 成功解决了此问题。事实上,从那时起(2016 年),scikit-learn 确实添加了一种关闭正则化的方法,根据 docs:

设置 penalty='none'

If ‘none’ (not supported by the liblinear solver), no regularization is applied.

现在应该将其视为关闭正则化的规范方法。

因此,将这些更改合并到您的代码中,我们有:

np.random.seed(42) # for reproducibility

#### Statsmodels
# first artificially add intercept to x, as advised in the docs:
x_ = sm.add_constant(x)
res_sm = sm.Logit(y, x_).fit(method="ncg", maxiter=max_iter) # x_ here
print(res_sm.params)

给出结果:

Optimization terminated successfully.
         Current function value: 0.403297
         Iterations: 5
         Function evaluations: 6
         Gradient evaluations: 10
         Hessian evaluations: 5
[-1.65822763  3.65065752]

数组的第一个元素是截距,第二个元素是 x 的系数。而对于 scikit 学习我们有:

#### Scikit-Learn

res_sk = LogisticRegression(solver='newton-cg', max_iter=max_iter, fit_intercept=True, penalty='none')
res_sk.fit( x.reshape(n, 1), y )
print(res_sk.intercept_, res_sk.coef_)

结果为:

[-1.65822806] [[3.65065707]]

这些结果几乎完全相同,都在机器的数值精度范围内。

np.random.seed() 的不同值重复此过程不会改变上面显示的结果的本质。