Skip to content

xAI: Clustering Dynamics

The stride.xai.clustering subpackage discovers class-conditional sub-populations with X-means, tracks them between two stream windows, and decides on drift with a permutation test.


Overview

Clustering dynamics track multimodal feature deformations and density shifts across sliding stream windows. Clusters are discovered within each class with BIC-based X-means splitting; the detection window is assigned to the reference clusters, so STRIDE identifies cluster displacement, birth, and extinction on a common partition. See the user guide for the method.

from stride.xai.clustering import (
    ClusterBasedDriftDetector,
    assign_to_reference,
    run_xmeans,
)

Key Components

Class / Function Description
ClusterBasedDriftDetector Orchestrator: per-class X-means, cluster tracking, the four drift criteria, drift strength and permutation test.
run_xmeans Executes X-means clustering with dynamic \(K \in [k_{\text{init}}, k_{\max}]\) selection via BIC; optional restarts keep the best BIC.
bic_score BIC of a hard clustering under the spherical Gaussian model of Pelleg & Moore.
assign_to_reference Assigns a new window to reference clusters and detects appeared and disappeared clusters.
map_new_clusters_to_old Minimum-weight bipartite matching between two sets of centroids (Kuhn-Munkres), used by matching="independent".
merge_clusters Combines per-class cluster results into globally unique cluster IDs.
compute_desc_stats_for_clusters Computes mean, median and standard deviation per cluster and feature in both windows.
calculate_shift_significance Two-sample test statistics for centroid, statistic and dispersion changes, scaled by cluster size.

Visualization

All plots return a matplotlib.figure.Figure and never call plt.show().

Function Description
plot_drift_clustered Both windows side by side, samples coloured by cluster.
plot_clusters_by_class One row per class: clusters of the class before and after the change on shared axes; classes selects the classes to plot.
plot_centers_shift Cluster centroids before and after the change, joined by arrows.
plot_cluster_changes_by_class One panel per class with both windows overlaid and the fate of each cluster (tracked with its centroid shift, disappeared, appeared); readable with many clusters.
plot_clustering_heatmap Cluster × feature statistics that exceed the threshold.
plot_feature_shift_heatmap Signed change of a per-cluster statistic for every feature and cluster.
plot_permutation_tests Observed drift strength of several detections against their permutation distributions.
plot_cluster_fate Number of tracked, disappeared and appeared clusters of several detections.
from stride.xai.clustering import plot_cluster_fate, plot_permutation_tests

detectors = {"T1": detector_t1, "control": detector_control}  # after detect()
fig = plot_permutation_tests(detectors)
fig = plot_cluster_fate(detectors)

API Specification

stride.xai.clustering

Class-conditional X-means clustering, reference cluster tracking and permutation-tested drift detection.

ClusterBasedDriftDetector

ClusterBasedDriftDetector(
    X_before,
    y_before,
    X_after,
    y_after,
    k_init=2,
    k_max=10,
    thr_clusters=1,
    thr_centroid_shift=0.15,
    thr_centroid_disappear=0.5,
    thr_desc_stats=0.2,
    thr_avg_distance_to_center_change=0.1,
    decision_thr=0.5,
    weights=[0.4, 0.25, 0.25, 0.1],
    random_state=42,
    matching="reference",
    alpha=None,
    n_permutations=50,
    permutation_alpha=0.05,
    xmeans_repeat=1,
    novelty_quantile=0.95,
    n_jobs=None,
)

Cluster-based concept and data drift detector using X-Means clustering.

Within each class, X-Means discovers the cluster structure of the reference block. By default (matching="reference") the detection block is assigned to the nearest reference centroid, so both blocks are compared on the same partition; clusters that appear (regions not covered by the reference model) or disappear (reference clusters that lose their mass) are detected relative to that model. Drift is evaluated across four criteria:

  1. Changes in the number of clusters within a class (clusters that appeared or disappeared).
  2. Changes in descriptive statistics computed for each cluster.
  3. Spatial shifts of cluster centroids (\(\|c_{\text{before}} - c_{\text{after}}\|_2\)).
  4. Changes in average sample-to-centroid dispersion.

Criteria 2-4 are evaluated only for clusters present in both blocks. Their weighted share of triggered checks is the drift strength. The decision is made by a permutation test: blocks are re-split at random within each class and the strength is recomputed, giving a p-value that controls the false-alarm rate.

Attributes:

Name Type Description
drift_flag bool

Whether drift was detected (permutation p-value below permutation_alpha, or strength above decision_thr without permutations).

strength_of_drift float

Weighted share of triggered criteria in \([0.0, 1.0]\).

p_value float | None

Permutation p-value of strength_of_drift (None without permutations).

null_strengths ndarray | None

Drift strengths obtained under the permutations.

effective_weights ndarray | None

Criterion weights actually used for the score, i.e. weights renormalised over criteria that had at least one evaluation.

drift_details dict | None

Detailed breakdown of per-class criteria triggers.

cluster_labels_old ndarray | None

Cluster ID of every reference-block sample. Reference clusters are numbered 0 .. n-1, grouped by class.

cluster_labels_new ndarray | None

Cluster ID of every new-block sample. Tracked clusters keep their reference ID; clusters found only in the new block are numbered from n.

Examples:

>>> detector = ClusterBasedDriftDetector(X_ref, y_ref, X_det, y_det)
>>> flag, details = detector.detect()

Initialize the cluster-based drift detector.

Parameters:

Name Type Description Default
X_before DataFrame

Feature matrix of the reference data block.

required
y_before ndarray | Series

Class labels of the reference data block.

required
X_after DataFrame

Feature matrix of the detection data block.

required
y_after ndarray | Series

Class labels of the detection data block.

required
k_init int

Initial number of clusters for X-Means initialization.

2
k_max int

Maximum allowable clusters per class.

10
thr_clusters int

