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
- [1] Wachter, S., Mittelstadt, B. & Russell, C. (2017). "Counterfactual Explanations without Opening the Black Box." Harvard JOLT 31(2). https://arxiv.org/abs/1711.00399
- [2] Keane, M.T. & Smyth, B. (2020). "Good Counterfactuals and Where to Find Them." ICCBR 2020. https://arxiv.org/abs/2005.13997
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)
NearestCounterfactualRetrieve 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)
NearestCounterfactualStore 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]
NearestCounterfactualRender 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
ConfigObjectGenerates the component related Json Schema.
Returns
- dict
- Dictionary representing the Json Schema of the component.
validate_and_transform(self, raw_data: dict) -> dict
ConfigObjectIt 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.