Example: a component with a known parameter#

The problem. A detector measures a weak signal on top of noise. The noise is centered at zero by calibration, so its mean is known; its spread, the position of the signal and the share of the signal are not. When the signal is small, the data can hardly tell how much of it is signal and how much is noise. Fixing the known mean with family.view(mu=0) removes this freedom.

How to read the numbers. The data are generated from a known mixture: noise N(0, 1) with share 0.85 and signal N(2, 0.5) with share 0.15. We judge a fit by the error of the signal: the distance of its mean from 2 plus the distance of its share from 0.15. Zero is a perfect estimate.

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

LABELS = ["noise", "signal"]


def signal_error(fitted: MixtureModel) -> float:
    return abs(fitted[1].parameters["mu"] - 2) + abs(fitted.weights[1] - 0.15)

One sample#

The same start and the same 100 EM iterations, once with two free normal families and once with the mean of the noise fixed at 0. With the fixed mean the noise component has only sigma as a free parameter.

truth = MixtureModel([normal(mu=0, sigma=1), normal(mu=2, sigma=0.5)], weights=[0.85, 0.15])
X = truth.generate(size=200, random_state=0)

variants = {"both means free": [normal, normal], "noise mean fixed at 0": [normal.view(mu=0), normal]}
fits = {}
for name, families in variants.items():
    start = ClusterInitializer(KMeansPartitioner()).initialize(X, families, random_state=0)
    fits[name] = em(100).fit(X, start)
    print(f"{name}: error of the signal {signal_error(fits[name]):.3f}")
    compare(truth, fits[name], LABELS)
    print()

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}: error {signal_error(fitted):.2f}", truth=truth, labels=LABELS, bins=40)
plt.show()
both means free: error of the signal 0.205
component              true                                       fitted                                    
noise                  share 0.85: mu=0, sigma=1                  share 0.86: mu=0.216, sigma=1.05          
signal                 share 0.15: mu=2, sigma=0.5                share 0.14: mu=2.2, sigma=0.354           

noise mean fixed at 0: error of the signal 0.103
component              true                                       fitted                                    
noise                  share 0.85: mu=0, sigma=1                  share 0.78: sigma=0.978                   
signal                 share 0.15: mu=2, sigma=0.5                share 0.22: mu=2.03, sigma=0.469          
../../../_images/664da5a3027dbf010c7661c26ee322d9de9b89f8aedec89c47b6067b3456b9ba.png

What to look at: the orange signal component. With both means free, the noise component may shift away from 0 and take part of the signal, and the signal comes out at a wrong place or with a wrong share. With the fixed mean, the noise stays at 0 and the rest of the sample is left to the signal.

Twenty samples#

One sample can be lucky. Twenty samples from the same mixture, each fitted both ways:

errors = {name: [] for name in variants}
for seed in range(20):
    X = truth.generate(size=200, random_state=seed)
    for name, families in variants.items():
        fitted = em(100).fit(X, ClusterInitializer(KMeansPartitioner()).initialize(X, families, random_state=0))
        errors[name].append(signal_error(fitted))

fig, ax = plt.subplots(figsize=(7, 3.5))
ax.boxplot(list(errors.values()), tick_labels=list(errors))
ax.set_ylabel("error of the signal (0 is perfect)")
ax.set_title("Each box: 20 samples; the line inside is the median")
plt.show()
for name, values in errors.items():
    print(f"{name:25} median error {np.median(values):.3f}")

assert np.median(errors["noise mean fixed at 0"]) < np.median(errors["both means free"]) / 2
../../../_images/d8f8002772ce0992cf7122d3b9b9105bcd0317770d9f222f4e096193db547ea9.png
both means free           median error 0.554
noise mean fixed at 0     median error 0.101

Reading the result. The box of the fixed variant is lower and narrower: the typical error of the signal is several times smaller, and bad estimates are rarer.

Takeaway#

Fix what you know. The initializer and the estimators keep a fixed parameter exactly, and the order of the components follows families, so the fixed component is always component 0.