Search

Search papers and lessons

Cross-Entropy Method

Level 3 · 10 min read

Cross-entropy method: sample candidates from a Gaussian, keep the best few, refit the Gaussian to them, and repeat until the samples cluster on the optimum.

On this page

  • Colour = topic mix
  • Probability
  • Calculus
  • Discrete math
  • World models
  • Inference
  • Sampling
  • Sign in to see your progress

TL;DR

The cross-entropy method (CEM) searches for the input that maximises a score function when you cannot compute its gradient. It keeps a probability distribution over inputs, usually a Gaussian. Each round it draws many candidates from that distribution, keeps the best few, and refits the Gaussian so it matches those elite candidates. The distribution moves toward good regions and narrows as it converges.

It needs only the ability to evaluate the score, so it works on black boxes such as simulators, games and learned models.

Where you'll see it: in planning with a learned world model, where it picks action sequences that a model predicts will do well, as in PlaNet, and in policy search and black-box tuning of controllers.

Intuition

Hunting with a net that shrinks

Suppose you are looking for the highest point of a hilly field in fog. You cannot see the slope, but you can measure the height where you stand. One strategy: throw a handful of stones across a wide area, note where the ones that landed highest are, then throw the next handful around that spot, with a smaller spread. Repeat. The throws drift toward the peak and tighten as you go.

That is CEM. The throws are samples from a Gaussian, the "keep the best few" step is the elite selection, and "refit the Gaussian" moves its centre to the average of the elites and sets its width to their spread. The method needs no derivatives, which matters when the score comes from a physics engine or a neural network whose gradient is painful to use.

A single Gaussian can only describe one bump of good answers. If the good answers sit in two separate peaks, CEM tends to settle on one of them. Keep that in mind for the tradeoffs.

flowchart LR
  A[Fit a Gaussian to the current belief] --> B[Sample N candidates]
  B --> C[Score each candidate]
  C --> D[Keep the top K elites]
  D --> E[Refit mean and variance to the elites]
  E --> A
−3−2−10123400.511.5xdensity
  • start: mean 0, sigma 2
  • after one update: mean 2.25, sigma 0.25
One CEM update on a toy problem with optimum at x = 3. The new Gaussian moves toward the elites and becomes much narrower. The numbers come from the worked example below.

The math

The problem

We want to maximise a score function ff over vectors x∈Rd\mathbf{x} \in \mathbb{R}^d:

x⋆=arg⁡max⁡xf(x).\mathbf{x}^\star = \arg\max_{\mathbf{x}} f(\mathbf{x}).

We cannot differentiate ff, so instead we work with a family of distributions pθ(x)p_\theta(\mathbf{x}) indexed by parameters θ\theta. For CEM the family is the multivariate Gaussian with a diagonal covariance, so θ=(μ,σ)\theta = (\boldsymbol{\mu}, \boldsymbol{\sigma}) and

pθ(x)=∏j=1d1σj2πexp⁡ ⁣(−(xj−μj)22σj2).p_\theta(\mathbf{x}) = \prod_{j=1}^{d} \frac{1}{\sigma_j\sqrt{2\pi}} \exp\!\left(-\frac{(x_j - \mu_j)^2}{2\sigma_j^2}\right).

Here xjx_j is coordinate jj of x\mathbf{x}, μj\mu_j is its mean, and σj\sigma_j its standard deviation. The product form says the coordinates are independent under pθp_\theta, which is the diagonal-covariance case from the Gaussian lesson.

The ideal target distribution

Pick a threshold γ\gamma and let EE be the set of samples with score at least γ\gamma. Define the distribution that puts all its weight on that level set:

q⋆(x)=pθ(x) 1{f(x)≥γ}Pθ(f(X)≥γ).q^\star(\mathbf{x}) = \frac{p_\theta(\mathbf{x})\,\mathbf{1}\{f(\mathbf{x}) \ge \gamma\}}{\mathbb{P}_\theta\big(f(\mathbf{X}) \ge \gamma\big)}.

The indicator 1{⋅}\mathbf{1}\{\cdot\} is 1 when its condition holds and 0 otherwise. The denominator is the probability, under pθp_\theta, of landing above the threshold, and it normalises q⋆q^\star to total 1. If γ\gamma is close to the best score, q⋆q^\star concentrates near the optimum.

We would like pθp_\theta to look like q⋆q^\star. The natural measure of mismatch is the KL divergence, and the cross-entropy is closely related:

H(q⋆,pθ′)=−Eq⋆[log⁡pθ′(X)].H(q^\star, p_{\theta'}) = -\mathbb{E}_{q^\star}\big[\log p_{\theta'}(\mathbf{X})\big].

