Example: degenerate data#

The problem. Real samples contain values that break the picture of a smooth mixture: a sensor stuck at one reading, single outliers. A component built on such a group is almost a spike. Here the log-likelihood becomes a trap: a spike explains its few points extremely well, so a start with a spike has a higher likelihood than a sensible start — and EM never leaves the spike. This notebook shows the two checks that keep such starts out, and what happens without them.

How to read the numbers. The sample has two real modes, N(0, 1000) and N(6000, 1500), plus 40 stuck readings. A good fit has one component near each mode; the stuck readings belong to no real mode, and the last section gives them a component of their own that is not a spike.

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,
    InitializationError,
    KMeansPartitioner,
    MultiStartInitializer,
    RandomCentersPartitioner,
)

A stuck sensor#

The data: two wide modes and 40 readings stuck near 15000 (the thin bar on the right).

rng = np.random.default_rng(42)
X = np.concatenate([rng.normal(0, 1000, 1000), rng.normal(6000, 1500, 1000), 15000 + rng.uniform(-0.001, 0.001, 40)])
modes = MixtureModel([normal(mu=0, sigma=1000), normal(mu=6000, sigma=1500)])
families = [normal, normal]
initializer = ClusterInitializer(RandomCentersPartitioner())

fig, ax = plt.subplots(figsize=(9, 3.5))
plot_components(ax, X, modes, "Two real modes and the stuck readings", labels=["mode at 0", "mode at 6000"], bins=100)
plt.show()
../../../_images/8c54869864e7722dcc534bd94941389098f7258d2c5cea02034616ed583dcbc1.png

Ten draws of random centers. Some of them put the stuck readings into a cluster of their own. The component on it would be narrower than a millionth of the spread of the sample, so the width check rejects it, and the multistart skips the run with a warning:

for child in np.random.default_rng(13).spawn(10):
    try:
        initializer.initialize(X, families, random_state=child)
    except InitializationError as error:
        print("rejected run:", error)
print()

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    kept = MultiStartInitializer(initializer, n_init=10).initialize(X, families, random_state=13)
print("warning of the multistart:", caught[0].message)
rejected run: family 1 (Normal), cluster 1: the interquartile width of the component 0.0008062140295805875 does not exceed 1e-06 of the sample standard deviation 3601.1147442049764.

warning of the multistart: 1 of 10 runs failed; the last reason: family 1 (Normal), cluster 1: the interquartile width of the component 0.0008062140295805875 does not exceed 1e-06 of the sample standard deviation 3601.1147442049764.

What the rejected run would give. Build its start by hand — the stuck readings as one component, the rest as the other — and compare it with the kept start. The spike start has the higher likelihood: without the check it would win the multistart.

ordinary, stuck = X[:2000], X[2000:]
spike = MixtureModel(
    [normal(mu=ordinary.mean(), sigma=ordinary.std()), normal(mu=stuck.mean(), sigma=stuck.std())],
    weights=[2000 / 2040, 40 / 2040],
)
print(f"log-likelihood: spike start {spike.loglikelihood(X):.0f}, kept start {kept.loglikelihood(X):.0f}")
from_spike, from_kept = em(30).fit(X, spike), em(30).fit(X, kept)

fig, axes = plt.subplots(1, 2, figsize=(16, 3.5), sharey=True)
plot_components(axes[0], X, from_spike, "EM from the spike start", truth=modes, bins=100)
plot_components(axes[1], X, from_kept, "EM from the kept start", truth=modes, bins=100)
# the spike is thousands of times taller than the modes: cut the axis at the scale of the modes
axes[0].set_ylim(0, 1.3 * np.exp(modes.lpdf(X)).max())
plt.show()
print("EM from the spike start:")
compare(modes, from_spike, ["mode at 0", "mode at 6000"])
print("\nEM from the kept start:")
compare(modes, from_kept, ["mode at 0", "mode at 6000"])

assert spike.loglikelihood(X) > kept.loglikelihood(X)
assert from_spike[1].parameters["sigma"] < 1
assert from_kept[1].parameters["sigma"] > 1.5 * 1500
log-likelihood: spike start -18949, kept start -19181
../../../_images/6a08a5b165c1c4880e437548e4f84aaa71a5c1196704417b383a4b83ffb01147.png
EM from the spike start:
component              true                                       fitted                                    
mode at 0              share 0.50: mu=0, sigma=1e+03              share 0.98: mu=2.92e+03, sigma=3.22e+03   
mode at 6000           share 0.50: mu=6e+03, sigma=1.5e+03        share 0.02: mu=1.5e+04, sigma=0.00267     

