# Distributional models

``` 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 pandas as pd

from matplotlib.lines import Line2D

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

For most regression models, a function of the mean (aka the location parameter) of the response distribution is defined as a linear function of certain predictors, while the remaining parameters are considered auxiliary. For instance, if the response is a Gaussian, we model $`\mu`$ as a combination of predictors and $`\sigma`$ is estimated from the data, but assumed to be constant for all observations.

Instead, with distributional models we can specify predictor terms for all parameters of the response distribution. This can be useful, for example, to model heteroskedasticity, i.e. unequal variance. In this notebook we are going to do exactly that.

To better understand distributional models, let's begin fitting a non-distributional models. We are going to model the following synthetic dataset. And we are going to use a Gamma response with a `log` link function.

``` python
N = 200
a, b = 0.5, 1.1
x = rng.uniform(-1.5, 1.5, N)
shape = np.exp(0.3 + x * 0.5 + rng.normal(scale=0.1, size=N))
y = rng.gamma(shape, np.exp(a + b * x) / shape, N)
data = pd.DataFrame({"x": x, "y": y})
new_data = pd.DataFrame({"x": np.linspace(-1.5, 1.5, num=50)})
```

## Constant alpha

``` python
formula = bmb.Formula("y ~ x")
model_constant = bmb.Model(formula, data, family="gamma", link="log")
model_constant
```

           Formula: y ~ x
            Family: gamma
              Link: mu = log
      Observations: 200
            Priors: 
        target = mu
            Common-level effects
                Intercept ~ Normal(mu: 0.0, sigma: 2.502)
                x ~ Normal(mu: 0.0, sigma: 2.9324)
            
            Auxiliary parameters
                alpha ~ HalfCauchy(beta: 1.0)

``` python
model_constant.build()
model_constant.graph()
```

![](distributional_models_files/figure-html/cell-5-output-1.svg)

Take a moment to inspect the textual and graphical representations of the model, to ensure you understand how the parameters are related.

``` python
idata_constant = model_constant.fit(random_seed=seed)
model_constant.compute_log_likelihood(idata_constant)
```

    NUTS[nutpie]: [alpha, x, Intercept_centered]

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

```
```

Once the model is fitted let's visually inspect the result in terms of the mean (the line in the following figure) and the individual predictions (the band).

``` python
fig, ax = plt.subplots()
bmb.interpret.plot_predictions(model_constant, idata_constant, "x", target="y", on=ax)
ax.scatter(data["x"], data["y"], color="k", alpha=0.2)
ax.set(xlabel="Predictor", ylabel="Outcome");
```

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

The model correctly model that the outcome increases with the values of the predictor. So far so good, let's dive into the heart of the matter.

## Varying alpha

Now we are going to build the same model as before with the only, but crucial difference, that we are also going to make alpha depend on the predictor. The syntax is very simple besides the usual "y ~ x", we now add "alpha ~ x". Neat!

``` python
formula_varying = bmb.Formula("y ~ x", "alpha ~ x")
model_varying = bmb.Model(
    formula_varying, data, family="gamma", link={"mu": "log", "alpha": "log"}
)
model_varying
```

           Formula: y ~ x
                    alpha ~ x
            Family: gamma
              Link: mu = log
                    alpha = log
      Observations: 200
            Priors: 
        target = mu
            Common-level effects
                Intercept ~ Normal(mu: 0.0, sigma: 2.502)
                x ~ Normal(mu: 0.0, sigma: 2.9324)
        target = alpha
            Common-level effects
                alpha_Intercept ~ Normal(mu: 0.0, sigma: 1.0)
                alpha_x ~ Normal(mu: 0.0, sigma: 1.0)

``` python
model_varying.build()
model_varying.graph()
```

![](distributional_models_files/figure-html/cell-9-output-1.svg)

Take another moment to inspect the textual and visual representations of `model_varying` and also go back and compare those from `model_constant`.

``` python
idata_varying = model_varying.fit(random_seed=seed, include_response_params=True)
model_varying.compute_log_likelihood(idata_varying)
```

    NUTS[nutpie]: [x, Intercept_centered, alpha_x, alpha_Intercept_centered]

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

```
```

Now, with both models being fitted, let's see how the alpha parameter differs between both models. In the next figure you can see a blueish KDE for the alpha parameter estimated with `model_constant` and 200 black KDEs for the alpha parameter estimated from the `model_varying`. You can count it if you want :-), but we know they should be 200 because we should have one for each one of the 200 observations.

``` python
fig, ax = plt.subplots()

for idx in idata_varying.posterior.coords.get("__obs__"):
    values = idata_varying.posterior["alpha"].sel(__obs__=idx).to_numpy().flatten()
    grid, pdf, _ = az.kde(values)
    ax.plot(grid, pdf, lw=0.05, color="k")

values = idata_constant.posterior["alpha"].to_numpy().flatten()
grid, pdf, _ = az.kde(values)
ax.plot(grid, pdf, lw=2, color="C0")

