Install & Compatibility
Where this runs
tested against v3.1.6 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.291s · 89.8MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 3.6s · import 0.292s · 86MB
89MB installed
● package 89MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
EnsembleSampler
✓ from emcee import EnsembleSampler
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]}")
Debug
Known issues
breakingWhen upgrading from `emcee` v2.x to v3.x, several arguments to `EnsembleSampler` related to proposal control (`a`, `live_dangerously`) and parallelization (`threads`) were deprecated. These functionalities are now managed via the `moves` interface and the `pool` argument, respectively. [8]fixConsult the `emcee` v3 documentation for the `EnsembleSampler` constructor and the `Moves` and `Parallelization` sections to adapt your code. For parallelization, use a `pool` object (e.g., from `multiprocessing`). [8]
affects: Upgrading from <3.0 to >=3.0
gotchaThe `log_prob_fn` passed to `EnsembleSampler` must return the natural logarithm of the *posterior probability*, not just the likelihood. It should also return `-np.inf` if the parameters are unphysical or lead to a probability of zero. [2, 11]fixEnsure your `log_prob_fn` includes both the log-prior and log-likelihood terms. For parameter values outside valid physical bounds, explicitly return `-np.inf` from `log_prob_fn`. [11]
affects: All versions
gotchaPoor initialization of walkers can lead to slow convergence, biased results, or errors (e.g., 'Too few points to create valid contours' or math warnings). Walkers should be initialized in a region of non-zero probability. [15, 17, 18]fixInitialize walkers by drawing from a small Gaussian ball around a reasonable guess (e.g., a maximum likelihood estimate) or from a broad, valid prior distribution. Ensure all initial positions have finite `log_prob` values. [11]
affects: All versions
gotchaSpecific versions of `emcee` have included compatibility fixes for `numpy` and `scipy`. For example, v3.1.6 fixed compatibility with older NumPy versions, and v3.1.4 addressed the updated `kstest` interface in SciPy 1.10. [12]fixIf encountering unexpected behavior related to numerical operations or statistical tests, check `emcee`'s release notes for dependency-specific fixes and ensure your `numpy` and `scipy` versions are compatible with your `emcee` version. Upgrading all libraries to their latest stable versions is generally recommended.
affects: Potentially specific minor versions of `emcee` with older/newer `numpy`/`scipy` versions.
Errors
Common errors & fixes
ValueError: The number of walkers must be at least twice the dimension of the problem
The `emcee` ensemble sampler requires the number of walkers to be at least twice the number of dimensions (parameters) in the problem being sampled for its affine-invariant algorithm to function correctly. [7, 10]
fixInitialize `emcee.EnsembleSampler` with `nwalkers` (number of walkers) greater than or equal to `2 * dim` (number of dimensions/parameters).
AttributeError: 'module' object has no attribute 'log_prob_fn' (or similar for 'lnprob')
When using `emcee` with multiprocessing, the `log_prob_fn` (or `lnprob` in older examples) must be defined as a top-level, pickleable function in a module, particularly on Windows, where child processes cannot easily access functions defined within other functions or methods. [16]
fixMove your `log_prob_fn` definition to the global scope of your Python script or module. If running on Windows, ensure your main execution block is guarded by `if __name__ == '__main__':`.
AttributeError: 'EnsembleSampler' object has no attribute 'run'
The `emcee.EnsembleSampler` object does not have a method named `run`. The correct method to perform MCMC sampling is `run_mcmc`.
fixReplace calls to `sampler.run(...)` with `sampler.run_mcmc(...)` to start the sampling process.
emcee sampler stalls indefinitely with multiprocessing
On certain systems or with complex models, the default 'fork' multiprocessing context can cause `emcee`'s `EnsembleSampler` to hang or stall when a `pool` is used for parallel execution. [12]
fixManually set the multiprocessing context to 'spawn' before creating the pool. For example: `import multiprocessing; with multiprocessing.get_context('spawn').Pool() as pool: sampler = emcee.EnsembleSampler(..., pool=pool)`. Upgrade
Version history
3.1.6latest on PyPI · released Apr 19, 2024
Audit
Dependencies
numpyrequiredRequired for numerical operations and array handling.
scipyoptionalOften used for optimization and statistical functions, and some internal fixes relate to SciPy compatibility (e.g., kstest).