Skip to content

GLANCE

Group-Level Anchor-based Counterfactual Explanations

GLANCE uses anchors to define groups and generate group-level counterfactuals.

Overview

GLANCE identifies anchor points that define natural groupings and generates counterfactuals applicable to each group.

Usage

from counterfactuals.cf_methods.group_methods import GLANCE

method = GLANCE(
    gen_model=gen_model,
    disc_model=classifier,
    disc_model_criterion=criterion,
    device="cuda"
)

result = method.explain(
    X=X_test,
    y_origin=y_test,
    y_target=target_class,
    X_train=X_train,
    y_train=y_train
)

API Reference

GLANCE

GLANCE(X_test, y_test, model, features, k=-1, s=4, m=1)
Source code in counterfactuals/cf_methods/group_methods/glance/glance.py
def __init__(
    self,
    X_test,
    y_test,
    model,
    features,
    k: int = -1,
    s: int = 4,
    m: int = 1,
) -> None:
    self.features = features
    self.model = model
    self.X = X_test[y_test != 1]
    self.Y = y_test[y_test != 1]
    self.n = len(self.X)

    self.k = k if k > 0 else self.n  # starting number of a groups
    self.s = s
    self.m = m

__merge_clusters

__merge_clusters(_c1, _c2, actions)

Merge two clusters by averaging their centroids, updating the labels and merging the actions

Source code in counterfactuals/cf_methods/group_methods/glance/glance.py
def __merge_clusters(self, _c1: tuple, _c2: tuple, actions: dict) -> dict:
    """Merge two clusters by averaging their centroids, updating the labels and merging the actions"""
    new_centroid = (np.array(_c1[0]) + np.array(_c2[0])) / 2
    new_label = self.k
    self.k += 1

    c1_action_set = actions[_c1]
    c2_action_set = actions[_c2]

    assert isinstance(c1_action_set, set)
    assert isinstance(c2_action_set, set)

    merged_actions = c1_action_set.union(c2_action_set)

    # Remove from actions
    del actions[_c1]
    del actions[_c2]

    # Add the new cluster
    actions[(tuple(new_centroid), new_label)] = merged_actions

get_clusters

get_clusters()

Returns the final clusters as a list of tuples

Each tuple contains: - The centroid of the cluster - The label of the cluster - The average action of the cluster (centroid + action = counterfactual)

Source code in counterfactuals/cf_methods/group_methods/glance/glance.py
def get_clusters(self) -> list[tuple]:
    """
    Returns the final clusters as a list of tuples

    Each tuple contains:
    - The centroid of the cluster
    - The label of the cluster
    - The average action of the cluster (centroid + action = counterfactual)
    """
    return self.final_clusters