Saltar al contenido principal

NearestCounterfactual

LocalExplainer
DashAI.back.explainability.explainers.NearestCounterfactual

Case-based counterfactual explainer for tabular classification.

For each instance to explain, this explainer answers "what would have to be different for the model to predict another class?" by retrieving the nearest real training examples that the model classifies differently (nearest unlike neighbors). Because counterfactuals are actual dataset rows, they are always plausible and never out of distribution, unlike synthetic perturbation-based counterfactuals.

The explainer is fully model agnostic: it only queries predict.

References

Parameters

n_counterfactuals : integer, default=3
Number of counterfactual examples to retrieve for each instance. Each counterfactual is a real training example that the model classifies differently.
distance : string, default=l1
Distance used to rank candidate counterfactuals. Numeric features are normalized by their range; non-numeric features add a constant penalty when they differ.

Methods

explain_instance(self, instances)

Defined on NearestCounterfactual

Retrieve the nearest counterfactual examples for each instance.

Parameters

instances : DatasetDict
Instances to be explained.

Returns

dict
Dictionary with, for each instance, the model prediction and the retrieved counterfactual examples.

fit(self, background_dataset, **kwargs)

Defined on NearestCounterfactual

Store the background data and its model predictions.

Parameters

background_dataset : Tuple[DatasetDict, DatasetDict]
Tuple (x, y) with the dataset splits. The train split is used as the pool of counterfactual candidates.
**kwargs : Any
Ignored; present for interface compatibility.

Returns

NearestCounterfactual
The fitted explainer instance (self).

plot(self, explanation: dict) -> List[DashAI.back.core.artifacts.GroupedArtifacts]

Defined on NearestCounterfactual

Render each instance as a comparison table plus a text summary.

Parameters

explanation : dict
Dictionary with the explanation generated by the explainer.

Returns

List[GroupedArtifacts]
A single grouped artifact with one group per explained instance, each holding that instance's comparison table and text summary.

get_schema(cls) -> dict

Defined on ConfigObject

Generates the component related Json Schema.

Returns

dict
Dictionary representing the Json Schema of the component.

validate_and_transform(self, raw_data: dict) -> dict

Defined on ConfigObject

It takes the data given by the user to initialize the model and returns it with all the objects that the model needs to work.

Parameters

raw_data : dict
A dictionary with the data provided by the user to initialize the model.

Returns

dict
A validated dictionary with the necessary objects.

Compatible with