Skip to content

xAI: Recurring Concepts & Memory

The stride.xai.recurrence subpackage provides tools for archiving stream window representations, computing pairwise structural distance matrices, and discovering recurring concept regimes using HDBSCAN density clustering.


Overview

Recurring concept detection addresses streams that alternate between distinct recurring distributions over time. By maintaining prototype vectors per window and clustering distance matrices with HDBSCAN, STRIDE recognizes when a previously seen concept re-emerges.

from stride.xai.recurrence import (
    FullWindowStorage,
    cluster_windows,
    get_drift_from_clusters,
)

Key Components

Class / Function Description
FullWindowStorage Archives window snapshots (features, labels, class prototypes, fitted explainers) and computes pairwise inter-window distance matrices.
cluster_windows Clusters precomputed window distance matrices using HDBSCAN with optional noise outlier reassignment (fix_outliers=True).
get_drift_from_clusters Identifies concept transition timestamps where the assigned active concept regime ID changes.

API Specification

stride.xai.recurrence

Recurring concept memory, prototype trees, and historical window distance matrices.

FullWindowStorage

FullWindowStorage()

Stores data for every window during the stream, enabling distance computations.

Initialize storage for all windows.

Source code in src/stride/xai/recurrence/full_window_storage.py
def __init__(self):
    """Initialize storage for all windows."""
    self.windows: dict[int, tuple[TDataBatch, TTarget]] = {}
    self.prototypes: dict[int, TPrototypes] = {}
    self.explainers: dict[int, TExplainer] = {}
    self.drift_detected: dict[int, bool] = {}

compare_two_windows

compare_two_windows(
    iter_a,
    iter_b,
    measure="centroid_displacement",
    strategy="total",
    distance="l2",
)

Compare two specific windows.

Parameters:

Name Type Description Default
iter_a int

First iteration number

required
iter_b int

Second iteration number

required
measure Literal['mutual_information', 'rand_index', 'completeness', 'fowlkes_mallows', 'centroid_displacement', 'minimal_distance', 'prototype_reassignment_impact']

Comparison metric to use

'centroid_displacement'
strategy Literal['class', 'total']

"class" for class-wise, "total" for overall

'total'
distance Literal['l2', 'tree']

"l2" for Euclidean, "tree" for tree-based distance

'l2'

Returns:

Type Description
float

Distance/similarity score between the two windows

Source code in src/stride/xai/recurrence/full_window_storage.py
def compare_two_windows(
    self,
    iter_a: int,
    iter_b: int,
    measure: Literal[
        "mutual_information",
        "rand_index",
        "completeness",
        "fowlkes_mallows",
        "centroid_displacement",
        "minimal_distance",
        "prototype_reassignment_impact",
    ] = "centroid_displacement",
    strategy: Literal["class", "total"] = "total",
    distance: Literal["l2", "tree"] = "l2",
) -> float:
    """Compare two specific windows.

    Args:
        iter_a: First iteration number
        iter_b: Second iteration number
        measure: Comparison metric to use
        strategy: "class" for class-wise, "total" for overall
        distance: "l2" for Euclidean, "tree" for tree-based distance

    Returns:
        Distance/similarity score between the two windows
    """
    x_a, y_a, proto_a, exp_a = self.get_window_data(iter_a)
    x_b, y_b, proto_b, exp_b = self.get_window_data(iter_b)

    return self._compute_metric(proto_a, proto_b, exp_a, exp_b, x_b, y_b, measure, strategy, distance)

compare_window_to_all

compare_window_to_all(
    target_iter,
    measure="centroid_displacement",
    strategy="total",
    distance="l2",
)

Compare one window against all other stored windows.

Parameters:

Name Type Description Default
target_iter int

Iteration number to compare

required
measure Literal['mutual_information', 'rand_index', 'completeness', 'fowlkes_mallows', 'centroid_displacement', 'minimal_distance', 'prototype_reassignment_impact']

Comparison metric to use

'centroid_displacement'
strategy Literal['class', 'total']

"class" for class-wise, "total" for overall

'total'
distance Literal['l2', 'tree']

"l2" for Euclidean, "tree" for tree-based distance

'l2'

Returns:

Type Description
Series

Series with iteration numbers as index and distances as values

Source code in src/stride/xai/recurrence/full_window_storage.py
def compare_window_to_all(
    self,
    target_iter: int,
    measure: Literal[
        "mutual_information",
        "rand_index",
        "completeness",
        "fowlkes_mallows",
        "centroid_displacement",
        "minimal_distance",
        "prototype_reassignment_impact",
    ] = "centroid_displacement",
    strategy: Literal["class", "total"] = "total",
    distance: Literal["l2", "tree"] = "l2",
) -> pd.Series:
    """Compare one window against all other stored windows.

    Args:
        target_iter: Iteration number to compare
        measure: Comparison metric to use
        strategy: "class" for class-wise, "total" for overall
        distance: "l2" for Euclidean, "tree" for tree-based distance

    Returns:
        Series with iteration numbers as index and distances as values
    """
    x_target, y_target, proto_target, exp_target = self.get_window_data(target_iter)

    iterations = self.get_all_iterations()
    distances = {}

    for iter_num in iterations:
        x, y, proto, exp = self.get_window_data(iter_num)

        score = self._compute_metric(proto_target, proto, exp_target, exp, x, y, measure, strategy, distance)
        distances[iter_num] = score

    return pd.Series(distances, name=f"distance_from_{target_iter}")

