Example: a mixture of different families#

The problem. Response times of a service, in milliseconds, come from three sources:

  • most requests hit a cache and finish quickly — an exponential component starting at 0;

  • requests that go to the database take about 60 ms — a normal peak;

  • timeouts and retries are spread evenly up to 200 ms — a uniform background.

We know these three families and want EM to find their parameters and shares. EM needs a starting mixture, and the start is built by ClusterInitializer, which first splits the sample into clusters. The question of this notebook: which way of splitting gives a start from which EM finds the true mixture?

How to read the numbers. The sample here is generated from a known mixture, so every fitted mixture can be compared with the truth by the log-likelihood ℓ — how well the 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.

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()

from sklearn.cluster import AgglomerativeClustering, KMeans

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

NAMES = {"Exponential": "cache hits (exponential)", "Normal": "database (normal)", "ContinuousUniform": "background (uniform)"}


def gap(mixture: MixtureModel) -> float:
    """How much worse the mixture explains the sample than the true mixture; near 0 is as good as the truth."""
    return mixture.loglikelihood(X) - truth.loglikelihood(X)


def compare(fitted: MixtureModel) -> None:
    """Print the true and the fitted parameters side by side, one row per component."""
    print(f"{'component':28} {'true':44} {'fitted':44}")
    for true, est, w_true, w_est in zip(truth, fitted, truth.weights, fitted.weights):
        cells = []
        for component, weight in ((true, w_true), (est, w_est)):
            parameters = ", ".join(f"{name}={value:.3g}" for name, value in component.parameters.items())
            cells.append(f"share {weight:.2f}: {parameters}")
        print(f"{NAMES[true.family_name]:28} {cells[0]:44} {cells[1]:44}")


def plot_components(ax, mixture: MixtureModel, title: str) -> None:
    """Histogram of the sample, every component of the mixture and the true mixture."""
    grid = np.linspace(0, X.max(), 1000)
    ax.hist(X, bins=80, density=True, color="lightgray")
    for weight, component in zip(mixture.weights, mixture):
        density = weight * np.exp(MixtureModel([component]).lpdf(grid))
        ax.plot(grid, density, label=NAMES[component.family_name])
    ax.plot(grid, np.exp(truth.lpdf(grid)), "k--", linewidth=1, label="true mixture")
    ax.set_title(title)
    ax.set_xlabel("response time, ms")
    ax.legend(fontsize=8)

The data#

800 response times from the true mixture. The plot shows each source separately: the exponential part is the tall left edge, the database peak is at 60 ms, and the background is the low flat line that continues to 200 ms.

truth = MixtureModel(
    [expon(lambda_=1 / 15), normal(mu=60, sigma=6), uniform(lower_bound=0, upper_bound=200)], weights=[0.45, 0.3, 0.25]
)
X = truth.generate(size=800, random_state=42)
families = [expon, normal, uniform]

fig, ax = plt.subplots(figsize=(9, 3.5))
plot_components(ax, truth, "The true mixture and its three sources")
ax.set_ylabel("density")
plt.show()
../../../_images/b75fa28fb37d8f3dee26c38e7c2b34dca85182358fa26a6215358a326314c96b.png

Five ways to split the sample#

Each partitioner gives a start; then 20 EM iterations improve it. The table shows the gap before and after EM.

What to look at in the plots below:

  • the green flat line of the uniform background: in the true mixture (dashed) it covers 0–200 ms. EM can shrink the range of a uniform component but never widen it, so a start that puts the background in the wrong place keeps it there;

  • the orange database peak: in the truth it is narrow; when the background is missing near the peak, the normal component widens to cover that part of the sample.

partitioners = {
    "k-means": KMeansPartitioner(),
    "quantile": QuantilePartitioner(),
    "random centers": RandomCentersPartitioner(),
    "sklearn KMeans": SklearnPartitioner(KMeans(n_init=1)),
    "agglomerative": SklearnPartitioner(AgglomerativeClustering()),
}
fits = {}
print(f"{'partitioner':16} {'gap of the start':>18} {'gap after EM':>14}  background starts at")
for name, partitioner in partitioners.items():
    start = ClusterInitializer(partitioner).initialize(X, families, random_state=0)
    fits[name] = em(20).fit(X, start)
    background = fits[name][2].parameters["lower_bound"]
    print(f"{name:16} {gap(start):18.1f} {gap(fits[name]):14.1f}  {background:6.1f} ms")

fig, axes = plt.subplots(1, len(fits), figsize=(22, 3.8), sharey=True)
for ax, (name, fitted) in zip(axes, fits.items()):
    plot_components(ax, fitted, f"{name}: gap {gap(fitted):.0f}")
