[英]Mixed effects logistic regression
我正在嘗試在 python 中實現混合效應邏輯回歸。 作為比較,我在 R 中使用lme4
包中的glmer
函數。
我發現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 的斜率之外,這似乎與我在 R 中得到的內容不匹配glmer(Survived ~ Age + (1 | Pclass), data = titanic, family = "binomial")
:
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 值? 最后,他們是否有更類似於 R 中的實現的混合效應邏輯回歸的任何 python 實現?
只需要對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 ***
作為附加評論(抱歉從主要問題轉移),我在帶有Python 3.8.8
的Ubuntu 20.04
機器上運行了這個。 不確定其他人是否遇到過這個問題,但是當使用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 等效結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.