Python中的logit回归和奇异矩阵错误

21

我正在尝试对德国信贷数据(www4.stat.ncsu.edu/~boos/var.select/german.credit.html)运行逻辑回归。为了测试这段代码,我只使用了数值变量,并尝试用以下代码将其与结果进行回归。

import pandas as pd
import statsmodels.api as sm
import pylab as pl
import numpy as np

df = pd.read_csv("germandata.txt",delimiter=' ')
df.columns = ["chk_acc","duration","history","purpose","amount","savings_acc","employ_since","install_rate","pers_status","debtors","residence_since","property","age","other_plans","housing","existing_credit","job","no_people_liab","telephone","foreign_worker","admit"]

#pls note that I am only retaining numeric variables
cols_to_keep = ['admit','duration', 'amount', 'install_rate','residence_since','age','existing_credit','no_people_liab']

# rank of cols_to_keep is 8
print np.linalg.matrix_rank(df[cols_to_keep].values)
data = df[cols_to_keep]

data['intercept'] = 1.0

train_cols = data.columns[1:]

#to check the rank of train_cols, which in this case is 8
print np.linalg.matrix_rank(data[train_cols].values)

#fit logit model
logit = sm.Logit(data['admit'], data[train_cols])
result = logit.fit()

当我检查数据时,所有8.0列似乎相互独立。尽管如此,我仍然收到奇异矩阵错误的提示。请问您能帮忙解决吗?

谢谢。

3个回答

30

endog变量的取值必须为0或1。在这个数据集中它的取值是1和2。如果我们减去1,就能得到正确的结果。

>>> logit = sm.Logit(data['admit'] - 1, data[train_cols])
>>> result = logit.fit()
>>> print result.summary()
                           Logit Regression Results                           
==============================================================================
Dep. Variable:                  admit   No. Observations:                  999
Model:                          Logit   Df Residuals:                      991
Method:                           MLE   Df Model:                            7
Date:                Fri, 19 Sep 2014   Pseudo R-squ.:                 0.05146
Time:                        10:06:06   Log-Likelihood:                -579.09
converged:                       True   LL-Null:                       -610.51
                                        LLR p-value:                 4.103e-11
===================================================================================
                      coef    std err          z      P>|z|      [95.0% Conf. Int.]
-----------------------------------------------------------------------------------
duration            0.0261      0.008      3.392      0.001         0.011     0.041
amount           7.062e-05    3.4e-05      2.075      0.038      3.92e-06     0.000
install_rate        0.2039      0.073      2.812      0.005         0.062     0.346
residence_since     0.0411      0.067      0.614      0.539        -0.090     0.172
age                -0.0213      0.007     -2.997      0.003        -0.035    -0.007
existing_credit    -0.1560      0.130     -1.196      0.232        -0.412     0.100
no_people_liab      0.1264      0.201      0.628      0.530        -0.268     0.521
intercept          -1.5746      0.430     -3.661      0.000        -2.418    -0.732
===================================================================================

然而,在其他情况下,当我们远离最优点评估海森矩阵时,可能会出现海森矩阵不是正定的情况,例如在起始值不佳的情况下。在这些情况下,切换到不使用海森矩阵的优化器通常会成功。例如,scipy的“bfgs”是一种很好的优化器,在许多情况下都能正常工作。

result = logit.fit(method='bfgs')

1
这已经被修复以提供良好的错误信息。https://github.com/statsmodels/statsmodels/pull/1978 - jseabold
3
好的答案。还要检查另一件事:如果您的“exog”变量都为零(就像我的情况一样),那么它也会导致这个错误。 - Jacob Stern

5

我通过删除方差过低的列来解决了这个问题:

from sklearn.feature_selection import VarianceThreshold

def variance_threshold_selector(data, threshold=0.5):
    # https://dev59.com/TlkS5IYBdhLWcg3wdmrC#39813304
    selector = VarianceThreshold(threshold)
    selector.fit(data)
    return data[data.columns[selector.get_support(indices=True)]]

# min_variance = .9 * (1 - .9)  # You can play here with different values.
min_variance = 0.0001
low_variance = variance_threshold_selector(df, min_variance) 
print('columns removed:')
df.columns ^ low_variance.columns
df.shape
df.shape
X = low_variance
# (Logit(y_train, X), logit.fit()... etc)

为了提供更多上下文:在此步骤之前,我对某些分类数据进行了一位有效编码,并且其中一些列只有很少的1


1
感谢您的评论。我认为这样做可能会偶然地解决这个问题。当设计矩阵(或独热编码后的分类数据)具有可以相加得到1列(截距)的列时,会出现奇异矩阵。 - Charlotte Deng

0

这可能会帮助像我这样的新手!

确保您不要将targetpredictors一起包含。我不小心将targetpredictors一起包含,因为这样一个愚蠢的错误让我苦苦挣扎了很长时间。

解释:由于您将targetpredictors一起包含,而它们之间存在完美的相关性,这将导致奇异矩阵错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接