Run EM for a 1D Gaussian mixture

Why it matters Mixture models still label speaker clusters and score anomaly likelihoods in production pipelines.

A Gaussian mixture explains data as k bell curves. EM alternates soft assignment and refitting.

Write gmm_em_1d(x, means, variances, weights, iters). Each iteration: E step r[i, j] proportional to weights[j] * N(x_i | means[j], variances[j]) normalised over j; M step N_j = sum_i r[i, j], weights = N_j / n, means = sum_i r x / N_j, variances = sum_i r (x - new mean)^2 / N_j. Return (means, variances, weights) as arrays after iters iterations.

Floor each variance at 1e-6 after the M step.

Signaturedef gmm_em_1d(x, means, variances, weights, iters)

Example

x = [0, 0, 10, 10], means [1, 9], variances [1, 1], weights [0.5, 0.5], 5 iterations ends near means [0, 10], weights [0.5, 0.5], variances close to 0 (floored at 1e-6).

Understand the idea

A Gaussian mixture says the data came from k bell curves, each with a mean, variance and weight. EM alternates two steps. The E step asks, for every point, how responsible each curve is for it. The M step refits each curve using those soft responsibilities as fractional counts. Worked example of one E step: x = 0, means [0, 2], variances [1, 1], weights [0.5, 0.5]. N(0 | 0, 1) = 0.399 and N(0 | 2, 1) = 0.399 * exp(-2) = 0.054. Normalising 0.5 * 0.399 and 0.5 * 0.054 gives responsibilities about [0.881, 0.119]. Rule: r[i, j] is proportional to weights[j] * N(x_i | means[j], variances[j]) with N(x | mu, v) = exp(-(x - mu)^2 / (2v)) / sqrt(2 pi v), normalised over j. Then N_j = sum_i r[i, j], weights = N_j / n, means = sum_i r x / N_j, variances = sum_i r (x - new mean)^2 / N_j, floored at 1e-6. Keep the 1 / sqrt(2 pi v) factor, since components with different variances need it. Work in log space for stability. Used in: speaker models, density estimation and anomaly scoring.

Shapes and data flow

x[:, None] (n, 1) vs m (k,) -> log p (n, k) -> r (n, k)
N = r.sum(0) (k,), m, v, w (k,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplegmm_em_1d([0, 0, 10, 10], [1, 9], [1, 1], [0.5, 0.5], 5)
  • Sample 2: overlapgmm_em_1d(_x, [-1, 1], [1, 1], [0.5, 0.5], 10)