Beta Regression

This example has been contributed by Tyler James Burch (@tjburch on GitHub).

Code
%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 scipy.special import expit

plt.style.use("bambi.mplstyle")
seed = sum(map(ord, "Beta regression"))
rng = np.random.default_rng(seed)

In this example, we’ll look at using the Beta distribution for regression models. The Beta distribution is a probability distribution bounded on the interval [0, 1], which makes it well-suited to model probabilities or proportions. In fact, in much of the Bayesian literature, the Beta distribution is introduced as a prior distribution for the probability p parameter of the Binomial distribution (in fact, it’s the conjugate prior for the Binomial distribution).

Simulated Beta Distribution

To start getting an intuitive sense of the Beta distribution, we’ll model coin flipping probabilities. Say we grab all the coins out of our pocket, we might have some fresh from the mint, but we might also have some old ones. Due to the variation, some may be slightly biased toward heads or tails, and our goal is to model distribution of the probabilities of flipping heads for the coins in our pocket.

Since we trust the mint, we’ll say the \alpha and \beta are both large, we’ll use 1,000 for each, which gives a distribution spanning from 0.45 to 0.55.

alpha = 1_000
beta = 1_00
p = rng.beta(alpha, beta, size=10_000)

fig, ax = plt.subplots()
ax.hist(p, bins=50, density=True)
ax.set(xlabel="$p$", ylabel="Density");

Next, we’ll use Bambi to try to recover the parameters of the Beta distribution. Since we have no predictors, we can do a intercept-only model to try to recover them.

data = pd.DataFrame({"probabilities": p})
model = bmb.Model("probabilities ~ 1", data, family="beta")
fitted = model.fit(random_seed=seed)
NUTS[nutpie]: [kappa, Intercept]

pc = az.plot_trace_dist(
    fitted,
    figure_kwargs={
        "layout": "constrained",
        "figsize": (7, 3.2),
    },
);

az.summary(fitted)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
Intercept 2.30152 0.00105 2.3 2.3 3560 2727 1.00 1.8e-05 1.2e-05
kappa 1114.1 15.7 1100 1100 3750 2846 1.00 0.26 0.2

The model fit, but clearly these parameters are not the ones that we used above. For Beta regression, we use a linear model for the mean, so we use the \mu and \sigma formulation. To link the two, we use

\alpha = \mu \kappa

\beta = (1-\mu)\kappa

and \kappa is a function of the mean and variance,

\kappa = \frac{\mu(1-\mu)}{\sigma^2} - 1

Rather than \sigma, you’ll note Bambi returns \kappa. We’ll define a function to retrieve our original parameters.

def mukappa_to_alphabeta(mu, kappa):
    # Calculate alpha and beta
    alpha = mu * kappa
    beta = (1 - mu) * kappa

    # Get mean values and 95% HDIs
    alpha_mean = alpha.mean(("chain", "draw")).item()
    alpha_hdi = az.hdi(alpha, prob=0.95).to_numpy()
    beta_mean = beta.mean(("chain", "draw")).item()
    beta_hdi = az.hdi(beta, prob=0.95).to_numpy()

    return alpha_mean, alpha_hdi, beta_mean, beta_hdi


alpha, alpha_hdi, beta, beta_hdi = mukappa_to_alphabeta(
    expit(fitted.posterior["Intercept"]), fitted.posterior["kappa"]
)

print(
    f"Alpha - mean: {np.round(alpha)}, 95% HDI: {np.round(alpha_hdi[0])} - {np.round(alpha_hdi[1])}"
)
print(
    f"Beta - mean: {np.round(beta)}, 95% HDI: {np.round(beta_hdi[0])} - {np.round(beta_hdi[1])}"
)
Alpha - mean: 1013.0, 95% HDI: 985.0 - 1041.0
Beta - mean: 101.0, 95% HDI: 99.0 - 104.0

We’ve managed to recover our parameters with an intercept-only model.

Beta Regression with Predictors

Perhaps we have a little more information on the coins in our pocket. We notice that the coins have accumulated dirt on either side, which would shift the probability of getting a tails or heads. In reality, we would not know how much the dirt affects the probability distribution, we would like to recover that parameter. We’ll construct this toy example by saying that each micron of dirt shifts the \alpha parameter by 5.0. Further, the amount of dirt is distributed according to a Half Normal distribution with a standard deviation of 25 per side.

We’ll start by looking at the difference in probability for a coin with a lot of dirt on either side.

effect_per_micron = 5.0

# Clean Coin
alpha = 1_000
beta = 1_000
p = rng.beta(alpha, beta, size=10_000)

# Add two std to tails side (heads more likely)
p_heads = rng.beta(alpha + 50 * effect_per_micron, beta, size=10_000)

# Add two std to heads side (tails more likely)
p_tails = rng.beta(alpha - 50 * effect_per_micron, beta, size=10_000)

fig, ax = plt.subplots(figsize=(6, 4))

