API Reference¶
Complete API documentation for the Counterfactuals library.
The API reference documentation is auto-generated from source code docstrings.
Core Modules¶
Counterfactual Methods¶
The main counterfactual explanation methods.
counterfactual_base
¶
ExplanationResult
dataclass
¶
Data structure for storing the result of a counterfactual explanation.
This dataclass encapsulates all the important outputs from a counterfactual explanation process, including the generated counterfactuals, their targets, the original instances, and any additional logging information.
Attributes:
| Name | Type | Description |
|---|---|---|
x_cfs |
ndarray
|
Generated counterfactual examples. |
y_cf_targets |
ndarray
|
Target labels/values for the counterfactuals. |
x_origs |
ndarray
|
Original input instances. |
y_origs |
ndarray
|
Original labels/values for the input instances. |
logs |
Optional[Dict[str, Any]]
|
Additional logging information such as loss curves, convergence metrics, or method-specific data. |
BaseCounterfactualMethod
¶
BaseCounterfactualMethod(gen_model=None, disc_model=None, disc_model_criterion=None, device=None, **kwargs)
Bases: ABC
Abstract base class for all counterfactual explanation methods.
This class defines the interface that all counterfactual methods must implement. It provides a consistent API for fitting, explaining, and generating counterfactuals across different methodological approaches.
The class supports both individual explanations and batch processing through DataLoader objects, making it suitable for various use cases from single instance explanations to large-scale evaluations.
Attributes:
| Name | Type | Description |
|---|---|---|
gen_model |
Generative model used for counterfactual generation (if applicable). |
|
disc_model |
PytorchBase
|
Discriminative/classification model to be explained. |
disc_model_criterion |
Loss function for the discriminative model. |
|
device |
str
|
Computing device ('cpu' or 'cuda') for PyTorch operations. |
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen_model
|
Optional[Any]
|
Generative model for CF generation. Can be None for methods that don't use generative models. |
None
|
disc_model
|
Optional[PytorchBase]
|
The model to be explained. Should be a PyTorch-based model wrapped in our PytorchBase interface. |
None
|
disc_model_criterion
|
Optional[Any]
|
Loss function for the discriminative model. Required by optimization-based methods. |
None
|
device
|
Optional[str]
|
Device for computation. Defaults to 'cpu'. |
None
|
**kwargs
|
Additional method-specific parameters. |
{}
|
Source code in counterfactuals/cf_methods/counterfactual_base.py
fit
¶
Fit the counterfactual method on training data.
This method allows the counterfactual explanation method to learn from training data. This might involve training auxiliary models, learning data distributions, or other preparatory steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_train
|
ndarray
|
Training features with shape (n_samples, n_features). |
required |
y_train
|
ndarray
|
Training labels with shape (n_samples,). |
required |
**kwargs
|
Additional method-specific parameters. |
{}
|
Source code in counterfactuals/cf_methods/counterfactual_base.py
explain
abstractmethod
¶
Generate counterfactual explanations for given instances.
This is the core method that generates counterfactual explanations for input instances. It should return counterfactuals that, when passed through the model, produce the desired target outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray
|
Input instances to explain with shape (n_instances, n_features). |
required |
y_origin
|
ndarray
|
Original predictions/labels for X with shape (n_instances,). |
required |
y_target
|
ndarray
|
Desired target predictions/labels with shape (n_instances,). |
required |
X_train
|
Optional[ndarray]
|
Training data, if needed by the method. |
None
|
y_train
|
Optional[ndarray]
|
Training labels, if needed by the method. |
None
|
**kwargs
|
Additional method-specific parameters. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
ExplanationResult |
ExplanationResult
|
Object containing counterfactuals, targets, originals, and any additional logging information. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the method is not implemented by the subclass. |
Source code in counterfactuals/cf_methods/counterfactual_base.py
explain_dataloader
abstractmethod
¶
Generate counterfactual explanations for data provided via DataLoader.
This method is designed for batch processing of counterfactual generation, particularly useful for optimization-based methods that require iterative search procedures. It processes data in batches and typically involves gradient-based optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataloader
|
DataLoader
|
PyTorch DataLoader containing (X, y) pairs where X are instances to explain and y are their labels. |
required |
epochs
|
int
|
Maximum number of optimization epochs per instance. |
required |
lr
|
float
|
Learning rate for optimization procedures. |
required |
patience_eps
|
Union[float, int]
|
Convergence threshold. When loss drops below this value, optimization can terminate early. |
1e-05
|
**search_step_kwargs
|
Additional parameters passed to the search step function, such as regularization weights, constraints, etc. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
ExplanationResult |
ExplanationResult
|
Object containing all generated counterfactuals, their targets, original instances, and detailed logging information including loss curves and convergence metrics. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the method is not implemented by the subclass. |
Source code in counterfactuals/cf_methods/counterfactual_base.py
Datasets¶
Dataset loading and configuration utilities.
file_dataset
¶
FileDataset
¶
Bases: DatasetBase
File dataset loader compatible with DatasetBase.
config_path: Path to the dataset configuration file.
dataset_name: Optional name for the dataset (used for model paths).
Source code in counterfactuals/datasets/file_dataset.py
preprocess
¶
Preprocesses raw data into feature and target arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw_data
|
DataFrame
|
Raw dataset as a pandas DataFrame. |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
Tuple (X, y) as numpy arrays. |
Source code in counterfactuals/datasets/file_dataset.py
Models¶
Classifiers¶
logistic_regression
¶
multilayer_perceptron
¶
Generative Models¶
kde
¶
Implementations of various mixture models.
GenerativeModel
¶
Bases: ABC, Module
Base class inherited by all generative models in pytorch-generative.
Provides
- An abstract
sample()method which is implemented by subclasses that support generating samples. - Variables
self._c, self._h, self._wwhich store the shape of the (first) image Tensor the model was trained with. Note thatforward()must have been called at least once and the input must be an image for these variables to be available. - A
deviceproperty which returns the device of the model's parameters.
__call__
¶
Saves input tensor attributes so they can be accessed during sampling.
Source code in counterfactuals/models/generative/kde.py
load_state_dict
¶
Registers dynamic buffers before loading the model state.
Source code in counterfactuals/models/generative/kde.py
Kernel
¶
Bases: ABC, Module
Base class which defines the interface for all kernels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bandwidth
|
The kernel's (band)width. |
1.0
|
Source code in counterfactuals/models/generative/kde.py
forward
abstractmethod
¶
ParzenWindowKernel
¶
GaussianKernel
¶
KernelDensityEstimator
¶
Bases: GenerativeModel
The KernelDensityEstimator model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_Xs
|
The "training" data to use when estimating probabilities. |
required | |
kernel
|
The kernel to place on each of the train_Xs. |
None
|
Source code in counterfactuals/models/generative/kde.py
KDE
¶
Bases: PytorchBase, GenerativePytorchMixin
Source code in counterfactuals/models/generative/kde.py
forward
¶
Forward pass with optional context for compatibility.
Source code in counterfactuals/models/generative/kde.py
predict_log_proba
¶
Predict log probabilities for input data.
Source code in counterfactuals/models/generative/kde.py
sample_and_log_proba
¶
Sample from KDE and return log probabilities.
auto_reshape
¶
Decorator which flattens image inputs and reshapes them before returning.
This is used to enable non-convolutional models to transparently work on images.
Source code in counterfactuals/models/generative/kde.py
Quick Links¶
For method-specific API documentation, see: