BAyesian Model-Building Interface in Python

Community

Contributing guide
Code of conduct
Full license
Citing bambi

Developers

Tomás Capretto

Maintainer

Osvaldo Martin

Maintainer

Gabriel Stechschulte

Maintainer

Ravin Kumar

Maintainer

Meta

Requires: Python >=3.12
Provides-Extra: jax, nutpie
Package Info

PyPi version Build Status codecov Code style: black

Bambi is a high-level Bayesian model-building interface written in Python. It works with the PyMC probabilistic programming framework and is designed to make it extremely easy to fit Bayesian mixed-effects models common in biology, social sciences and other disciplines.

Installation

Run these commands in an active Python environment.

Released version

pip install bambi
conda install -c conda-forge bambi
uv pip install bambi

GitHub version

Install the development version directly from GitHub:

pip install git+https://github.com/bambinos/bambi.git

Use pip inside your active conda environment:

conda install -c conda-forge pip
python -m pip install git+https://github.com/bambinos/bambi.git
uv pip install git+https://github.com/bambinos/bambi.git

Examples

import arviz as az
import bambi as bmb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

Sleepstudy

Fit a hierarchical linear model of reaction time, with an intercept and slope for each subject.

data = bmb.load_data("sleepstudy")
data["Days"] = data["Days"].astype(float)

model = bmb.Model("Reaction ~ Days + (Days | Subject)", data, categorical="Subject")
idata = model.fit(random_seed=1211, chains=4)
                                                                                
                                  Step    Grad                                  
  Progress        Draw    Dive…   size    evals   Speed          Elap…   Rema…  
 ────────────────────────────────────────────────────────────────────────────── 
  ━━━━━━ ━━━━━━   1000    0       0.358   31      0.00 draws/s   0:00…   0:00…  
  ━━━━━━ ━━━━━━   1000    0       0.319   31      0.00 draws/s   0:00…   0:00…  
  ━━━━━━ ━━━━━━   1000    0       0.349   15      0.00 draws/s   0:00…   0:00…  
  ━━━━━━ ━━━━━━   1000    0       0.365   15      0.00 draws/s   0:00…   0:00…  
                                                                                
az.summary(
    idata,
    var_names=["Intercept", "Days", "1|Subject_sigma", "Days|Subject_sigma", "sigma"],
)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
Intercept 251.4 7.6 240 260 1547 2005 1.00 0.19 0.13
Days 10.5 1.7 7.8 13 878 1376 1.00 0.057 0.035
1|Subject_sigma 27.5 6.8 18 40 1379 1681 1.00 0.19 0.14
Days|Subject_sigma 6.58 1.46 4.6 9.2 1136 1381 1.00 0.044 0.036
sigma 25.79 1.51 23 28 3750 3247 1.00 0.025 0.024
fig = plt.figure(figsize=(8, 9), layout="constrained")
bmb.interpret.plot_predictions(
    model,
    idata,
    conditional=["Days", "Subject"],
    subplot_kwargs={"main": "Days", "panel": "Subject"},
    fig_kwargs={
        "ylabel": "Reaction time",
        "title": "Subject: {}".format,
        "wrap": 3,
        "theme": dict(plt.rcParams),
    },
    on=fig,
)

for ax, subject in zip(fig.get_axes(), data["Subject"].unique()):
    ax.scatter(
        data.loc[data["Subject"] == subject, "Days"].to_numpy(),
        data.loc[data["Subject"] == subject, "Reaction"].to_numpy(),
        color="white",
        ec="0.2",
        s=25,
        zorder=10,
    )
    ax.set(xticks=[0, 2, 4, 6, 8, 10])

Predicted mean reaction time and credible bands for each of the 18 subjects, with observed reaction times overlaid.

Distribution of adoption times

Fit an exponential survival model for black cats and other cats, treating outcomes other than adoption as right-censored. The histograms show the posterior distributions of the mean adoption times in days.

cats = pd.read_csv("data/AustinCats.csv.gz", sep=";")
cats["months"] = cats["days_to_event"] / 31
cats["status"] = np.where(cats["out_event"] == "Adoption", "none", "right")
cats["coat"] = np.where(cats["color"] == "Black", "Black cats", "Other cats")

cat_model = bmb.Model(
    "censored(months, status) ~ 0 + coat",
    cats,
    family="exponential",
    link="log",
    categorical="coat",
    priors={"coat": bmb.Prior("Normal", mu=0, sigma=1)},
)

cat_idata = cat_model.fit(random_seed=1305, chains=4)
                                                                                
                                  Step    Grad                                  
  Progress        Draw    Dive…   size    evals   Speed          Elap…   Rema…  
 ────────────────────────────────────────────────────────────────────────────── 
  ━━━━━━ ━━━━━━   1000    0       1.298   3       206.43 draw…   0:00…   0:00…  
  ━━━━━━ ━━━━━━   1000    0       1.128   3       222.81 draw…   0:00…   0:00…  
  ━━━━━━ ━━━━━━   1000    0       1.096   3       223.75 draw…   0:00…   0:00…  
  ━━━━━━ ━━━━━━   1000    0       1.131   3       222.40 draw…   0:00…   0:00…  
                                                                                
cat_predictions = cat_model.predict(
    cat_idata,
    data=pd.DataFrame({"coat": ["Other cats", "Black cats"]}),
    inplace=False,
)
adoption_times = cat_predictions.predictions["mu"] * 31

fig, ax = plt.subplots(figsize=(7, 3))
for index, label in enumerate(["Other cats", "Black cats"]):
    ax.hist(
        adoption_times.isel(__obs__=index).values.ravel(),
        bins=50,
        density=True,
        alpha=0.7,
        label=label,
    )
ax.set(xlabel="Days", ylabel="Density", title="Distribution of Adoption Times")
ax.legend();

Posterior distributions of mean adoption times in days for black cats and other cats.

For the full analyses, see Sleepstudy and Survival models. More examples are available in the gallery.

Donations

If you want to support Bambi financially, you can make a donation to our sister project PyMC.