compute_distance_matrix

compute_distance_matrix(
    measure="centroid_displacement",
    strategy="total",
    distance="l2",
    verbose=False,
)

Compute full distance matrix between all stored windows.

Parameters:

Name Type Description Default
measure Literal['mutual_information', 'rand_index', 'completeness', 'fowlkes_mallows', 'centroid_displacement', 'minimal_distance', 'prototype_reassignment_impact']

Comparison metric to use

'centroid_displacement'
strategy Literal['class', 'total']

"class" for class-wise, "total" for overall

'total'
distance Literal['l2', 'tree']

"l2" for Euclidean, "tree" for tree-based distance

'l2'
verbose bool

Whether to print progress during matrix calculation.

False

Returns:

Type Description
DataFrame

DataFrame where rows and columns are iteration numbers, values are distances

Source code in src/stride/xai/recurrence/full_window_storage.py
def compute_distance_matrix(
    self,
    measure: Literal[
        "mutual_information",
        "rand_index",
        "completeness",
        "fowlkes_mallows",
        "centroid_displacement",
        "minimal_distance",
        "prototype_reassignment_impact",
    ] = "centroid_displacement",
    strategy: Literal["class", "total"] = "total",
    distance: Literal["l2", "tree"] = "l2",
    verbose: bool = False,
) -> pd.DataFrame:
    """Compute full distance matrix between all stored windows.

    Args:
        measure: Comparison metric to use
        strategy: "class" for class-wise, "total" for overall
        distance: "l2" for Euclidean, "tree" for tree-based distance
        verbose: Whether to print progress during matrix calculation.

    Returns:
        DataFrame where rows and columns are iteration numbers, values are distances
    """
    iterations = self.get_all_iterations()
    n = len(iterations)

    if verbose:
        print(f"Computing {n}x{n} distance matrix using {measure}...")
    matrix = np.zeros((n, n))

    for i, iter_a in enumerate(iterations):
        if i % 10 == 0:
            if verbose:
                print(f"  Progress: {i}/{n}")

        x_a, y_a, proto_a, exp_a = self.get_window_data(iter_a)

        for j, iter_b in enumerate(iterations):
            if i == j:
                matrix[i, j] = 0.0
                continue

            if matrix[j, i] != 0.0:
                # Matrix is symmetric
                matrix[i, j] = matrix[j, i]
                continue

            x_b, y_b, proto_b, exp_b = self.get_window_data(iter_b)

            score = self._compute_metric(proto_a, proto_b, exp_a, exp_b, x_b, y_b, measure, strategy, distance)
            matrix[i, j] = score

    if verbose:
        print("Complete!")
    return pd.DataFrame(matrix, index=iterations, columns=iterations)

get_all_iterations

get_all_iterations()

Get all stored iteration numbers.

Source code in src/stride/xai/recurrence/full_window_storage.py
def get_all_iterations(self) -> list[int]:
    """Get all stored iteration numbers."""
    return sorted(self.windows.keys())

get_window_data

get_window_data(iteration)

Get all data for a specific window.

Returns:

Type Description
tuple[TDataBatch, TTarget, TPrototypes, TExplainer]

Tuple of (x, y, prototypes, explainer)

Source code in src/stride/xai/recurrence/full_window_storage.py
def get_window_data(self, iteration: int) -> tuple[TDataBatch, TTarget, TPrototypes, TExplainer]:
    """Get all data for a specific window.

    Returns:
        Tuple of (x, y, prototypes, explainer)
    """
    if iteration not in self.windows:
        raise ValueError(f"Window at iteration {iteration} not found")

    x, y = self.windows[iteration]
    prototypes = self.prototypes[iteration]
    explainer = self.explainers[iteration]
    return x, y, prototypes, explainer

store_window

store_window(iteration, x, y, prototypes, explainer, drift)

Store window data for a given iteration.

Source code in src/stride/xai/recurrence/full_window_storage.py
def store_window(
    self, iteration: int, x: TDataBatch, y: TTarget, prototypes: TPrototypes, explainer: TExplainer, drift: bool
) -> None:
    """Store window data for a given iteration."""
    self.windows[iteration] = (deepcopy(x), deepcopy(y))
    self.prototypes[iteration] = deepcopy(prototypes)
    self.explainers[iteration] = deepcopy(explainer)
    self.drift_detected[iteration] = drift