我正在尝试在python中实现混合效果逻辑回归。作为比较,我正在使用R中glmer
包中的lme4
函数。
我发现statsmodels
模块具有一个BinomialBayesMixedGLM
,应该能够适合这样的模型。但是,我遇到了许多问题:
statsmodels
函数的文档并不完全有用或不清晰,因此我不确定如何正确使用该函数。glmer
拟合模型时得到的结果。BinomialBayesMixedGLM
函数不会计算p值,因为它是贝叶斯函数,但是我似乎无法弄清楚如何访问参数的全部后验分布。作为测试用例,我使用的是here的泰坦尼克号数据集。
import os
import pandas as pd
import statsmodels.genmod.bayes_mixed_glm as smgb
titanic = pd.read_csv(os.path.join(os.getcwd(), 'titanic.csv'))
r = {"Pclass": '0 + Pclass'}
mod = smgb.BinomialBayesMixedGLM.from_formula('Survived ~ Age', r, titanic)
fit = mod.fit_map()
fit.summary()
# Type Post. Mean Post. SD SD SD (LB) SD (UB)
# Intercept M 3.1623 0.3616
# Age M -0.0380 0.0061
# Pclass V 0.0754 0.5669 1.078 0.347 3.351
但是,除了Age的斜率外,这似乎与我在glmer(Survived ~ Age + (1 | Pclass), data = titanic, family = "binomial")
中获得的R不匹配:
Random effects:
Groups Name Variance Std.Dev.
Pclass (Intercept) 0.8563 0.9254
Number of obs: 887, groups: Pclass, 3
Fixed effects:
Estimate Std. Error z value Pr(>|z|)
(Intercept) 0.961780 0.573402 1.677 0.0935 .
Age -0.038708 0.006243 -6.200 5.65e-10 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
那么在python中创建模型时出现什么错误?而且,一旦解决了该问题,如何提取后验值或p值?最后,他们的混合效果逻辑回归的python实现是否更类似于R中的实现?
答案 0 :(得分:2)
只需要对 Python
做一些类似的事情,正如评论中所建议的 Pymer4
似乎提供了一种合适的方法(特别是如果您熟悉 R
)。
使用问题中提到的示例数据集“泰坦尼克号”:
from pymer4.models import Lmer
model = Lmer("Survived ~ Age + (1|Pclass)",
data=titanic, family = 'binomial')
print(model.fit())
退出:
Formula: Survived~Age+(1|Pclass)
Family: binomial Inference: parametric
Number of observations: 887 Groups: {'Pclass': 3.0}
Log-likelihood: -525.812 AIC: 1057.624
Random effects:
Name Var Std
Pclass (Intercept) 0.856 0.925
No random effect correlations specified
Fixed effects:
Estimate 2.5_ci 97.5_ci SE OR OR_2.5_ci OR_97.5_ci \
(Intercept) 0.962 -0.162 2.086 0.573 2.616 0.85 8.050
Age -0.039 -0.051 -0.026 0.006 0.962 0.95 0.974
Prob Prob_2.5_ci Prob_97.5_ci Z-stat P-val Sig
(Intercept) 0.723 0.460 0.889 1.677 0.093 .
Age 0.490 0.487 0.493 -6.200 0.000 ***
作为附加评论(抱歉从主要问题中转移),我在带有 Ubuntu 20.04
的 Python 3.8.8
机器上运行此程序。不确定其他人是否遇到过这个问题,但是当使用 Pymer4
运行上面的模型时,包抛出了一个错误(当我尝试从 Pymer4
文档 here ):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
参考/pymer4/models/Lmer.py包文件中的这一行:
--> 444 if design_matrix:
我通过将其更改为(不确定这是否是最优雅或最安全的方法,很高兴在此处更正)来解决此问题:
if design_matrix.any():
这似乎使程序包运行并在我测试的少数情况下提供了等效于 R 的结果。