Cluster count difference threshold to flag drift.

1
thr_centroid_shift float

Normalized Euclidean centroid displacement threshold.

0.15
thr_centroid_disappear float

Distance threshold separating migration from cluster disappearance.

0.5
thr_desc_stats float

Threshold on the absolute change of per-cluster mean, median and standard deviation, in standard deviations of the (standardised) feature.

0.2
thr_avg_distance_to_center_change float

Threshold on the relative change of the mean sample-to-centroid distance.

0.1
decision_thr float

Weighted score threshold required to declare global drift when n_permutations is 0. With permutations (the default) the decision is made by the permutation test and this threshold is not used.

0.5
weights Sequence[float]

4-element sequence specifying relative weights for each criterion.

[0.4, 0.25, 0.25, 0.1]
random_state int

Random state for deterministic clustering and permutations.

42
matching str

How the new block's clusters are related to the reference block. "independent" clusters both blocks separately and matches centroids with the Hungarian algorithm (centroids farther apart than thr_centroid_disappear count as disappeared + appeared). "reference" assigns new samples to the nearest reference centroid, so both blocks are compared on the same partition, and detects appeared/disappeared clusters relative to the reference model (see :func:~stride.xai.clustering.matching.assign_to_reference).

'reference'
alpha float | None

Per-test significance level. When set, a centroid shift, statistic change or dispersion change is flagged only if it also passes a two-sample test that accounts for the cluster size (see :func:~stride.xai.clustering.statistics.calculate_shift_significance). None uses the thresholds alone. In "reference" matching it is also the level of the cluster-disappearance test.

None
n_permutations int

Number of permutations for calibrating the decision. When positive, samples are shuffled between the blocks within each class, the drift strength is recomputed for every permutation, and drift_flag is set when the permutation p-value is below permutation_alpha (instead of comparing the strength with decision_thr).

50
permutation_alpha float

Significance level of the permutation test.

0.05
xmeans_repeat int

Number of X-Means runs per clustering; the run with the best BIC is kept.

1
novelty_quantile float

In "reference" matching, quantile of reference within-cluster distances beyond which a new sample counts as novel.

0.95
n_jobs int | None

Number of worker processes for the permutation test (joblib semantics; None or 1 runs sequentially). The result does not depend on this value. Each worker imports stride anew, which takes a few seconds, so parallelism pays off for long series of detections in batch jobs rather than for single interactive calls.

None
Source code in src/stride/xai/clustering/clustering.py
def __init__(
    self,
    X_before: pd.DataFrame,
    y_before: np.ndarray | pd.Series,
    X_after: pd.DataFrame,
    y_after: np.ndarray | pd.Series,
    k_init: int = 2,
    k_max: int = 10,
    thr_clusters: int = 1,
    thr_centroid_shift: float = 0.15,
    thr_centroid_disappear: float = 0.5,
    thr_desc_stats: float = 0.2,
    thr_avg_distance_to_center_change: float = 0.1,
    decision_thr: float = 0.5,
    weights: Sequence[float] = [0.4, 0.25, 0.25, 0.1],
    random_state: int = 42,
    matching: str = "reference",
    alpha: float | None = None,
    n_permutations: int = 50,
    permutation_alpha: float = 0.05,
    xmeans_repeat: int = 1,
    novelty_quantile: float = 0.95,
    n_jobs: int | None = None,
) -> None:
    """Initialize the cluster-based drift detector.

    Args:
        X_before: Feature matrix of the reference data block.
        y_before: Class labels of the reference data block.
        X_after: Feature matrix of the detection data block.
        y_after: Class labels of the detection data block.
        k_init: Initial number of clusters for X-Means initialization.
        k_max: Maximum allowable clusters per class.
        thr_clusters: Cluster count difference threshold to flag drift.
        thr_centroid_shift: Normalized Euclidean centroid displacement threshold.
        thr_centroid_disappear: Distance threshold separating migration from cluster disappearance.
        thr_desc_stats: Threshold on the absolute change of per-cluster mean, median and
            standard deviation, in standard deviations of the (standardised) feature.
        thr_avg_distance_to_center_change: Threshold on the relative change of the mean
            sample-to-centroid distance.
        decision_thr: Weighted score threshold required to declare global drift when
            ``n_permutations`` is 0. With permutations (the default) the decision is
            made by the permutation test and this threshold is not used.
        weights: 4-element sequence specifying relative weights for each criterion.
        random_state: Random state for deterministic clustering and permutations.
        matching: How the new block's clusters are related to the reference block.
            ``"independent"`` clusters both blocks separately and matches centroids
            with the Hungarian algorithm (centroids farther apart than
            `thr_centroid_disappear` count as disappeared + appeared).
            ``"reference"`` assigns new samples to the nearest reference centroid, so
            both blocks are compared on the same partition, and detects
            appeared/disappeared clusters relative to the reference model (see
            :func:`~stride.xai.clustering.matching.assign_to_reference`).
        alpha: Per-test significance level. When set, a centroid shift, statistic
            change or dispersion change is flagged only if it also passes a
            two-sample test that accounts for the cluster size (see
            :func:`~stride.xai.clustering.statistics.calculate_shift_significance`).
            ``None`` uses the thresholds alone. In ``"reference"`` matching it is
            also the level of the cluster-disappearance test.
        n_permutations: Number of permutations for calibrating the decision. When
            positive, samples are shuffled between the blocks within each class,
            the drift strength is recomputed for every permutation, and
            `drift_flag` is set when the permutation p-value is below
            `permutation_alpha` (instead of comparing the strength with
            `decision_thr`).
        permutation_alpha: Significance level of the permutation test.
        xmeans_repeat: Number of X-Means runs per clustering; the run with the best
            BIC is kept.
        novelty_quantile: In ``"reference"`` matching, quantile of reference
            within-cluster distances beyond which a new sample counts as novel.
        n_jobs: Number of worker processes for the permutation test (joblib
            semantics; ``None`` or 1 runs sequentially). The result does not
            depend on this value. Each worker imports ``stride`` anew, which
            takes a few seconds, so parallelism pays off for long series of
            detections in batch jobs rather than for single interactive calls.
    """

    X_before, X_after = self._scale_data(X_before, X_after)

    assert sorted(X_after.columns.values) == sorted(X_before.columns.values)
    self.columns = X_before.columns

    if hasattr(X_before, "values"):
        X_before = X_before.values
    if hasattr(y_before, "values"):
        y_before = y_before.values
    if hasattr(X_after, "values"):
        X_after = X_after.values
    if hasattr(y_after, "values"):
        y_after = y_after.values

    assert thr_centroid_disappear > thr_centroid_shift, "thr_centroid_disappear must be greater than thr_centroid_shift"

    self.X_old = X_before
    self.y_old = y_before
    self.X_new = X_after
    self.y_new = y_after

    self.k_init = k_init
    self.k_max = k_max

    n_features = self.X_old.shape[1]
    self.thr_clusters = thr_clusters
    self.thr_centroid_shift = thr_centroid_shift * np.sqrt(n_features)
    self.thr_centroid_disappear = thr_centroid_disappear * np.sqrt(n_features)
    self.thr_desc_stats = thr_desc_stats
    self.thr_avg_distance_to_center_change = thr_avg_distance_to_center_change

    self.decision_thr = decision_thr

    assert len(weights) == 4, "Number of weights must be 4"
    self.weights = np.array(weights) / np.sum(weights)
    self.effective_weights = None

    self.centers_old = None
    self.centers_new = None
    self.cluster_labels_old = None
    self.cluster_labels_new = None

    self.stats_combined = None
    self.stats_shifts = None
    self.cluster_shifts = None
    self.avg_distance_old = None
    self.avg_distance_new = None
    self.avg_distance_shift = None

    self.number_of_clusters_old = None
    self.number_of_clusters_new = None

    self.drift_flag = False
    self.drift_details = None
    self.strength_of_drift = 0.0

    if matching not in ("independent", "reference"):
        raise ValueError(f"matching must be 'independent' or 'reference', got {matching!r}")
    if alpha is not None and not 0 < alpha < 1:
        raise ValueError(f"alpha must be in (0, 1) or None, got {alpha}")
    if n_permutations < 0:
        raise ValueError(f"n_permutations must be non-negative, got {n_permutations}")
    if not 0 < permutation_alpha < 1:
        raise ValueError(f"permutation_alpha must be in (0, 1), got {permutation_alpha}")
    if not 0 < novelty_quantile < 1:
        raise ValueError(f"novelty_quantile must be in (0, 1), got {novelty_quantile}")

    self.random_state = random_state
    self.classes = None
    self.matching = matching
    self.alpha = alpha
    self.n_permutations = n_permutations
    self.permutation_alpha = permutation_alpha
    self.xmeans_repeat = xmeans_repeat
    self.novelty_quantile = novelty_quantile
    self.n_jobs = n_jobs
    self.p_value = None
    self.null_strengths = None
    self.shift_significance = None

detect

detect()

Run drift detection across all classes.

Returns:

Type Description
tuple[bool, dict[int, dict]]

Tuple of (drift_flag, details) where: - drift_flag: Whether drift was detected. - details: Per-class drift breakdown keyed by class label.

Source code in src/stride/xai/clustering/clustering.py
def detect(self) -> tuple[bool, dict[int, dict]]:
    """Run drift detection across all classes.

    Returns:
        Tuple of `(drift_flag, details)` where:
            - `drift_flag`: Whether drift was detected.
            - `details`: Per-class drift breakdown keyed by class label.
    """
    self._run()

    if self.n_permutations > 0:
        self.null_strengths = self._permutation_strengths()
        # Small tolerance so that permutations tying with the observed value count as
        # at least as extreme despite floating-point noise.
        n_extreme = int(np.sum(self.null_strengths >= self.strength_of_drift - 1e-12))
        self.p_value = (1 + n_extreme) / (1 + self.n_permutations)
        self.drift_flag = bool(self.p_value < self.permutation_alpha)
    else:
        self.drift_flag = bool(self.strength_of_drift > self.decision_thr)

    return self.drift_flag, self.drift_details

assign_to_reference

assign_to_reference(
    X_old,
    centers_old,
    clusters_old,
    X_new,
    clusters_new,
    novelty_quantile=0.95,
    alpha=0.01,
    min_share_ratio=0.2,
)

Label the new block with the clusters of the reference (old) block.

Instead of matching two independent clusterings, new samples are assigned to the nearest old centroid, so both blocks are split by the same Voronoi cells (the cells of a k-means/X-Means partition). Differences between the blocks then reflect sampling noise or genuine change rather than two different, equally valid partitions of the same data.

Structural changes are detected relative to the reference model:

  • appeared — a cluster of the new block's own clustering (clusters_new) whose members are mostly novel, i.e. farther from their nearest old centroid than novelty_quantile of that old cluster's own samples;
  • disappeared — an old cluster that receives significantly fewer new samples than its reference share (one-sided binomial test at alpha) and less than min_share_ratio of the expected count. Its new samples are reassigned to the nearest remaining old cluster.

Parameters:

Name Type Description Default
X_old ndarray

Reference samples of one class, shape (n_old, d).

required
centers_old ndarray

X-Means centroids of X_old, shape (k, d).

required
clusters_old list[list[int]]

X-Means clusters of X_old (sample indices per centroid).

required
X_new ndarray

New samples of the same class, shape (n_new, d).

required
clusters_new list[list[int]]

Independent X-Means clusters of X_new, used only to find appeared clusters.

required
novelty_quantile float

Quantile of the old within-cluster distances defining each cluster's radius.

