# Hierarchical Linear Regression (Pigs dataset)

## Prepare Notebook

``` python
%config InlineBackend.figure_format = "retina"
%config InlineBackend.print_figure_kwargs = {'bbox_inches': None}

import arviz as az
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pymc as pm
import statsmodels.api as sm

plt.style.use("bambi.mplstyle")
seed = sum(map(ord, "multi-level_regression"))
rng = np.random.default_rng(seed)
```

We'll use a dataset included with `statsmodels` containing [the growth curve of pigs](https://www.rdocumentation.org/packages/doBy/versions/4.6-2/topics/data-dietox).

This model aims to analyse how pig weight changes over time. We know each pig's growth is unique; at the same time, these pigs belong to the same species/population, so there also lies some similarity among them. Hierarchical models are beneficial for these kinds of problems.

This notebook will demonstrate how to perform a Bayesian hierarchical linear regression in Bambi and PyMC.

## Load data & EDA

``` python
# Load up data from statsmodels
df = sm.datasets.get_rdataset("dietox", "geepack").data
df.describe()
```

|       | Pig         | Litter     | Start      | Weight     | Feed       | Time       |
|-------|-------------|------------|------------|------------|------------|------------|
| count | 861.000000  | 861.000000 | 861.000000 | 861.000000 | 789.000000 | 861.000000 |
| mean  | 6238.319396 | 12.135889  | 25.672701  | 60.725769  | 80.728645  | 6.480836   |
| std   | 1323.845928 | 7.427252   | 3.624336   | 24.978881  | 52.877736  | 3.444735   |
| min   | 4601.000000 | 1.000000   | 15.000000  | 15.000000  | 3.300003   | 1.000000   |
| 25%   | 4857.000000 | 5.000000   | 23.799990  | 38.299990  | 32.800003  | 3.000000   |
| 50%   | 5866.000000 | 11.000000  | 25.700000  | 59.199980  | 74.499996  | 6.000000   |
| 75%   | 8050.000000 | 20.000000  | 27.299990  | 81.199950  | 123.000000 | 9.000000   |
| max   | 8442.000000 | 24.000000  | 35.399990  | 117.000000 | 224.500000 | 12.000000  |

``` python
df.sample()
```

|     | Pig  | Evit    | Cu    | Litter | Start | Weight   | Feed  | Time |
|-----|------|---------|-------|--------|-------|----------|-------|------|
| 822 | 8273 | Evit000 | Cu035 | 22     | 25.0  | 94.39996 | 145.5 | 10   |

``` python
# Time vs Weight for 10 random pigs
random_pigs = rng.choice(df["Pig"].unique(), 10, replace=False)
fig, axes = plt.subplots(
    2, 5, figsize=(7, 4), sharex=True, sharey=True, layout="constrained"
)
for ax, (pig, group) in zip(
    axes.flat, df[df["Pig"].isin(random_pigs)].groupby("Pig", observed=True)
):
    ax.scatter(group["Time"], group["Weight"], alpha=0.8)
    ax.set(title=f"Pig {pig}")

axes[0, 0].set(ylabel="Weight (kg)")
axes[1, 0].set(xlabel="Time (week)", ylabel="Weight (kg)")
axes[1, 1].set(xlabel="Time (week)")
axes[1, 2].set(xlabel="Time (week)")
axes[1, 3].set(xlabel="Time (week)")
axes[1, 4].set(xlabel="Time (week)");
```

![](multi-level_regression_files/figure-html/cell-5-output-1.png)

From the plot, time and weight seem to be linearly related. However, the slope and intercept vary pig by pig. So, we'll estimate a model that allows varying intercepts and slopes for time for each pig.

## Model Definition

``` math
Y_i = \alpha_i + \beta_i X_i + \epsilon_i
```

where

``` math
\begin{aligned}
\alpha_i &= \alpha_{\text{global}} + \alpha_{\text{specific}, i} \\
\beta_i &= \beta_{\text{global}} + \beta_{\text{specific}, i}
\end{aligned}
```

So the first equation can be further diluted as

