科研 Skill

多层线性混合模型

alterlab-multilevel-models

Fits mixed-effects/multilevel models (random slopes, ICC, GLMMs) for nested or longitudinal data via statsmodels, bambi, or R lme4/brms. Use for grouped data with within- vs between-cluster questions.

发布者 Codar安全审核通过v0.1.0更新于 2026-11-18

SKILL.md

Multilevel Models — Fit the Nesting, Report the Whole Model

Skill type: ANALYSIS MODULE. Correlated data (pupils in schools, repeated measures within people, panel waves) violate independence; a mixed-effects model partitions variance into levels. The value here is discipline, not a fit() call: methods reviews document a reporting crisis — models specified and reported inconsistently — so this skill enforces the reporting standard.

Core Mission

FITTING THE MODEL IS EASY; REPORTING IT COMPLETELY IS THE JOB.
STATE THE FULL FIXED + RANDOM STRUCTURE, THE ICC, THE ESTIMATION, THE CHECKS.

When to Use This Skill

  • "I have students nested in schools / repeated measures / panel data — fit a multilevel model."
  • "Random intercepts and slopes for [group]; what's the ICC?"
  • "Multilevel logistic / Poisson (GLMM)."
  • "How much variance is between groups vs within?"

Does NOT Trigger

The request is really about…Route toWhy not this skill
Single-level / ordinary regression, no groupingalterlab-statsmodels / alterlab-statistical-analysisNo random-effects structure needed.
Panel fixed effects for causal identification (DiD/within)alterlab-causal-inferenceFE-for-identification, not variance partitioning.
Latent variables / SEM / factor structurealterlab-sem-psychometricsMeasurement model.
Whether the design/question even needs multilevelalterlab-ssci-design-gateDesign routing.

Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-statsmodels) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.

Running the code. In Claude Code, run analysis code in a throwaway environment instead of installing packages: uv run --python ">=3.11" --with "statsmodels>=0.14" --with pandas python mlm.py. This needs no install approval and leaves the user's environment untouched. If uv or the network is unavailable, say so and hand over the script; never report results you did not compute.

Structure ≠ question

Having a multilevel data structure is not the same as having a question that requires multilevel analysis. If inference is at one level and clustering is only a nuisance, cluster-robust (sandwich) SEs may suffice; reach for a mixed model when the question concerns between-cluster variation (e.g. how much of the outcome varies across schools, or whether an effect varies by group). State which case you are in.

Verified calls (pinned)

Python — statsmodels MixedLM:

import statsmodels.formula.api as smf
m = smf.mixedlm("y ~ x", data, groups=data["group"], re_formula="~x")   # random intercept + slope
res = m.fit(reml=True)                    # REML for final variance estimates
res.summary(); res.cov_re                 # fixed effects + random-effect covariance

vc_formula= adds named variance components. Bambi (Bayesian, on PyMC): import bambi as bmb; bmb.Model("y ~ x + (1 + x | group)", data).fit() — lme4-style (1|group) / (x|group) syntax.

R — lme4 / glmmTMB / brms (field standard):

library(lme4); library(lmerTest)          # lmerTest adds Satterthwaite dof + p-values (lme4 omits them)
m <- lmer(y ~ x + (1 + x | group), data)
glmer(y01 ~ x + (1 | group), family = binomial, data = data)     # GLMM
performance::icc(m); performance::r2(m)    # variance-partition ICC + Nakagawa marginal/conditional R2

glmmTMB (zero-inflation, faster) and brms (Bayesian via Stan) share the (1|group) syntax.

Note: statsmodels has no built-in variance-partition ICC — compute it from cov_re and the residual scale (see the reference). pingouin.intraclass_corr computes a reliability ICC (Shrout & Fleiss), which is a different quantity — do not confuse them.

The reporting checklist (the reason this skill exists)

SPECIFICATION:  full fixed-effects + full random-effects structure (which slopes vary by which group)
CENTERING:      predictor centering decision (grand-mean / group-mean / none) + rationale
VARIANCE:       variance components + ICC (proportion of variance between clusters)
ESTIMATION:     ML vs REML (REML for final variance estimates; ML to compare fixed effects)
ASSUMPTIONS:    residual + random-effect normality, homoscedasticity, influential clusters
COMPARISON:     nested-model comparisons (LRT / AIC / BIC), and convergence/singularity checks
EFFECT SIZE:    standardized fixed effects and/or Nakagawa marginal & conditional R2

These are exactly the items methods reviews find under-reported. There is no single correct LMM — surface the modeling decisions as a justified path, don't hardcode one recipe.

References

  • references/mlm_reporting.md — the full reporting standard, ICC/R² computation, centering, convergence, power.

Part of the AlterLab Academic Skills suite.

示例提示词

我的数据是学生嵌套在班级里的,想拟合随机截距的多层模型。

所属插件

社会学、政治学与城市研究面向社会科学研究:问卷与访谈设计、质性编码、文本即数据、社会网络、ABM、比较政治与选举数据、RCT 与 DID、城市与区域分析。

安装该插件会一并获得同领域的 58 个 Skill / MCP。

同插件的其他科研 Skill

常见问题

多层线性混合模型能做什么?

Fits mixed-effects/multilevel models (random slopes, ICC, GLMMs) for nested or longitudinal data via statsmodels, bambi, or R lme4/brms. Use for grouped data with within- vs between-cluster questions。

如何安装多层线性混合模型?

在科搭 Codar 左侧点击「插件」,在「组件」页签搜索「多层线性混合模型」并安装;在 Claude Code 或 Codex 中可以发送本页的安装提示词,或下载 Skill 包后解压到 ~/.claude/skills 或 ~/.codex/skills。

多层线性混合模型需要哪些权限?

该科研 Skill没有声明额外权限;执行具体操作时仍由 Agent 按自身规则请求确认。

多层线性混合模型经过官方审核吗?

是。SpeedSkills 收录的每个版本都会记录内容摘要与权限声明,当前版本已通过安全审核。