Because DKL(q⋆ ∥ pθ′)=H(q⋆,pθ′)−H(q⋆)D_{\mathrm{KL}}(q^\star \,\|\, p_{\theta'}) = H(q^\star, p_{\theta'}) - H(q^\star), and H(q⋆)H(q^\star) does not depend on θ′\theta', minimising cross-entropy over θ′\theta' is the same as minimising the KL divergence. That is where the name comes from.

Turning the target into samples

We cannot compute the expectation under q⋆q^\star directly, but we can draw from pθp_\theta and keep the samples that pass the threshold. Those kept samples are distributed as q⋆q^\star. So the expectation becomes an average over the elites:

θ′=arg⁡max⁡θ′1K∑i∈Elog⁡pθ′(xi),\theta' = \arg\max_{\theta'} \frac{1}{K} \sum_{i \in E} \log p_{\theta'}(\mathbf{x}_i),

where K=∣E∣K = |E| is the number of elites. This is exactly the maximum likelihood estimate of θ′\theta' from the elite samples. CEM is "fit the model to the best samples, then repeat".

The Gaussian update in closed form

Write out the log density for the diagonal Gaussian:

log⁡pθ′(x)=−d2log⁡(2π)−∑j=1dlog⁡σj′−∑j=1d(xj−μj′)22σj′2.\log p_{\theta'}(\mathbf{x}) = -\frac{d}{2}\log(2\pi) - \sum_{j=1}^{d} \log \sigma'_j - \sum_{j=1}^{d} \frac{(x_j - \mu'_j)^2}{2\sigma'^2_j}.

Set the derivative with respect to μj′\mu'_j to zero and the derivative with respect to σj′\sigma'_j to zero. The solution is

μjnew=1K∑i∈Exi,j,(σjnew)2=1K∑i∈E(xi,j−μjnew)2.\begin{aligned} \mu_j^{\text{new}} &= \frac{1}{K}\sum_{i \in E} x_{i,j}, \\ \left(\sigma_j^{\text{new}}\right)^2 &= \frac{1}{K}\sum_{i \in E}\big(x_{i,j} - \mu_j^{\text{new}}\big)^2. \end{aligned}

So the new mean is the average of the elites and the new variance is their average squared spread. Note the divisor KK, not K−1K - 1: this is the maximum likelihood version of the variance.

The algorithm

Algorithm
Cross-entropy method
  1. Initialise μ\boldsymbol{\mu} to a guess and σ\boldsymbol{\sigma} to a wide spread.
  2. Draw NN samples x1,…,xN\mathbf{x}_1, \dots, \mathbf{x}_N from pθp_\theta.
  3. Score each sample with ff.
  4. Sort by score and keep the top K=ρNK = \rho N samples as elites, for some elite fraction ρ\rho such as 0.10.1.
  5. Set μ\boldsymbol{\mu} and σ\boldsymbol{\sigma} to the elite sample mean and standard deviation, as above.
  6. Repeat from step 2 until the spread is small or the budget runs out. Return the best sample seen.

The threshold γ\gamma is never chosen by hand. It is the score of the KK-th best sample in the current batch, so the method adapts it automatically.

Worked examples

Example 1: one update by hand

Maximise f(x)=−(x−3)2f(x) = -(x - 3)^2 on the line, starting from μ=0\mu = 0 and σ=2\sigma = 2. Draw six samples. These are chosen by hand to make the arithmetic checkable; they are not random draws.

Example
One CEM update with six samples
  1. Samples and scores: x=−1.0  (f=−16)x = -1.0 \;(f = -16), 0.5  (f=−6.25)0.5 \;(f = -6.25), 2.0  (f=−1)2.0 \;(f = -1), 2.5  (f=−0.25)2.5 \;(f = -0.25), 4.5  (f=−2.25)4.5 \;(f = -2.25), 6.0  (f=−9)6.0 \;(f = -9).
  2. Elite fraction ρ=1/3\rho = 1/3, so K=2K = 2. The two best scores are −0.25-0.25 (at 2.52.5) and −1-1 (at 2.02.0). The threshold is γ=−1\gamma = -1.
  3. New mean: μ=2.5+2.02=2.25\mu = \frac{2.5 + 2.0}{2} = 2.25.
  4. New variance: σ2=(2.5−2.25)2+(2.0−2.25)22=0.0625+0.06252=0.0625\sigma^2 = \frac{(2.5 - 2.25)^2 + (2.0 - 2.25)^2}{2} = \frac{0.0625 + 0.0625}{2} = 0.0625, so σ=0.25\sigma = 0.25.
  5. Interpretation: the Gaussian moved from centre 00 to centre 2.252.25, toward the true optimum at 33, and its width dropped from 22 to 0.250.25. With only two elites the estimate is noisy, which is why real runs use far more samples.

Example 2: a seeded run in two dimensions

Maximise f(x)=−[(x1−1)2+(x2+2)2]f(\mathbf{x}) = -\left[(x_1 - 1)^2 + (x_2 + 2)^2\right], whose optimum is (1,−2)(1, -2). Start from mean (0,0)(0, 0) and σ=(3,3)\sigma = (3, 3). Use N=100N = 100 samples per round and K=10K = 10 elites. I ran a 30-line Python script with random seed 0 and recorded the first three rounds:

roundelite thresholdbest scoremeansigma
1-1.813-0.041(0.895, -2.011)(0.554, 0.699)
2-0.046-0.003(1.047, -1.978)(0.108, 0.116)
3-0.002-0.000(1.002, -2.006)(0.023, 0.019)
Example
Reading the table
  1. The elite threshold climbs from −1.81-1.81 to −0.002-0.002 in three rounds. The best sample is within about 0.20.2 of the optimum after round 1, since 0.041≈0.20\sqrt{0.041} \approx 0.20.
  2. The spread shrinks by roughly a factor of five per round in the early rounds: 0.55→0.11→0.020.55 \to 0.11 \to 0.02 in the first coordinate.
  3. By round 5 the sigmas are at most 0.0010.001 and the mean is (1.000,−2.000)(1.000, -2.000) to three decimals. Further rounds change nothing. Running them longer buys nothing because the distribution has collapsed onto the answer.
  4. Interpretation: the method found the optimum with 300 score evaluations. A grid search at similar resolution would need far more.

Tradeoffs and failure modes

CEM is simple and robust when the search space is low to moderate dimensional and the score is cheap to evaluate. It fails in predictable ways.

situationwhat goes wrongbetter choice
Score has two or more separate good regionsA single Gaussian covers both poorly and collapses onto oneMixture of Gaussians, or several restarts
Spread collapses too earlySigma reaches almost zero on a poor answer; the search stops exploringAdd a small noise floor to sigma each round, or smooth the update with the previous parameters
Very high dimensionsWith a fixed sample budget, the elite set is poorly estimatedGradient methods such as [[evolution-strategies
Score is cheap and gradients are availableCEM wastes evaluationsOrdinary [[gradient-descent
Score is an inaccurate modelCEM finds inputs that exploit model errorsEnsembles or uncertainty-aware scoring, as in [[model-predictive-control

The main practical knob is the elite fraction ρ\rho. Small ρ\rho focuses hard on the top samples and risks collapse. Large ρ\rho averages in mediocre samples and converges slowly. Values around 0.10.1 to 0.20.2 are common defaults.

History

Reuven Rubinstein developed the method in the late 1990s. It began as an adaptive importance sampling procedure for estimating the probability of rare events in simulations, where the goal was to pick a sampling distribution close to the ideal one. The key observation was that this selection step could be written as a cross-entropy minimisation, and that it also worked as an optimiser. Rubinstein and Dirk Kroese collected the theory and many applications in a 2004 book.

It later spread to machine learning, including policy search in reinforcement learning. It caught on in planning with learned models because it needs nothing but the ability to score candidate plans. The PlaNet paper used it to pick action sequences in a learned latent space, which is why it appears among that paper's prerequisites.

Check yourself

QuestionWhat is the elite set in one round of CEM, and what does it contribute to the update?Show answer

The elite set is the top KK samples by score in the current batch. The update fits the Gaussian to them by maximum likelihood, so the new mean and variance describe where the good samples were. The rest of the batch is discarded.

QuestionScores for five samples are f(x)=xf(x) = x with x∈{3,7,1,5,6}x \in \{3, 7, 1, 5, 6\}. With elite fraction 0.40.4, what is the new mean?Show answer

K=0.4×5=2K = 0.4 \times 5 = 2, so the elites are the two largest samples, 77 and 66. The new mean is 7+62=6.5\frac{7 + 6}{2} = 6.5. The new variance is (7−6.5)2+(6−6.5)22=0.25\frac{(7 - 6.5)^2 + (6 - 6.5)^2}{2} = 0.25, so the new sigma is 0.50.5.

QuestionWhy does minimising cross-entropy against the elite-weighted distribution give the same answer as maximum likelihood on the elites?Show answer

The expectation under q⋆q^\star is approximated by averaging over the samples that passed the threshold, because those samples are distributed as q⋆q^\star. Maximising the average log likelihood of those samples is exactly the maximum likelihood problem on the elites. Cross-entropy and KL differ only by a term that does not depend on the new parameters, so the minimiser is the same.

QuestionYou run CEM on a robot-arm plan. After four rounds the sigmas are near zero but the best score is poor. What happened, and what would you change?Show answer

The distribution collapsed onto a poor region before finding a good one. The usual cause is too small an elite fraction or too few samples per round, so early rounds were not exploratory enough. Remedies include a larger sample count, a larger elite fraction, a minimum sigma, or restarts from several initial means.

Sources