``` math
\begin{aligned}
Y_i = \alpha_{\text{global}}+ \alpha_{\text{specific}, i} + [\beta_{\text{global}} + \beta_{\text{specific}, i}]X_i + \epsilon_i \\
\end{aligned}
```

where $`\alpha_{\text{global}}`$ and $`\beta_{\text{global}}`$ are the usual common intercept and slope you find in a linear regression. $`\alpha_{\text{specific}, i}`$ and $`\beta_{\text{specific}, i}`$ are the group specific components for the pig $`i`$, influencing its intercept and slope, respectively.

Finally, $`\epsilon_i`$ is the random error we always see in these models, assumed to be Gaussian with mean 0 and variance $`\sigma^2`$.

Note that here we use "common" and "group specific" effects to denote what in many fields are known as "fixed" and "random" effects, respectively.

### PyMC Model

We will first define a PyMC model with the same mathematical conventions used before for better understanding.

We used the `coords` argument inside `pm.Model()` to add dimensionality for our model. Also, notice that we passed the `dims` argument only for group-level terms. By doing so, we made those terms vectors instead of scalars. For example, `α_specific__offset` will have 72 (total number of pigs) independent $`\mathcal{N}(0, 1)`$ distributions. The same can be achieved with the `shape` argument, but using `dims` enhances compatibility with ArviZ.

``` python
pig, n_pig = df.Pig.factorize()
coords = {"Pig": n_pig}

with pm.Model(coords=coords) as pymc_model:
    # Common-level effects
    α_global = pm.Normal("α_global", mu=60, sigma=20)
    β_global = pm.Normal("β_global", mu=0, sigma=1)

    # Grou-level effects (non-centered parametrization)
    α_specific_offset = pm.Normal("α_specific_offset", mu=0, sigma=1, dims="Pig")
    α_specific_sigma = pm.HalfNormal("α_specific_sigma", sigma=5)
    β_specific_offset = pm.Normal("β_specific_offset", mu=0, sigma=1, dims="Pig")
    β_specific_sigma = pm.HalfNormal("β_specific_sigma", sigma=1)

    α_specific = pm.Deterministic(
        "α_specific", α_specific_offset * α_specific_sigma, dims="Pig"
    )
    β_specific = pm.Deterministic(
        "β_specific", β_specific_offset * β_specific_sigma, dims="Pig"
    )

    # Standard deviation of Y | X (the same as the standard deviation of epsilon_i)
    σ = pm.HalfStudentT("σ", nu=4, sigma=10)

    # Build mu_i
    α = α_global + α_specific[pig]
    β = β_global + β_specific[pig]
    μ = pm.Deterministic("μ", α + β * df["Time"])

    # Observational model
    Y = pm.Normal("Weight", mu=μ, sigma=σ, observed=df["Weight"])

    # Sampling
    pymc_idata = pm.sample(random_seed=seed)
```

    NUTS[nutpie]: [α_global, β_global, α_specific_offset, α_specific_sigma, β_specific_offset, β_specific_sigma, σ]

*\[Rich HTML output -- view on the documentation site\]*

```
```

``` python
az.plot_trace_dist(
    pymc_idata,
    var_names=["α_global", "β_global", "α_specific", "β_specific", "σ"],
    figure_kwargs={"figsize": (7, 9)},
);
```

![](multi-level_regression_files/figure-html/cell-7-output-1.png)

### Bambi Model

