Skip to content

xAI: Decision Boundary Analysis

The stride.xai.boundary subpackage provides tools for projecting high-dimensional feature spaces into 2D manifolds, rendering Supervised Decision Boundary Maps (SDBM), and characterizing boundary shifts using surrogate disagreement decision trees.


Overview

Boundary analysis tracks geometric deformations in classifier decision frontiers between reference and detection windows. It uses Self-Supervised Neighbor Projection (SSNP) for bi-directional dimensionality reduction and samples continuous latent grids to detect regions where models disagree.

from stride.xai.boundary import (
    DecisionBoundaryDriftAnalyzer,
    compute_disagreement_analysis,
)

Key Components

Class / Function Description
DecisionBoundaryDriftAnalyzer High-level orchestrator that projects windows, fits pre- and post-drift classifiers, computes grid predictions, and evaluates disagreement regions.
compute_disagreement_analysis Identifies disagreement regions where \(f_{\text{pre}}(x) \neq f_{\text{post}}(x)\) and fits surrogate decision trees to extract bounding decision rules.
SSNP Neural autoencoder mapping \(\mathbb{R}^D \leftrightarrow \mathbb{R}^2\) while preserving neighborhood distances (requires tensorflow>=2.15).

API Specification

stride.xai.boundary

Decision boundary migration analysis, neural projections, and disagreement trees.

DecisionBoundaryDriftAnalyzer

DecisionBoundaryDriftAnalyzer(
    X_before, y_before, X_after, y_after, random_state=42
)

Analyze decision boundary shifts between data stream windows.

Projects high-dimensional feature spaces \(\mathbb{R}^D\) into an interpretable 2D manifold \(\mathbb{R}^2\) using Self-Supervised Neighbor Projection (SSNP) or passthrough scaling. A single SSNP projection is trained on both windows together and shared by both decision maps. Evaluates classifiers trained before (\(f_{\text{pre}}\)) and after (\(f_{\text{post}}\)) drift, reconstructs dense decision grids, and trains Disagreement Decision Trees to extract geometric boundary shift explanations.

Attributes:

Name Type Description
random_state

Pseudo-random generator seed.

X_before

Pre-drift feature array of shape (n_samples, n_features).

y_before

Pre-drift target labels.

X_after

Post-drift feature array.

y_after

Post-drift target labels.

Initialize the decision boundary analyzer with window splits.

Parameters:

Name Type Description Default
X_before ndarray | DataFrame

Reference feature data before drift.

required
y_before ndarray | Series

Reference target labels before drift.

required
X_after ndarray | DataFrame

Detection feature data after drift.

required
y_after ndarray | Series

Detection target labels after drift.

required
random_state int

Random state used to ensure reproducible projections.

42
Source code in src/stride/xai/boundary/analysis.py
def __init__(
    self,
    X_before: np.ndarray | pd.DataFrame,
    y_before: np.ndarray | pd.Series,
    X_after: np.ndarray | pd.DataFrame,
    y_after: np.ndarray | pd.Series,
    random_state: int = 42,
) -> None:
    """Initialize the decision boundary analyzer with window splits.

    Args:
        X_before: Reference feature data before drift.
        y_before: Reference target labels before drift.
        X_after: Detection feature data after drift.
        y_after: Detection target labels after drift.
        random_state: Random state used to ensure reproducible projections.
    """
    self.random_state = random_state
    np.random.seed(self.random_state)
    random.seed(self.random_state)
    try:
        import tensorflow as tf

        tf.random.set_seed(self.random_state)
    except Exception:
        pass

    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

    self.X_before = np.asarray(X_before)
    self.y_before = np.asarray(y_before)
    self.X_after = np.asarray(X_after)
    self.y_after = np.asarray(y_after)

analyze

analyze(
    model_class=None,
    model_params=None,
    grid_size=300,
    ssnp_epochs=10,
    ssnp_patience=5,
    feature_names=None,
)

Compute decision boundary shifts and disagreement explanation trees.

Parameters:

Name Type Description Default
model_class Any | None

Classifier class used to map decision boundaries. Defaults to MLPModel.

None
model_params dict[str, Any] | None

Initialization keyword arguments passed to model_class.

None
grid_size int

Number of sampling intervals along each axis of the 2D grid (\(N imes N\)).

300
ssnp_epochs int

Training epochs for SSNP autoencoder projection network.

10
ssnp_patience int

Early stopping patience epochs for SSNP training.

5
feature_names list[str] | None

Optional sequence of human-readable feature column names.

None

Returns:

Type Description
dict[str, Any]

Dictionary containing: - 'pre': Pre-drift results dictionary with classifier, 2D coordinates, and grid surfaces. - 'post': Post-drift results dictionary. - 'ssnp_model': Fitted projection model instance. - 'grid_size': Evaluated grid dimension. - 'disagreement': Disagreement analysis report and decision tree rules. - 'is_2d': Whether input data was natively 2-dimensional.

Raises:

Type Description
OptionalDependencyError

If input dimension \(> 2\) and tensorflow is not installed.

Source code in src/stride/xai/boundary/analysis.py
def analyze(
    self,
    model_class: Any | None = None,
    model_params: dict[str, Any] | None = None,
    grid_size: int = 300,
    ssnp_epochs: int = 10,
    ssnp_patience: int = 5,
    feature_names: list[str] | None = None,
) -> dict[str, Any]:
    """Compute decision boundary shifts and disagreement explanation trees.

    Args:
        model_class: Classifier class used to map decision boundaries. Defaults to `MLPModel`.
        model_params: Initialization keyword arguments passed to `model_class`.
        grid_size: Number of sampling intervals along each axis of the 2D grid ($N \times N$).
        ssnp_epochs: Training epochs for SSNP autoencoder projection network.
        ssnp_patience: Early stopping patience epochs for SSNP training.
        feature_names: Optional sequence of human-readable feature column names.

    Returns:
        Dictionary containing:
            - 'pre': Pre-drift results dictionary with classifier, 2D coordinates, and grid surfaces.
            - 'post': Post-drift results dictionary.
            - 'ssnp_model': Fitted projection model instance.
            - 'grid_size': Evaluated grid dimension.
            - 'disagreement': Disagreement analysis report and decision tree rules.
            - 'is_2d': Whether input data was natively 2-dimensional.

    Raises:
        OptionalDependencyError: If input dimension $> 2$ and `tensorflow` is not installed.
    """
    scaler = MinMaxScaler()
    X_before_scaled = scaler.fit_transform(self.X_before)
    X_after_scaled = scaler.transform(self.X_after)

    is_2d = self.X_before.shape[1] == 2

    if is_2d:
        ssnp: Any = DummyProjector()
    else:
        try:
            from stride.xai.boundary.ssnp import SSNP

            # One projection trained on both windows: a projection trained on the before window
            # alone decodes only before-like points, so the post-drift map loses fidelity when
            # the after data moves away from them.
            ssnp = SSNP(epochs=ssnp_epochs, patience=ssnp_patience, verbose=0)
            ssnp.fit(
                np.vstack([X_before_scaled, X_after_scaled]),
                np.concatenate([self.y_before, self.y_after]),
            )
        except Exception as err:
            raise OptionalDependencyError(
                package_name="tensorflow",
                feature_name="High-dimensional decision boundary projection (SSNP)",
                extra_name="deeplearning",
            ) from err

    X_before_2d = ssnp.transform(X_before_scaled)
    X_after_2d = ssnp.transform(X_after_scaled)

    if model_class is None:
        from stride.models.mlp import MLPModel

        model_class = MLPModel

    if model_params is None:
        model_params = {}

    model_params["random_state"] = self.random_state

    def process_window(
        X_train: np.ndarray, y_train: np.ndarray, X_2d_train: np.ndarray, grid_bounds: Any = None
    ) -> dict[str, Any]:
        clf = model_class(**model_params)
        clf.fit(X_train, y_train)

        if grid_bounds is None:
            xmin, xmax = float(np.min(X_2d_train[:, 0])), float(np.max(X_2d_train[:, 0]))
            ymin, ymax = float(np.min(X_2d_train[:, 1])), float(np.max(X_2d_train[:, 1]))
            x_margin = (xmax - xmin) * 0.1
            y_margin = (ymax - ymin) * 0.1
            bounds = (xmin - x_margin, xmax + x_margin, ymin - y_margin, ymax + y_margin)
        else:
            bounds = grid_bounds

        xmin, xmax, ymin, ymax = bounds

        x_intrvls = np.linspace(xmin, xmax, num=grid_size)
        y_intrvls = np.linspace(ymin, ymax, num=grid_size)

        xx, yy = np.meshgrid(x_intrvls, y_intrvls)
        pts = np.c_[xx.ravel(), yy.ravel()]

        batch_size = 50000
        n_pts = len(pts)

        probs_list = []
        labels_list = []

        for i in range(0, n_pts, batch_size):
            batch_pts = pts[i : i + batch_size]
            batch_high_dim = ssnp.inverse_transform(batch_pts)

            batch_probs = clf.predict_proba(batch_high_dim)
            batch_labels = clf.predict(batch_high_dim)

            if hasattr(batch_probs, "max"):
                batch_alpha = batch_probs.max(axis=1)
            else:
                batch_alpha = np.ones(len(batch_labels))

            probs_list.append(batch_alpha)
            labels_list.append(batch_labels)

        probs_flat = np.concatenate(probs_list)
        labels_flat = np.concatenate(labels_list)

        prob_grid = probs_flat.reshape(grid_size, grid_size)
        label_grid = labels_flat.reshape(grid_size, grid_size)

        return {
            "clf": clf,
            "X_train": X_train,
            "y_train": y_train,
            "X_2d": X_2d_train,
            "grid_probs": prob_grid,
            "grid_labels": label_grid,
            "grid_bounds": bounds,
        }

    result_pre = process_window(X_before_scaled, self.y_before, X_before_2d)
    result_post = process_window(X_after_scaled, self.y_after, X_after_2d)

    b = result_post["grid_bounds"]
    x_intrvls = np.linspace(b[0], b[1], num=grid_size)
    y_intrvls = np.linspace(b[2], b[3], num=grid_size)
    xx, yy = np.meshgrid(x_intrvls, y_intrvls)
    pts_2d = np.c_[xx.ravel(), yy.ravel()]

    X_grid_high_scaled = ssnp.inverse_transform(pts_2d)

    disagreement_results = compute_disagreement_analysis(
        clf_pre=result_pre["clf"],
        clf_post=result_post["clf"],
        X_eval_raw=self.X_after,
        X_eval_scaled=X_after_scaled,
        X_grid_high_scaled=X_grid_high_scaled,
        feature_names=feature_names,
        scaler=scaler,
    )

    return {
        "pre": result_pre,
        "post": result_post,
        "ssnp_model": ssnp,
        "grid_size": grid_size,
        "disagreement": disagreement_results,
        "is_2d": is_2d,
    }

