Recourse methods#

class method.method_object.MethodObject(target_model, seed=None, device='cpu', desired_class=None, **kwargs)[source]#

Bases: ABC

Base 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() and get_counterfactuals(); the inherited predict() wraps the raw counterfactual dataframe into a frozen counterfactual DatasetObject and attaches runtime, prediction, and target-label metadata.

Parameters:
_need_grad#

Whether the method requires a differentiable target model.

Type:

bool

_desired_class#

Target class for recourse. None means “flip” for binary problems and “keep current label” otherwise.

Type:

int or str or None

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 = True in __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 with NaN.

Return type:

pandas.DataFrame

counterfactual_set_metadata(factual_index, feature_columns)[source]#
Parameters:
Return type:

dict[str, object] | None

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 carry NaN features and target -1. The returned object also stores runtime_seconds, runtime_total_seconds, factual_prediction_index, target_prediction_index, and (when desired_class is set) an evaluation_filter.

Parameters:
Returns:

A frozen counterfactual dataset aligned to testset.

Return type:

DatasetObject

Raises: