Example: escaping local optima with a multistart#
The problem. Six normal modes at uneven distances. EM improves a mixture step by step, but only locally: from a bad start it ends in a local optimum, a mixture that no small change improves although it is wrong — typically two components share one mode while another component covers two modes. This notebook shows how often a single start ends like that, and compares three strategies with the same budget of 300 EM iterations:
one run: one start, 300 iterations;
multistart by the start: ten starts, keep the one with the best likelihood, then 300 iterations;
emEM: ten starts with 20 iterations each, keep the best fit, then 100 more iterations.
How to read the numbers. The sample is generated from a known mixture, so every fitted mixture can be compared
with the truth by the log-likelihood ℓ — how well a mixture explains the sample; higher is better. Only the
difference matters, so the notebook shows the gap ℓ(fitted) − ℓ(true mixture):
a gap near 0 (above −5) means the fit explains the sample as well as the true mixture does;
a gap of −100 or lower means the fit is clearly wrong, and the plot shows where.
A gap can even be slightly positive: a fitted mixture is tuned to this very sample.
import warnings
import matplotlib.pyplot as plt
import numpy as np
from pysatl_core.families import ParametricFamilyRegister
from pysatl_core.types import FamilyName
from pysatl_mpest.core import MixtureModel
from pysatl_mpest.estimators import EM
from pysatl_mpest.estimators.iterative import StepBreakpointer
from pysatl_mpest.optimizers import ScipyNelderMead
normal = ParametricFamilyRegister.get(FamilyName.NORMAL)
expon = ParametricFamilyRegister.get(FamilyName.EXPONENTIAL)
uniform = ParametricFamilyRegister.get(FamilyName.CONTINUOUS_UNIFORM)
def show(mixture: MixtureModel) -> None:
for weight, component in zip(mixture.weights, mixture):
parameters = {name: round(value, 3) for name, value in component.parameters.items()}
print(f"weight={weight:.3f} {component.family_name} {parameters}")
def em(steps: int) -> EM:
return EM(breakpointers=[StepBreakpointer(steps)], pruners=[], optimizer=ScipyNelderMead())
def plot_mixtures(ax, X, mixtures, bins=60):
grid = np.linspace(X.min(), X.max(), 1000)
ax.hist(X, bins=bins, density=True, color="lightgray")
for label, mixture in mixtures.items():
ax.plot(grid, np.exp(mixture.lpdf(grid)), label=label)
ax.legend()
def gap(mixture: MixtureModel, X: np.ndarray, truth: MixtureModel) -> float:
"""How much worse the mixture explains X than the true mixture; near 0 is as good as the truth."""
return mixture.loglikelihood(X) - truth.loglikelihood(X)
def describe(component) -> str:
return ", ".join(f"{name}={value:.3g}" for name, value in component.parameters.items())
def compare(truth: MixtureModel, fitted: MixtureModel, labels: list[str]) -> None:
"""Print the true and the fitted components side by side."""
print(f"{'component':22} {'true':42} {'fitted':42}")
for label, true, est, w_true, w_est in zip(labels, truth, fitted, truth.weights, fitted.weights):
left, right = f"share {w_true:.2f}: {describe(true)}", f"share {w_est:.2f}: {describe(est)}"
print(f"{label:22} {left:42} {right:42}")
def plot_components(ax, X, mixture, title, truth=None, labels=None, bins=60, xlabel="x"):
"""Histogram of X, every component of the mixture separately and the true mixture dashed."""
grid = np.linspace(X.min(), X.max(), 1000)
ax.hist(X, bins=bins, density=True, color="lightgray")
for j, (weight, component) in enumerate(zip(mixture.weights, mixture)):
label = labels[j] if labels else f"component {j}"
ax.plot(grid, weight * np.exp(MixtureModel([component]).lpdf(grid)), label=label)
if truth is not None:
ax.plot(grid, np.exp(truth.lpdf(grid)), "k--", linewidth=1, label="true mixture")
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.legend(fontsize=8)
from pysatl_mpest.initializers import (
ClusterInitializer,
MultiStartInitializer,
MultiStartRefiningInitializer,
RandomCentersPartitioner,
)
LABELS = [f"mode {j + 1}" for j in range(6)]
The data#
900 points from six equal normal modes. The dashed line is the true mixture.
means = [-20, -14, -4, 0, 9, 20]
truth = MixtureModel([normal(mu=m, sigma=1) for m in means])
X = truth.generate(size=900, random_state=3)
families = [normal] * len(means)
initializer = ClusterInitializer(RandomCentersPartitioner())
fig, ax = plt.subplots(figsize=(9, 3.5))
plot_components(ax, X, truth, "The true mixture: six modes", labels=LABELS, bins=100)
plt.show()
Ten single runs#
Ten starts with independent generators, each followed by 300 EM iterations.
What to look at: green bars reached the truth, red ones ended in a local optimum.
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
singles = [em(300).fit(X, initializer.initialize(X, families, random_state=child)) for child in np.random.default_rng(0).spawn(10)]
gaps = [gap(mixture, X, truth) for mixture in singles]
fig, ax = plt.subplots(figsize=(9, 3.2))
ax.bar(range(10), gaps, color=["tab:green" if value > -5 else "tab:red" for value in gaps])
ax.axhline(0, color="black", linewidth=1)
ax.set_xlabel("run")
ax.set_ylabel("gap after EM")
ax.set_title("Green: as good as the true mixture; red: a local optimum")
plt.show()
print("runs that reached the truth:", sum(value > -5 for value in gaps), "of 10")
runs that reached the truth: 2 of 10
What a local optimum looks like. The worst of the ten runs, component by component:
worst = singles[int(np.argmin(gaps))]
fig, ax = plt.subplots(figsize=(9, 3.5))
plot_components(ax, X, worst, f"The worst single run: gap {min(gaps):.0f}", truth=truth, bins=100)
plt.show()
Reading the result. Compare the colored components with the dashed truth: some mode is covered by two components, and some wide component sits over two modes. EM cannot move a component across the empty space between modes, so 300 more iterations would not fix it. Most single runs end like this.
Three strategies, one budget#
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
by_start = em(300).fit(X, MultiStartInitializer(initializer, n_init=10).initialize(X, families, random_state=0))
em_em = em(100).fit(X, MultiStartRefiningInitializer(initializer, em(20), n_init=10).initialize(X, families, random_state=0))
strategies = {"one run": singles[0], "multistart by the start": by_start, "emEM": em_em}
for name, mixture in strategies.items():
print(f"{name:25} gap {gap(mixture, X, truth):7.1f}")
fig, axes = plt.subplots(1, 3, figsize=(20, 3.5), sharey=True)
for ax, (name, mixture) in zip(axes, strategies.items()):
plot_components(ax, X, mixture, f"{name}: gap {gap(mixture, X, truth):.0f}", truth=truth, bins=100)
plt.show()
assert gap(em_em, X, truth) > -5 and gap(em_em, X, truth) > gap(by_start, X, truth) + 10
one run gap -22.7
multistart by the start gap -22.5
emEM gap 11.5
Reading the result. The likelihood of a start says little about where EM will end, so a multistart by the start may keep a start that leads to a local optimum. emEM compares runs after 20 iterations, when the bad ones have already shown themselves, and spends the rest of the budget on the best one. With the same 300 iterations it reaches the truth.
Takeaway#
When a sample has many modes, do not trust a single start. MultiStartRefiningInitializer(initializer, short_em, n_init) gives emEM in one line.