CounterfactUS 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- counterfactus-0.1.0/LICENSE +21 -0
- counterfactus-0.1.0/PKG-INFO +142 -0
- counterfactus-0.1.0/README.md +92 -0
- counterfactus-0.1.0/pyproject.toml +42 -0
- counterfactus-0.1.0/setup.cfg +4 -0
- counterfactus-0.1.0/src/CounterfactUS.egg-info/PKG-INFO +142 -0
- counterfactus-0.1.0/src/CounterfactUS.egg-info/SOURCES.txt +14 -0
- counterfactus-0.1.0/src/CounterfactUS.egg-info/dependency_links.txt +1 -0
- counterfactus-0.1.0/src/CounterfactUS.egg-info/requires.txt +7 -0
- counterfactus-0.1.0/src/CounterfactUS.egg-info/top_level.txt +1 -0
- counterfactus-0.1.0/src/counterfactus/__init__.py +5 -0
- counterfactus-0.1.0/src/counterfactus/covariance_GPLSIM.py +312 -0
- counterfactus-0.1.0/src/counterfactus/fit_GPLSIM.py +412 -0
- counterfactus-0.1.0/src/counterfactus/main.py +1047 -0
- counterfactus-0.1.0/src/counterfactus/solver.py +587 -0
- counterfactus-0.1.0/tests/test_main.py +155 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Antonio Navas Orozco
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: CounterfactUS
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Optimal and robust counterfactual explanations
|
|
5
|
+
Author-email: Antonio Navas Orozco <anavas1@us.es>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 Antonio Navas Orozco
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/antnavoro/CounterfactUS
|
|
29
|
+
Project-URL: Repository, https://github.com/antnavoro/CounterfactUS
|
|
30
|
+
Project-URL: Bug Tracker, https://github.com/antnavoro/CounterfactUS/issues
|
|
31
|
+
Classifier: Programming Language :: Python :: 3
|
|
32
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
33
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Operating System :: OS Independent
|
|
37
|
+
Classifier: Intended Audience :: Science/Research
|
|
38
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
39
|
+
Requires-Python: >=3.9
|
|
40
|
+
Description-Content-Type: text/markdown
|
|
41
|
+
License-File: LICENSE
|
|
42
|
+
Requires-Dist: numpy
|
|
43
|
+
Requires-Dist: pandas
|
|
44
|
+
Requires-Dist: matplotlib
|
|
45
|
+
Requires-Dist: seaborn
|
|
46
|
+
Requires-Dist: scipy
|
|
47
|
+
Requires-Dist: rpy2
|
|
48
|
+
Requires-Dist: gurobipy
|
|
49
|
+
Dynamic: license-file
|
|
50
|
+
|
|
51
|
+
# CounterfactUS: Optimal & Robust Counterfactual Explanations
|
|
52
|
+
|
|
53
|
+
**CounterfactUS** is a Python library designed to generate optimal and robust counterfactual explanations for predictive models. It formulates the counterfactual generation as a Mixed-Integer Programming (MIP) problem, allowing for exact counterfactuals.
|
|
54
|
+
|
|
55
|
+
## 🚀 Key Features
|
|
56
|
+
|
|
57
|
+
* **Model Support:** Designed for Generalized Partially Linear Single-Index Models (GPLSIM), including special subcases like Single-Index Models (SIM) and Generalized Linear Models (GLM). (Uses R's `mgcv` and `gplsim` internally).
|
|
58
|
+
* **Optimal Explanations:** Uses Gurobi as an optimization backend to find counterfactuals that minimize distance exactly, rather than relying on heuristics.
|
|
59
|
+
* **Statistical Robustness:** Provides ground-truth model guarantees by enforcing prediction thresholds within a user-defined *confidence level*.
|
|
60
|
+
* **Highly Customizable Constraints:**
|
|
61
|
+
* **Distance Metrics:** Support for L1, L2, Gower, and combined L0+L1 distances.
|
|
62
|
+
* **Sparsity (L0):** Limit the maximum number of features that can be modified.
|
|
63
|
+
* **Immutability & Bounds:** Prevent specific features (e.g., *Age*, *Race*) from changing or restrict their allowable ranges.
|
|
64
|
+
* **Directional Weights:** Assign different weights to increasing or decreasing specific features.
|
|
65
|
+
* **Linear Constraints:** Define linear relationships (e.g., $X_1 + X_2 \le b$).
|
|
66
|
+
* **Automated Preprocessing:** Automatically infers feature types (binary, categorical, continuous), normalizes data, and handles one-hot encoding internally.
|
|
67
|
+
|
|
68
|
+
## 📦 Installation
|
|
69
|
+
|
|
70
|
+
This package requires Python 3.9+ and an active Gurobi license (or academic license) to solve the MIP problems. Additionally, it requires an R installation with the `mgcv` and `gplsim` packages available.
|
|
71
|
+
|
|
72
|
+
You can install the package directly via pip:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install CounterfactUS
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
*Note: Ensure that your system's R environment is accessible to Python via `rpy2`.*
|
|
79
|
+
|
|
80
|
+
## 💡 Quick Start
|
|
81
|
+
|
|
82
|
+
Generating counterfactuals is as simple as calling the `compute_counterfactuals` function.
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
import pandas as pd
|
|
86
|
+
from counterfactus import compute_counterfactuals
|
|
87
|
+
|
|
88
|
+
# 1. Load your dataset
|
|
89
|
+
X_train = pd.DataFrame(...) # Non-parametric features (e.g., continuous variables for GPLSIM)
|
|
90
|
+
Z_train = pd.DataFrame(...) # Linear features (e.g., categorical variables or strict linear effects)
|
|
91
|
+
Y_train = pd.Series(...) # Target variable
|
|
92
|
+
|
|
93
|
+
# 2. Define the query instances you want to explain
|
|
94
|
+
x_queries = pd.DataFrame(...)
|
|
95
|
+
z_queries = pd.DataFrame(...)
|
|
96
|
+
|
|
97
|
+
# 3. Generate counterfactuals
|
|
98
|
+
results_df = compute_counterfactuals(
|
|
99
|
+
X=X_train,
|
|
100
|
+
Z=Z_train,
|
|
101
|
+
Y=Y_train,
|
|
102
|
+
family_name="binomial",
|
|
103
|
+
link_name="logit",
|
|
104
|
+
prediction_threshold=0.5, # Target prediction threshold
|
|
105
|
+
x0s=x_queries,
|
|
106
|
+
z0s=z_queries,
|
|
107
|
+
distance="l1", # Distance metric to minimize
|
|
108
|
+
max_l0=2, # Allow a maximum of 2 feature changes
|
|
109
|
+
confidence_level=0.95, # Ensure 95% statistical confidence in the recourse
|
|
110
|
+
inmutable_z=["Race", "Sex"], # Prevent demographic features from changing
|
|
111
|
+
gurobi_verbose=False
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# 4. View results
|
|
115
|
+
print(results_df)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## ⚙️ Advanced Usage
|
|
119
|
+
|
|
120
|
+
`compute_counterfactuals` handles complex parameter grids natively. You can pass lists to parameters like `prediction_threshold`, `max_l0`, or `confidence_level` to explore the Pareto frontier of counterfactuals.
|
|
121
|
+
|
|
122
|
+
By default, the library computes the Cartesian product of all list parameters. You can change this behavior to iterate through the lists concurrently by setting `use_zip_iteration=True`.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
# Explore trade-offs between sparsity and target threshold
|
|
126
|
+
results = compute_counterfactuals(
|
|
127
|
+
# ... data ...
|
|
128
|
+
prediction_threshold=[0.5, 0.6, 0.7, 0.8],
|
|
129
|
+
max_l0=[1, 2, 3],
|
|
130
|
+
confidence_level=[0.5, 0.90, 0.95],
|
|
131
|
+
)
|
|
132
|
+
# or
|
|
133
|
+
# Automatically generate trade-off plots
|
|
134
|
+
results = compute_counterfactuals(
|
|
135
|
+
# ... data ...
|
|
136
|
+
plot_figures=True
|
|
137
|
+
)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## 📄 License
|
|
141
|
+
|
|
142
|
+
MIT License
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# CounterfactUS: Optimal & Robust Counterfactual Explanations
|
|
2
|
+
|
|
3
|
+
**CounterfactUS** is a Python library designed to generate optimal and robust counterfactual explanations for predictive models. It formulates the counterfactual generation as a Mixed-Integer Programming (MIP) problem, allowing for exact counterfactuals.
|
|
4
|
+
|
|
5
|
+
## 🚀 Key Features
|
|
6
|
+
|
|
7
|
+
* **Model Support:** Designed for Generalized Partially Linear Single-Index Models (GPLSIM), including special subcases like Single-Index Models (SIM) and Generalized Linear Models (GLM). (Uses R's `mgcv` and `gplsim` internally).
|
|
8
|
+
* **Optimal Explanations:** Uses Gurobi as an optimization backend to find counterfactuals that minimize distance exactly, rather than relying on heuristics.
|
|
9
|
+
* **Statistical Robustness:** Provides ground-truth model guarantees by enforcing prediction thresholds within a user-defined *confidence level*.
|
|
10
|
+
* **Highly Customizable Constraints:**
|
|
11
|
+
* **Distance Metrics:** Support for L1, L2, Gower, and combined L0+L1 distances.
|
|
12
|
+
* **Sparsity (L0):** Limit the maximum number of features that can be modified.
|
|
13
|
+
* **Immutability & Bounds:** Prevent specific features (e.g., *Age*, *Race*) from changing or restrict their allowable ranges.
|
|
14
|
+
* **Directional Weights:** Assign different weights to increasing or decreasing specific features.
|
|
15
|
+
* **Linear Constraints:** Define linear relationships (e.g., $X_1 + X_2 \le b$).
|
|
16
|
+
* **Automated Preprocessing:** Automatically infers feature types (binary, categorical, continuous), normalizes data, and handles one-hot encoding internally.
|
|
17
|
+
|
|
18
|
+
## 📦 Installation
|
|
19
|
+
|
|
20
|
+
This package requires Python 3.9+ and an active Gurobi license (or academic license) to solve the MIP problems. Additionally, it requires an R installation with the `mgcv` and `gplsim` packages available.
|
|
21
|
+
|
|
22
|
+
You can install the package directly via pip:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install CounterfactUS
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
*Note: Ensure that your system's R environment is accessible to Python via `rpy2`.*
|
|
29
|
+
|
|
30
|
+
## 💡 Quick Start
|
|
31
|
+
|
|
32
|
+
Generating counterfactuals is as simple as calling the `compute_counterfactuals` function.
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import pandas as pd
|
|
36
|
+
from counterfactus import compute_counterfactuals
|
|
37
|
+
|
|
38
|
+
# 1. Load your dataset
|
|
39
|
+
X_train = pd.DataFrame(...) # Non-parametric features (e.g., continuous variables for GPLSIM)
|
|
40
|
+
Z_train = pd.DataFrame(...) # Linear features (e.g., categorical variables or strict linear effects)
|
|
41
|
+
Y_train = pd.Series(...) # Target variable
|
|
42
|
+
|
|
43
|
+
# 2. Define the query instances you want to explain
|
|
44
|
+
x_queries = pd.DataFrame(...)
|
|
45
|
+
z_queries = pd.DataFrame(...)
|
|
46
|
+
|
|
47
|
+
# 3. Generate counterfactuals
|
|
48
|
+
results_df = compute_counterfactuals(
|
|
49
|
+
X=X_train,
|
|
50
|
+
Z=Z_train,
|
|
51
|
+
Y=Y_train,
|
|
52
|
+
family_name="binomial",
|
|
53
|
+
link_name="logit",
|
|
54
|
+
prediction_threshold=0.5, # Target prediction threshold
|
|
55
|
+
x0s=x_queries,
|
|
56
|
+
z0s=z_queries,
|
|
57
|
+
distance="l1", # Distance metric to minimize
|
|
58
|
+
max_l0=2, # Allow a maximum of 2 feature changes
|
|
59
|
+
confidence_level=0.95, # Ensure 95% statistical confidence in the recourse
|
|
60
|
+
inmutable_z=["Race", "Sex"], # Prevent demographic features from changing
|
|
61
|
+
gurobi_verbose=False
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
# 4. View results
|
|
65
|
+
print(results_df)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## ⚙️ Advanced Usage
|
|
69
|
+
|
|
70
|
+
`compute_counterfactuals` handles complex parameter grids natively. You can pass lists to parameters like `prediction_threshold`, `max_l0`, or `confidence_level` to explore the Pareto frontier of counterfactuals.
|
|
71
|
+
|
|
72
|
+
By default, the library computes the Cartesian product of all list parameters. You can change this behavior to iterate through the lists concurrently by setting `use_zip_iteration=True`.
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
# Explore trade-offs between sparsity and target threshold
|
|
76
|
+
results = compute_counterfactuals(
|
|
77
|
+
# ... data ...
|
|
78
|
+
prediction_threshold=[0.5, 0.6, 0.7, 0.8],
|
|
79
|
+
max_l0=[1, 2, 3],
|
|
80
|
+
confidence_level=[0.5, 0.90, 0.95],
|
|
81
|
+
)
|
|
82
|
+
# or
|
|
83
|
+
# Automatically generate trade-off plots
|
|
84
|
+
results = compute_counterfactuals(
|
|
85
|
+
# ... data ...
|
|
86
|
+
plot_figures=True
|
|
87
|
+
)
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## 📄 License
|
|
91
|
+
|
|
92
|
+
MIT License
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "CounterfactUS"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Optimal and robust counterfactual explanations"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
authors = [
|
|
12
|
+
{ name = "Antonio Navas Orozco", email = "anavas1@us.es" }
|
|
13
|
+
]
|
|
14
|
+
license = { file = "LICENSE" }
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.9",
|
|
18
|
+
"Programming Language :: Python :: 3.10",
|
|
19
|
+
"Programming Language :: Python :: 3.11",
|
|
20
|
+
"License :: OSI Approved :: MIT License",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Intended Audience :: Science/Research",
|
|
23
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
dependencies = [
|
|
27
|
+
"numpy",
|
|
28
|
+
"pandas",
|
|
29
|
+
"matplotlib",
|
|
30
|
+
"seaborn",
|
|
31
|
+
"scipy",
|
|
32
|
+
"rpy2",
|
|
33
|
+
"gurobipy",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Homepage = "https://github.com/antnavoro/CounterfactUS"
|
|
38
|
+
Repository = "https://github.com/antnavoro/CounterfactUS"
|
|
39
|
+
"Bug Tracker" = "https://github.com/antnavoro/CounterfactUS/issues"
|
|
40
|
+
|
|
41
|
+
[tool.setuptools.packages.find]
|
|
42
|
+
where = ["src"]
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: CounterfactUS
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Optimal and robust counterfactual explanations
|
|
5
|
+
Author-email: Antonio Navas Orozco <anavas1@us.es>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 Antonio Navas Orozco
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/antnavoro/CounterfactUS
|
|
29
|
+
Project-URL: Repository, https://github.com/antnavoro/CounterfactUS
|
|
30
|
+
Project-URL: Bug Tracker, https://github.com/antnavoro/CounterfactUS/issues
|
|
31
|
+
Classifier: Programming Language :: Python :: 3
|
|
32
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
33
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Operating System :: OS Independent
|
|
37
|
+
Classifier: Intended Audience :: Science/Research
|
|
38
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
39
|
+
Requires-Python: >=3.9
|
|
40
|
+
Description-Content-Type: text/markdown
|
|
41
|
+
License-File: LICENSE
|
|
42
|
+
Requires-Dist: numpy
|
|
43
|
+
Requires-Dist: pandas
|
|
44
|
+
Requires-Dist: matplotlib
|
|
45
|
+
Requires-Dist: seaborn
|
|
46
|
+
Requires-Dist: scipy
|
|
47
|
+
Requires-Dist: rpy2
|
|
48
|
+
Requires-Dist: gurobipy
|
|
49
|
+
Dynamic: license-file
|
|
50
|
+
|
|
51
|
+
# CounterfactUS: Optimal & Robust Counterfactual Explanations
|
|
52
|
+
|
|
53
|
+
**CounterfactUS** is a Python library designed to generate optimal and robust counterfactual explanations for predictive models. It formulates the counterfactual generation as a Mixed-Integer Programming (MIP) problem, allowing for exact counterfactuals.
|
|
54
|
+
|
|
55
|
+
## 🚀 Key Features
|
|
56
|
+
|
|
57
|
+
* **Model Support:** Designed for Generalized Partially Linear Single-Index Models (GPLSIM), including special subcases like Single-Index Models (SIM) and Generalized Linear Models (GLM). (Uses R's `mgcv` and `gplsim` internally).
|
|
58
|
+
* **Optimal Explanations:** Uses Gurobi as an optimization backend to find counterfactuals that minimize distance exactly, rather than relying on heuristics.
|
|
59
|
+
* **Statistical Robustness:** Provides ground-truth model guarantees by enforcing prediction thresholds within a user-defined *confidence level*.
|
|
60
|
+
* **Highly Customizable Constraints:**
|
|
61
|
+
* **Distance Metrics:** Support for L1, L2, Gower, and combined L0+L1 distances.
|
|
62
|
+
* **Sparsity (L0):** Limit the maximum number of features that can be modified.
|
|
63
|
+
* **Immutability & Bounds:** Prevent specific features (e.g., *Age*, *Race*) from changing or restrict their allowable ranges.
|
|
64
|
+
* **Directional Weights:** Assign different weights to increasing or decreasing specific features.
|
|
65
|
+
* **Linear Constraints:** Define linear relationships (e.g., $X_1 + X_2 \le b$).
|
|
66
|
+
* **Automated Preprocessing:** Automatically infers feature types (binary, categorical, continuous), normalizes data, and handles one-hot encoding internally.
|
|
67
|
+
|
|
68
|
+
## 📦 Installation
|
|
69
|
+
|
|
70
|
+
This package requires Python 3.9+ and an active Gurobi license (or academic license) to solve the MIP problems. Additionally, it requires an R installation with the `mgcv` and `gplsim` packages available.
|
|
71
|
+
|
|
72
|
+
You can install the package directly via pip:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install CounterfactUS
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
*Note: Ensure that your system's R environment is accessible to Python via `rpy2`.*
|
|
79
|
+
|
|
80
|
+
## 💡 Quick Start
|
|
81
|
+
|
|
82
|
+
Generating counterfactuals is as simple as calling the `compute_counterfactuals` function.
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
import pandas as pd
|
|
86
|
+
from counterfactus import compute_counterfactuals
|
|
87
|
+
|
|
88
|
+
# 1. Load your dataset
|
|
89
|
+
X_train = pd.DataFrame(...) # Non-parametric features (e.g., continuous variables for GPLSIM)
|
|
90
|
+
Z_train = pd.DataFrame(...) # Linear features (e.g., categorical variables or strict linear effects)
|
|
91
|
+
Y_train = pd.Series(...) # Target variable
|
|
92
|
+
|
|
93
|
+
# 2. Define the query instances you want to explain
|
|
94
|
+
x_queries = pd.DataFrame(...)
|
|
95
|
+
z_queries = pd.DataFrame(...)
|
|
96
|
+
|
|
97
|
+
# 3. Generate counterfactuals
|
|
98
|
+
results_df = compute_counterfactuals(
|
|
99
|
+
X=X_train,
|
|
100
|
+
Z=Z_train,
|
|
101
|
+
Y=Y_train,
|
|
102
|
+
family_name="binomial",
|
|
103
|
+
link_name="logit",
|
|
104
|
+
prediction_threshold=0.5, # Target prediction threshold
|
|
105
|
+
x0s=x_queries,
|
|
106
|
+
z0s=z_queries,
|
|
107
|
+
distance="l1", # Distance metric to minimize
|
|
108
|
+
max_l0=2, # Allow a maximum of 2 feature changes
|
|
109
|
+
confidence_level=0.95, # Ensure 95% statistical confidence in the recourse
|
|
110
|
+
inmutable_z=["Race", "Sex"], # Prevent demographic features from changing
|
|
111
|
+
gurobi_verbose=False
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# 4. View results
|
|
115
|
+
print(results_df)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## ⚙️ Advanced Usage
|
|
119
|
+
|
|
120
|
+
`compute_counterfactuals` handles complex parameter grids natively. You can pass lists to parameters like `prediction_threshold`, `max_l0`, or `confidence_level` to explore the Pareto frontier of counterfactuals.
|
|
121
|
+
|
|
122
|
+
By default, the library computes the Cartesian product of all list parameters. You can change this behavior to iterate through the lists concurrently by setting `use_zip_iteration=True`.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
# Explore trade-offs between sparsity and target threshold
|
|
126
|
+
results = compute_counterfactuals(
|
|
127
|
+
# ... data ...
|
|
128
|
+
prediction_threshold=[0.5, 0.6, 0.7, 0.8],
|
|
129
|
+
max_l0=[1, 2, 3],
|
|
130
|
+
confidence_level=[0.5, 0.90, 0.95],
|
|
131
|
+
)
|
|
132
|
+
# or
|
|
133
|
+
# Automatically generate trade-off plots
|
|
134
|
+
results = compute_counterfactuals(
|
|
135
|
+
# ... data ...
|
|
136
|
+
plot_figures=True
|
|
137
|
+
)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## 📄 License
|
|
141
|
+
|
|
142
|
+
MIT License
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/CounterfactUS.egg-info/PKG-INFO
|
|
5
|
+
src/CounterfactUS.egg-info/SOURCES.txt
|
|
6
|
+
src/CounterfactUS.egg-info/dependency_links.txt
|
|
7
|
+
src/CounterfactUS.egg-info/requires.txt
|
|
8
|
+
src/CounterfactUS.egg-info/top_level.txt
|
|
9
|
+
src/counterfactus/__init__.py
|
|
10
|
+
src/counterfactus/covariance_GPLSIM.py
|
|
11
|
+
src/counterfactus/fit_GPLSIM.py
|
|
12
|
+
src/counterfactus/main.py
|
|
13
|
+
src/counterfactus/solver.py
|
|
14
|
+
tests/test_main.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
counterfactus
|