Examples
Worked examples
Each example is a narrated, executed notebook: the question, the data, the model written in mathematics and in PyMC, every check, and what the result means. Read them in the browser, then run and modify them locally. The foundations come first; after that, each series stands on its own.
E01–E06
Foundations
The core of applied Bayesian work: writing a model down, checking what the priors claim, reading a posterior, pooling information across groups, comparing models and handling censored data. Every challenge assumes these.
coords/dims, pm.Data, prior & posterior predictive checks, DataTree, diagnostics, out-of-sample predictionE02Hierarchical modelsMinnesota radon surveypooling, shrinkage, divergences, centred vs non-centred, group-level predictorsE03GLMs and model comparisonBangladesh arsenic wellslogistic regression, interpretable priors, calibration checks, PSIS-LOOE04Changepoints and discrete latentsUK coal-mining disasterswhy NUTS cannot do discrete, compound steps, marginalisationE05Gaussian processes with HSGPMotorcycle crash testGP priors, exact vs Hilbert-space GPs, heteroskedastic noiseE06Survival analysis and censoringMastectomy survivalpm.Censored, Weibull AFT, survival curves, prior sensitivityD01–D03
Data work
Most models that refuse to sample are data problems in disguise. These cover the craft around the model: preparing arrays, treating missingness and measurement error as part of the model, and carrying an analysis through to a report.
E07–E10, E46–E51, E78–E80
Mechanistic and scientific models
When theory supplies the regression function. Earthquakes as a point process in space and time, the expansion of the universe from supernovae, differential equations with JAX gradients, a black-hole ringdown in real LIGO strain, chaotic dynamics (fitting, forecasting and controlling systems that amplify every error, from blowflies to Lorenz's toy atmospheres), jump-diffusion SDEs for market crashes, and reaction-diffusion PDEs for cell invasion and signaling gradients, designing heaters, insulation and sensors for a heat-equation plate, and finding planets in Kepler light curves and proving an interstellar comet is unbound; and cosmology from whole images: every pixel of a Planck CMB patch, and a Hubble Einstein ring modelled pixel by pixel.
jax.vjp, pytensor.wrap_jax, whole-model JAX (nutpie/NumPyro), a JAX ODE solver, multimodal likelihoods and start pointsE10Signal in the noise: GW150914Real LIGO Hanford + Livingston strain (GWOSC)PSD estimation and whitening, exact time-domain likelihood, black-hole ringdown -> remnant mass and spin, Bayes factor signal vs noise, an honest chirp-mass failureE46Taming chaos: inference, prediction and control of chaotic dynamicsSimulated chaotic Ricker population (Wood 2010's benchmark); Nicholson's blowflies, 180 bidaily counts (gamair)bifurcation diagram and Lyapunov exponent, why trajectory matching fails (a comb of ~1000 likelihood spikes, gradients growing like e^(lambda t), frozen NUTS chains), multiple shooting, …E47Weather jiu-jitsu on the butterfly: Bayesian assimilation and regime control of Lorenz-63Simulated Lorenz-63 with process noise and multiplicative observation error (the setting of Liu, Huang & Lall 2026, Chaos, Solitons & Fractals)two-regime attractor and residence times, instantaneous vs finite-time Lyapunov exponents (and what the LLE does not predict), multiple-shooting centred latent states with RK4 in PyTensor recovering sigma/rho/beta, …E48Regimes and extremes in a seasonal chaotic atmosphere: a Bayesian NHMM for Lorenz-84 and a test of NHMM-triggered controlSimulated seasonally forced Lorenz-84 (Lorenz 1990), daily noisy observations (the setting of Liu, Huang & Lall 2026, Phys. Rev. E)nonautonomous chaos, choosing regime variables (eddy amplitude, not phase), nonhomogeneous HMM with seasonal softmax transitions and AR(1) emissions via scan, HMM multimodality and multi-start MAP initialisation, ordered transform vs a -inf Potential, …E49Jumps: Bayesian jump-diffusion SDEs for the S&P 500S&P 500 daily returns 2008-19compound-Poisson jump-diffusion simulated exactly and by Euler, the Poisson-mixture transition density with the jump count summed out, Merton model (jumps absorbing volatility clustering), non-centred stochastic volatility with and without jumps (SVJ), …E50Reaction-diffusion in biology: cell invasion in a scratch assay, and reading a signaling gradientPC-3 scratch assay, 38 columns x 5 times (Jin et al. 2016, counts via Simpson, Murphy & Maclaren 2024); simulated Nodal/Lefty-scale morphogen images and FRAPFisher-KPP by the method of lines (finite volumes, no-flux, explicit Euler in scan with a stability check), Poisson counts with an estimated carrying capacity, a start-up delay tanh(beta t) and the fourfold bias in D without it, …E51Designing a thermal gradient plate: heaters, insulation and sensors for the 2-D heat equationSimulated 40 x 20 cm plate, calibration experiment (3 test heaters, 12 thermocouples) and operating disturbancesfinite-volume 2-D steady heat equation as a linear system, influence maps and superposition, Bayesian calibration with pt.linalg.solve inside PyMC (a weakly identified edge loss whose interval misses the truth), …E78Finding exoplanets and an interstellar cometKepler-10 light curves (NASA/MAST, 15 quarters) + NASA Exoplanet Archive; MPC astrometry of 2I/Borisov + JPL Horizons/SBDBBLS transit search in Numba, Gumbel false-alarm posterior, limb-darkened transit model (tested quadrature, tabulated in PyMC), marginalised local baselines, b-density degeneracy and reparameterisation, odd/even + occultation as model expansion, …E79CMB field-level inference: the sky behind the LMCPlanck 2018 SMICA map patches (IRSA mirror of the Planck Legacy Archive), half-mission noise, common mask, best-fit TT spectrumGaussian random fields on a flat-sky patch, naive masked-power bias checked on simulations, joint sky + bandpower posterior in PyMC (Hartley basis), centred / non-centred / partial non-centring at low and high signal-to-noise, why a mask hole defeats HMC, …E80A gravitational lens, pixel by pixelHST/ACS image of the Einstein ring SDSS J1627-0053 (MAST), SLACS published modelspixel-level forward model (SIE + shear, Sérsic lens light, FFT PSF from field stars), drizzle-correlated noise whitened in Fourier space, linear amplitudes integrated out, staged vs random starts, wrap_jax + nutpie low-rank, …E52–E61
Cell biology and biophysics
Mechanistic models of living cells, fitted to what biologists measure: signals that travel through the membrane and the cytosol, the fluctuation test that showed mutations arise before selection, why a neuron fires (conductance models fitted to real patch-clamp recordings), transcriptional bursting read from allele-resolved single-cell RNA counts, and how bacteria control their size, measured through noisy segmentation, and single molecules tracked in living nuclei, and super-resolution (STORM) microscopy: localising, detecting and counting single blinking molecules below the diffraction limit, and kinesin's steps counted from MINFLUX traces, the forces cells exert on their substrate (traction force microscopy), and decisions from dynamics: Turing patterns and kinetic proofreading in T cells. See also E50 (reaction-diffusion in tissues).
E62
When the model cannot answer
Most failed analyses do not crash: they answer a question nobody asked, report numbers the prior chose, or never finish. Three real problems fail in these ways - an MMM that cannot split credit between channels, a Gaussian process too large to fit, a trial whose hazard ratio is not the clinic's question - and each is followed by the pivot: a question the data can answer, a cheaper model checked against the exact one, and an answer audit.
E63–E66
Causal designs, doses, cascades and experiments
Workhorse models from four fields, each carried through to a decision. Difference-in-differences, regression discontinuity and instrumental variables on classic natural experiments, with each identifying assumption written as a prior; population pharmacokinetics from theophylline and warfarin to a patient's dose after two monitoring samples; Hawkes and ETAS aftershock forecasts for the 2019 Ridgecrest sequence; and thousands of real headline A/B tests: winner's curse, peeking, and bandits.
E67–E73
Rankings, choices, raters, compositions, topics and decisions
Outcomes that are not one number on a line. Skills estimated from who beat whom in tennis and from whole Formula 1 finishing orders; what people will pay for, from a panel of stated choices, with a market simulator; the true label when pathologists or anaesthetists disagree and nobody knows the answer; data that are parts of a whole; and quick decisions, where a drift diffusion model explains both the choice and how long it took, and says how cautious a person should be; and topic models for anything that comes as a bag of features: the stories behind Upworthy's headlines, the palettes of a century of posters, the intents behind web visits and the missions behind shopping baskets - and the newer topic models built for LDA's problems, tested on the same data.
E74–E77
Colour, light and images
When the estimate is a colour, a spectrum, a region or a word. How the dyes of Japanese woodblock prints fade, and what a 1766 Harunobu print looked like when new; why two paints can match in the shop and differ at home (metamers), inverted from colour to spectrum with a prior learned from 1,269 Munsell chips; segmenting photographs with an unknown number of regions and checking the result, and its confidence, against the people who outlined them; and how 110 languages divide colour space, speaker by speaker - each with uncertainty displays that still work when colour cannot be used to show the uncertainty.
E81–E83
Directions, experiments and quantiles
Three model families that need their own tricks. Angles wrap around, so means, priors and links that work on a line break on a circle (wind at Santa Barbara, ocelots and their prey); Bayesian optimisation chooses the next reaction on a fully measured chemistry screen and is scored against 50 real chemists; and quantile regression for birth weights shows why the asymmetric Laplace posterior is too sure of itself, and how to fix it.
E11–E17
At the research frontier
Neural networks inside differential equations, inference beyond plain NUTS, state-space models, likelihood-free inference, BART, the display of uncertainty and privacy-preserving meta-analysis. Expect honest negative results next to the successes.
pymc_extras.statespace, 3 sampled parameters instead of 400, decomposition, one-step-ahead checks, a counterfactual with a negative control, missing data and forecasting for free - and an honest speed comparisonE14Simulation-based inference: Bayes without a likelihoodS&P 500 returns; 114 years of Canadian lynxrejection ABC calibrated against a known posterior, tolerance and summary statistics as the two approximations, pm.Simulator + SMC, the g-and-k distribution, Wood's synthetic likelihood, a population model that cannot produce the cycleE15Bayesian additive regression treesCapital Bikeshare hourly rentals (subsampled); LaLonde job trainingthe BART prior over functions, pmb.BART inside an ordinary PyMC model, PGBART + NUTS and diagnosing in function space, partial dependence / ICE / variable importance, out-of-sample prediction, an honest comparison with a GLM, BART for causal g-computationE16Showing uncertainty: one posterior, twenty displaysMotorcycle crash test; Minnesota radon with county boundaries; Premier League 2024/25epistemic vs predictive bands, fan charts, why a band is not a set of curves, spaghetti, animated hypothetical outcome plots, quantile dotplots, exceedance curves, caterpillars and ridgelines, …E17Meta-analysis: a database of studies that never shares a patientmetadat benchmarks: 13 BCG trials, 16 magnesium trials (ISIS-4), 56 studies in 11 districtssufficient statistics and why aggregate tables are lossless, two-stage vs one-stage models, forest plots with prediction intervals, tau / I² posteriors, meta-regression, leave-one-out and cumulative meta-analysis, …E18–E23
Correlation structures and graphs
Dependence that lives on a map, a network or a tree: areal models, learning graphs and causal structure from data, network outcomes, many correlated outcomes at once, and regression along a phylogeny.
pm.ICAR / pm.CAR / BYM2, Moran's I residual check, exceedance-probability maps, PSIS-LOO vs refit K-fold, spatial confoundingE19Learning a graph: Bayesian Gaussian graphical modelsSachs et al. (2005) T-cell flow cytometry, 11 phosphoproteins + 20-edge consensus networkmarginal vs partial correlation, LKJCholeskyCov precision and partial-correlation deterministics, why a horseshoe on the precision matrix leaves the positive-definite cone, Bayesian neighbourhood selection (node-wise horseshoe, AND/OR), …E20Learning a directed graph: Bayesian causal discoverySachs et al. (2005), 7466 cells in 9 intervention conditionslinear-Gaussian SEMs, Markov equivalence seen through LOO and pm.do, NOTEARS acyclicity as a pm.Potential (and why it is multimodal and scale-dependent), fixed-order horseshoe DAGs, exact BGe + dynamic-programming averaging over all orders, …E21Network data as the outcome: latent-space and stochastic block modelsLazega law-firm coworker network (71 lawyers, 2485 dyads)dyad logistic vs sociality random effects, Hoff latent space + Procrustes, mixed-membership SBM with marginalised roles (degree-corrected or not), co-clustering matrix, network PPCs (degree, transitivity, shared partners, geodesics), …E22Many correlated outcomes: full covariance, factor models, copulasKen French 12 and 30 US industry portfolios, daily 2015-2024EWMA volatility standardisation, MvNormal + LKJCholeskyCov, low-rank + diagonal factor models, sign-flip / rotation non-identifiability and what r_hat does (not) see, anchored loadings vs Procrustes alignment, choosing K by held-out density, …E23Correlation from a tree: phylogenetic regressionPrimates301 brain / body / group size + 10kTrees phylogenyreading an R phylo object without R, covariance from shared branch length, Brownian motion / Pagel's lambda / OU-as-GP regression, the OU ridge and a reparameterisation, conditional LOO from the precision matrix (and two wrong shortcuts), whitening, …E24–E29
More model families
Hidden Markov models, joint longitudinal and survival models, Dirichlet-process mixtures, sparse regression, imperfect detection in ecology and Bayesian neural networks.
pytensor.scan vs pymc_extras DiscreteMarkovChain + marginalize, label switching and ordering, forward-backward and Viterbi per draw, dwell times, pseudo-residuals, integrated LOO and leave-future-out, padded multi-track HMM, …E25Joint longitudinal-survival modelsMayo Clinic PBC trial: serial bilirubin + survivalmixed model + Weibull hazard sharing LKJ random effects, cumulative hazard by Gauss-Legendre quadrature, baseline / LOCF / two-stage biases, informative dropout, centred vs non-centred vs hierarchically centred, …E26Bayesian nonparametrics: Dirichlet process mixturesEnzyme activity of 245 people (Richardson & Green 1997); PBC bilirubin slopesstick-breaking and the implied prior on the number of clusters, pm.StickBreakingWeights + pm.NormalMixture, truncation check, label-free diagnostics, co-clustering and Binder / VI point clustering, sensitivity to alpha, …E27Sparse regression: horseshoe, regularised horseshoe, spike-and-slabProstate cancer (ESL split); LARS diabetes, 64 predictors on 120 patientsshrinkage factor kappa, ridge vs Bayesian lasso vs horseshoe, tau0 from a prior guess and the simulated m_eff prior, horseshoe divergences and their fixes, spike-and-slab via pymc_extras.marginalize vs exact enumeration, correlated predictors, …E28Imperfect detection: occupancy, N-mixture, capture-recaptureSwiss breeding-bird survey (crossbill, mallard); snowshoe hare capture historieslatent presence / abundance summed out in pm.CustomDist (checked against pymc_extras.marginalize), finite-sample occupancy, naive vs corrected trends, visits x prior confounding, N-mixture truncation check, Poisson vs NegBin, …E29Bayesian neural networks: what the posterior over weights buys youMotorcycle crash test; concrete compressive strength (Yeh 1998, UCI)an MLP in PyMC with dims, priors over functions and the 1/sqrt(width) GP limit, NUTS vs ADVI / Pathfinder / MAP ensemble / last-layer Laplace on held-out density, function-space r_hat, per-input prior scales (ARD), BNN vs HSGP vs GLM, PIT and coverage, …E30–E31
Random partitions and random features
Exchangeable partitions and latent binary features: Pólya urns, Pitman–Yor processes and unseen species, and the Indian buffet process.
E32–E35, E45, E84–E85
Media measurement and market structure
One open multi-brand e-commerce dataset and five questions a marketing team actually asks: a custom likelihood for spend that chases demand, a hierarchical marketing-mix model with a budget decision, a synthetic control, causal mediation, and which shape of response curve the data support (a Weibull transform written in JAX). Plus market structure from household panels: which margarines compete, read off a Bayesian choice map, and what that means for a merger screen; and the same question from the 6-month purchase-incidence tables and partial demographics most studies actually get.
expm1 + series switch, …E84Market structure analysis: who competes with whom?Allenby & Rossi (1991) margarine scanner panel (bayesm): 516 households, 4,470 purchases of 10 products with all shelf pricesswitching matrix and switching lift, IIA (logit diversion proportional to share), nested-logit tests of form vs brand vs tier hierarchies scored on held-out last purchases, factor-structured hierarchical logit as a choice map, …E85Market structure from purchase incidence: combining panel, activity and demographic data84.51 Complete Journey (CC0): household x 14 cereals 0/1 for Jan-Jun 2017 (2,391 households), shopping trips, demographics for a third, Jul-Dec as a test waveco-purchase lift confounded by volume, Bernoulli-logit factor model ladder (activity, category propensity, centred-loading choice map), a naive map whose first axis is volume, …E36–E41
State of the art, explained for everyone
Six model families used in practice today, each with a plain-language opening and a closing section of uncertainty displays for readers with no statistics: MRP, extreme-event attribution, epidemic nowcasting, radiocarbon chronologies, election forecasting and growth charts.
ZeroSumNormal effects and interactions, random-walk prior on ordered groups, state-level predictors, per-draw poststratification (states, age within state), …E37Extreme-event attribution: how much did warming load the dice for the 2021 Pacific Northwest heatwave?NOAA GHCN-Daily annual maximum temperature at Sea-Tac and Portland; NASA GISTEMP global temperatureblock maxima and the GEV (pymc_extras GenExtreme checked against scipy), a geophysical shape prior, a reparameterisation that removes support-wall divergences, non-stationary GEV on smoothed global temperature, …E38Real-time epidemic tracking: is it growing right now? Nowcasting + a renewal-equation RGerman COVID-19 hospitalisation reporting triangle (RKI via the Hospitalization Nowcast Hub), winter 2021/22the reporting triangle and real data-as-of-then snapshots, a delay-hazard nowcast (reporting weekday + weekly drift, negative binomial cells), the renewal equation as a triangular solve, a spurious "wave is ending" from truncated data, …E39How old is it? Radiocarbon calibration and Bayesian chronologiesIntCal20 calibration curve; all 49 measurements from the 1988 Shroud of Turin dating (3 labs, shroud + 3 known-age controls, hand-transcribed from Damon et al. 1989); 31 dates from the Sluggan Bog peat core (Bchron)calibration through a wiggly, uncertain curve, why NUTS on a calendar date fails (r_hat 2.85) and summing the date out on a 1-year grid instead, lab offsets and lab-by-sample heterogeneity anchored by controls, …E40Who will win? Dynamic Bayesian poll aggregation and election forecasting2016 US presidential polls (HuffPost Pollster via the Economist's us-potus-model), 1976-2016 state results, fundamentals, ACS state demographicsLinzer reverse random walks from a fundamentals prior, correlated state innovations, house/mode/population effects, poll-level + shared polling error with a rotation for the unidentified truth/bias split, electoral-college simulation and tipping points, …E41Is my child normal? Distributional regression (GAMLSS/LMS) and growth centile chartsFourth Dutch Growth Study: BMI of 7,294 boys aged 0-21 (gamlss.data dbbmi)constant-spread vs smooth-spread vs skewed vs heavy-tailed models, Bayesian P-splines (centred RW2, low-rank mass matrix) for every distribution parameter, …E42–E44
Posteriors as labelled arrays
A posterior is a labelled array with named chain, draw and model dimensions. These notebooks do all their data and posterior work by name, and use it for derived quantities, time aggregation, binning and unusual plots.
date x hour Dataset with non-dimension coords, stack/unstack round trip to model rows, DataTree navigation and thinning, az.extract, broadcasting counterfactual grids by name, apply_ufunc RNG, "sum the draws, …E43Transforming posteriors with coords: dates, exceedances, ranks and anomaliesNOAA GHCN-Daily TMAX, Sea-Tac + Portland 1948-2025long -> wide xarray, align join pitfalls, concat over a named station dim, a harmonic basis as a DataArray shared by model and posterior, date posteriors with idxmax + interp (summer onset and length), …E44Plotting posteriors creatively from labelled arraysPalmer penguins (raw field records)multivariate normal with one LKJ covariance per species, apply_ufunc for KDEs / Cholesky / rankdata / solve, xr.dot ellipses and correlated draws, pairwise contrast matrices by renaming a dim, stack/sortby, FacetGrids straight from the posterior, …