Sign in

Bayesian inference

Updating a belief about an unknown parameter with data: a prior times a likelihood gives a posterior, in closed form when the prior is conjugate.

Overview

You begin with a prior: a distribution that says which values of an unknown quantity you find plausible before seeing data. Each observation then reweights those values by how well they explain it. The result is the posterior, a new distribution that blends what you believed with what you saw. For some pairs of prior and data model the posterior stays in the same family as the prior, so updating is just arithmetic on two numbers. Such a prior is called conjugate. With little data the prior dominates, and with much data the observations do.

A short history

Thomas Bayes' essay on inverse probability was published in 1763, after his death, by Richard Price. Pierre-Simon Laplace developed the same idea independently and applied it widely. For most of the 1900s the method was limited to cases with closed-form answers, such as conjugate priors. From about 1990, Markov chain Monte Carlo sampling on cheap computers made posteriors for general models practical.

How it works

  1. Choose a model for the data and a conjugate prior for its parameter: Beta for a Bernoulli probability, Gamma for a Poisson rate, Normal for a Normal mean with known noise variance.
  2. Set the two prior parameters. They act like observations seen in advance: Beta(2, 2) behaves like one earlier success and one earlier failure on top of a flat prior.
  3. Fold the data in. For the Beta prior add the successes to the first parameter and the failures to the second.
  4. Read the answers off the posterior: its mean, its variance, its mode (the MAP estimate, short for maximum a posteriori) and a credible interval.
  5. Chain updates when more data arrives. The posterior from one batch is the prior for the next, and the order of the batches does not matter.
  6. When no conjugate pair fits, evaluate prior times likelihood on a grid of parameter values and normalize, which is what grid_posterior does in log space.

Watch out for

  • A strong prior can overrule the data. Beta(50, 50) needs hundreds of observations to move far from 0.5, so always check how sensitive the answer is to the prior.
  • The MAP estimate and the posterior mean differ when the posterior is skewed. Reporting one number hides that, so report the interval as well.
  • A 95% credible interval says the parameter lies inside with probability 0.95 given the model and the prior. It is not the same statement as a 95% confidence interval.
  • The normal model here assumes the noise variance is known. If you plug in a variance estimated from the same small sample, the posterior will be too narrow.
  • This template covers one parameter and three conjugate pairs. Real models with many parameters usually need sampling methods such as Markov chain Monte Carlo.

Use cases

When to use it

Estimating a rate, a proportion or a mean from few observations, when you want an honest statement of uncertainty and a principled way to include what you knew beforehand.

In industry

Online experimentation
A/B testing tools model each variant's conversion rate with a Beta prior and report the posterior probability that one variant beats the other.
Clinical trials
Adaptive trial designs update the posterior for a treatment effect as patients report, and use it to stop early or shift patients between arms.
Email filtering
Naive Bayes spam filters combine a prior spam rate with word likelihoods to give the posterior chance that a message is spam.

Choosing it: what must hold

  • A likelihood: a model for how the data arise given the unknown parameter.
  • A prior you can state and defend, from earlier data or from domain knowledge.
  • A conjugate prior for a closed-form posterior, or a sampler when the prior is not conjugate.
  • A need for a full distribution over the parameter, not only a single best value.

When to choose something else

IfUse instead
Data are plentiful and a single best value is enoughLikelihood and maximum likelihood estimation
The prior is not conjugate, so the posterior has no closed formMonte Carlo methods, such as Metropolis-Hastings
You only need a yes or no decision at a fixed error rateHypothesis testing

Math foundations

  1. Bayes' theorem for a parameter

    p(θ∣x)=p(x∣θ) p(θ)p(x),p(x)=∫p(x∣θ) p(θ) dθp(\theta \mid x) = \frac{p(x \mid \theta)\,p(\theta)}{p(x)}, \qquad p(x) = \int p(x \mid \theta)\,p(\theta)\,d\theta

    The posterior is the likelihood times the prior, divided by a constant that makes it integrate to 1. That constant, the evidence, does not depend on θ\theta.

  2. Beta prior, Bernoulli data

    θ∼Beta⁡(α,β) ⟹ θ∣x∼Beta⁡(α+s, β+n−s)\theta \sim \operatorname{Beta}(\alpha, \beta) \ \Longrightarrow\ \theta \mid x \sim \operatorname{Beta}(\alpha + s,\ \beta + n - s)

    With ss successes in nn trials the likelihood is θs(1−θ)n−s\theta^{s}(1-\theta)^{n-s}, which has the same shape as a Beta density. Multiplying the two just adds the exponents.

  3. Gamma prior, Poisson data

    λ∼Gamma⁡(α,β) ⟹ λ∣x∼Gamma⁡ ⁣(α+∑i=1nxi, β+n)\lambda \sim \operatorname{Gamma}(\alpha, \beta) \ \Longrightarrow\ \lambda \mid x \sim \operatorname{Gamma}\!\left(\alpha + \sum_{i=1}^{n} x_i,\ \beta + n\right)

    Here β\beta is a rate parameter. The shape collects the total count and the rate collects the number of observations, so the posterior mean is close to events per observation.

  4. Normal prior, Normal data

    1τn2=1τ02+nσ2,μn=τn2(μ0τ02+∑ixiσ2)\frac{1}{\tau_n^{2}} = \frac{1}{\tau_0^{2}} + \frac{n}{\sigma^{2}}, \qquad \mu_n = \tau_n^{2}\left(\frac{\mu_0}{\tau_0^{2}} + \frac{\sum_{i} x_i}{\sigma^{2}}\right)

    Precisions, the reciprocals of variances, add. The posterior mean is a weighted average of the prior mean and the data, each weighted by its precision.

  5. Point estimates from a Beta posterior

    E[θ∣x]=α′α′+β′,θMAP=α′−1α′+β′−2(α′,β′>1)\mathbb{E}[\theta \mid x] = \frac{\alpha'}{\alpha' + \beta'}, \qquad \theta_{\text{MAP}} = \frac{\alpha' - 1}{\alpha' + \beta' - 2} \quad (\alpha', \beta' > 1)

    The mean is the centre of mass of the posterior and the MAP estimate is its peak. With a flat Beta(1, 1) prior the MAP estimate equals the plain success fraction s/ns/n.

  6. Equal-tailed credible interval

    ∫−∞ℓp(θ∣x) dθ=∫u∞p(θ∣x) dθ=1−c2\int_{-\infty}^{\ell} p(\theta \mid x)\,d\theta = \int_{u}^{\infty} p(\theta \mid x)\,d\theta = \frac{1 - c}{2}

    The interval from ℓ\ell to uu holds posterior mass cc and leaves the same mass in each tail. The template finds the two ends by inverting the posterior's cumulative distribution on a grid.

Symbols

θ\theta
the unknown parameter, for example a success probability
xx
the observed data, x1,…,xnx_1, \dots, x_n
p(θ)p(\theta)
the prior density
p(x∣θ)p(x \mid \theta)
the likelihood: the probability of the data for a given parameter
p(θ∣x)p(\theta \mid x)
the posterior density
α, β\alpha,\ \beta
prior parameters: prior_a and prior_b in the config
α′, β′\alpha',\ \beta'
posterior parameters after the update
s, ns,\ n
the number of successes and the number of observations
λ\lambda
the Poisson rate
μ0, τ02\mu_0,\ \tau_0^{2}
the mean and variance of the Normal prior
μn, τn2\mu_n,\ \tau_n^{2}
the mean and variance of the Normal posterior
σ2\sigma^{2}
the known noise variance of each observation
cc
the credible level, 0.95 by default
ℓ, u\ell,\ u
the lower and upper ends of the credible interval

Worked by hand

A coin of unknown bias is tossed 10 times and lands heads 7 times. Start from the flat prior Beta(1, 1), so α=β=1\alpha = \beta = 1, s=7s = 7 and n=10n = 10.

α′=1+7=8,β′=1+(10−7)=4\alpha' = 1 + 7 = 8, \qquad \beta' = 1 + (10 - 7) = 4
E[θ∣x]=88+4=0.667\mathbb{E}[\theta \mid x] = \frac{8}{8 + 4} = 0.667
θMAP=8−18+4−2=710=0.7\theta_{\text{MAP}} = \frac{8 - 1}{8 + 4 - 2} = \frac{7}{10} = 0.7
Var⁡[θ∣x]=8×4122×13=321872≈0.0171\operatorname{Var}[\theta \mid x] = \frac{8 \times 4}{12^{2} \times 13} = \frac{32}{1872} \approx 0.0171

The posterior is Beta(8, 4). Its peak sits at the observed fraction 0.7, its mean is pulled slightly toward 0.5 by the prior, and its standard deviation is about 0.13.