EM from the kept start:
component              true                                       fitted                                    
mode at 0              share 0.50: mu=0, sigma=1e+03              share 0.44: mu=-137, sigma=903            
mode at 6000           share 0.50: mu=6e+03, sigma=1.5e+03        share 0.56: mu=5.75e+03, sigma=2.69e+03   

Reading the result. From the spike start, one component stays on the stuck readings and the other covers both real modes with one wide bell (dashed: what it should be). From the kept start, EM finds the mode at 0, but the right component stretches from the mode at 6000 to the stuck readings: its sigma is almost twice the true one. This is not a failure of EM — it has converged — and not of the start: two normal components have to explain all 2040 points, and the 40 stuck readings far to the right pull the nearest one towards them.

A background component#

The stuck readings need a component of their own, but not a spike. A third component ContinuousUniform serves as a background: it is wide and low, so it takes the stuck readings and leaves the modes alone. Its upper bound is fixed at the largest value of the sample with uniform.view(upper_bound=X.max()), so the background covers the stuck readings whatever cluster it gets; the lower bound comes from its cluster. The width check applies to the background too: a run that puts it on the stuck readings alone is rejected like the spike above.

background = uniform.view(upper_bound=X.max())
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    start = MultiStartInitializer(initializer, n_init=10).initialize(X, [normal, normal, background], random_state=13)
print("warning of the multistart:", caught[0].message)
with_background = em(30).fit(X, start)

fig, ax = plt.subplots(figsize=(9, 3.5))
labels = ["component 0", "component 1", "background"]
plot_components(ax, X, with_background, "EM with a background component", truth=modes, labels=labels, bins=100)
plt.show()
compare(modes, with_background, ["mode at 0", "mode at 6000"])
lower = with_background[2].parameters["lower_bound"]
print(f"{'background':22} {'':42} share {with_background.weights[2]:.2f}: from {lower:.0f} to {X.max():.0f}")

assert abs(with_background[1].parameters["mu"] - 6000) < 300
assert abs(with_background[1].parameters["sigma"] - 1500) < 150
warning of the multistart: 2 of 10 runs failed; the last reason: No assignment gives every family a suitable cluster. Impossible pairs:
family 0 (Normal), cluster 1: the interquartile width of the component 0.0006919807601661887 does not exceed 1e-06 of the sample standard deviation 3601.1147442049764.
family 1 (Normal), cluster 1: the interquartile width of the component 0.0006919807601661887 does not exceed 1e-06 of the sample standard deviation 3601.1147442049764.
family 2 (ContinuousUniform), cluster 1: the interquartile width of the component 0.0008011641548364423 does not exceed 1e-06 of the sample standard deviation 3601.1147442049764.
../../../_images/c577f82198ae35161b24680426363547766e5be5d0a04a3322999225f18732fd.png
component              true                                       fitted                                    
mode at 0              share 0.50: mu=0, sigma=1e+03              share 0.49: mu=-17.2, sigma=1e+03         
mode at 6000           share 0.50: mu=6e+03, sigma=1.5e+03        share 0.48: mu=5.84e+03, sigma=1.45e+03   
background                                                        share 0.03: from 7849 to 15000

Reading the result. Both modes are found: the background takes the stuck readings and a little of the right tail of the mode at 6000 that lies over its range.

An outlier#

A small sample of 20 points with one value at 100. Without the size threshold (min_cluster_size=1) k-means gives the outlier a cluster of its own, and the start has a component on one point. With the default threshold — at least 4 points per cluster for Normal, twice its two free parameters — such a partition is rejected, and a multistart looks for another one.

rng = np.random.default_rng(42)
small = np.concatenate([rng.normal(0, 1, 20), [100.0]])

lax = ClusterInitializer(KMeansPartitioner(), min_cluster_size=1).initialize(small, [normal, expon], random_state=0)
print("min_cluster_size=1 — the second component is built on the outlier alone:")
for weight, component in zip(lax.weights, lax):
    print(f"  share {weight:.3f}: {component.family_name} {describe(component)}")

try:
    ClusterInitializer(KMeansPartitioner()).initialize(small, [normal, normal], random_state=0)
except InitializationError as error:
    print("\ndefault threshold:", error)
min_cluster_size=1 — the second component is built on the outlier alone:
  share 0.952: Normal mu=-0.0329, sigma=0.848
  share 0.048: Exponential lambda_=0.01

default threshold: The partition has clusters with fewer than 4 points: cluster 1 has 1.

Takeaway#

Both checks are on by default and need no tuning: the width check catches groups of almost equal values, the size threshold catches clusters of a few points. Neither silently replaces a bad component: the run fails, and a multistart finds another one.

The checks keep a spike out of the start, but they do not clean the data: values that belong to no real mode still have to go into some component. A wide background component gives them a place without distorting the modes.