Recourse methods#
- class method.method_object.MethodObject(target_model, seed=None, device='cpu', desired_class=None, **kwargs)[source]#
Bases:
ABCBase class for an algorithmic recourse method.
A method wraps a trained target model and generates counterfactuals that flip (or move toward) a desired class. Subclasses implement
fit()andget_counterfactuals(); the inheritedpredict()wraps the raw counterfactual dataframe into a frozen counterfactualDatasetObjectand attaches runtime, prediction, and target-label metadata.- Parameters:
target_model (ModelObject)
seed (int | None)
device (str)
- _desired_class#
Target class for recourse.
Nonemeans “flip” for binary problems and “keep current label” otherwise.
- abstractmethod fit(trainset)[source]#
Fit the method (train auxiliary models, build search structures).
- Parameters:
trainset (DatasetObject or None) – Finalized training data. Methods that need no training should set
self._is_trained = Truein__init__; otherwise set it here.
- abstractmethod get_counterfactuals(factuals)[source]#
Generate counterfactuals for a batch of factual rows.
- Parameters:
factuals (pandas.DataFrame) – Feature rows to explain (no target column).
- Returns:
Same rows and feature columns as
factuals. Rows with no valid counterfactual must be filled withNaN.- Return type:
- predict(testset, batch_size=20)[source]#
Generate counterfactuals over a dataset and package the result.
Calls
get_counterfactuals()in batches, validates that row count and feature columns are preserved, and returns a frozen counterfactual dataset. Failed rows carryNaNfeatures and target-1. The returned object also storesruntime_seconds,runtime_total_seconds,factual_prediction_index,target_prediction_index, and (whendesired_classis set) anevaluation_filter.- Parameters:
testset (DatasetObject) – Frozen factual dataset. Must not already be a counterfactual dataset.
batch_size (int, default 20) – Factual rows per call to
get_counterfactuals().
- Returns:
A frozen counterfactual dataset aligned to
testset.- Return type:
- Raises:
RuntimeError – If the method is not trained.
ValueError – If
batch_size < 1,testsetis already a counterfactual, orget_counterfactuals()does not preserve rows/columns.