ax.hist(p, label="Clean coin", lw=2, bins=30, histtype="step", density=True)
ax.hist(
    p_heads, label="Biased towards heads", lw=2, bins=30, histtype="step", density=True
)
ax.hist(
    p_tails, label="Biased towards tails", lw=2, bins=30, histtype="step", density=True
)
ax.set(xlabel="$p$", ylabel="Density", ylim=(0, 45))
ax.legend(fontsize=10, loc=(0.025, 0.8));

Next, we’ll generate a toy dataset according to our specifications above. As an added foil, we will also assume that we’re limited in our measuring equipment, that we can only measure correctly to the nearest integer micron.

# Create amount of dirt on top and bottom
heads_bias_dirt = np.abs(rng.normal(scale=25, size=1_000))
tails_bias_dirt = np.abs(rng.normal(scale=25, size=1_000))

# Create the probability per coin
alpha = np.repeat(1_000, 1_000)
alpha = (
    alpha + effect_per_micron * heads_bias_dirt - effect_per_micron * tails_bias_dirt
)
beta = np.repeat(1_000, 1_000)

p = rng.beta(alpha, beta)

df = pd.DataFrame(
    {
        "p": p,
        "heads_bias_dirt": heads_bias_dirt.round(),
        "tails_bias_dirt": tails_bias_dirt.round(),
    }
)
df.head()
p heads_bias_dirt tails_bias_dirt
0 0.519531 18.0 8.0
1 0.507517 15.0 9.0
2 0.468618 2.0 33.0
3 0.497881 18.0 35.0
4 0.446733 11.0 42.0

Taking a look at our new dataset:

fig, ax = plt.subplots(1, 3, figsize=(7, 3), sharey=True, layout="constrained")

ax[0].hist(df["p"], bins=20)
ax[0].set(xlabel="$p$", ylabel="Count")

ax[1].hist(df["heads_bias_dirt"], bins=20)
ax[1].set(xlabel="Dirt Biasing Toward Heads ($\\mu m$)")

ax[2].hist(df["tails_bias_dirt"], bins=20)
ax[2].set(xlabel="Dirt Biasing Toward Tails ($\\mu m$)");

Next we want to make a model to recover the effect per micron of dirt per side. So far, we’ve considered the biasing toward one side or another independently. A linear model might look something like this:

\begin{aligned} p &\sim \text{Beta}(\mu, \sigma) \\ \text{logit}(\mu) &= \text{ Normal}( \alpha + \beta_h d_h + \beta_t d_t) \end{aligned}

Where d_h and d_t are the measured dirt (in microns) biasing the probability toward heads and tails respectively, \beta_h and \beta_t are coefficients for how much a micron of dirt affects each independent side, and \alpha is the intercept. Also note the logit link function used here, since our outcome is on the scale of 0-1, it makes sense that the link must also put our mean on that scale. Logit is the default link function, however Bambi supports the identity, probit, and cloglog links as well.

In this toy example, we’ve constructed it such that dirt should not affect one side differently from another, so we can wrap those into one coefficient: \beta = \beta_h = -\beta_t. This makes the last line of the model:

\text{logit}(\mu) = \text{ Normal}( \alpha + \beta \Delta d)

where \Delta d = d_h - d_t.

Putting that into our dataset, then constructing this model in Bambi,

df["delta_d"] = df["heads_bias_dirt"] - df["tails_bias_dirt"]
dirt_model = bmb.Model("p ~ delta_d", df, family="beta")
dirt_fitted = dirt_model.fit(random_seed=seed)
dirt_model.predict(dirt_fitted, kind="response")
NUTS[nutpie]: [kappa, delta_d, Intercept_centered]

az.summary(dirt_fitted, var_names=["delta_d", "kappa", "Intercept"])
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
delta_d 0.004995 7.3e-05 0.0049 0.0051 5605 3116 1.00 9.7e-07 6.9e-07
kappa 1702 76 1600 1800 6672 3288 1.00 0.93 0.66
Intercept -0.00626 0.00155 -0.0087 -0.0038 6230 3186 1.00 2e-05 1.4e-05
az.plot_ppc_dist(dirt_fitted, var_names=["p"]);

Next, we’ll see if we can in fact recover the effect on \alpha. Remember that in order to return to \alpha, \beta space, the linear equation passes through an inverse logit transformation, so we must apply this to the coefficient on \Delta d to get the effect on \alpha. The inverse logit is nicely defined in scipy.special as expit.

mean_effect = expit(dirt_fitted.posterior.delta_d.mean())
hdi = az.hdi(dirt_fitted.posterior.delta_d, prob=0.95)
lower = expit(hdi.values[0])
upper = expit(hdi.values[1])
print(f"Mean effect: {mean_effect.item():.4f}")
print(f"95% interval {lower.item():.4f} - {upper.item():.4f}")
Mean effect: 0.5012
95% interval 0.5012 - 0.5013

The recovered effect is very close to the true effect of 0.5.

Example - Revisiting Baseball Data

In the Hierarchical Logistic regression with Binomial family notebook, we modeled baseball batting averages (times a player reached first via a hit per times at bat) via a Hierarchical Logisitic regression model. If we’re interested in league-wide effects, we could look at a Beta regression. We work off the assumption that the league-wide batting average follows a Beta distribution, and that individual player’s batting averages are samples from that distribution.