In Bambi, we use the formula syntax to specify the model. Previously in PyMC, we specified common and group specific components separately. Now, thanks to [formulae](https://github.com/bambinos/formulae), you can specify model formulas just as you would do with R packages like [lme4](https://CRAN.R-project.org/package=lme4) and [brms](https://CRAN.R-project.org/package=brms).

In a nutshell, the term on the left side tells `Weight` is the response variable, `Time` on the right-hand side tells we include a main effect for the variable `Time`, and `(Time|Pig)` indicates we want to allow a each pig to have its own slope for `Time` as well as its own intercept (which is implicit).

If we only wanted different intercepts, we would have written `Weight ~ Time + (1 | Pig)` and if we wanted slopes specific to each pig without including a pig specific intercept, we would write `Weight ~ Time + (0 + Time | Pig)`.

``` python
df["Time"] = df["Time"].astype(float)
bmb_model = bmb.Model("Weight ~ Time + (Time|Pig)", df)
bmb_model  # Inspect the model
```

           Formula: Weight ~ Time + (Time|Pig)
            Family: gaussian
              Link: mu = identity
      Observations: 861
            Priors: 
        target = mu
            Common-level effects
                Intercept ~ Normal(mu: 60.7258, sigma: 133.0346)
                Time ~ Normal(mu: 0.0, sigma: 18.1283)
            
            Group-level effects
                1|Pig ~ Normal(mu: 0.0, sigma: HalfNormal(sigma: 133.0346))
                Time|Pig ~ Normal(mu: 0.0, sigma: HalfNormal(sigma: 18.1283))
            
            Auxiliary parameters
                sigma ~ HalfStudentT(nu: 4.0, sigma: 24.9644)

Referring to the above section, we had explicitly defined all the priors. But here, Bambi has chosen sensible defaults for us.

We can explore these priors through samples generated from them with a call to the [`.plot_priors`](../reference/Model.plot_priors.md) method, which plots a kernel density estimate for each prior.

``` python
bmb_model.build()
bmb_model.plot_priors(
    var_names=["Intercept", "Time", "1|Pig_sigma", "Time|Pig_sigma", "sigma"],
    figure_kwargs={"figsize": (7, 4)},
    col_wrap=3,
);
```

![](multi-level_regression_files/figure-html/cell-9-output-1.png)

Both models are literally the same. Take a moment to inspect and compare the graphical representation of both models using `bmb_model.graph()` and `pymc_model.to_graphviz()` . It will help to understand how the parameters in Bambi are related to our mathematical (or PyMC) representation.

Let's now fit the model via the `.fit()` method:

``` python
bmb_idata = bmb_model.fit(random_seed=seed)
```

    NUTS[nutpie]: [sigma, Time, Intercept_centered, 1|Pig_sigma, 1|Pig_offset, Time|Pig_sigma, Time|Pig_offset]

*\[Rich HTML output -- view on the documentation site\]*

```
```

## Forest plots

Now we are ready to check the results. We can get credible interval plots from forest plots using ArviZ.

Here, the thin line indicates a 94% credible interval calculated as higher posterior density, the thicker line represents the 50% interval, and the dot is the median.

We also made a comparison between a few parameters. We can quickly note a few things:

- Both the models ended up in the same posterior, even with different priors, as a result of the amount of information in the data.
- The credible interval for `Time` is far from 0, so we can be confident there's a positive relationship between the `Weight` of the pigs and `Time`. As expected!

We're not making any great discoveries by stating that, as time passes, we expect the pigs to weigh more. Still, this very simple example can be used as a starting point in applications where the relationship between the variables is not that clear beforehand.

``` python
# Rename PyMC variables to match Bambi names, so ArviZ can automatically match them
pymc_idata_renamed = pymc_idata.copy()
pymc_idata_renamed["posterior"] = pymc_idata_renamed.posterior.to_dataset().rename(
    {"α_global": "Intercept", "β_global": "Time", "σ": "sigma"}
)

# Now plot with matching variable names
pc = az.plot_dist(
    {"PyMC Model": pymc_idata_renamed, "Bambi Model": bmb_idata},
    var_names=["Intercept", "Time", "sigma"],
    figure_kwargs={"figsize": (7, 3)},
)
pc.add_legend("model");
```

![](multi-level_regression_files/figure-html/cell-11-output-1.png)

## Trace plots

Using `az.plot_trace()` we get traceplots that show the values sampled from the posteriors and density estimates that gives us an idea of the shape of the marginal posteriors of our parameters.

``` python
az.plot_trace_dist(
    bmb_idata,
    var_names=["Intercept", "Time", "1|Pig", "Time|Pig", "sigma"],
    figure_kwargs={"figsize": (7, 6)},
);
```

![](multi-level_regression_files/figure-html/cell-12-output-1.png)

The same plot could have been generated with less typing by calling

`az.plot_trace(bmb_idata, var_names=["~1|Pig_sigma", "~Time|Pig_sigma"]);`

which uses an alternative notation to pass `var_names` based on the negation symbol in Python, `~`. There we are telling ArviZ to plot all the variables in the InferenceData object `bmb_idata`, except from `1|Pig_sigma` and `Time|Pig_sigma`.

## Posterior summary

The plots generated by `az.plot_trace()` are enough to be confident that the sampler did a good job and conclude about plausible values for the distribution of each parameter in the model. But if we want to, and it is a good idea to do it, we can get numerical summaries for the posteriors with `az.summary()`.

``` python
az.summary(
    bmb_idata,
    var_names=["Intercept", "Time", "1|Pig_sigma", "Time|Pig_sigma", "sigma"],
)
```

|  | mean | sd | eti89_lb | eti89_ub | ess_bulk | ess_tail | r_hat | mcse_mean | mcse_sd |
|----|----|----|----|----|----|----|----|----|----|
| Intercept | 15.73 | 0.56 | 15 | 17 | 804 | 1271 | 1.01 | 0.02 | 0.014 |
| Time | 6.944 | 0.081 | 6.8 | 7.1 | 713 | 1170 | 1.01 | 0.003 | 0.0022 |
| 1\|Pig_sigma | 4.54 | 0.44 | 3.9 | 5.3 | 1153 | 1540 | 1.00 | 0.013 | 0.01 |
| Time\|Pig_sigma | 0.661 | 0.062 | 0.57 | 0.76 | 1190 | 1469 | 1.00 | 0.0018 | 0.0015 |
| sigma | 2.46 | 0.065 | 2.4 | 2.6 | 3323 | 2714 | 1.00 | 0.0011 | 0.00079 |

## Estimated regression line

Here we'll visualise the regression equations we have sampled for a few particular pigs, and then we'll compare the mean regression equation for all 72 pigs in the dataset.  

The following plot shows the 94% HDI from 4000 (4 chains x 1000 draws each) linear regressions for 10 random pigs, the same pigs previously plotted in the EDA. The mean regression line is plotted in black, and the pink dots represent the observed weights for this pig.

``` python
time = np.array(range(1, 13))

fig = bmb.interpret.plot_predictions(
    model=bmb_model,
    idata=bmb_idata,
    prob=0.95,
    conditional={"Time": time, "Pig": random_pigs},
    fig_kwargs={
        "theme": {"figure.figsize": (7, 4)},
        "xlabel": "Time (week)",
        "ylabel": "Weight (kg)",
        "title": "Pig {}".format,
        "wrap": 5,
    },
    subplot_kwargs={"main": "Time", "panel": "Pig"},
)

axes = fig.get_axes()
for pig, ax in zip(random_pigs, axes):
    df_pig = df[df["Pig"] == pig]
    ax.scatter(df_pig["Time"], df_pig["Weight"], alpha=0.7, color="0.3", s=20)
fig
```

![](multi-level_regression_files/figure-html/cell-14-output-1.png)

Next, we calculate the mean regression line for each pig and show them together in one plot. Here we clearly see each pig has a different pair of intercept and slope.

``` python
bmb.interpret.plot_predictions(
    model=bmb_model,
    idata=bmb_idata,
    conditional={"Time": time, "Pig": df.Pig.unique()},
    prob=None,
    fig_kwargs={"legend": False},
)
```

![](multi-level_regression_files/figure-html/cell-15-output-1.png)

We can also plot the posterior overlaid with a region of practical equivalence (ROPE). This region indicates a range of parameter values that are considered to be practically equivalent to some reference value of interest to the particular application, for example 0. In the following plot we can see that the marginals posterior distributions for `Intercept` and `Time` fall outside of this range.

``` python
pc = az.plot_dist(
    bmb_idata,
    var_names=["Intercept", "Time"],
    figure_kwargs={"figsize": (6, 4)},
    col_wrap=1,
)
az.add_lines(pc, 0)
az.add_bands(pc, [(-1, 1)]);
```

![](multi-level_regression_files/figure-html/cell-16-output-1.png)

If instead of a plot we want to get numbers, we can use the function `ci_in_rope` to get the percentage of the confidence interval that falls within a region of practical equivalence (ROPE):

``` python
az.ci_in_rope(bmb_idata, var_names=["Intercept", "Time"], rope=(-1, 1))
```

![](data:image/svg+xml;base64,PHN2ZyBzdHlsZT0icG9zaXRpb246IGFic29sdXRlOyB3aWR0aDogMDsgaGVpZ2h0OiAwOyBvdmVyZmxvdzogaGlkZGVuIj4KPGRlZnM+CjxzeW1ib2wgaWQ9Imljb24tZGF0YWJhc2UiIHZpZXdib3g9IjAgMCAzMiAzMiI+CjxwYXRoIGQ9Ik0xNiAwYy04LjgzNyAwLTE2IDIuMjM5LTE2IDV2NGMwIDIuNzYxIDcuMTYzIDUgMTYgNXMxNi0yLjIzOSAxNi01di00YzAtMi43NjEtNy4xNjMtNS0xNi01eiIgLz4KPHBhdGggZD0iTTE2IDE3Yy04LjgzNyAwLTE2LTIuMjM5LTE2LTV2NmMwIDIuNzYxIDcuMTYzIDUgMTYgNXMxNi0yLjIzOSAxNi01di02YzAgMi43NjEtNy4xNjMgNS0xNiA1eiIgLz4KPHBhdGggZD0iTTE2IDI2Yy04LjgzNyAwLTE2LTIuMjM5LTE2LTV2NmMwIDIuNzYxIDcuMTYz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XoiIC8+CjxwYXRoIGQ9Ik0yMyAxOGgtMTRjLTAuNTUyIDAtMS0wLjQ0OC0xLTFzMC40NDgtMSAxLTFoMTRjMC41NTIgMCAxIDAuNDQ4IDEgMXMtMC40NDggMS0xIDF6IiAvPgo8L3N5bWJvbD4KPC9kZWZzPgo8L3N2Zz4=)

``` xr-text-repr-fallback
<xarray.Dataset> Size: 16B
Dimensions:    ()
Data variables:
    Intercept  float64 8B 0.0
    Time       float64 8B 0.0
Attributes:
    created_at:                  2026-08-29T16:05:40.505966+00:00
    creation_library:            ArviZ
    creation_library_version:    1.3.0
    creation_library_language:   Python
    sample_dims:                 ['chain', 'draw']
    inference_library:           nutpie
    inference_library_version:   0.16.11
    sampling_time:               0.5797491073608398
    tuning_steps:                1000
    modeling_interface:          bambi
    modeling_interface_version:  0.20.1.dev78+g69d4473ea.d20260829
```

xarray.Dataset

Dimensions:

Data variables: (2)

Intercept

()

float64

0.0

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    array(0.)

Time

()

float64

0.0

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWZpbGUtdGV4dDIiPjx1c2UgeGxpbms6aHJlZj0iI2ljb24tZmlsZS10ZXh0MiIgLz48L3N2Zz4=)