compute_disagreement_analysis

compute_disagreement_analysis(
    clf_pre,
    clf_post,
    X_eval_raw,
    X_eval_scaled,
    X_grid_high_scaled=None,
    feature_names=None,
    scaler=None,
)

Computes disagreement using the Inverse-Projected Grid (SDBM approach) to ensure visual consistency between the table and the plot.

Source code in src/stride/xai/boundary/disagreement.py
def compute_disagreement_analysis(
    clf_pre, clf_post, X_eval_raw, X_eval_scaled, X_grid_high_scaled=None, feature_names=None, scaler=None
):
    """
    Computes disagreement using the Inverse-Projected Grid (SDBM approach) to ensure
    visual consistency between the table and the plot.
    """
    if feature_names is None:
        if hasattr(X_eval_raw, "columns"):
            feature_names = list(X_eval_raw.columns)
        else:
            feature_names = [f"Feature {i}" for i in range(X_eval_raw.shape[1])]

    # 1. Real Drift Rate (based on actual data samples)
    pred_pre = clf_pre.predict(X_eval_scaled)
    pred_post = clf_post.predict(X_eval_scaled)
    y_delta_real = (pred_pre != pred_post).astype(int)
    drift_rate_real = np.mean(y_delta_real)

    if drift_rate_real == 0:
        return {"drift_rate": 0.0, "disagreement_table": None, "drift_leaf_ids": [], "viz_tree": None}

    # 2. Train Visualization Tree
    if X_grid_high_scaled is not None:
        grid_pred_pre = clf_pre.predict(X_grid_high_scaled)
        grid_pred_post = clf_post.predict(X_grid_high_scaled)
        y_delta_grid = (grid_pred_pre != grid_pred_post).astype(int)

        X_train_tree = X_grid_high_scaled
        y_train_tree = y_delta_grid
    else:
        # Fallback to data if grid not provided
        X_train_tree = X_eval_scaled
        y_train_tree = y_delta_real

    # Train Tree
    viz_tree = DecisionTreeClassifier(max_depth=4, min_samples_leaf=0.01, class_weight="balanced", random_state=42)
    viz_tree.fit(X_train_tree, y_train_tree)

    # 3. Generate Rules
    df_rules, drift_leaf_ids = get_disagreement_table(
        viz_tree, feature_names, X_raw=X_eval_raw, X_scaled=X_eval_scaled, scaler=scaler
    )

    return {
        "drift_rate": drift_rate_real,  # Metric from real data
        "disagreement_table": df_rules,
        "drift_leaf_ids": drift_leaf_ids,
        "viz_tree": viz_tree,
    }