Visual example

Loading the example.

Try this

  • Leave the data at 7 heads in 10 and raise both α and β to 10: a confident prior near 0.5 holds the posterior back.
  • Set n to 100 and s to 70. The prior now hardly matters.
  • Set n to 0 and the posterior is the prior.

Code sample

from impl import BayesianInference, bayes_rule
from config import BayesianInferenceConfig

coin = BayesianInference(BayesianInferenceConfig(model="beta_bernoulli", prior_a=1.0, prior_b=1.0))
coin.update([1, 1, 1, 0, 1, 1, 0, 1, 0, 1])     # 7 heads, 3 tails -> Beta(8, 4)
coin.posterior_mean()                            # 0.6667
coin.map_estimate()                              # 0.7
coin.credible_interval()                         # about (0.39, 0.89)

bayes_rule([0.01, 0.99], [0.99, 0.05])           # P(ill | positive test) = 0.1667
Read the implementation (157 lines)
"""Bayesian inference with conjugate priors.

A prior is updated by data into a posterior of the same family, in closed form:
Beta prior with Bernoulli data, Gamma prior with Poisson data, Normal prior with Normal data of known variance.
The posterior mean, variance, MAP estimate and an equal-tailed credible interval are read off the posterior.
`bayes_rule` and `grid_posterior` cover the discrete case and any one-parameter model on a grid.
"""
from __future__ import annotations

import math
from statistics import NormalDist

import numpy as np

try:
    from .config import BayesianInferenceConfig
except ImportError:  # run from the template's own folder
    from config import BayesianInferenceConfig

_lgamma = np.vectorize(math.lgamma, otypes=[float])


def bayes_rule(prior, likelihood) -> np.ndarray:
    """Posterior over a finite set of hypotheses: prior * likelihood, renormalized.

    prior:      array (k,), P(H_i), sums to 1.
    likelihood: array (k,), P(data | H_i).
    Returns array (k,), P(H_i | data).
    """
    prior = np.asarray(prior, dtype=float)
    likelihood = np.asarray(likelihood, dtype=float)
    if prior.shape != likelihood.shape:
        raise ValueError("prior and likelihood must have the same shape")
    joint = prior * likelihood
    evidence = joint.sum()
    if evidence <= 0:
        raise ValueError("the data has probability zero under every hypothesis")
    return joint / evidence


def grid_posterior(log_prior, log_likelihood) -> np.ndarray:
    """Posterior weights on a parameter grid from log prior and log likelihood values, both arrays (g,).

    Works in log space so long data sets do not underflow. The weights sum to 1.
    """
    log_post = np.asarray(log_prior, dtype=float) + np.asarray(log_likelihood, dtype=float)
    log_post = log_post - log_post.max()
    weights = np.exp(log_post)
    return weights / weights.sum()


