emcee

3.1.6 · active · verified Wed Apr 15

emcee is an MIT licensed pure-Python implementation of Goodman & Weare's Affine Invariant Markov chain Monte Carlo (MCMC) Ensemble sampler. It is a widely used toolkit for Bayesian parameter estimation in scientific fields, particularly astronomy, and maintains an active release cadence with minor updates and bug fixes. [3, 6, 9]

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `emcee` to sample a 2-dimensional Gaussian distribution. It defines a `log_prob` function for the posterior, initializes walkers, runs a burn-in phase, resets the sampler, and then runs the main MCMC chain to obtain samples. [2]

import numpy as np
import emcee

# Define the logarithm of the posterior probability density function
def log_prob(x, mu, cov):
    diff = x - mu
    return -0.5 * np.dot(diff, np.linalg.solve(cov, diff))

# Set up the problem dimensions and parameters
ndim = 2  # Number of dimensions
nwalkers = 32 # Number of MCMC walkers

# True mean and covariance for the Gaussian
np.random.seed(42)
mu_true = np.array([0.5, -0.2])
cov_true = np.array([[1.0, 0.5], [0.5, 1.5]])

# Initialize walkers in a small ball around the true mean
p0 = mu_true + 1e-3 * np.random.randn(nwalkers, ndim)

# Instantiate the sampler
sampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob, args=(mu_true, cov_true))

# Run the MCMC production chain
state = sampler.run_mcmc(p0, 100)
# After burn-in, reset and run for more steps
sampler.reset()
state = sampler.run_mcmc(state, 1000)

# Get the chain of samples
samples = sampler.get_chain(flat=True)

print(f"Mean acceptance fraction: {np.mean(sampler.acceptance_fraction):.3f}")
print(f"First 5 samples:\n{samples[:5]}")

view raw JSON →