scikit-learn - scikit学习: how to check coefficients significance

标签 scikit-learn logistic-regression anova dummy-data

我尝试使用 SKLearn 对相当大的数据集进行 LR,该数据集包含约 600 个虚拟变量和很少的区间变量(数据集中有 300 K 行),并且生成的混淆矩阵看起来很可疑。我想检查返回系数和方差分析的显着性,但我找不到如何访问它。有可能吗?对于包含大量虚拟变量的数据,最佳策略是什么?多谢!

最佳答案

Scikit-learn 故意不支持统计推断。如果您想要开箱即用的系数显着性检验(以及更多),您可以使用 Logit来自Statsmodels的估计器。该包模仿 R 中的接口(interface) glm 模型,因此您可能会发现它很熟悉。

如果您仍然想坚持使用 scikit-learn LogisticRegression,您可以使用渐近逼近来分布最大似然估计。准确地说,对于最大似然估计值 theta 的向量,其方差-协方差矩阵可以估计为 inverse(H),其中 Htheta 处的对数似然 Hessian 矩阵。这正是下面函数的作用:

import numpy as np
from scipy.stats import norm
from sklearn.linear_model import LogisticRegression

def logit_pvalue(model, x):
    """ Calculate z-scores for scikit-learn LogisticRegression.
    parameters:
        model: fitted sklearn.linear_model.LogisticRegression with intercept and large C
        x:     matrix on which the model was fit
    This function uses asymtptics for maximum likelihood estimates.
    """
    p = model.predict_proba(x)
    n = len(p)
    m = len(model.coef_[0]) + 1
    coefs = np.concatenate([model.intercept_, model.coef_[0]])
    x_full = np.matrix(np.insert(np.array(x), 0, 1, axis = 1))
    ans = np.zeros((m, m))
    for i in range(n):
        ans = ans + np.dot(np.transpose(x_full[i, :]), x_full[i, :]) * p[i,1] * p[i, 0]
    vcov = np.linalg.inv(np.matrix(ans))
    se = np.sqrt(np.diag(vcov))
    t =  coefs/se  
    p = (1 - norm.cdf(abs(t))) * 2
    return p

# test p-values
x = np.arange(10)[:, np.newaxis]
y = np.array([0,0,0,1,0,0,1,1,1,1])
model = LogisticRegression(C=1e30).fit(x, y)
print(logit_pvalue(model, x))

# compare with statsmodels
import statsmodels.api as sm
sm_model = sm.Logit(y, sm.add_constant(x)).fit(disp=0)
print(sm_model.pvalues)
sm_model.summary()

print() 的输出是相同的,而且它们恰好是系数 p 值。

[ 0.11413093  0.08779978]
[ 0.11413093  0.08779979]

sm_model.summary() 还会打印格式良好的 HTML 摘要。

关于scikit-learn - scikit学习: how to check coefficients significance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25122999/

相关文章:

pandas - 无法在具有某些 'nan' 值的列中使用 apply 函数

python - 我可以多次调用 vectorizer.fit_transform 来更新矢量化器吗

r - 如何在 R 中对按行组织的样本执行单因素方差分析?

r - 在 R 中设置方差分析对比度的问题

python - 操作系统错误 : [Errno 12] Cannot allocate memory when using python multiprocessing Pool

python - Python 中的有界逻辑回归

python - 逻辑回归得到 sm.Logit 值(python,statsmodels)

r - R 中逻辑回归的交叉验证函数

r - for循环在r列表中的所有数据框中进行方差分析测试

python - 绘制超平面线性 SVM python