其原因的差异是,当你在与熊猫数据集中读取,在prog
变量如float
类型默认处理:
df.prog.head()
0 2.0
1 2.0
2 2.0
3 2.0
4 2.0
Name: prog, dtype: float32
在R例如,在另一方面,在prog
变量被明确地转换为因子(分类)变量:
dat <- within(dat, {
prog <- factor(prog, levels = 1:3, labels = c("General", "Academic", "Vocational"))
id <- factor(id)
})
其结果是,当你看到在R上的契合总结,你可以看到prog
变量已经被拆分成n-1的二进制编码方面:
> summary(m1 <- glm.nb(daysabs ~ math + prog, data = dat))
Call:
glm.nb(formula = daysabs ~ math + prog, data = dat, init.theta = 1.032713156,
link = log)
Deviance Residuals:
Min 1Q Median 3Q Max
-2.1547 -1.0192 -0.3694 0.2285 2.5273
Coefficients:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 2.615265 0.197460 13.245 < 2e-16 ***
math -0.005993 0.002505 -2.392 0.0167 *
progAcademic -0.440760 0.182610 -2.414 0.0158 *
progVocational -1.278651 0.200720 -6.370 1.89e-10 ***
比较这对prog
变量如何出现在您发布的Python的契合总结。
要解决此问题,可以使用C()
function将变量强制转换为statsmodels中的分类。这样你会得到相同的结果:
model = smf.glm(formula = "daysabs ~ math + C(prog)", data=df, family=sm.families.NegativeBinomial()).fit()
model.summary()
<class 'statsmodels.iolib.summary.Summary'>
"""
Generalized Linear Model Regression Results
==============================================================================
Dep. Variable: daysabs No. Observations: 314
Model: GLM Df Residuals: 310
Model Family: NegativeBinomial Df Model: 3
Link Function: log Scale: 1.06830885199
Method: IRLS Log-Likelihood: -865.68
Date: Thu, 16 Feb 2017 Deviance: 350.98
Time: 10:34:16 Pearson chi2: 331.
No. Iterations: 6
==================================================================================
coef std err z P>|z| [0.025 0.975]
----------------------------------------------------------------------------------
Intercept 2.6150 0.207 12.630 0.000 2.209 3.021
C(prog)[T.2.0] -0.4408 0.192 -2.302 0.021 -0.816 -0.065
C(prog)[T.3.0] -1.2786 0.210 -6.079 0.000 -1.691 -0.866
math -0.0060 0.003 -2.281 0.023 -0.011 -0.001
==================================================================================
"""
啊哈! V酷 - 谢谢! –
结果现在很接近,但仍不完全相同,例如截距系数是2.6150,而在R中是2.61526。我认为这不是什么可担心的事情,但是这个细微差别的原因是什么? –
请注意,statsmodels GLM不会为负二项式修正等于1的比例。因此,标准错误可能与R不同,因为statsmodels在GLM中默认为准负NegativeBinomial。我不知道这是一个错误还是statsmodels的一个功能https://github.com/statsmodels/statsmodels/issues/2888。 – user333700