Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Section 5.5 — Hierarchical models

Notebook setup

<Figure size 640x480 with 0 Axes>
datasets/ directory already exists.

Definitions

Hierarchical (multilevel) models

Model formula

A Bayesian hierarchical model is described by the following equations:

\def\calN{\mathcal{N}} \def\Tdist{\mathcal{T}} \def\Expon{\mathrm{Expon}}

Xj∼N(Mj, ΣX),Mj=B0+B0j,ΣX∼T+ ⁣(νΣX,σΣX),B0∼N(μB0,σB0),B0j∼N(0,ΣB0j),ΣB0j∼Expon(λ).\begin{align*} X_j &\sim \calN(M_{j}, \, \Sigma_X), \\ M_{j} &= B_0 + B_{0j}, \\ \Sigma_X &\sim \Tdist^+\!(\nu_{\Sigma_X}, \sigma_{\Sigma_X}), \\ B_0 &\sim \calN(\mu_{B_0},\sigma_{B_0}), \\ B_{0j} &\sim \calN(0,\Sigma_{B_{0j}}), \\ \Sigma_{B_{0j}} &\sim \Expon(\lambda). \end{align*}

Radon dataset

https://bambinos.github.io/bambi/notebooks/radon_example.html

  • Description: Contains measurements of radon levels in homes across various counties.

  • Source: Featured in Andrew Gelman and Jennifer Hill’s book Data Analysis Using Regression and Multilevel/Hierarchical Models.

  • Application: Demonstrates partial pooling and varying intercepts/slopes in hierarchical modeling.

Loading the data

(919, 6)
Loading...

Descriptive statistics

count 919.000000 mean 1.224623 std 0.853327 min -2.302585 25% 0.641854 50% 1.280934 75% 1.791759 max 3.875359 Name: log_radon, dtype: float64
85
floor basement 766 ground 153 Name: count, dtype: int64
<Figure size 1000x400 with 8 Axes>

Example 1: complete pooling model

= common linear regression model for all counties

Bayesian model

We can pool all the data and estimate one big regression to asses the influence of the floor variable on radon levels across all counties.

R∼N(MR, ΣR),MR=B0+B ⁣f ⁣⋅ ⁣f,ΣR∼T+ ⁣(4,1),B0∼N(1,2),Bf∼N(0,5).\begin{align*} R &\sim \calN(M_R, \, \Sigma_R), \\ M_R &= B_0 + B_{\!f}\!\cdot\!f, \\ \Sigma_R &\sim \Tdist^+\!(4, 1), \\ B_0 &\sim \calN(1, 2), \\ B_f &\sim \calN(0, 5). \end{align*}

The variable ff corresponds to the column floor in the radon data frame, which will be internally coded as binary with 0 representing basement, and 1 representing ground floor.

By ignoring the county feature, we do not differenciate on counties.

Bambi model

Formula: log_radon ~ 1 + floor Family: gaussian Link: mu = identity Observations: 919 Priors: target = mu Common-level effects Intercept ~ Normal(mu: 1.0, sigma: 2.0) floor ~ Normal(mu: 0.0, sigma: 5.0) Auxiliary parameters sigma ~ HalfStudentT(nu: 4.0, sigma: 1.0)
Loading...

Model fitting and analysis

Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, Intercept, floor]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Loading...
<Figure size 1725x345 with 3 Axes>
Default computed for conditional variable: floor
<Figure size 500x300 with 1 Axes>

Conclusion

not using group membership, so we have lots of bias

Example 2: no pooling model

= separate intercept for each county

Bayesian model

If we treat different counties as independent, so each one gets an intercept term:

Rj∼N(Mj, ΣR),Mj=B0j+B ⁣f ⁣⋅ ⁣f,ΣR∼T+ ⁣(4,1),B0j∼N(1,2),Bf∼N(0,5).\begin{align*} R_j &\sim \calN(M_j, \, \Sigma_R), \\ M_j &= B_{0j} + B_{\!f}\!\cdot\!f, \\ \Sigma_R &\sim \Tdist^+\!(4, 1), \\ B_{0j} &\sim \calN(1, 2), \\ B_f &\sim \calN(0, 5). \end{align*}

Bambi model

Formula: log_radon ~ 0 + county + floor Family: gaussian Link: mu = identity Observations: 919 Priors: target = mu Common-level effects county ~ Normal(mu: 1.0, sigma: 2.0) floor ~ Normal(mu: 0.0, sigma: 5.0) Auxiliary parameters sigma ~ HalfStudentT(nu: 4.0, sigma: 1.0)
Loading...

Model fitting and analysis

Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, county, floor]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 2 seconds.
Loading...
<Figure size 600x260 with 1 Axes>
<Figure size 1000x400 with 8 Axes>

Conclusion

treating each group independently, so we have lots of variance

