Example: comparing partitioners#

The problem. Which partitioner should be the default for a new problem? This notebook runs the five partitioners with twenty seeds on three typical samples and counts how often a start, refined by 10 EM iterations, reaches the true mixture.

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.

A run reaches the truth when its gap is above −5.

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)

import time

from sklearn.cluster import AgglomerativeClustering, KMeans

from pysatl_mpest.initializers import (
    ClusterInitializer,
    InitializationError,
    KMeansPartitioner,
    QuantilePartitioner,
    RandomCentersPartitioner,
    SklearnPartitioner,
)

Three samples#

  • separated — three distant modes of equal size;

  • overlapping — three modes closer than two standard deviations;

  • unequal — one wide mode and two narrow ones close to each other.

samples = {
    "separated": MixtureModel([normal(mu=m, sigma=1) for m in (-10, 0, 10)]),
    "overlapping": MixtureModel([normal(mu=m, sigma=1.5) for m in (-3, 0, 3)]),
    "unequal": MixtureModel(
        [normal(mu=0, sigma=3), normal(mu=15, sigma=0.3), normal(mu=17, sigma=0.3)], weights=[0.7, 0.15, 0.15]
    ),
}
data = {name: truth.generate(size=600, random_state=1) for name, truth in samples.items()}

fig, axes = plt.subplots(1, 3, figsize=(20, 3.5))
for ax, (name, truth) in zip(axes, samples.items()):
    plot_components(ax, data[name], truth, name)
plt.show()
../../../_images/557ddd2b07e5eb5f93c864aa006d04d34ecce522edd3dd4b80b1eb0a75d1644a.png

The benchmark#

partitioners = {
    "k-means": KMeansPartitioner,
    "quantile": QuantilePartitioner,
    "random centers": RandomCentersPartitioner,
    "sklearn KMeans": lambda: SklearnPartitioner(KMeans(n_init=1)),
    "agglomerative": lambda: SklearnPartitioner(AgglomerativeClustering()),
}
reached = {sample: {} for sample in samples}
times = {name: [] for name in partitioners}
for sample, X in data.items():
    for name, make in partitioners.items():
        hits = 0
        for seed in range(20):
            began = time.perf_counter()
            try:
                start = ClusterInitializer(make()).initialize(X, [normal] * 3, random_state=seed)
            except InitializationError:
                continue
            times[name].append(time.perf_counter() - began)
            hits += gap(em(10).fit(X, start), X, samples[sample]) > -5
        reached[sample][name] = hits / 20

print(f"{'share of runs that reached the truth':38}" + "".join(f"{sample:>14}" for sample in samples))
for name in partitioners:
    print(f"{name:38}" + "".join(f"{reached[sample][name]:14.0%}" for sample in samples))
print()
for name, values in times.items():
    print(f"{name:15} mean time of a start {1000 * np.mean(values):.1f} ms")
share of runs that reached the truth       separated   overlapping       unequal
k-means                                         100%          100%            5%
quantile                                        100%          100%            0%
random centers                                   65%          100%           15%
sklearn KMeans                                  100%          100%            0%
agglomerative                                   100%          100%            0%

k-means         mean time of a start 3.6 ms
quantile        mean time of a start 1.5 ms
random centers  mean time of a start 1.5 ms
sklearn KMeans  mean time of a start 3.1 ms
agglomerative   mean time of a start 5.1 ms
fig, ax = plt.subplots(figsize=(11, 3.8))
width = 0.16
for i, name in enumerate(partitioners):
    ax.bar(np.arange(3) + (i - 2) * width, [reached[sample][name] for sample in samples], width, label=name)
ax.set_xticks(np.arange(3), list(samples))
ax.set_ylabel("share of runs that reached the truth")
ax.set_ylim(0, 1.05)
ax.legend(fontsize=8)
plt.show()
../../../_images/5ab5f98fd7d6592c5c3040c5f16c91a6593a208c00b8ff74fced38236bc5cb50.png

Reading the result.

  • Separated modes: every deterministic partitioner reaches the truth every time. Random centers sometimes put two centers into one mode, and the short EM does not recover.

  • Overlapping modes: everyone reaches the truth — when modes overlap, EM fixes a rough start.

  • Unequal modes: the deterministic partitioners cut the wide mode in two and merge the two narrow ones on almost every seed. Only a few draws, mostly of random centers, find the right structure.

No partitioner wins everywhere. Deterministic ones are good single starts; random centers are a cheap source of different starts for a multistart, which keeps the good draws.

assert reached["separated"]["quantile"] == 1 and reached["separated"]["random centers"] < 1
assert reached["unequal"]["quantile"] == 0 and reached["unequal"]["random centers"] > 0