0.95
alpha float

Significance level of the disappearance test.

0.01
min_share_ratio float

A cluster can only disappear if it keeps less than this fraction of its expected number of new samples.

0.2

Returns:

Type Description
tuple[ndarray, ndarray, list[int], list[int]]

Tuple of (labels_old, labels_new, appeared, disappeared): - labels_old: Local cluster label per old sample (0 .. k-1). - labels_new: Local cluster label per new sample (old cluster ID, or k + i for the i-th appeared cluster). - appeared: Local IDs of appeared clusters. - disappeared: Local IDs of disappeared old clusters.

Source code in src/stride/xai/clustering/matching.py
def assign_to_reference(
    X_old: np.ndarray,
    centers_old: np.ndarray,
    clusters_old: list[list[int]],
    X_new: np.ndarray,
    clusters_new: list[list[int]],
    novelty_quantile: float = 0.95,
    alpha: float = 0.01,
    min_share_ratio: float = 0.2,
) -> tuple[np.ndarray, np.ndarray, list[int], list[int]]:
    """Label the new block with the clusters of the reference (old) block.

    Instead of matching two independent clusterings, new samples are assigned to
    the nearest *old* centroid, so both blocks are split by the same Voronoi
    cells (the cells of a k-means/X-Means partition).  Differences between the
    blocks then reflect sampling noise or genuine change rather than two
    different, equally valid partitions of the same data.

    Structural changes are detected relative to the reference model:

    * **appeared** — a cluster of the new block's own clustering (*clusters_new*)
      whose members are mostly *novel*, i.e. farther from their nearest old
      centroid than ``novelty_quantile`` of that old cluster's own samples;
    * **disappeared** — an old cluster that receives significantly fewer new
      samples than its reference share (one-sided binomial test at *alpha*) and
      less than ``min_share_ratio`` of the expected count.  Its new samples are
      reassigned to the nearest remaining old cluster.

    Args:
        X_old: Reference samples of one class, shape `(n_old, d)`.
        centers_old: X-Means centroids of `X_old`, shape `(k, d)`.
        clusters_old: X-Means clusters of `X_old` (sample indices per centroid).
        X_new: New samples of the same class, shape `(n_new, d)`.
        clusters_new: Independent X-Means clusters of `X_new`, used only to find appeared clusters.
        novelty_quantile: Quantile of the old within-cluster distances defining each cluster's radius.
        alpha: Significance level of the disappearance test.
        min_share_ratio: A cluster can only disappear if it keeps less than this fraction of its
            expected number of new samples.

    Returns:
        Tuple of `(labels_old, labels_new, appeared, disappeared)`:
            - `labels_old`: Local cluster label per old sample (`0 .. k-1`).
            - `labels_new`: Local cluster label per new sample (`old cluster ID`, or `k + i`
              for the *i*-th appeared cluster).
            - `appeared`: Local IDs of appeared clusters.
            - `disappeared`: Local IDs of disappeared old clusters.
    """
    from scipy.stats import binomtest

    k = len(centers_old)
    n_old, n_new = len(X_old), len(X_new)
    labels_old = reshape_clusters(clusters_old) if n_old else np.empty(0, dtype=int)

    if n_new == 0:
        return labels_old, np.empty(0, dtype=int), [], list(range(k))
    if k == 0:
        labels_new = reshape_clusters(clusters_new)
        return labels_old, labels_new, sorted(set(labels_new.tolist())), []

    radius = np.array(
        [np.quantile(np.linalg.norm(X_old[labels_old == j] - centers_old[j], axis=1), novelty_quantile) for j in range(k)]
    )
    dist = cdist(X_new, centers_old)
    nearest = dist.argmin(axis=1)
    novel = dist[np.arange(n_new), nearest] > radius[nearest]

    labels_new = nearest.copy()
    appeared = []
    for members in clusters_new:
        members = np.asarray(members)
        if len(members) and novel[members].mean() > 0.5:
            appeared.append(k + len(appeared))
            labels_new[members] = appeared[-1]

    shares = np.bincount(labels_old, minlength=k) / n_old
    counts = np.bincount(labels_new[labels_new < k], minlength=k)
    disappeared = [
        j
        for j in range(k)
        if counts[j] < min_share_ratio * shares[j] * n_new
        and binomtest(int(counts[j]), n_new, shares[j], alternative="less").pvalue < alpha
    ]

    if disappeared:
        orphans = np.isin(labels_new, disappeared)
        remaining = [j for j in range(k) if j not in disappeared]
        if remaining:
            labels_new[orphans] = np.asarray(remaining)[dist[np.ix_(orphans, remaining)].argmin(axis=1)]
        elif orphans.any():
            appeared.append(k + len(appeared))
            labels_new[orphans] = appeared[-1]

    return labels_old, labels_new, appeared, disappeared

bic_score

bic_score(X, centers, clusters)

Bayesian Information Criterion of a hard clustering (higher is better).

Uses the identical spherical Gaussian model of Pelleg & Moore (2000), with the per-dimension variance estimated from the pooled within-cluster scatter:

\[\hat\sigma^2 = \frac{1}{d (N - K)} \sum_j \sum_{x \in C_j} \lVert x - c_j \rVert^2, \qquad \mathrm{BIC} = \hat\ell - \frac{p}{2} \log N, \quad p = (K - 1) + K d + 1\]

Parameters:

Name Type Description Default
X ndarray

Feature matrix of shape (N, d).

required
centers ndarray

Cluster centroids of shape (K, d).

required
clusters Sequence[Sequence[int]]

Sample indices of each cluster, aligned with centers.

required

Returns:

Type Description
float

BIC value; -inf when the variance cannot be estimated (N <= K)

float

and +inf when every cluster has zero spread.

