在statsmodel中打开和建模数据为GLM

时间:2016-03-28 07:01:31

标签: python statistics statsmodels

我将python中的x和y变量数据存储为列表。如何将其导入python以运行statsmodels。

from __future__ import print_function
import statsmodels.api as sm
import statsmodels.formula.api as smf
import pandas as pd

x = [1,1,2,3]
y=[1,0,0,0]
data  = pd.DataFrame(x,y) #to merge the two side by side

star98 = sm.datasets.star98.load_pandas().data

formula = 'x ~ y'


pd.options.mode.chained_assignment = None  # default='warn'


mod1 = smf.glm(formula=formula, data=data, family=sm.families.Binomial()).fit()

x = mod1.summary()

ValueError:对deviance函数的第一次猜测返回了nan。这可能是一个边界问题,应该报告

1 个答案:

答案 0 :(得分:5)

你有几个小问题。首先,您构建数据的方式,y实际上被解释为数据框的索引:

In [3]:
    x = [1,1,2,3]
    y=[1,0,0,0]
    data  = pd.DataFrame(x,y) #to merge the two side by side
    data
Out[3]:
    0
1   1
0   1
0   2
0   3

相反,您必须将两者都作为列传递,并确保它们获取列名称;更容易的可能是字典:

In [13]:
    x = [1,1,2,3]
    y = [1,0,0,0]
    data = pd.DataFrame({'x' : x, 'y' : y}) #to merge the two side by side
    data
Out[13]:
    x   y
0   1   1
1   1   0
2   2   0
3   3   0

其次,你的公式错了(因为我猜你试图从y中的数据中对x进行分类),它应该是,

formula = 'y ~ x'

如果您对代码的其余部分采用这种方式,那么您将获得更好的结果。

In [21]:
    x
Out[21]:
Generalized Linear Model Regression Results
Dep. Variable:  y   No. Observations:   4
Model:  GLM Df Residuals:   2
Model Family:   Binomial    Df Model:   1
Link Function:  logit   Scale:  1.0
Method: IRLS    Log-Likelihood: -1.3863
Date:   Mon, 28 Mar 2016    Deviance:   2.7726
Time:   15:34:32    Pearson chi2:   2.00
No. Iterations: 22      
coef    std err z   P>|z|   [95.0% Conf. Int.]
Intercept   22.1423 3.9e+04 0.001   1.000   -7.64e+04 7.64e+04
x   -22.1423    3.9e+04 -0.001  1.000   -7.64e+04 7.64e+04

希望它有所帮助。