Optimal Counterfactual Explanations in Tree Ensembles
ocean is a full package dedicated to counterfactual explanations for tree ensembles.
The mixed-integer programming (MIP) formulation builds on
Parmentier and Vidal (2021), Optimal Counterfactual Explanations in Tree Ensembles.
The constraint programming (CP) formulation is presented in
Khouna et al. (2026), Optimal Counterfactual Search in Tree Ensembles: A Study Across Modeling and Solution Paradigms.
The package also includes a weighted MaxSAT backend for exact counterfactual
search on the same parsed tree ensembles.
Installation
You can install the package with the following command:
pip install oceanpy
Note : The MIP method requires the gurobi solver access. You can request for a free academic license here. Once you have installed gurobi, you can install the package with the command above. However, you can also use the CP method without gurobi.
From prediction to possibility
Explore the visual examples, try the quickstart, or contribute an idea.
Usage
The package provides multiple classes and functions to wrap the tree ensemble models from the scikit-learn library. A minimal example is provided below:
from sklearn.ensemble import RandomForestClassifier
from ocean import (
ConstraintProgrammingExplainer,
MaxSATExplainer,
MixedIntegerProgramExplainer,
)
from ocean.datasets import load_adult
# Load the adult dataset
(data, target), mapper = load_adult()
# Select an instance to explain from the dataset
x = data.iloc[0].to_frame().T
# Train a random forest classifier
rf = RandomForestClassifier(n_estimators=10, max_depth=3, random_state=42)
rf.fit(data, target)
# Predict the class of the selected instance
y = int(rf.predict(x).item())
x = x.to_numpy().flatten()
# Explain the prediction using the MIP backend
mip_model = MixedIntegerProgramExplainer(rf, mapper=mapper)
mip_explanation = mip_model.explain(
x, y=1 - y, norm=1, num_workers=1, random_seed=42
)
# Explain the prediction using the CP backend
cp_model = ConstraintProgrammingExplainer(rf, mapper=mapper)
cp_explanation = cp_model.explain(
x, y=1 - y, norm=1, num_workers=1, random_seed=42
)
# Explain the prediction using the MaxSAT backend
maxsat_model = MaxSATExplainer(rf, mapper=mapper)
maxsat_explanation = maxsat_model.explain(
x, y=1 - y, norm=1, num_workers=1, random_seed=42
)
Output for Adult row 0, predicted class 0, targeting class 1.
The Type column shows the encoding used by the dataset loader; bold
values differ from the query. Category labels are decoded for readability using
the Adult label mapping, verified against the
original UCI Adult data.
NativeCountry is binary in this dataset: United States versus other countries.
| Feature | Type | Query | MIP | CP | MaxSAT |
|---|---|---|---|---|---|
| Age | Discrete | 39 | 39 | 39 | 39 |
| CapitalGain | Continuous | 2174 | 2174 | 2174 | 2174 |
| CapitalLoss | Continuous | 0 | 0 | 0 | 0 |
| EducationNumber | Continuous | 13 | 13 | 13 | 13 |
| HoursPerWeek | Discrete | 40 | 40 | 40 | 40 |
| MaritalStatus | Categorical (one-hot) | Never married | Married (civilian spouse) | Married (civilian spouse) | Married (civilian spouse) |
| NativeCountry | Binary | United States | United States | United States | United States |
| Occupation | Categorical (one-hot) | Administrative / clerical | Professional specialty | Administrative / clerical | Administrative / clerical |
| Relationship | Categorical (one-hot) | Not in family | Husband | Husband | Husband |
| Sex | Binary | Male | Male | Male | Male |
| WorkClass | Categorical (one-hot) | State government | State government | Self-employed (incorporated) | Self-employed (incorporated) |
| Objective value (L1) | — | 3.0 | 3.0 | 3.0 | |
The objective row reports each backend's get_objective_value() for norm=1.
Feature values are rounded to six decimal places and objectives to one decimal
place; solvers may select different tied solutions. Each one-hot category change
counts as one unit of distance, so all three unrestricted objectives are 3.0. Run examples/readme.py to regenerate both tables
and verify that the explanations reach the target class.
Actionability (CP and MIP)
The unrestricted explanations above change MaritalStatus and Relationship.
For the same query, fix those features, Sex, and NativeCountry, and allow
Age, EducationNumber, and HoursPerWeek only to increase or stay unchanged:
from ocean.typing import Actionability
rules: Actionability = {
"Age": "increase",
"EducationNumber": "increase",
"HoursPerWeek": "increase",
"Sex": "fixed",
"NativeCountry": "fixed",
"MaritalStatus": "fixed",
"Relationship": "fixed",
}
mip_explanation = mip_model.explain(
x, y=1 - y, norm=1, actionability=rules, num_workers=1, random_seed=42
)
cp_explanation = cp_model.explain(
x, y=1 - y, norm=1, actionability=rules, num_workers=1, random_seed=42
)
Both explanations now keep the fixed features unchanged and increase
HoursPerWeek from 40 to 44. They also change the unrestricted features
CapitalGain, CapitalLoss, and WorkClass, at a higher objective value.
MaxSAT does not support actionability for now, so its entries are marked unavailable.
| Feature | Type | Query | MIP | CP | MaxSAT (unsupported) |
|---|---|---|---|---|---|
| Age | Discrete | 39 | 39 | 39 | — |
| CapitalGain | Continuous | 2174 | 5119.000488 | 5119.000488 | — |
| CapitalLoss | Continuous | 0 | 1820.500122 | 1820.500122 | — |
| EducationNumber | Continuous | 13 | 13 | 13 | — |
| HoursPerWeek | Discrete | 40 | 44 | 44 | — |
| MaritalStatus | Categorical (one-hot) | Never married | Never married | Never married | — |
| NativeCountry | Binary | United States | United States | United States | — |
| Occupation | Categorical (one-hot) | Administrative / clerical | Administrative / clerical | Administrative / clerical | — |
| Relationship | Categorical (one-hot) | Not in family | Not in family | Not in family | — |
| Sex | Binary | Male | Male | Male | — |
| WorkClass | Categorical (one-hot) | State government | Self-employed (incorporated) | Self-employed (incorporated) | — |
| Objective value (L1) | — | 4770.5 | 4770.5 | — | |
fixed preserves the input value; increase and decrease allow equality.
Omitted features are unrestricted. One-hot groups support fixed using the
original group name. Rules apply to decoded values in the processed feature
space and are removed by the default query cleanup, including after an
infeasible solve. See the explainer guide for details.
See the examples folder or the documentation for more usage examples.
Feature Preview & Roadmap
| Area | Status | Notes / References |
|---|---|---|
| MIP formulation | ✅ Done | Based on Parmentier & Vidal (2021). |
| Constraint Programming (CP) | ✅ Done | Based on Khouna et al. (2026). |
| MaxSAT formulation | ✅ Done | Based on Raevskaya & Lehtonen (2025). |
| Heuristics | ⏳ Upcoming | Fast approximate methods. |
| Other methods | ⏳ Upcoming | Additional formulations under exploration. |
| AdaBoost support | ✅ Ready | Fully supported in ocean. |
| Random Forest support | ✅ Ready | Fully supported in ocean. |
| XGBoost support | ✅ Ready | Fully supported in ocean. |
Legend: ✅ available · ⏳ upcoming
Citation
If you use OCEAN in your research, please cite the three main papers:
@misc{khouna2026optimalcounterfactualsearch,
title = {Optimal Counterfactual Search in Tree Ensembles: A Study Across Modeling and Solution Paradigms},
author = {Khouna, Awa and Emine, Youssouf and Ferry, Julien and Vidal, Thibaut},
year = {2026},
eprint = {2605.06561},
archivePrefix = {arXiv},
primaryClass = {cs.LG},
doi = {10.48550/arXiv.2605.06561},
url = {https://arxiv.org/abs/2605.06561}
}
@inproceedings{pmlr-v139-parmentier21a,
title = {Optimal Counterfactual Explanations in Tree Ensembles},
author = {Parmentier, Axel and Vidal, Thibaut},
booktitle = {Proceedings of the 38th International Conference on Machine Learning},
pages = {8422--8431},
year = {2021},
editor = {Meila, Marina and Zhang, Tong},
volume = {139},
series = {Proceedings of Machine Learning Research},
publisher = {PMLR},
url = {https://proceedings.mlr.press/v139/parmentier21a.html}
}
@article{faia250895,
title = {Optimal Counterfactual Explanations for Random Forests with MaxSAT},
author = {Raevskaya, Alesya and Lehtonen, Tuomo},
journal = {Frontiers in Artificial Intelligence and Applications},
volume = {350},
pages = {1--12},
year = {2025},
doi = {10.3233/FAIA250895},
url = {https://doi.org/10.3233/FAIA250895}
}
References
-
Awa Khouna, Youssouf Emine, Julien Ferry, and Thibaut Vidal. 2026. Optimal Counterfactual Search in Tree Ensembles: A Study Across Modeling and Solution Paradigms. arXiv:2605.06561. arXiv.
-
Axel Parmentier and Thibaut Vidal. 2021. Optimal Counterfactual Explanations in Tree Ensembles. Proceedings of the 38th International Conference on Machine Learning, PMLR 139:8422–8431. PMLR.
-
Raevskaya, Alesya & Lehtonen, Tuomo. (2025). Optimal Counterfactual Explanations for Random Forests with MaxSAT. 10.3233/FAIA250895. Available here.
Metadata
Release files for oceanpy 2.0.8
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| oceanpy-2.0.8.tar.gz | 366.7 kB | With provenance | Details for oceanpy-2.0.8.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| oceanpy-2.0.8-py3-none-any.whl | Python 3 | none | any | Details for oceanpy-2.0.8-py3-none-any.whl |
Total release size: 457.0 kB
Release files / oceanpy-2.0.8.tar.gz
| Download URL | oceanpy-2.0.8.tar.gz |
|---|---|
| Size | 366.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b2f9a1a27b21389f15b6e8c5954a0c99314d9dbd62fb33350a5f40dd69087f94
|
|
BLAKE2b-256 checksum How to use checksums |
15f4ce5cf70fcb7187cd454817d89e747072e073e5b6225b2900a7a1931ba19e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.
Transparency logRelease files / oceanpy-2.0.8-py3-none-any.whl
| Download URL | oceanpy-2.0.8-py3-none-any.whl |
|---|---|
| Size | 90.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6a5e9c9849b1af81c252001aa68f45461af1c437d2fe00d696a0dbe6bb47ebb0
|
|
BLAKE2b-256 checksum How to use checksums |
fa88dad5dede553284a9be4ce5af2ce7ad9dc6e646fbbd274e34aec9cb5d2a28
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.
Transparency logSecurity for oceanpy 2.0.8
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for oceanpy-2.0.8.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 10, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.