Source code in src/stride/xai/clustering/xmeans.py
def bic_score(X: np.ndarray, centers: np.ndarray, clusters: Sequence[Sequence[int]]) -> float:
    r"""Bayesian Information Criterion of a hard clustering (higher is better).

    Uses the identical spherical Gaussian model of Pelleg & Moore (2000), with the
    per-dimension variance estimated from the pooled within-cluster scatter:

    $$\hat\sigma^2 = \frac{1}{d (N - K)} \sum_j \sum_{x \in C_j} \lVert x - c_j \rVert^2, \qquad \mathrm{BIC} = \hat\ell - \frac{p}{2} \log N, \quad p = (K - 1) + K d + 1$$

    Args:
        X: Feature matrix of shape `(N, d)`.
        centers: Cluster centroids of shape `(K, d)`.
        clusters: Sample indices of each cluster, aligned with `centers`.

    Returns:
        BIC value; `-inf` when the variance cannot be estimated (`N <= K`)
        and `+inf` when every cluster has zero spread.
    """
    X = np.asarray(X)
    n, d = X.shape
    k = len(clusters)
    if n <= k:
        return float("-inf")

    sse = sum(float(np.sum((X[idx] - centers[j]) ** 2)) for j, idx in enumerate(clusters))
    if sse <= 0:
        return float("inf")
    sigma2 = sse / (d * (n - k))

    sizes = np.array([len(idx) for idx in clusters], dtype=float)
    sizes = sizes[sizes > 0]
    log_likelihood = float(np.sum(sizes * np.log(sizes / n))) - n * d / 2 * np.log(2 * np.pi * sigma2) - d * (n - k) / 2
    n_params = (k - 1) + k * d + 1
    return log_likelihood - n_params / 2 * np.log(n)

calculate_shift_significance

calculate_shift_significance(
    X_old,
    X_new,
    cluster_labels_old,
    cluster_labels_new,
    clusters,
    columns,
)

Two-sample test statistics for the per-cluster shifts.

The thresholds on centroid shift, descriptive statistics and dispersion are in absolute units, but the noise of these estimates shrinks with the cluster size: a 0.2-sigma change of the mean is noise for 10 samples and a clear signal for 500. This function provides the matching standard-error-scaled statistics so that a change can be required to be both large and statistically significant.

For a cluster with samples \(A\) (old) and \(B\) (new):

  • centroid — \(\chi^2 = \sum_f \Delta_f^2 / (s_{A,f}^2/n_A + s_{B,f}^2/n_B)\) with \(d\) degrees of freedom; its upper-tail p-value is returned;
  • mean / median / std — Welch-type z-scores using the standard errors \(s/\sqrt{n}\), \(1.2533\,s/\sqrt{n}\) and \(s/\sqrt{2(n-1)}\);
  • dispersion — Welch z-score of the mean sample-to-centroid distance.

Statistics are NaN when a cluster has fewer than two samples in a block.

Parameters:

Name Type Description Default
X_old ndarray

Feature matrix of the old data block.

required
X_new ndarray

Feature matrix of the new data block.

required
cluster_labels_old ndarray

Global cluster label per sample in the old block.

required
cluster_labels_new ndarray

Global cluster label per sample in the new block.

required
clusters Iterable[int]

Cluster IDs present in both blocks.

required
columns Sequence[str]

Feature names, used as keys of stats_z.

required

Returns:

Type Description
dict[int, dict]

Nested dictionary of {cluster: {"centroid_p": float, "stats_z": {feature: {stat: float}}, "dispersion_z": float}}.

Source code in src/stride/xai/clustering/statistics.py
def calculate_shift_significance(
    X_old: np.ndarray,
    X_new: np.ndarray,
    cluster_labels_old: np.ndarray,
    cluster_labels_new: np.ndarray,
    clusters: Iterable[int],
    columns: Sequence[str],
) -> dict[int, dict]:
    r"""Two-sample test statistics for the per-cluster shifts.

    The thresholds on centroid shift, descriptive statistics and dispersion are
    in absolute units, but the noise of these estimates shrinks with the cluster
    size: a 0.2-sigma change of the mean is noise for 10 samples and a clear
    signal for 500. This function provides the matching standard-error-scaled
    statistics so that a change can be required to be both large *and*
    statistically significant.

    For a cluster with samples $A$ (old) and $B$ (new):

    * **centroid** — $\chi^2 = \sum_f \Delta_f^2 / (s_{A,f}^2/n_A + s_{B,f}^2/n_B)$
      with $d$ degrees of freedom; its upper-tail p-value is returned;
    * **mean / median / std** — Welch-type z-scores using the standard errors
      $s/\sqrt{n}$, $1.2533\,s/\sqrt{n}$ and $s/\sqrt{2(n-1)}$;
    * **dispersion** — Welch z-score of the mean sample-to-centroid distance.

    Statistics are `NaN` when a cluster has fewer than two samples in a block.

    Args:
        X_old: Feature matrix of the old data block.
        X_new: Feature matrix of the new data block.
        cluster_labels_old: Global cluster label per sample in the old block.
        cluster_labels_new: Global cluster label per sample in the new block.
        clusters: Cluster IDs present in both blocks.
        columns: Feature names, used as keys of `stats_z`.

    Returns:
        Nested dictionary of `{cluster: {"centroid_p": float, "stats_z": {feature: {stat: float}}, "dispersion_z": float}}`.
    """
    from scipy.stats import chi2

    def _welch_z(diff, var_a, var_b):
        se = np.sqrt(var_a + var_b)
        with np.errstate(divide="ignore", invalid="ignore"):
            return np.where(se > 0, diff / np.where(se > 0, se, 1.0), np.where(diff == 0, 0.0, np.inf) * np.sign(diff))

    result: dict = {}
    for k in clusters:
        A = X_old[cluster_labels_old == k]
        B = X_new[cluster_labels_new == k]
        n_a, n_b = len(A), len(B)
        if n_a < 2 or n_b < 2:
            nan_stats = {f: {"mean": np.nan, "median": np.nan, "std": np.nan} for f in columns}
            result[k] = {"centroid_p": np.nan, "stats_z": nan_stats, "dispersion_z": np.nan}
            continue

        s_a, s_b = A.std(axis=0, ddof=1), B.std(axis=0, ddof=1)
        mean_diff = B.mean(axis=0) - A.mean(axis=0)
        var_mean_a, var_mean_b = s_a**2 / n_a, s_b**2 / n_b

        z_mean = _welch_z(mean_diff, var_mean_a, var_mean_b)
        z_median = _welch_z(np.median(B, axis=0) - np.median(A, axis=0), 1.2533**2 * var_mean_a, 1.2533**2 * var_mean_b)
        z_std = _welch_z(s_b - s_a, s_a**2 / (2 * (n_a - 1)), s_b**2 / (2 * (n_b - 1)))

        statistic = float(np.sum(np.where(np.isfinite(z_mean), z_mean, 0.0) ** 2))
        centroid_p = 0.0 if np.isinf(z_mean).any() else float(chi2.sf(statistic, df=A.shape[1]))

        d_a = np.linalg.norm(A - A.mean(axis=0), axis=1)
        d_b = np.linalg.norm(B - B.mean(axis=0), axis=1)
        z_disp = float(_welch_z(d_b.mean() - d_a.mean(), d_a.var(ddof=1) / n_a, d_b.var(ddof=1) / n_b))

        result[k] = {
            "centroid_p": centroid_p,
            "stats_z": {
                f: {"mean": float(z_mean[i]), "median": float(z_median[i]), "std": float(z_std[i])}
                for i, f in enumerate(columns)
            },
            "dispersion_z": z_disp,
        }
    return result

