Update a search distribution with the cross-entropy method

Why it matters CEM is a strong baseline for policy search and is used inside model-based planners for robots.

The cross-entropy method is a simple black-box policy search: sample parameter vectors, keep the best few, and refit a Gaussian to them.

Write cem_update(samples, scores, elite_frac, mean, std, smoothing, min_std). samples is (N, D), scores (N,) with higher better, mean and std (D,).
1. n_elite = max(1, ceil(elite_frac * N)). Elites are the n_elite highest scores (on equal scores the earlier sample ranks higher).
2. new_mean = elite mean per dimension, new_std = elite population std per dimension (ddof 0).
3. mean_out = smoothing * mean + (1 - smoothing) * new_mean, and the same for std; then std_out = max(std_out, min_std) elementwise.
Return (mean_out, std_out).

Signaturedef cem_update(samples, scores, elite_frac, mean, std, smoothing, min_std)

Example

samples [[0], [1], [2], [3]], scores [0, 1, 2, 3], elite_frac 0.5, mean [0], std [1], smoothing 0, min_std 0.1 gives (array([2.5]), array([0.5])).

Understand the idea

The cross-entropy method treats policy search like breeding: try many random candidates, keep the best ones, and make the next generation look like them. Candidates are drawn from a Gaussian; after scoring, the Gaussian is refit to the elite set, so it slides toward good regions and narrows as it gets confident.

Example: four 1-D candidates 0, 1, 2, 3 with scores equal to their values. Keeping the top half gives elites 2 and 3, so the new mean is 2.5 and the new std is 0.5.

Rules:
elites = top ceil(frac * N) samples by score
mean <- s * mean + (1 - s) * mean(elites)
std <- max(s * std + (1 - s) * std(elites), min_std)

It needs no gradients, so it works with any black-box reward. Model-based RL planners pick action sequences this way, and it is a useful sanity baseline before reaching for PPO.

Shapes and data flow

samples: (N, D) -> elites: (n_elite, D) -> mean, std: (D,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplecem_update([[0], [1], [2], [3]], [0, 1, 2, 3], 0.5, [0], [1], 0.0, 0.1)
  • Sample 2: 2d smoothingcem_update([[1, 0], [0, 1], [2, 2], [-1, 3], [3, -1]], [5, 1, 4, 0, 4], 0.4, [0, 0], [1, 1], 0.5, 0.05)