Example 3: hierarchical model

= partial pooling model = varying intercepts model

Bayesian hierarchical model

Rj∼N(Mj, ΣR),Mj=B0+B0j+Bf ⁣⋅ ⁣f,ΣR∼T+ ⁣(4,1),B0∼N(1,2),B0j∼N(0,ΣB0j),Bf∼N(0,5),ΣB0j∼Expon(1).\begin{align*} R_j &\sim \calN(M_j, \, \Sigma_R), \\ M_j &= B_0 + B_{0j} + B_f\!\cdot\!f, \\ \Sigma_R &\sim \Tdist^+\!(4, 1), \\ B_0 &\sim \calN(1,2), \\ B_{0j} &\sim \calN(0,\Sigma_{B_{0j}}), \\ B_f &\sim \calN(0, 5), \\ \Sigma_{B_{0j}} &\sim \Expon(1). \end{align*}

The partial pooling formula estimates per-county intercepts which drawn from the same distribution which is estimated jointly with the rest of the model parameters. The 1 is the intercept co-efficient. The estimates across counties will all have the same slope.

log_radon ~ 1 + (1|county_id) + floor

There is a middle ground to both of these extremes. Specifically, we may assume that the intercepts are different for each county as in the unpooled case, but they are drawn from the same distribution. The different counties are effectively sharing information through the common prior.

NOTE: some counties have very few sample; the hierarchical model will provide “shrinkage” for these groups, and use global information learned from all counties

count 919.000000 mean 1.224623 std 0.853327 min -2.302585 25% 0.641854 50% 1.280934 75% 1.791759 max 3.875359 Name: log_radon, dtype: float64
Loading...

Bambi model

Formula: log_radon ~ 1 + (1|county) + floor Family: gaussian Link: mu = identity Observations: 919 Priors: target = mu Common-level effects Intercept ~ Normal(mu: 1.0, sigma: 2.0) floor ~ Normal(mu: 0.0, sigma: 5.0) Group-level effects 1|county ~ Normal(mu: 0.0, sigma: Exponential(lam: 1.0)) Auxiliary parameters sigma ~ HalfStudentT(nu: 4.0, sigma: 1.0)
Loading...

Model fitting and analysis

Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, Intercept, floor, 1|county_sigma, 1|county]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 2 seconds.

The group level parameters

Loading...

The intercept offsets for each county are:

<Figure size 600x300 with 1 Axes>

Compare models

Compare complete pooling, no pooling, and partial pooling models

<Figure size 1000x400 with 8 Axes>

Conclusions

Explanations

Prior selection for hierarchical models

?

Varying intercepts and slopes model

= Group-specific slopes We can also make beta_x group-specific

The varying-slope, varying intercept model adds floor to the group-level co-efficients. Now estimates across counties will all have varying slope.

log_radon ~ 1 + floor + (1 + floor | county)
Formula: log_radon ~ 1 + (1|county) + floor + (floor|county) Family: gaussian Link: mu = identity Observations: 919 Priors: target = mu Common-level effects Intercept ~ Normal(mu: 1.0, sigma: 2.0) floor ~ Normal(mu: -1.0, sigma: 2.0) Group-level effects 1|county ~ Normal(mu: 0.0, sigma: Exponential(lam: 1.0)) floor|county ~ Normal(mu: 0.0, sigma: Exponential(lam: 1.0)) Auxiliary parameters sigma ~ HalfStudentT(nu: 4.0, sigma: 1.0)
Loading...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, Intercept, floor, 1|county_sigma, 1|county, floor|county_sigma, floor|county]
Loading...
Loading...
Sampling 4 chains for 3_000 tune and 2_000 draw iterations (12_000 + 8_000 draws total) took 17 seconds.
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details
Loading...
Loading...

The estimated mean standard deviation is the lowest of all the models we considered so far.

<Figure size 1000x400 with 8 Axes>
<Figure size 600x400 with 1 Axes>

Comparing models

The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details

Compare models based on their expected log pointwise predictive density (ELPD).

The ELPD is estimated either by Pareto smoothed importance sampling leave-one-out cross-validation (LOO) or using the widely applicable information criterion (WAIC). We recommend loo. Read more theory here - in a paper by some of the leading authorities on model comparison Spiegelhalter et al. (2002)

Loading...
<Figure size 600x400 with 1 Axes>

ELPD and elpd_loo

The ELPD is the theoretical expected log pointwise predictive density for a new dataset (Eq 1 in VGG2017), which can be estimated, e.g., using cross-validation. elpd_loo is the Bayesian LOO estimate of the expected log pointwise predictive density (Eq 4 in VGG2017) and is a sum of N individual pointwise log predictive densities. Probability densities can be smaller or larger than 1, and thus log predictive densities can be negative or positive. For simplicity the ELPD acronym is used also for expected log pointwise predictive probabilities for discrete models. Probabilities are always equal or less than 1, and thus log predictive probabilities are 0 or negative.