axes[0].set_ylabel("density")
plt.show()
partitioner        gap of the start   gap after EM  background starts at
k-means                       -70.6          -63.4   113.5 ms
quantile                     -235.0         -198.2    19.5 ms
random centers                -21.0            1.6    71.8 ms
sklearn KMeans                -70.8          -63.4   113.5 ms
agglomerative                -120.8         -102.8   147.3 ms
../../../_images/386340e6684b95528de2ffef610224b857fe08155f9383fcb730a86f3f4d6f8c.png

Reading the result.

  • Quantile cuts the sample into three parts with equal numbers of points. None of them is the database peak or the background: the background lands between 20 and 60 ms, where the sample has no background of its own, and the database component spreads over the whole range. The gap is around −200: the fit is clearly wrong.

  • k-means, its scikit-learn version and agglomerative clustering give the background only the slowest tail: it starts after 100 ms instead of 0 ms. The database peak widens to cover the background between 70 and 110 ms, so it comes out too low and too wide. The gap of several tens says the fit is noticeably worse than the truth.

  • Random centers depend on the draw; seed 0 here is one draw of many. Below we look at several draws.

assert gap(fits["quantile"]) < -100
for name in ("k-means", "sklearn KMeans", "agglomerative"):
    assert gap(fits[name]) < -30 and fits[name][2].parameters["lower_bound"] > 100

Several draws of random centers#

Random centers pick three points of the sample as centers of the clusters. Different seeds give different splits, and some of them put a center into the background. Ten draws, each followed by 20 EM iterations:

draws = []
for child in np.random.default_rng(0).spawn(10):
    start = ClusterInitializer(RandomCentersPartitioner()).initialize(X, families, random_state=child)
    draws.append(gap(em(20).fit(X, start)))

fig, ax = plt.subplots(figsize=(9, 3.2))
ax.bar(range(10), draws, color=["tab:green" if value > -5 else "tab:red" for value in draws])
ax.axhline(0, color="black", linewidth=1)
ax.set_xlabel("draw")
ax.set_ylabel("gap after EM")
ax.set_title("Green: as good as the true mixture; red: clearly worse")
plt.show()
print("draws as good as the truth:", sum(value > -5 for value in draws), "of 10")
../../../_images/53b2fec72a7765f07b2aa508ea9ff22a8f4be0bb91055ef46a9d568965905dec.png
draws as good as the truth: 6 of 10

Reading the result. Some draws end as badly as the quantile split, but some reach the truth. We cannot tell in advance which draw is good — but we can try several and keep the one whose fit is best. That is exactly what MultiStartInitializer around RefiningInitializer does.

Keeping the best of several draws#

RefiningInitializer makes «start + 20 EM iterations» one step; MultiStartInitializer repeats it five times and keeps the run with the highest log-likelihood.

refined = RefiningInitializer(ClusterInitializer(RandomCentersPartitioner()), em(20))
with warnings.catch_warnings():
    warnings.simplefilter("ignore", RuntimeWarning)
    best = MultiStartInitializer(refined, n_init=5).initialize(X, families, random_state=0)

print(f"gap: multistart {gap(best):.1f}, k-means {gap(fits['k-means']):.1f}")
print()
compare(best)

fig, axes = plt.subplots(1, 2, figsize=(16, 3.8), sharey=True)
plot_components(axes[0], fits["k-means"], f"k-means, after EM: gap {gap(fits['k-means']):.0f}")
plot_components(axes[1], best, f"best of 5 refined random draws, after EM: gap {gap(best):.0f}")
axes[0].set_ylabel("density")
plt.show()

assert gap(best) > -5 and gap(best) > gap(fits["k-means"]) + 30
gap: multistart 1.7, k-means -63.4

component                    true                                         fitted                                      
cache hits (exponential)     share 0.45: lambda_=0.0667                   share 0.53: lambda_=0.0508                  
database (normal)            share 0.30: mu=60, sigma=6                   share 0.30: mu=59.8, sigma=6.13             
background (uniform)         share 0.25: lower_bound=0, upper_bound=200   share 0.16: lower_bound=68.3, upper_bound=200
../../../_images/4256540ce486f8f4d317604f4289e46e1cb35589b01d7cba6ecb873dc1164b9c.png

Reading the result. The kept draw explains the sample as well as the true mixture (the gap is near 0), and the table shows why: the shares and the parameters of the cache and the database are close to the truth, and the background covers much more of the range than in the k-means fit. It still starts above 0 ms — below the database peak the background is hidden under the cache hits, and 800 points cannot tell them apart — so its share comes out smaller than 0.25.

Takeaway#

  • When the families have different supports, the way of splitting matters: a split that puts the background in the wrong place cannot be fixed by EM.

  • No single partitioner is safe here, but the result of EM tells good starts from bad ones. A multistart over refined random draws keeps the good one, at the price of a few extra EM runs.