First, load the Batting dataset again, and re-calculate batting average as hits/at-bat. In order to make sure that we have a sufficient sample, we’ll require at least 100 at-bats in order consider a batter. Last, we’ll focus on 1990-2018.

batting = bmb.load_data("batting")
batting["batting_avg"] = batting["H"] / batting["AB"]
batting = batting[batting["AB"] > 100]
df = batting[(batting["yearID"] > 1990) & (batting["yearID"] < 2018)]
fig, ax = plt.subplots()
ax.hist(df["batting_avg"], bins=30, density=True)
ax.set(xlabel="Batting Average", ylabel="Density");

If we’re interested in modeling the distribution of batting averages, we can start with an intercept-only model.

model_avg = bmb.Model("batting_avg ~ 1", df, family="beta")
avg_fitted = model_avg.fit(random_seed=seed)
NUTS[nutpie]: [kappa, Intercept]

az.summary(avg_fitted)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
Intercept -1.03806 0.00172 -1 -1 4009 3091 1.00 2.7e-05 1.9e-05
kappa 152.58 1.97 150 160 3821 2832 1.00 0.032 0.023

Looking at the posterior predictive,

model_avg.predict(avg_fitted, kind="response")
az.plot_ppc_dist(dirt_fitted, var_names=["p"]);

This appears to fit reasonably well. If, for example, we were interested in simulating players, we could sample from this distribution.

However, we can take this further. Say we’re interested in understanding how this distribution shifts if we know a player’s batting average in a previous year. We can condition the model on a player’s n-1 year, and use Beta regrssion to model that. Let’s construct that variable, and for sake of ease, we will ignore players without previous seasons.

# Add the player's batting average in the n-1 year
batting["batting_avg_shift"] = np.where(
    batting["playerID"] == batting["playerID"].shift(),
    batting["batting_avg"].shift(),
    np.nan,
)
df_shift = batting[(batting["yearID"] > 1990) & (batting["yearID"] < 2018)]
df_shift = df_shift[~df_shift["batting_avg_shift"].isna()]
df_shift[["batting_avg_shift", "batting_avg"]].corr()
batting_avg_shift batting_avg
batting_avg_shift 1.000000 0.229774
batting_avg 0.229774 1.000000

There is a lot of variance in year-to-year batting averages, it’s not known to be incredibly predictive, and we see that here. A correlation coefficient of 0.23 is only lightly predictive. However, we can still use it in our model to get a better understanding. We’ll fit two models. First, we’ll refit the previous, intercept-only, model using this updated dataset so we have an apples-to-apples comparison. Then, we’ll fit a model using the previous year’s batting average as a predictor.

Notice we need to explicitly ask for the inclusion of the log-likelihood values into the inference data object.

model_avg = bmb.Model("batting_avg ~ 1", df_shift, family="beta")
avg_fitted = model_avg.fit(random_seed=seed)
model_avg.compute_log_likelihood(avg_fitted)

model_lag = bmb.Model("batting_avg ~ batting_avg_shift", df_shift, family="beta")
lag_fitted = model_lag.fit(random_seed=seed)
model_lag.compute_log_likelihood(lag_fitted)
NUTS[nutpie]: [kappa, Intercept]

NUTS[nutpie]: [kappa, batting_avg_shift, Intercept_centered]

az.summary(lag_fitted)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
batting_avg_shift 1.357 0.272 0.94 1.8 5971 3205 1.00 0.0035 0.0025
Intercept_centered -1.0243 0.0095 -1 -1 6391 2903 1.00 0.00012 8.5e-05
kappa 135.9 9.3 120 150 5168 3041 1.00 0.13 0.095
Intercept -1.377 0.071 -1.5 -1.3 5969 3158 1.00 0.00092 0.00067
az.compare({"intercept-only": avg_fitted, "lag-model": lag_fitted})
rank elpd_diff dse p_worse diag_diff diag_elpd p elpd se weight
lag-model 0 0.0 0.0 NaN 3.0 790.0 15.0 0.99
intercept-only 1 -11.0 4.7 0.99 2.1 770.0 15.0 0.01

Adding the predictor results in a higher loo than the intercept-only model.

model_lag.predict(lag_fitted, kind="response")
az.plot_ppc_dist(lag_fitted, var_names=["batting_avg"]);

The biggest question this helps us understand is, for each point of batting average in the previous year, how much better do we expect a player to be in the current year?

mean_effect = lag_fitted.posterior.batting_avg_shift.mean().item()
hdi = az.hdi(lag_fitted.posterior.batting_avg_shift, prob=0.95)
lower = expit(hdi[0]).item()
upper = expit(hdi[1]).item()
print(f"Mean effect: {expit(mean_effect):.4f}")
print(f"95% interval {lower:.4f} - {upper:.4f}")
Mean effect: 0.7953
95% interval 0.6916 - 0.8676
bmb.interpret.plot_predictions(
    model_lag,
    lag_fitted,
    conditional="batting_avg_shift",
    target="batting_avg",
    prob=[0.68, 0.95],
    fig_kwargs={
        "xlabel": "Previous Year's Batting Average",
        "ylabel": "Batting Average",
    },
)

%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