gpe-framework 1.3.0__tar.gz → 1.3.2__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.
Files changed (32) hide show
  1. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/PKG-INFO +18 -18
  2. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/README.md +17 -17
  3. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/baselines/anchors_wrapper.py +62 -82
  4. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/baselines/lime_wrapper.py +26 -77
  5. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/baselines/shap_wrapper.py +17 -14
  6. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe/__init__.py +3 -2
  7. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe/certified.py +13 -15
  8. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe/compiled.py +81 -8
  9. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe/core.py +111 -27
  10. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe/explanation.py +116 -31
  11. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe/metrics.py +22 -14
  12. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe/novel_methods.py +169 -90
  13. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe/tree_utils.py +116 -70
  14. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe/variants.py +53 -38
  15. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe/visualization.py +2 -1
  16. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe_framework.egg-info/PKG-INFO +18 -18
  17. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe_framework.egg-info/SOURCES.txt +3 -0
  18. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/setup.py +1 -1
  19. gpe_framework-1.3.2/tests/test_baselines.py +120 -0
  20. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/tests/test_certified.py +74 -9
  21. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/tests/test_facts.py +2 -1
  22. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/tests/test_metrics.py +2 -2
  23. gpe_framework-1.3.2/tests/test_robustness.py +880 -0
  24. gpe_framework-1.3.2/tests/test_tree_utils.py +230 -0
  25. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/tests/test_variants.py +10 -7
  26. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/LICENSE +0 -0
  27. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/baselines/__init__.py +0 -0
  28. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe_framework.egg-info/dependency_links.txt +0 -0
  29. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe_framework.egg-info/requires.txt +0 -0
  30. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/gpe_framework.egg-info/top_level.txt +0 -0
  31. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/setup.cfg +0 -0
  32. {gpe_framework-1.3.0 → gpe_framework-1.3.2}/tests/test_core.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gpe-framework
3
- Version: 1.3.0
3
+ Version: 1.3.2
4
4
  Summary: Greedy-Prune-Explain: Minimal local explanations for decision tree predictions
5
5
  Home-page: https://github.com/vladdehtiarov/gpe-framework
6
6
  Author: Vladyslav Dehtiarov