compare_desc_stats_for_clusters

compare_desc_stats_for_clusters(stats_combined)

Compute relative per-statistic shifts between data blocks for each cluster.

Parameters:

Name Type Description Default
stats_combined DataFrame

Output of compute_desc_stats_for_clusters.

required

Returns:

Type Description
dict[int, dict[str, dict[str, float]]]

Nested {cluster: {feature: {statistic: change}}} mapping, where change

dict[int, dict[str, dict[str, float]]]

is after - before. The detector compares standardised features, so the

dict[int, dict[str, dict[str, float]]]

change is expressed in standard deviations of the feature.

dict[int, dict[str, dict[str, float]]]

NaN marks statistics unavailable in either block.

Source code in src/stride/xai/clustering/statistics.py
def compare_desc_stats_for_clusters(
    stats_combined: pd.DataFrame,
) -> dict[int, dict[str, dict[str, float]]]:
    """Compute relative per-statistic shifts between data blocks for each cluster.

    Args:
        stats_combined: Output of `compute_desc_stats_for_clusters`.

    Returns:
        Nested `{cluster: {feature: {statistic: change}}}` mapping, where *change*
        is `after - before`. The detector compares standardised features, so the
        change is expressed in standard deviations of the feature.
        `NaN` marks statistics unavailable in either block.
    """
    details: dict = {}

    for cluster in stats_combined.index:
        row_df = stats_combined.loc[[cluster]]
        details[cluster] = {}
        features = row_df.columns.levels[1]

        for feature in features:
            details[cluster][feature] = {}
            stats_available = row_df.columns.levels[2]

            for stat in stats_available:
                col_old = ("before", feature, stat)
                col_new = ("after", feature, stat)

                if col_old not in row_df.columns or col_new not in row_df.columns:
                    details[cluster][feature][stat] = np.nan
                    continue

                old_val = row_df[col_old].iloc[0]
                new_val = row_df[col_new].iloc[0]

                if np.isnan(old_val) or np.isnan(new_val):
                    details[cluster][feature][stat] = np.nan
                    continue

                details[cluster][feature][stat] = new_val - old_val

    return details

compute_desc_stats_for_clusters

compute_desc_stats_for_clusters(
    X_old,
    X_new,
    cluster_labels_old,
    cluster_labels_new,
    columns,
)

Compute descriptive statistics per cluster for both data blocks.

Parameters:

Name Type Description Default
X_old ndarray

Feature matrix of the old data block (scaled, shape (n_old, d)).

required
X_new ndarray

Feature matrix of the new data block (scaled, shape (n_new, d)).

required
cluster_labels_old ndarray

Global cluster label per sample in the old block.

required
cluster_labels_new ndarray

Global cluster label per sample in the new block.

required
columns Index

Feature names used as column labels in the returned DataFrame.

required

Returns:

Type Description
DataFrame

3-level MultiIndex column DataFrame (block, feature, statistic)

DataFrame

where block is "before" or "after".