class BayesianInference:
    """Conjugate Bayesian updating for one parameter.

    After `update(data)` the attributes `a` and `b` hold the posterior parameters, with the same meaning as
    `prior_a` and `prior_b` in the config. Updates can be chained: the posterior of one batch is the prior of
    the next.
    """

    def __init__(self, config: BayesianInferenceConfig | None = None) -> None:
        self.config = config or BayesianInferenceConfig()
        self.a = float(self.config.prior_a)
        self.b = float(self.config.prior_b)
        self.n_observations = 0

    def update(self, data) -> "BayesianInference":
        """Fold observations, array (n,), into the posterior. Returns self."""
        x = np.asarray(data, dtype=float).ravel()
        n = x.size
        model = self.config.model
        if model == "beta_bernoulli":
            if np.any((x != 0) & (x != 1)):
                raise ValueError("Bernoulli data must be 0 or 1")
            self.a += x.sum()
            self.b += n - x.sum()
        elif model == "gamma_poisson":
            if np.any(x < 0) or np.any(x != np.round(x)):
                raise ValueError("Poisson data must be non-negative whole numbers")
            self.a += x.sum()
            self.b += n
        else:
            precision = 1.0 / self.b + n / self.config.noise_variance
            self.a = (self.a / self.b + x.sum() / self.config.noise_variance) / precision
            self.b = 1.0 / precision
        self.n_observations += n
        return self

    def posterior_params(self) -> tuple[float, float]:
        """(a, b) of the current posterior."""
        return self.a, self.b

    def posterior_mean(self) -> float:
        model = self.config.model
        if model == "beta_bernoulli":
            return self.a / (self.a + self.b)
        if model == "gamma_poisson":
            return self.a / self.b
        return self.a

    def posterior_variance(self) -> float:
        model = self.config.model
        if model == "beta_bernoulli":
            s = self.a + self.b
            return self.a * self.b / (s * s * (s + 1.0))
        if model == "gamma_poisson":
            return self.a / self.b**2
        return self.b

    def map_estimate(self) -> float:
        """Mode of the posterior density (maximum a posteriori estimate)."""
        model = self.config.model
        if model == "beta_bernoulli":
            if self.a > 1 and self.b > 1:
                return (self.a - 1.0) / (self.a + self.b - 2.0)
            if self.a <= 1 < self.b:
                return 0.0
            if self.b <= 1 < self.a:
                return 1.0
            raise ValueError("the Beta posterior has no single mode when both parameters are at most 1")
        if model == "gamma_poisson":
            return max(self.a - 1.0, 0.0) / self.b
        return self.a

    def log_pdf(self, theta) -> np.ndarray:
        """Log posterior density at theta (any shape)."""
        theta = np.asarray(theta, dtype=float)
        model = self.config.model
        with np.errstate(divide="ignore", invalid="ignore"):
            if model == "beta_bernoulli":
                log_norm = math.lgamma(self.a + self.b) - math.lgamma(self.a) - math.lgamma(self.b)
                return log_norm + (self.a - 1) * np.log(theta) + (self.b - 1) * np.log1p(-theta)
            if model == "gamma_poisson":
                log_norm = self.a * math.log(self.b) - math.lgamma(self.a)
                return log_norm + (self.a - 1) * np.log(theta) - self.b * theta
            return -0.5 * math.log(2 * math.pi * self.b) - 0.5 * (theta - self.a) ** 2 / self.b

    def credible_interval(self) -> tuple[float, float]:
        """Equal-tailed interval holding `credible_level` of the posterior mass."""
        tail = (1.0 - self.config.credible_level) / 2.0
        if self.config.model == "normal_normal":
            dist = NormalDist(self.a, math.sqrt(self.b))
            return dist.inv_cdf(tail), dist.inv_cdf(1.0 - tail)
        if self.config.model == "beta_bernoulli":
            low, high = 0.0, 1.0
        else:
            low = 0.0
            high = self.posterior_mean() + 15.0 * math.sqrt(self.posterior_variance())
        edges = np.linspace(low, high, self.config.grid_size)
        mids = 0.5 * (edges[:-1] + edges[1:])
        mass = np.exp(self.log_pdf(mids))
        cdf = np.concatenate([[0.0], np.cumsum(mass)])
        cdf /= cdf[-1]
        return float(np.interp(tail, cdf, edges)), float(np.interp(1.0 - tail, cdf, edges))

    def predictive_mean(self) -> float:
        """Expected value of the next observation under the posterior."""
        return self.posterior_mean()
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Create BayesianInference with the default config (beta_bernoulli, prior 1 and 1), call update on the ten tosses 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 and print posterior_params, posterior_mean, map_estimate and credible_interval. Repeat with prior_a and prior_b set to 20 and compare the interval. Then feed the same data in two batches of five and confirm the posterior is identical.

Check on learning

  1. With a Beta(20, 20) prior and 7 heads in 10 tosses, where will the posterior mean land, and what does that tell you about how to read the prior parameters?
    A way to think about it

    Add the counts and compute 27/5027/50. Compare the weight of 40 imagined tosses with the weight of 10 real ones.

  2. Why does the order of the observations not change the posterior in these conjugate models?
    A way to think about it

    Look at what the update uses from the data. In each case it is a sum and a count, and neither depends on order.

  3. After 3 heads in 3 tosses with a flat prior, the MAP estimate is 1 but the posterior mean is 0.8. Which would you report for a decision that is costly if the coin can land tails, and why?
    A way to think about it

    The peak of Beta(4, 1) sits on the boundary, yet most of the mass is below it. Ask which summary accounts for the chance of tails.

  4. In the normal model, what happens to the posterior variance as nn grows, and does it depend on the values observed?
    A way to think about it

    Read the precision formula. Only nn and the two variances appear, so think about what that says when the data look surprising.

  5. When would you prefer grid_posterior to the conjugate update, and what limits the grid approach?
    A way to think about it

    Consider a prior that is not in the conjugate family, then count how many grid points a model with five parameters would need.