# Create legend
handles = [
    Line2D([0], [0], label="Varying alpha", lw=1.5, color="k", alpha=0.6),
    Line2D([0], [0], label="Constant alpha", lw=1.5, color="C0"),
]

legend = ax.legend(handles=handles, loc="upper right", fontsize=14)
ax.set(xlabel="Alpha posterior", ylabel="Density");
```

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

This is nice statistical art and a good insight into what the model is actually doing. But at this point you may be wondering how the results look like, and more importantly, how different they are from `model_constant`. Let's plot the mean and predictions as we did before, but for both models.

``` python
model_constant.predict(idata_constant, kind="response", data=new_data)

qts_constant = (
    az.extract(idata_constant, "predictions", var_names="y")
    .quantile([0.025, 0.975], "sample")
    .to_numpy()
)
mean_constant = (
    az.extract(idata_constant, "predictions", var_names="y").mean("sample").to_numpy()
)

model_varying.predict(idata_varying, kind="response", data=new_data)

qts_varying = (
    az.extract(idata_varying, "predictions", var_names="y")
    .quantile([0.025, 0.975], "sample")
    .to_numpy()
)
mean_varying = (
    az.extract(idata_varying, "predictions", var_names="y").mean("sample").to_numpy()
)
```

``` python
fig, ax = plt.subplots()

ax.fill_between(new_data["x"], qts_constant[0], qts_constant[1], alpha=0.4)
ax.plot(new_data["x"], mean_constant, color="C0", label="constant")

ax.fill_between(new_data["x"], qts_varying[0], qts_varying[1], alpha=0.4)
ax.plot(new_data["x"], mean_varying, color="C1", label="varying")
ax.set(xlabel="Predictor", ylabel="Outcome")
ax.legend();
```

![](distributional_models_files/figure-html/cell-13-output-1.png)

We can see that mean is virtually the same for both models but the predictions are not, in particular for larger values of the predictiors.

We can also check that the models actually look different under the LOO metric, with a slight preference for the varying model.

``` python
az.compare({"constant": idata_constant, "varying": idata_varying})
```

|          | rank | elpd_diff | dse | p_worse | diag_diff | diag_elpd | p   | elpd   | se   | weight |
|----------|------|-----------|-----|---------|-----------|-----------|-----|--------|------|--------|
| varying  | 0    | 0.0       | 0.0 | NaN     |           |           | 3.8 | -270.0 | 19.0 | 0.91   |
| constant | 1    | -10.0     | 5.1 | 0.98    |           |           | 3.2 | -280.0 | 20.0 | 0.09   |

## Distributional models with splines

Time to step up our game. In this example we are going to use the bikes [data set](https://archive.ics.uci.edu/ml/datasets/bike+sharing+dataset) from the University of California Irvine's Machine Learning Repository, and we are going to estimate the number of rental bikes rented per hour over a 24 hour period.

As the number of bikes is a count variable we are going to use a `negativebinomial` family, and we are going to use two splines: one for the mean, and one for alpha.

``` python
data = bmb.load_data("bikes")
# Remove data, you may later try to refit the model to the whole data
data = data[::50]
data = data.reset_index(drop=True)
data["hour"] = data["hour"].astype(float)
```

``` python
formula = bmb.Formula(
    "count ~ 0 + bs(hour, 8, intercept=True)", "alpha ~ 0 + bs(hour, 8, intercept=True)"
)
model_bikes = bmb.Model(formula, data, family="negativebinomial")
model_bikes
```

           Formula: count ~ 0 + bs(hour, 8, intercept=True)
                    alpha ~ 0 + bs(hour, 8, intercept=True)
            Family: negativebinomial
              Link: mu = log
                    alpha = log
      Observations: 348
            Priors: 
        target = mu
            Common-level effects
                bs(hour, 8, intercept=True) ~ Normal(mu: [0. 0. 0. 0. 0. 0. 0. 0.], sigma: [11.3704 13.9185
                    11.9926 10.6887 10.6819 12.1271 13.623  11.366 ])

        target = alpha
            Common-level effects
                alpha_bs(hour, 8, intercept=True) ~ Normal(mu: 0.0, sigma: 1.0)

``` python
idata_bikes = model_bikes.fit(inference_method="pymc", random_seed=seed)
```

    Initializing NUTS using jitter+adapt_diag...
    Multiprocess sampling (4 chains in 4 jobs)
    NUTS: [bs(hour, 8, intercept=True), alpha_bs(hour, 8, intercept=True)]

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

```
```

    Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 6 seconds.

``` python
fig, ax = plt.subplots(figsize=(7, 3))
bmb.interpret.plot_predictions(
    model_bikes,
    idata_bikes,
    "hour",
    target="count",
    on=ax,
)
ax.scatter(data["hour"], data["count"], color="0.4", alpha=0.8, s=12);
```

![](distributional_models_files/figure-html/cell-18-output-1.png)

``` 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
    pandas    : 2.3.3

    Watermark: 2.6.0