Source code in src/stride/xai/clustering/statistics.py
def compute_desc_stats_for_clusters(
    X_old: np.ndarray,
    X_new: np.ndarray,
    cluster_labels_old: np.ndarray,
    cluster_labels_new: np.ndarray,
    columns: pd.Index,
) -> pd.DataFrame:
    """Compute descriptive statistics per cluster for both data blocks.

    Args:
        X_old: Feature matrix of the old data block (scaled, shape `(n_old, d)`).
        X_new: Feature matrix of the new data block (scaled, shape `(n_new, d)`).
        cluster_labels_old: Global cluster label per sample in the old block.
        cluster_labels_new: Global cluster label per sample in the new block.
        columns: Feature names used as column labels in the returned DataFrame.

    Returns:
        3-level MultiIndex column DataFrame `(block, feature, statistic)`
        where *block* is `"before"` or `"after"`.
    """

    def _compute(X: np.ndarray, labels: np.ndarray) -> pd.DataFrame:
        df = pd.DataFrame(X, columns=columns)
        df["cluster"] = labels
        features = df.columns[:-1]
        clusters = sorted(df["cluster"].unique())

        records = []
        for cluster in clusters:
            cdf = df[df["cluster"] == cluster]
            stats: dict = {}
            for f in features:
                stats[(f, "median")] = cdf[f].median()
                stats[(f, "mean")] = cdf[f].mean()
                stats[(f, "std")] = cdf[f].std()
            stats[("cluster", "id")] = cluster
            records.append(stats)

        stats_df = pd.DataFrame(records)
        stats_df.set_index([("cluster", "id")], inplace=True)
        stats_df.sort_index(inplace=True)
        return stats_df

    stats_old = _compute(X_old, cluster_labels_old)
    stats_new = _compute(X_new, cluster_labels_new)

    stats_old.columns = pd.MultiIndex.from_tuples([("before", f, s) for f, s in stats_old.columns])
    stats_new.columns = pd.MultiIndex.from_tuples([("after", f, s) for f, s in stats_new.columns])

    combined = pd.concat([stats_old, stats_new], axis=1)
    combined.fillna(np.nan, inplace=True)
    combined.columns = combined.columns.set_levels(
        pd.CategoricalIndex(combined.columns.levels[0], categories=["before", "after"], ordered=True),
        level=0,
    )
    return combined.sort_index(axis=1)

map_new_clusters_to_old

map_new_clusters_to_old(
    centers_old, centers_new, thr_centroid_disappear
)

Match new cluster centroids to old ones using the Hungarian algorithm.

Clusters whose centroid moved further than thr_centroid_disappear are treated as disappeared/appeared rather than shifted.

Parameters:

Name Type Description Default
centers_old ndarray

Array of centroid coordinates for the old data block (shape (k_old, d)).

required
centers_new ndarray

Array of centroid coordinates for the new data block (shape (k_new, d)).

required
thr_centroid_disappear float

Euclidean-distance threshold above which a centroid pair is considered a disappearance + appearance rather than a migration.

required

Returns:

Type Description
tuple[dict[int, int], list[int], list[int]]

Tuple of (mapping, disappeared, appeared) where: - mapping: Maps each new cluster index to its matched old cluster index. - disappeared: Old cluster indices that have no close match in the new block. - appeared: New cluster indices that have no close match in the old block.

Source code in src/stride/xai/clustering/matching.py
def map_new_clusters_to_old(
    centers_old: np.ndarray,
    centers_new: np.ndarray,
    thr_centroid_disappear: float,
) -> tuple[dict[int, int], list[int], list[int]]:
    """Match new cluster centroids to old ones using the Hungarian algorithm.

    Clusters whose centroid moved further than `thr_centroid_disappear` are
    treated as disappeared/appeared rather than shifted.

    Args:
        centers_old: Array of centroid coordinates for the *old* data block (shape `(k_old, d)`).
        centers_new: Array of centroid coordinates for the *new* data block (shape `(k_new, d)`).
        thr_centroid_disappear: Euclidean-distance threshold above which a centroid pair is
            considered a disappearance + appearance rather than a migration.

    Returns:
        Tuple of `(mapping, disappeared, appeared)` where:
            - `mapping`: Maps each **new** cluster index to its matched **old** cluster index.
            - `disappeared`: Old cluster indices that have no close match in the new block.
            - `appeared`: New cluster indices that have no close match in the old block.
    """
    n_old = len(centers_old)
    n_new = len(centers_new)

    dist = cdist(centers_old, centers_new, metric="euclidean")
    dist[dist > thr_centroid_disappear] = 1e10

    size = max(n_old, n_new)
    padded = np.full((size, size), 1e9)
    padded[:n_old, :n_new] = dist

    row_ind, col_ind = linear_sum_assignment(padded)

    mapping: dict[int, int] = {}
    disappeared: list[int] = []
    appeared: list[int] = []

    for r, c in zip(row_ind, col_ind):
        if r < n_old and c < n_new:
            if dist[r, c] < 1e10:
                mapping[c] = r
            else:
                disappeared.append(r)
                appeared.append(c)
        elif r < n_old and c >= n_new:
            disappeared.append(r)
        elif r >= n_old and c < n_new:
            appeared.append(c)

    return mapping, disappeared, appeared

merge_clusters

merge_clusters(clusters, y, classes, maps=None)

Flatten per-class X-Means results into a single global label array.

Parameters:

Name Type Description Default
clusters list[list[list[int]]]

3-D list: outer = classes, middle = clusters, inner = sample indices.

required
y ndarray

Class-label vector aligned with the original sample order.

required
classes Sequence

Class labels in the same order as the outer level of clusters (and of maps). Classes absent from y must have an empty cluster list.

required
maps list[tuple[dict[int, int | str], list[int], list[int]]] | None

Per-class matching tuples. When None (old block), the identity mapping is used — no renaming needed.

None

Returns:

Type Description
ndarray

Integer label array of shape (n_samples,) with globally unique IDs.

Raises:

Type Description
ValueError

If number of classes does not match the outer length of clusters.

Source code in src/stride/xai/clustering/matching.py
def merge_clusters(
    clusters: list[list[list[int]]],
    y: np.ndarray,
    classes: Sequence,
    maps: list[tuple[dict[int, int | str], list[int], list[int]]] | None = None,
) -> np.ndarray:
    """Flatten per-class X-Means results into a single global label array.

    Args:
        clusters: 3-D list: outer = classes, middle = clusters, inner = sample indices.
        y: Class-label vector aligned with the original sample order.
        classes: Class labels in the same order as the outer level of `clusters` (and of
            `maps`). Classes absent from `y` must have an empty cluster list.
        maps: Per-class matching tuples. When `None` (old block), the identity
            mapping is used — no renaming needed.

    Returns:
        Integer label array of shape `(n_samples,)` with globally unique IDs.

    Raises:
        ValueError: If number of classes does not match the outer length of clusters.
    """
    if len(classes) != len(clusters):
        raise ValueError(f"Got {len(classes)} classes but cluster results for {len(clusters)} classes.")

    y = np.asarray(y)
    final_labels = np.zeros(len(y))
    transformed_labels = []

    if maps is None:
        maps = [({j: j for j in range(len(clusters[i]))}, [], []) for i in range(len(clusters))]

    for mapp, klass in zip(maps, clusters):
        mapping, _, _ = mapp
        cluster_labels = reshape_clusters(klass)
        new_ids = set(np.unique(cluster_labels)).difference(set(mapping.keys()))
        for local_id in new_ids:
            mapping[local_id] = f"new_{local_id}"
        transformed_labels.append(transform_labels_with_mapping(cluster_labels, mapping))

    transformed_labels = get_final_labels(transformed_labels, maps)

    for klass, labels in zip(classes, transformed_labels):
        final_labels[y == klass] = np.array(labels)

    return final_labels.astype(int)

