如何用Statsmodels实现含两个随机效应的混合模型?附R语言lmer示例
Replicating R's
lmer Model in Statsmodels Got it! To replicate your R mixed-effects model with two random intercepts in Statsmodels, you'll use the MixedLM (Mixed Linear Models) class. Here's how to adapt your existing Python code to match the R model lmer(frequency ~ attitude + (1|subject) + (1|scenario), data=df):
Full Working Code
import pandas as pd import statsmodels.regression.mixed_linear_model as smlm # Load and clean data (your existing code) df = pd.read_csv('http://www.bodowinter.com/tutorial/politeness_data.csv') df = df.drop(38) # Fit the mixed-effects model with two random intercepts model = smlm.MixedLM.from_formula( formula='frequency ~ attitude', data=df, groups=df['subject'], # Maps to R's (1|subject) random intercept vc_formula={'scenario': '1'} # Maps to R's (1|scenario) random intercept ) result = model.fit() # Print the full results summary print(result.summary())
Key Details Matching Your R Model
- The fixed effect structure (
frequency ~ attitude) is identical to your R formula. groups=df['subject']defines the first random intercept term(1|subject)as the primary grouping variable.vc_formula={'scenario': '1'}adds the second random intercept term(1|scenario)as an additional variance component, which is how Statsmodels handles multiple independent random effects.
What to Expect in the Results
When you run this code, the output will mirror your R model's output closely:
- Random effects: Variance and standard deviation values for
subject,scenario, and the residual (you'll see these labeled under "Variance Components"). - Fixed effects: The intercept estimate and the coefficient for
attitudepol, along with their standard errors and t-values, will align with the results you got in R.
内容的提问来源于stack exchange,提问作者HappyPy
相关产品推荐
相关产品推荐

