Example: a partitioner from domain knowledge#
The problem. k-means assumes clusters of similar size and spread. On a sample with one wide mode and two narrow modes close to each other it cuts the wide mode in two and merges the narrow ones, and EM from such a start stays in a local optimum. If an expert knows where the modes are separated, the partition does not need clustering at all: a partitioner of a few lines splits the sample at the known thresholds.
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, IdentityMatcher, KMeansPartitioner, Partitioner
LABELS = ["wide mode", "narrow mode at 15", "narrow mode at 17"]
The data#
A wide mode around 0 and two narrow modes at 15 and 17.
truth = 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]
)
X = truth.generate(size=600, random_state=1)
families = [normal] * 3
fig, ax = plt.subplots(figsize=(9, 3.5))
plot_components(ax, X, truth, "One wide mode and two narrow ones", labels=LABELS, bins=100)
plt.show()
The partitioner#
The contract of Partitioner.partition(X, k, rng): a matrix of shape (n, k) with exactly one 1 in a row, and all
randomness from rng — here there is none. The expert says the modes are separated at 12 and 16. The columns go from
left to right, the families are listed from left to right too, and IdentityMatcher gives column j to family j.
A wrong number of clusters is an error of the configuration, so it is a ValueError, not an InitializationError.
class ThresholdPartitioner(Partitioner):
def __init__(self, thresholds: list[float]) -> None:
self.thresholds = np.asarray(thresholds, dtype=np.float64)
def partition(self, X: np.ndarray, k: int, rng: np.random.Generator) -> np.ndarray:
if k != len(self.thresholds) + 1:
raise ValueError(f"{len(self.thresholds)} thresholds make {len(self.thresholds) + 1} clusters, not {k}.")
return np.eye(k)[np.searchsorted(self.thresholds, X)]
initializers = {
"expert thresholds 12 and 16": ClusterInitializer(ThresholdPartitioner([12.0, 16.0]), matcher=IdentityMatcher()),
"k-means": ClusterInitializer(KMeansPartitioner()),
}
fits = {name: em(100).fit(X, initializer.initialize(X, families, random_state=0)) for name, initializer in initializers.items()}
for name, fitted in fits.items():
print(f"{name}: gap after EM {gap(fitted, X, truth):.1f}")
compare(truth, fitted, LABELS)
print()
expert thresholds 12 and 16: gap after EM 4.5
component true fitted
wide mode share 0.70: mu=0, sigma=3 share 0.71: mu=0.195, sigma=3.1
narrow mode at 15 share 0.15: mu=15, sigma=0.3 share 0.16: mu=15, sigma=0.263
narrow mode at 17 share 0.15: mu=17, sigma=0.3 share 0.14: mu=17, sigma=0.316
k-means: gap after EM -99.3
component true fitted
wide mode share 0.70: mu=0, sigma=3 share 0.37: mu=-1.27, sigma=2.6
narrow mode at 15 share 0.15: mu=15, sigma=0.3 share 0.34: mu=1.82, sigma=2.79
narrow mode at 17 share 0.15: mu=17, sigma=0.3 share 0.29: mu=16, sigma=1.03
What to look at: in the k-means fit, two components share the wide mode and one wide component covers both narrow modes; the dashed truth has two sharp peaks there. With the expert thresholds each component gets its own mode.
fig, axes = plt.subplots(1, 2, figsize=(16, 3.5), sharey=True)
for ax, (name, fitted) in zip(axes, fits.items()):
plot_components(ax, X, fitted, f"{name}: gap {gap(fitted, X, truth):.0f}", truth=truth, bins=100)
plt.show()
try:
initializers["expert thresholds 12 and 16"].initialize(X, [normal] * 2, random_state=0)
except ValueError as error:
print("configuration error:", error)
assert gap(fits["expert thresholds 12 and 16"], X, truth) > -5
assert gap(fits["k-means"], X, truth) < -50
configuration error: 2 thresholds make 3 clusters, not 2.
Takeaway#
A partitioner is the place for domain knowledge: anything that returns one cluster per point works with the
matchers, the checks and the multistart of the library. When the partitioner already knows which cluster belongs to
which family, IdentityMatcher keeps that order.