via https://mc-stan.org/loo/reference/loo-glossary.html

Frequentist multilevel models

We can use statsmodels to fit multilevel models too.

Random intercepts model using statsmodels

Loading...
-0.6929937406558051
0.7555891484188185
Loading...
array([0.40649212])
array(0.41388794)

This is very close to the mean of the random effect coefficient for AITKIN in the Bayesian model mod3 which was -0.268.

Random intercepts and slopes model using statsmodels (BONUS TOPIC)

Loading...
-0.6810977572101939
0.7461559982563548
0.34867221107257745
0.3435539748320272
-0.3372303607779022

Discussion

Alternative notations for hierarchical models

  • IMPORT FROM Gelman & Hill Section 12.5 printout

  • watch the subscripts!

Computational challenges associated with hierarchical models

  • centred vs. noncentred representations

Benefits of multilevel models

  • TODO LIST

  • Better than repeated measures ANOVA because:

    • tells you the direction and magnitude of effect

    • can handle more multiple grouping scenarios (e.g. by-item, and by-student)

    • works for categorical predictors

Applications

  • Need for hierarchical models often occurs in social sciences (better than ANOVA)

  • Hierarchical models are often used for Bayesian meta-analysis

Exercises

Exercise: mod1u

Same model as Example 3 but also include the predictor log_uranium.

Formula: log_radon ~ 1 + floor + (1|county) + log_uranium Family: gaussian Link: mu = identity Observations: 919 Priors: target = mu Common-level effects Intercept ~ Normal(mu: 1.2246, sigma: 2.1322) floor ~ Normal(mu: 0.0, sigma: 10.0) log_uranium ~ Normal(mu: 0.0, sigma: 10.0) Group-level effects 1|county ~ Normal(mu: 0.0, sigma: Exponential(lam: 1.0)) Auxiliary parameters sigma ~ Exponential(lam: 1.0)
Loading...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, Intercept, Time, 1|Pig_sigma, 1|Pig_offset, Time|Pig_sigma, Time|Pig_offset]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 8 seconds.
Loading...

Exercise: educational data

cf. https://mc-stan.org/users/documentation/case-studies/tutorial_rstanarm.html

1.1 Data example We will be analyzing the Gcsemv dataset (Rasbash et al. 2000) from the mlmRev package in R. The data include the General Certificate of Secondary Education (GCSE) exam scores of 1,905 students from 73 schools in England on a science subject. The Gcsemv dataset consists of the following 5 variables:

  • school: school identifier

  • student: student identifier

  • gender: gender of a student (M: Male, F: Female)

  • written: total score on written paper

  • course: total score on coursework paper

Loading...
Formula: course ~ 1 + (1 | school) Family: gaussian Link: mu = identity Observations: 1523 Priors: target = mu Common-level effects Intercept ~ Normal(mu: 73.3814, sigma: 41.0781) Group-level effects 1|school ~ Normal(mu: 0.0, sigma: HalfNormal(sigma: 41.0781)) Auxiliary parameters sigma ~ HalfStudentT(nu: 4.0, sigma: 16.4312)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, Intercept, 1|school_sigma, 1|school_offset]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 5 seconds.
Loading...
Formula: course ~ gender + (1 + gender|school) Family: gaussian Link: mu = identity Observations: 1523 Priors: target = mu Common-level effects Intercept ~ Normal(mu: 73.3814, sigma: 53.4663) gender ~ Normal(mu: 0.0, sigma: 83.5292) Group-level effects 1|school ~ Normal(mu: 0.0, sigma: HalfNormal(sigma: 53.4663)) gender|school ~ Normal(mu: 0.0, sigma: HalfNormal(sigma: 83.5292)) Auxiliary parameters sigma ~ HalfStudentT(nu: 4.0, sigma: 16.4312)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, Intercept, gender, 1|school_sigma, 1|school_offset, gender|school_sigma, gender|school_offset]
Loading...
Loading...
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 5 seconds.

Exercise: sleepstudy dataset

  • Description: Contains reaction times of subjects under sleep deprivation conditions.

  • Source: Featured in the R package lme4.

  • Application: Demonstrates linear mixed-effects modeling with random slopes and intercepts.

Links:

Loading...

Exercise: tadpoles (BONUS)

https://www.youtube.com/watch?v=iwVqiiXYeC4

logistic regression model

EXTRA MATERIAL

References
  1. Spiegelhalter, D. J., Best, N. G., Carlin, B. P., & Van Der Linde, A. (2002). Bayesian Measures of Model Complexity and Fit. Journal of the Royal Statistical Society Series B: Statistical Methodology, 64(4), 583–639. 10.1111/1467-9868.00353