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.
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:
- Changes in the number of clusters within a class (clusters that appeared or disappeared).
- Changes in descriptive statistics computed for each cluster.
- Spatial shifts of cluster centroids (\(\|c_{\text{before}} - c_{\text{after}}\|_2\)).
- 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
|
strength_of_drift |
float
|
Weighted share of triggered criteria in \([0.0, 1.0]\). |
p_value |
float | None
|
Permutation p-value of |
null_strengths |
ndarray | None
|
Drift strengths obtained under the permutations. |
effective_weights |
ndarray | None
|
Criterion weights actually used for the score, i.e. |
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 |
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 |
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
|
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.
|
'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: |
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
|
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 |
0.95
|
n_jobs
|
int | None
|
Number of worker processes for the permutation test (joblib
semantics; |
None
|
Source code in src/stride/xai/clustering/clustering.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | |
detect
Run drift detection across all classes.
Returns:
| Type | Description |
|---|---|
tuple[bool, dict[int, dict]]
|
Tuple of |
Source code in src/stride/xai/clustering/clustering.py
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_quantileof 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_ratioof 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 |
required |
centers_old
|
ndarray
|
X-Means centroids of |
required |
clusters_old
|
list[list[int]]
|
X-Means clusters of |
required |
X_new
|
ndarray
|
New samples of the same class, shape |
required |
clusters_new
|
list[list[int]]
|
Independent X-Means clusters of |
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 |
Source code in src/stride/xai/clustering/matching.py
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | |
bic_score
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:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Feature matrix of shape |
required |
centers
|
ndarray
|
Cluster centroids of shape |
required |
clusters
|
Sequence[Sequence[int]]
|
Sample indices of each cluster, aligned with |
required |
Returns:
| Type | Description |
|---|---|
float
|
BIC value; |
float
|
and |
Source code in src/stride/xai/clustering/xmeans.py
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 |
required |
Returns:
| Type | Description |
|---|---|
dict[int, dict]
|
Nested dictionary of |
Source code in src/stride/xai/clustering/statistics.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | |
compare_desc_stats_for_clusters
Compute relative per-statistic shifts between data blocks for each cluster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stats_combined
|
DataFrame
|
Output of |
required |
Returns:
| Type | Description |
|---|---|
dict[int, dict[str, dict[str, float]]]
|
Nested |
dict[int, dict[str, dict[str, float]]]
|
is |
dict[int, dict[str, dict[str, float]]]
|
change is expressed in standard deviations of the feature. |
dict[int, dict[str, dict[str, float]]]
|
|
Source code in src/stride/xai/clustering/statistics.py
compute_desc_stats_for_clusters
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 |
required |
X_new
|
ndarray
|
Feature matrix of the new data block (scaled, shape |
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 |
DataFrame
|
where block is |
Source code in src/stride/xai/clustering/statistics.py
map_new_clusters_to_old
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 |
required |
centers_new
|
ndarray
|
Array of centroid coordinates for the new data block (shape |
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 |
Source code in src/stride/xai/clustering/matching.py
merge_clusters
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 |
required |
maps
|
list[tuple[dict[int, int | str], list[int], list[int]]] | None
|
Per-class matching tuples. When |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Integer label array of shape |
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
reshape_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. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Flat array of integer cluster-label assignments, e.g. |
Source code in src/stride/xai/clustering/xmeans.py
run_xmeans
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 |
1
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, list[list[int]]]
|
Tuple of |
Raises:
| Type | Description |
|---|---|
OptionalDependencyError
|
If pyclustering is not installed. |
ValueError
|
If repeat is less than 1. |