@@ -56,25 +56,17 @@ Dynamic: summary
56
56
  [![PyPI version](https://badge.fury.io/py/gpe-framework.svg)](https://badge.fury.io/py/gpe-framework)
57
57
  [![Tests](https://github.com/vladdehtiarov/gpe-framework/actions/workflows/tests.yml/badge.svg)](https://github.com/vladdehtiarov/gpe-framework/actions/workflows/tests.yml)
58
58
 
59
- **GPE (Greedy-Prune-Explain)** is a novel method for generating minimal, interpretable local explanations for decision tree predictions. Unlike existing methods like LIME, SHAP, or Anchors, GPE leverages the inherent structure of decision trees to produce explanations that are:
59
+ **GPE (Greedy-Prune-Explain)** explains one prediction of a decision tree with a short IF-THEN rule: the literals of the decision path that are needed to keep the model's answer on real data, measured on a background sample.
60
60
 
61
- - ✅ **Minimal** — Contains only essential conditions (1-2 instead of 5)
62
- - ✅ **Precise** — 99.4% precision on real-world financial data
63
- - ✅ **Fast** — 48x faster than LIME, 19x faster than Anchors
64
- - ✅ **Actionable** — Simple IF-THEN rules like "income < 50000 AND debt_ratio > 0.4"
61
+ The rule says how the **model** behaves in a region. Its precision is agreement with the model, not the correctness of the prediction, and without `CertifiedGPE` it is an estimate with no guarantee on new data.
65
62
 
66
- ## 📊 Benchmark Results
63
+ The search is a standard greedy deletion, also used by LmPAXp (Izza et al.) and by Bounia and Setitra; what differs is the measure and the certificate. See [Method Properties](#-method-properties).
67
64
 
68
- Tested on 3 financial datasets (632K records total):
65
+ ## 📊 Benchmark Results
69
66
 
70
- | Method | Time (ms) | Complexity | Precision | Speedup |
71
- |--------|-----------|------------|-----------|---------|
72
- | **GPE-Core** | **4.4** | **1.4** | **99.4%** | **48x** |
73
- | GPE-IT | 3.0 | 1.4 | 97.9% | 71x |
74
- | LIME | 213 | 5.0 | — | 1x |
75
- | Anchors | 82 | 0.7 | 99.2% | 3x |
67
+ The current benchmark and its results will be published here once it is complete.
76
68
 
77
- *All results are statistically significant (p < 0.001)*
69
+ Numbers in articles published before 2026-11 (4.4 ms, 1.4 conditions, 99.4%) came from an earlier protocol, with in-sample precision and two degenerate datasets. They should not be cited as the performance of this package.
78
70
 
79
71
  ## 🚀 Installation
80
72
 
@@ -138,7 +130,7 @@ print(explanation.to_natural_language())
138
130
  ```
139
131
  ```
140
132
  The model predicts 'setosa' because petal length is at most 2.45.
141
- This explanation covers 33.3% of similar cases with 100.0% accuracy.
133
+ This rule covers 33.3% of the background rows, and the model gives the same answer on 100.0% of them.
142
134
  ```
143
135
 
144
136
  ## 🔧 GPE Variants
@@ -211,12 +203,16 @@ while conditions > 1:
211
203
 
212
204
  ### 3. EXPLAIN Phase
213
205
  Return the minimal rule with metrics:
214
- - **Precision** — Accuracy for instances satisfying the rule
206
+ - **Precision** — Share of rows satisfying the rule on which the model gives the same class. NaN when no row satisfies it, never 1.0
215
207
  - **Coverage** — Proportion of dataset satisfying the rule
216
208
  - **Complexity** — Number of conditions
217
209
 
218
210
  ## 📊 Metrics
219
211
 
212
+ Undefined values are NaN, on purpose: without a background sample, or on an empty region, there is nothing measured. `aggregate_metrics` skips them and reports how many rows it used as `n`. If you average by hand, use `np.nanmean`.
213
+
214
+ Missing values follow the tree: a literal accepts NaN when the tree sends NaN that way, and the rule prints `(or missing)`.
215
+
220
216
  ```python
221
217
  from gpe import (
222
218
  precision_score,
@@ -255,6 +251,7 @@ What it does not cover:
255
251
  - It holds for one explanation at a time. For the whole tree at once use `compile_explanations(explainer, simultaneous=True)`.
256
252
  - It is conservative and needs data. A rule with no errors needs `min_coverage(k)` calibration rows: 194 at `k=10`, `tau=0.95`, `delta=0.05`. When nothing can be certified, the full path is returned with `cert.trivial=True`; its precision is exactly 1 because its region lies inside one leaf.
257
253
  - `interval='wilson'` has no finite-sample coverage, and its certificates carry `guarantee=False`.
254
+ - `alpha_scheme='chain'` certifies the event `precision >= min_precision` for the threshold fixed in advance, and nothing more. `cert.lower_bound` is then the statistic of the last passed test, not a confidence bound, and `cert.confidence_bound_valid` is `False`. Do not compare it with another threshold.
258
255
  - With imbalanced classes, high precision can just mean the base rate. Use `min_lift` to require the rule to beat it.
259
256
 
260
257
  ## 📦 Compiled Explanations
@@ -268,8 +265,11 @@ table = compile_explanations(explainer)
268
265
  explanation = table.explain(x)
269
266
  arrays = table.to_arrays() # leaf_ids, bit masks over the path, K, n
270
267
  print(table.storage_bytes()) # size on top of the tree itself
268
+ rule = table.rule_from_mask(leaf) # the rule back from the mask and the tree
271
269
  ```
272
270
 
271
+ A set bit keeps the literal at that depth of the path. When the path bounds a feature more than once, the kept literal stands for all of those bounds, so it accepts a missing value only if each of them does; `conditions_from_mask(path, mask)` applies this rule.
272
+
273
273
  ## 🔬 Method Properties
274
274
 
275
275
  1. **GPE-Core** — rules from subsets of the decision path, evaluated on real data rather than perturbations
@@ -285,7 +285,7 @@ gpe-framework/
285
285
  │ ├── core.py # GPEExplainer
286
286
  │ ├── certified.py # CertifiedGPE, confidence bounds
287
287
  │ ├── compiled.py # compile_explanations: leaf-to-rule table
288
- │ ├── novel_methods.py # GPE-IT, GPE-CF (scientific contribution)
288
+ │ ├── novel_methods.py # GPE-IT, GPE-CF, GPE-Stable, GPE-Multi
289
289
  │ ├── variants.py # GPEOptimal, GPEWeighted, GPEMonotonic, GPEEnsemble
290
290
  │ ├── explanation.py # Data structures
291
291
  │ ├── metrics.py # Evaluation metrics
@@ -5,25 +5,17 @@
5
5
  [![PyPI version](https://badge.fury.io/py/gpe-framework.svg)](https://badge.fury.io/py/gpe-framework)
6
6
  [![Tests](https://github.com/vladdehtiarov/gpe-framework/actions/workflows/tests.yml/badge.svg)](https://github.com/vladdehtiarov/gpe-framework/actions/workflows/tests.yml)
7
7
 
8
- **GPE (Greedy-Prune-Explain)** is a novel method for generating minimal, interpretable local explanations for decision tree predictions. Unlike existing methods like LIME, SHAP, or Anchors, GPE leverages the inherent structure of decision trees to produce explanations that are:
8
+ **GPE (Greedy-Prune-Explain)** explains one prediction of a decision tree with a short IF-THEN rule: the literals of the decision path that are needed to keep the model's answer on real data, measured on a background sample.
9
9
 
10
- - ✅ **Minimal** — Contains only essential conditions (1-2 instead of 5)
11
- - ✅ **Precise** — 99.4% precision on real-world financial data
12
- - ✅ **Fast** — 48x faster than LIME, 19x faster than Anchors
13
- - ✅ **Actionable** — Simple IF-THEN rules like "income < 50000 AND debt_ratio > 0.4"
10
+ The rule says how the **model** behaves in a region. Its precision is agreement with the model, not the correctness of the prediction, and without `CertifiedGPE` it is an estimate with no guarantee on new data.
14
11
 
15
- ## 📊 Benchmark Results
12
+ The search is a standard greedy deletion, also used by LmPAXp (Izza et al.) and by Bounia and Setitra; what differs is the measure and the certificate. See [Method Properties](#-method-properties).
16
13
 
17
- Tested on 3 financial datasets (632K records total):
14
+ ## 📊 Benchmark Results
18
15
 
19
- | Method | Time (ms) | Complexity | Precision | Speedup |
20
- |--------|-----------|------------|-----------|---------|
21
- | **GPE-Core** | **4.4** | **1.4** | **99.4%** | **48x** |
22
- | GPE-IT | 3.0 | 1.4 | 97.9% | 71x |
23
- | LIME | 213 | 5.0 | — | 1x |
24
- | Anchors | 82 | 0.7 | 99.2% | 3x |
16
+ The current benchmark and its results will be published here once it is complete.
25
17
 
26
- *All results are statistically significant (p < 0.001)*
18
+ Numbers in articles published before 2026-11 (4.4 ms, 1.4 conditions, 99.4%) came from an earlier protocol, with in-sample precision and two degenerate datasets. They should not be cited as the performance of this package.
27
19
 
28
20
  ## 🚀 Installation
29
21
 
@@ -87,7 +79,7 @@ print(explanation.to_natural_language())
87
79
  ```
88
80
  ```
89
81
  The model predicts 'setosa' because petal length is at most 2.45.
90
- This explanation covers 33.3% of similar cases with 100.0% accuracy.
82
+ This rule covers 33.3% of the background rows, and the model gives the same answer on 100.0% of them.
91
83
  ```
92
84
 
93
85
  ## 🔧 GPE Variants
@@ -160,12 +152,16 @@ while conditions > 1:
160
152
 
161
153
  ### 3. EXPLAIN Phase
162
154
  Return the minimal rule with metrics:
163
- - **Precision** — Accuracy for instances satisfying the rule
155
+ - **Precision** — Share of rows satisfying the rule on which the model gives the same class. NaN when no row satisfies it, never 1.0
164
156
  - **Coverage** — Proportion of dataset satisfying the rule
165
157
  - **Complexity** — Number of conditions
166
158
 
167
159
  ## 📊 Metrics
168
160
 
161
+ Undefined values are NaN, on purpose: without a background sample, or on an empty region, there is nothing measured. `aggregate_metrics` skips them and reports how many rows it used as `n`. If you average by hand, use `np.nanmean`.
162
+
163
+ Missing values follow the tree: a literal accepts NaN when the tree sends NaN that way, and the rule prints `(or missing)`.
164
+
169
165
  ```python
170
166
  from gpe import (
171
167
  precision_score,
@@ -204,6 +200,7 @@ What it does not cover:
204
200
  - It holds for one explanation at a time. For the whole tree at once use `compile_explanations(explainer, simultaneous=True)`.
205
201
  - It is conservative and needs data. A rule with no errors needs `min_coverage(k)` calibration rows: 194 at `k=10`, `tau=0.95`, `delta=0.05`. When nothing can be certified, the full path is returned with `cert.trivial=True`; its precision is exactly 1 because its region lies inside one leaf.
206
202
  - `interval='wilson'` has no finite-sample coverage, and its certificates carry `guarantee=False`.
203
+ - `alpha_scheme='chain'` certifies the event `precision >= min_precision` for the threshold fixed in advance, and nothing more. `cert.lower_bound` is then the statistic of the last passed test, not a confidence bound, and `cert.confidence_bound_valid` is `False`. Do not compare it with another threshold.
207
204
  - With imbalanced classes, high precision can just mean the base rate. Use `min_lift` to require the rule to beat it.
208
205
 
209
206
  ## 📦 Compiled Explanations
@@ -217,8 +214,11 @@ table = compile_explanations(explainer)
217
214
  explanation = table.explain(x)
218
215
  arrays = table.to_arrays() # leaf_ids, bit masks over the path, K, n
219
216
  print(table.storage_bytes()) # size on top of the tree itself
217
+ rule = table.rule_from_mask(leaf) # the rule back from the mask and the tree
220
218
  ```
221
219
 
220
+ A set bit keeps the literal at that depth of the path. When the path bounds a feature more than once, the kept literal stands for all of those bounds, so it accepts a missing value only if each of them does; `conditions_from_mask(path, mask)` applies this rule.
221
+
222
222
  ## 🔬 Method Properties
223
223
 
224
224
  1. **GPE-Core** — rules from subsets of the decision path, evaluated on real data rather than perturbations
@@ -234,7 +234,7 @@ gpe-framework/
234
234
  │ ├── core.py # GPEExplainer
235
235
  │ ├── certified.py # CertifiedGPE, confidence bounds
236
236
  │ ├── compiled.py # compile_explanations: leaf-to-rule table
237
- │ ├── novel_methods.py # GPE-IT, GPE-CF (scientific contribution)
237
+ │ ├── novel_methods.py # GPE-IT, GPE-CF, GPE-Stable, GPE-Multi
238
238
  │ ├── variants.py # GPEOptimal, GPEWeighted, GPEMonotonic, GPEEnsemble
239
239
  │ ├── explanation.py # Data structures
240
240
  │ ├── metrics.py # Evaluation metrics
@@ -7,6 +7,7 @@ the GPE Explanation format.
7
7
  Author: Vladyslav Dehtiarov
8
8
  """
9
9
 
10
+ import re
10
11
  import numpy as np
11
12
  import time
12
13
  from typing import List, Optional, Dict, Any
@@ -16,6 +17,22 @@ sys.path.insert(0, '..')
16
17
  from gpe.explanation import Condition, Rule, Explanation
17
18
 
18
19
 
20
+ _NUMBER = r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?"
21
+
22
+
23
+ def _snap(printed: float, edges: np.ndarray, value: float, operator: str) -> float:
24
+ """Closest quartile edge to a rounded bound, among those keeping x in the region."""
25
+ if edges.size == 0:
26
+ return printed
27
+ if operator in ('>', '>='):
28
+ fitting = edges[edges < value]
29
+ else:
30
+ fitting = edges[edges >= value]
31
+ if fitting.size == 0:
32
+ return printed
33
+ return float(fitting[np.argmin(np.abs(fitting - printed))])
34
+
35
+
19
36
  class AnchorsWrapper:
20
37
  """
21
38
  Wrapper for Anchors explanations.
@@ -67,7 +84,7 @@ class AnchorsWrapper:
67
84
  )
68
85
 
69
86
  self.explainer = anchor_tabular.AnchorTabularExplainer(
70
- class_names=['0', '1'], # Will be updated based on model
87
+ class_names=[str(c) for c in getattr(self.model, 'classes_', ['0', '1'])],
71
88
  feature_names=self.feature_names,
72
89
  train_data=self.X_train,
73
90
  categorical_names=self.categorical_names
@@ -114,9 +131,10 @@ class AnchorsWrapper:
114
131
 
115
132
  computation_time = time.time() - start_time
116
133
 
117
- # Get metrics from Anchors
118
- precision = anchor_exp.precision() if hasattr(anchor_exp, 'precision') else 1.0
119
- coverage = anchor_exp.coverage() if hasattr(anchor_exp, 'coverage') else 0.0
134
+ # Metrics as Anchors reports them, on its own perturbation distribution.
135
+ # Comparisons must recompute them on data: see anchor issue #82.
136
+ precision = anchor_exp.precision() if hasattr(anchor_exp, 'precision') else float('nan')
137
+ coverage = anchor_exp.coverage() if hasattr(anchor_exp, 'coverage') else float('nan')
120
138
 
121
139
  return Explanation(
122
140
  instance=x,
@@ -132,99 +150,61 @@ class AnchorsWrapper:
132
150
  }
133
151
  )
134
152
 
153
+ def _features_of_names(self, features) -> List[int]:
154
+ """
155
+ The feature of each string in anchor_exp.names(), in order.
156
+
157
+ features() keeps one entry per bound, so a feature bounded twice (or by two quartile edges on one side)
158
+ appears several times, while names() has one string per ordinal feature, at its first appearance
159
+ (anchor_tabular.add_names_to_exp). Equality conditions get one string each.
160
+ """
161
+ out, handled = [], set()
162
+ for j in map(int, features):
163
+ equality = j in self.explainer.categorical_names and j not in self.explainer.ordinal_features
164
+ if not equality:
165
+ if j in handled:
166
+ continue
167
+ handled.add(j)
168
+ out.append(j)
169
+ return out
170
+
135
171
  def _parse_anchor_rules(
136
172
  self,
137
173
  anchor_exp,
138
174
  x: np.ndarray
139
175
  ) -> List[Condition]:
140
176
  """
141
- Parse Anchors explanation into Conditions.
177
+ Turn an anchor into conditions.
142
178
 
143
- Anchors format examples:
144
- - "feature_0 > 3.50"
145
- - "feature_1 <= 2.00"
146
- - "3.50 < feature_0 <= 5.00"
179
+ Feature indices come from anchor_exp.features(). Only the strings hold the
180
+ bounds, rounded to two decimals, so each bound is snapped to the quartile edge
181
+ of the discretizer it was printed from. The feature name is cut out of the
182
+ string first, so it may contain any characters.
147
183
  """
148
- import re
149
-
150
184
  conditions = []
151
-
152
- if not hasattr(anchor_exp, 'names'):
153
- return conditions
154
-
155
- for rule_str in anchor_exp.names():
156
- # Try different patterns
157
-
158
- # Pattern: "value < feature <= value"
159
- match = re.match(r"([\d.-]+)\s*<\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*<=\s*([\d.-]+)", rule_str)
160
- if match:
161
- low = float(match.group(1))
162
- feature_name = match.group(2)
163
- high = float(match.group(3))
164
-
165
- try:
166
- idx = self.feature_names.index(feature_name)
167
- except ValueError:
168
- continue
169
-
170
- # Add both bounds
171
- conditions.append(Condition(
172
- feature_index=idx,
173
- feature_name=feature_name,
174
- operator='>',
175
- threshold=low
176
- ))
185
+ features = self._features_of_names(anchor_exp.features())
186
+ names = list(anchor_exp.names())
187
+ if len(features) != len(names):
188
+ raise ValueError(f"anchor features {list(anchor_exp.features())} do not match names {names}")
189
+ for j, text in zip(features, names):
190
+ name = self.feature_names[j]
191
+ before, _, after = text.partition(name)
192
+ if j in self.explainer.categorical_names and j not in self.explainer.ordinal_features:
177
193
  conditions.append(Condition(
178
- feature_index=idx,
179
- feature_name=feature_name,
180
- operator='<=',
181
- threshold=high
194
+ j, name, '==', float(x[j]), is_categorical=False
182
195
  ))
183
196
  continue
184
197
 
185
- # Pattern: "feature <= value" or "feature > value"
186
- match = re.match(r"([a-zA-Z_][a-zA-Z0-9_]*)\s*(<=|<|>=|>|=)\s*([\d.-]+)", rule_str)
187
- if match:
188
- feature_name = match.group(1)
189
- operator = match.group(2)
190
- threshold = float(match.group(3))
191
-
192
- try:
193
- idx = self.feature_names.index(feature_name)
194
- except ValueError:
195
- continue
196
-
197
- # Normalize operator
198
- if operator == '=':
199
- operator = '=='
200
-
198
+ edges = np.asarray(self.explainer.disc.mins[j][1:], dtype=float)
199
+ low = re.search(rf"({_NUMBER})\s*<\s*$", before)
200
+ if low:
201
+ conditions.append(Condition(j, name, '>', _snap(float(low.group(1)), edges, x[j], '>')))
202
+ high = re.search(rf"^\s*(<=|>|<|>=)\s*({_NUMBER})", after)
203
+ if high:
204
+ operator = high.group(1)
201
205
  conditions.append(Condition(
202
- feature_index=idx,
203
- feature_name=feature_name,
204
- operator=operator,
205
- threshold=threshold
206
+ j, name, operator, _snap(float(high.group(2)), edges, x[j], operator)
206
207
  ))
207
- continue
208
-
209
- # Categorical pattern: "feature = category_name"
210
- match = re.match(r"([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*([a-zA-Z_][a-zA-Z0-9_]*)", rule_str)
211
- if match:
212
- feature_name = match.group(1)
213
- category = match.group(2)
214
-
215
- try:
216
- idx = self.feature_names.index(feature_name)
217
- except ValueError:
218
- continue
219
-
220
- conditions.append(Condition(
221
- feature_index=idx,
222
- feature_name=feature_name,
223
- operator='==',
224
- threshold=category,
225
- is_categorical=True
226
- ))
227
-
228
208
  return conditions
229
209
 
230
210
  def explain_batch(
@@ -123,16 +123,7 @@ class LIMEWrapper:
123
123
  prediction = self.model.predict(x.reshape(1, -1))[0]
124
124
 
125
125
  # Convert LIME explanation to GPE format
126
- conditions = []
127
-
128
- for feature_weight in lime_exp.as_list():
129
- # Parse LIME feature string (e.g., "3.50 < feature_0 <= 5.00")
130
- feature_str = feature_weight[0]
131
- weight = feature_weight[1]
132
-
133
- condition = self._parse_lime_condition(feature_str, x)
134
- if condition is not None:
135
- conditions.append(condition)
126
+ conditions = self._conditions_from_exp(lime_exp, x)
136
127
 
137
128
  # Create rule
138
129
  rule = Rule(
@@ -159,75 +150,33 @@ class LIMEWrapper:
159
150
  }
160
151
  )
161
152
 
162
- def _parse_lime_condition(
163
- self,
164
- feature_str: str,
165
- x: np.ndarray
166
- ) -> Optional[Condition]:
153
+ def _conditions_from_exp(self, lime_exp, x: np.ndarray) -> List[Condition]:
167
154
  """
168
- Parse a LIME feature string into a Condition.
155
+ Turn LIME's selected features into conditions.
169
156
 
170
- LIME format examples:
171
- - "feature_0 <= 3.50"
172
- - "3.50 < feature_0 <= 5.00"
173
- - "feature_1 > 2.00"
157
+ Indices and bin edges come from the explainer. The strings of as_list()
158
+ round the edges to two decimals and depend on feature names. A selected
159
+ feature gives both edges of the quartile bin of x, which is the region
160
+ LIME reports, so the rule is true on x. LIME selects n_features features
161
+ whatever the data, so the length of this rule is a setting, not a result.
174
162
  """
175
- import re
176
-
177
- # Try to match patterns
178
- # Pattern 1: "feature <= value" or "feature > value"
179
- pattern1 = r"([a-zA-Z_][a-zA-Z0-9_]*)\s*(<=|<|>=|>)\s*([\d.-]+)"
180
- # Pattern 2: "value < feature <= value"
181
- pattern2 = r"([\d.-]+)\s*<\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*<=\s*([\d.-]+)"
182
-
183
- match2 = re.match(pattern2, feature_str)
184
- if match2:
185
- low = float(match2.group(1))
186
- feature_name = match2.group(2)
187
- high = float(match2.group(3))
188
-
189
- # Find feature index
190
- try:
191
- feature_idx = self.feature_names.index(feature_name)
192
- except ValueError:
193
- return None
194
-
195
- # Return the more restrictive condition based on instance value
196
- value = x[feature_idx]
197
- if abs(value - low) < abs(value - high):
198
- return Condition(
199
- feature_index=feature_idx,
200
- feature_name=feature_name,
201
- operator='>',
202
- threshold=low
203
- )
204
- else:
205
- return Condition(
206
- feature_index=feature_idx,
207
- feature_name=feature_name,
208
- operator='<=',
209
- threshold=high
210
- )
211
-
212
- match1 = re.match(pattern1, feature_str)
213
- if match1:
214
- feature_name = match1.group(1)
215
- operator = match1.group(2)
216
- threshold = float(match1.group(3))
217
-
218
- try:
219
- feature_idx = self.feature_names.index(feature_name)
220
- except ValueError:
221
- return None
222
-
223
- return Condition(
224
- feature_index=feature_idx,
225
- feature_name=feature_name,
226
- operator=operator,
227
- threshold=threshold
228
- )
229
-
230
- return None
163
+ label = sorted(lime_exp.local_exp)[0] if self.mode == 'classification' else 0
164
+ selected = [int(j) for j, _ in lime_exp.local_exp[label]]
165
+ discretizer = self.explainer.discretizer
166
+ bins = discretizer.discretize(x.reshape(1, -1))[0]
167
+ conditions = []
168
+ for j in selected:
169
+ name = self.feature_names[j]
170
+ if j not in discretizer.to_discretize:
171
+ conditions.append(Condition(j, name, '==', float(x[j])))
172
+ continue
173
+ index = int(bins[j])
174
+ edges = discretizer.mins[j], discretizer.maxs[j]
175
+ if index > 0:
176
+ conditions.append(Condition(j, name, '>', float(edges[0][index])))
177
+ if index < len(edges[0]) - 1:
178
+ conditions.append(Condition(j, name, '<=', float(edges[1][index])))
179
+ return conditions
231
180
 
232
181
  def _estimate_metrics(
233
182
  self,
@@ -238,7 +187,7 @@ class LIMEWrapper:
238
187
  mask = rule.evaluate_batch(self.X_train)
239
188
 
240
189
  if mask.sum() == 0:
241
- return 1.0, 0.0
190
+ return float('nan'), 0.0
242
191
 
243
192
  coverage = mask.mean()
244
193
 
@@ -121,28 +121,30 @@ class SHAPWrapper:
121
121
  # Get SHAP values
122
122
  shap_values = self.explainer.shap_values(x.reshape(1, -1))
123
123
 
124
- # Handle different SHAP output formats
124
+ # One value per feature, for the predicted class. shap returns a list of
125
+ # per-class arrays or an array of shape (rows, features[, classes]).
126
+ prediction = self.model.predict(x.reshape(1, -1))[0]
127
+ class_index = 0
128
+ if hasattr(self.model, 'classes_'):
129
+ class_index = int(np.flatnonzero(self.model.classes_ == prediction)[0])
125
130
  if isinstance(shap_values, list):
126
- # Multi-class classification
127
- prediction = self.model.predict(x.reshape(1, -1))[0]
128
- if hasattr(self.model, 'classes_'):
129
- pred_idx = np.where(self.model.classes_ == prediction)[0][0]
130
- else:
131
- pred_idx = int(prediction)
132
- shap_values = shap_values[pred_idx].flatten()
131
+ shap_values = np.asarray(shap_values[class_index])[0]
133
132
  else:
134
- shap_values = shap_values.flatten()
135
- prediction = self.model.predict(x.reshape(1, -1))[0]
133
+ shap_values = np.asarray(shap_values)[0]
134
+ if shap_values.ndim == 2:
135
+ shap_values = shap_values[:, class_index]
136
136
 
137
- # Convert SHAP values to conditions
137
+ # SHAP gives attributions, not rules. To compare them with rule methods we
138
+ # build conditions around x with an arbitrary margin of 10% of the range, so
139
+ # the numbers of this rule measure this conversion and not SHAP itself. For
140
+ # attributions as such use metadata['top_features'].
138
141
  # Select top n_features by absolute SHAP value
139
142
  n_features = min(self.n_features, len(x), len(shap_values))
140
143
  top_indices = np.argsort(np.abs(shap_values))[-n_features:][::-1]
141
144
 
142
145
  conditions = []
146
+ top_indices = [int(idx) for idx in top_indices]
143
147
  for idx in top_indices:
144
- if idx >= len(x): # Skip if index out of bounds
145
- continue
146
148
  if np.abs(shap_values[idx]) < 1e-6:
147
149
  continue
148
150
 
@@ -190,6 +192,7 @@ class SHAPWrapper:
190
192
  computation_time=computation_time,
191
193
  metadata={
192
194
  'shap_values': shap_values.tolist(),
195
+ 'top_features': top_indices,
193
196
  'explainer_type': self.explainer_type,
194
197
  'n_features': self.n_features
195
198
  }
@@ -204,7 +207,7 @@ class SHAPWrapper:
204
207
  mask = rule.evaluate_batch(self.X_train)
205
208
 
206
209
  if mask.sum() == 0:
207
- return 1.0, 0.0
210
+ return float('nan'), 0.0
208
211
 
209
212
  coverage = mask.mean()
210
213
 
@@ -45,7 +45,7 @@ Email: vvdehtiarov@gmail.com
45
45
  License: MIT
46
46
  """
47
47
 
48
- __version__ = "1.3.0"
48
+ __version__ = "1.3.2"
49
49
  __author__ = "Vladyslav Dehtiarov"
50
50
  __email__ = "vvdehtiarov@gmail.com"
51
51
  __license__ = "MIT"
@@ -55,7 +55,7 @@ from .core import GPEExplainer
55
55
 
56
56
  # Certified explanations and leaf tables
57
57
  from .certified import CertifiedGPE, lower_bound, min_coverage
58
- from .compiled import CompiledExplanations, compile_explanations
58
+ from .compiled import CompiledExplanations, compile_explanations, conditions_from_mask
59
59
 
60
60
  # Variants
61
61
  from .variants import (
@@ -118,6 +118,7 @@ __all__ = [
118
118
  "Certificate",
119
119
  "CompiledExplanations",
120
120
  "compile_explanations",
121
+ "conditions_from_mask",
121
122
  "lower_bound",
122
123
  "min_coverage",
123
124