reshape_clusters

reshape_clusters(clusters)

Convert a list of clusters (each a list of sample indices) into a flat label array.

Parameters:

Name Type Description Default
clusters Sequence[Sequence[int]]

List of lists where each sublist contains the indices of samples belonging to that cluster, e.g. [[0, 2, 3], [1, 4]].

required

Returns:

Type Description
ndarray

Flat array of integer cluster-label assignments, e.g. array([0, 1, 0, 0, 1]).

Source code in src/stride/xai/clustering/xmeans.py
def reshape_clusters(clusters: Sequence[Sequence[int]]) -> np.ndarray:
    """Convert a list of clusters (each a list of sample indices) into a flat label array.

    Args:
        clusters: List of lists where each sublist contains the indices of samples belonging to
            that cluster, e.g. `[[0, 2, 3], [1, 4]]`.

    Returns:
        Flat array of integer cluster-label assignments, e.g. `array([0, 1, 0, 0, 1])`.
    """
    n_samples = sum(len(c) for c in clusters)
    reshaped = np.empty(n_samples, dtype=int)
    for idx, cluster in enumerate(clusters):
        for sample_index in cluster:
            reshaped[sample_index] = idx
    return reshaped

run_xmeans

run_xmeans(X, k_init, k_max, random_state=42, repeat=1)

Run the X-Means clustering algorithm on X.

Parameters:

Name Type Description Default
X ndarray

Feature matrix (rows are samples, columns are features).

required
k_init int

Minimum number of clusters passed to the k-means++ initialiser.

required
k_max int

Maximum number of clusters allowed by X-Means.

required
random_state int | None

Seed passed to pyclustering's k-means++ initialiser and to X-Means itself, so that every cluster split is reproducible. When None the result is non-deterministic.

42
repeat int

Number of independent X-Means runs, seeded with random_state, random_state + 1, ...; the result with the highest BIC (see bic_score) is returned.

1

Returns:

Type Description
tuple[ndarray, list[list[int]]]

Tuple of (centers, clusters) where: - centers: 2-D array of cluster-centroid coordinates. - clusters: List of lists where each sublist contains the sample indices belonging to the corresponding centroid.

Raises:

Type Description
OptionalDependencyError

If pyclustering is not installed.

ValueError

If repeat is less than 1.

Source code in src/stride/xai/clustering/xmeans.py
def run_xmeans(
    X: np.ndarray,
    k_init: int,
    k_max: int,
    random_state: int | None = 42,
    repeat: int = 1,
) -> tuple[np.ndarray, list[list[int]]]:
    """Run the X-Means clustering algorithm on *X*.

    Args:
        X: Feature matrix (rows are samples, columns are features).
        k_init: Minimum number of clusters passed to the k-means++ initialiser.
        k_max: Maximum number of clusters allowed by X-Means.
        random_state: Seed passed to pyclustering's k-means++ initialiser and to X-Means itself,
            so that every cluster split is reproducible. When None the result is non-deterministic.
        repeat: Number of independent X-Means runs, seeded with `random_state`,
            `random_state + 1`, ...; the result with the highest BIC (see `bic_score`) is returned.

    Returns:
        Tuple of `(centers, clusters)` where:
            - `centers`: 2-D array of cluster-centroid coordinates.
            - `clusters`: List of lists where each sublist contains the sample indices belonging to
              the corresponding centroid.

    Raises:
        OptionalDependencyError: If pyclustering is not installed.
        ValueError: If repeat is less than 1.
    """
    try:
        from pyclustering.cluster.xmeans import kmeans_plusplus_initializer, xmeans
    except ImportError as err:
        raise OptionalDependencyError(
            package_name="pyclustering",
            feature_name="X-Means clustering",
            extra_name="clustering",
        ) from err

    X = np.asarray(X)
    n_samples = len(X)
    if n_samples == 0:
        return np.empty((0, X.shape[1])), []
    if n_samples < k_init:
        # k-means++ needs at least k_init points; such a small group is a single cluster.
        return X.mean(axis=0, keepdims=True), [list(range(n_samples))]

    if repeat < 1:
        raise ValueError(f"repeat must be at least 1, got {repeat}")

    best: tuple[float, np.ndarray, list[list[int]]] | None = None
    rng_state = random.getstate()
    try:
        for r in range(repeat):
            seed = None if random_state is None else random_state + r
            init_centers = kmeans_plusplus_initializer(X, k_init, random_state=seed).initialize()

            # ccore=False: the bundled C++ library is built for x86_64 only and fails to load on arm64.
            xm = xmeans(X, init_centers, kmax=k_max, ccore=False, random_state=seed)
            xm.process()
            centers, clusters = np.array(xm.get_centers()), xm.get_clusters()
            if repeat == 1:
                return centers, clusters

            score = bic_score(X, centers, clusters)
            if best is None or score > best[0]:
                best = (score, centers, clusters)
    finally:
        random.setstate(rng_state)

    return best[1], best[2]