Example: choosing the number of components#
The problem. The components are normal, but how many of them are there? More components always explain the
sample better, so the log-likelihood alone keeps growing with k. The Bayesian information criterion adds a
penalty for every parameter:
BIC = −2 ℓ + p ln n,
where p counts the free parameters and the weights, and n is the size of the sample. Lower is better: the
chosen k is the one where an extra component no longer pays for its parameters.
Every k needs its own fit, and every fit needs a start. Here each k gets a multistart of refined runs with its own
child of one seed, so the whole search is reproducible.
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, KMeansPartitioner, MultiStartInitializer, RefiningInitializer
The data#
900 points from three normal components; the dashed line is the truth that the search does not know.
truth = MixtureModel([normal(mu=-6, sigma=1), normal(mu=0, sigma=1.5), normal(mu=5, sigma=1)], weights=[0.3, 0.4, 0.3])
X = truth.generate(size=900, random_state=7)
fig, ax = plt.subplots(figsize=(9, 3.5))
plot_components(ax, X, truth, "Three normal components")
plt.show()
A fit for every k#
initializer = MultiStartInitializer(RefiningInitializer(ClusterInitializer(KMeansPartitioner()), em(50)), n_init=5)
candidates = range(1, 7)
fits, bic = {}, {}
print(f"{'k':>2} {'log-likelihood':>15} {'parameters p':>13} {'penalty p ln n':>15} {'BIC':>9}")
for k, child in zip(candidates, np.random.default_rng(42).spawn(len(candidates))):
fits[k] = initializer.initialize(X, [normal] * k, random_state=child)
p = sum(len(component.parameters) for component in fits[k]) + k - 1
bic[k] = -2 * fits[k].loglikelihood(X) + p * np.log(len(X))
print(f"{k:>2} {fits[k].loglikelihood(X):15.1f} {p:13} {p * np.log(len(X)):15.1f} {bic[k]:9.1f}")
chosen = min(bic, key=bic.get)
print("\nchosen k:", chosen)
k log-likelihood parameters p penalty p ln n BIC
1 -2612.5 2 13.6 5238.5
2 -2444.3 5 34.0 4922.7
3 -2338.7 8 54.4 4731.9
4 -2338.5 11 74.8 4751.8
5 -2336.2 14 95.2 4767.6
6 -2334.6 17 115.6 4784.8
chosen k: 3
What to look at: the log-likelihood grows quickly up to k = 3 and then almost stops, while the penalty
keeps growing by about 20 per component. BIC has its minimum where these two meet.
fig, axes = plt.subplots(1, 4, figsize=(24, 3.5))
axes[0].plot(list(bic), list(bic.values()), "o-")
axes[0].axvline(chosen, color="tab:red", linestyle="--")
axes[0].set_xlabel("number of components k")
axes[0].set_ylabel("BIC (lower is better)")
for ax, k in zip(axes[1:], (2, 3, 4)):
plot_components(ax, X, fits[k], f"k={k}", truth=truth)
plt.show()
assert chosen == 3
Reading the result. With k = 2 one component has to cover two modes; with k = 4 an extra component
splits a mode that one component already describes. Only k = 3 matches the dashed truth, and BIC picks it.
Takeaway#
Choose k by a criterion that pays for parameters, not by the log-likelihood. Giving every k its own child of one
generator keeps the search reproducible.