Sample Stan or PyMC models
Maintained. Last release 5 months ago, commits in 9 of the last 26 weeks. Weaker on contributor spread.
pip install nutpienutpie: A fast sampler for Bayesian posteriors
The nutpie package provides a fast NUTS sampler for PyMC and Stan models.
See the documentation for more details.
Installation
nutpie can be installed using Conda or Mamba from conda-forge with
mamba install -c conda-forge nutpie
Or using pip:
pip install nutpie
To install it from source, install a Rust compiler and maturin and then
maturin develop --release
If you want to use the nightly SIMD implementation for some of the math functions,
switch to Rust nightly and then install with the simd_support feature in then
nutpie directory:
rustup override set nightly
maturin develop --release --features=simd_support
Usage with PyMC
First, PyMC and Numba need to be installed, for example using
mamba install -c conda-forge pymc numba
We need to create a model:
import pymc as pm
import numpy as np
import nutpie
import pandas as pd
import seaborn as sns
# Load the radon dataset
data = pd.read_csv(pm.get_data("radon.csv"))
data["log_radon"] = data["log_radon"].astype(np.float64)
county_idx, counties = pd.factorize(data.county)
coords = {"county": counties, "obs_id": np.arange(len(county_idx))}
# Create a simple hierarchical model for the radon dataset
with pm.Model(coords=coords, check_bounds=False) as pymc_model:
intercept = pm.Normal("intercept", sigma=10)
# County effects
raw = pm.ZeroSumNormal("county_raw", dims="county")
sd = pm.HalfNormal("county_sd")
county_effect = pm.Deterministic("county_effect", raw * sd, dims="county")
# Global floor effect
floor_effect = pm.Normal("floor_effect", sigma=2)
# County:floor interaction
raw = pm.ZeroSumNormal("county_floor_raw", dims="county")
sd = pm.HalfNormal("county_floor_sd")
county_floor_effect = pm.Deterministic(
"county_floor_effect", raw * sd, dims="county"
)
mu = (
intercept
+ county_effect[county_idx]
+ floor_effect * data.floor.values
+ county_floor_effect[county_idx] * data.floor.values
)
sigma = pm.HalfNormal("sigma", sigma=1.5)
pm.Normal(
"log_radon", mu=mu, sigma=sigma, observed=data.log_radon.values, dims="obs_id"
)
We then compile this model and sample form the posterior:
compiled_model = nutpie.compile_pymc_model(pymc_model)
trace_pymc = nutpie.sample(compiled_model)