# BAyesian Model-Building Interface in Python

![](logos/RGB/Bambi_logo.png)

[![PyPi version](https://badge.fury.io/py/bambi.svg)](https://badge.fury.io/py/bambi) [![Build Status](https://github.com/bambinos/bambi/actions/workflows/ci.yml/badge.svg)](https://github.com/bambinos/bambi/actions/workflows/ci.yml) [![codecov](https://codecov.io/gh/bambinos/bambi/branch/master/graph/badge.svg?token=ZqH0KCLKAE)](https://codecov.io/gh/bambinos/bambi) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black)

Bambi is a high-level Bayesian model-building interface written in Python. It works with the [PyMC](https://www.pymc.io/) 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**

``` bash
pip install bambi
```

**conda**

``` bash
conda install -c conda-forge bambi
```

**uv**

``` bash
uv pip install bambi
```

#### GitHub version

Install the development version directly from GitHub:

**pip**

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

**conda**

Use pip inside your active conda environment:

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

**uv**

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

### Examples

``` python
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.

``` python
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…  
                                                                                    

``` python
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 |

``` python
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])
```

![](index_files/figure-html/notebooks-homepage_examples-cell-5-output-1.png)

#### 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.

``` python
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…  
                                                                                    

``` python
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();
```

![](index_files/figure-html/notebooks-homepage_examples-cell-7-output-1.png)

For the full analyses, see [Sleepstudy](notebooks/sleepstudy.ipynb) and [Survival models](notebooks/survival_model.ipynb). More examples are available in the [gallery](notebooks/index.md).

### Donations

If you want to support Bambi financially, you can [make a donation](https://numfocus.org/donate-to-pymc) to our sister project PyMC.