![](data:image/svg+xml;base64,PHN2ZyBjbGFzcz0iaWNvbiB4ci1pY29uLWRhdGFiYXNlIj48dXNlIHhsaW5rOmhyZWY9IiNpY29uLWRhdGFiYXNlIiAvPjwvc3ZnPg==)

&nbsp;

    array(0.)

Attributes: (11)

created_at :  
2026-08-29T16:05:40.505966+00:00

creation_library :  
ArviZ

creation_library_version :  
1.3.0

creation_library_language :  
Python

sample_dims :  
\['chain', 'draw'\]

inference_library :  
nutpie

inference_library_version :  
0.16.11

sampling_time :  
0.5797491073608398

tuning_steps :  
1000

modeling_interface :  
bambi

modeling_interface_version :  
0.20.1.dev78+g69d4473ea.d20260829

``` python
%load_ext watermark
%watermark -n -u -v -iv -w
```

    Last updated: Sat, 29 Aug 2026

    Python implementation: CPython
    Python version       : 3.14.7
    IPython version      : 9.16.1

    arviz      : 1.3.0
    bambi      : 0.20.1.dev78+g69d4473ea.d20260829
    matplotlib : 3.11.1
    numpy      : 2.4.6
    pymc       : 6.3.1
    statsmodels: 0.14.6

    Watermark: 2.6.0
