gpe-framework 1.3.1__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.1 → gpe_framework-1.3.2}/PKG-INFO +5 -1
  2. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/README.md +4 -0
  3. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/baselines/anchors_wrapper.py +23 -2
  4. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe/__init__.py +3 -2
  5. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe/certified.py +1 -0
  6. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe/compiled.py +78 -5
  7. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe/explanation.py +26 -2
  8. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe/tree_utils.py +46 -13
  9. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe_framework.egg-info/PKG-INFO +5 -1
  10. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/setup.py +1 -1
  11. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/tests/test_baselines.py +19 -0
  12. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/tests/test_certified.py +67 -4
  13. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/tests/test_robustness.py +76 -0
  14. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/tests/test_tree_utils.py +34 -0
  15. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/LICENSE +0 -0
  16. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/baselines/__init__.py +0 -0
  17. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/baselines/lime_wrapper.py +0 -0
  18. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/baselines/shap_wrapper.py +0 -0
  19. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe/core.py +0 -0
  20. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe/metrics.py +0 -0
  21. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe/novel_methods.py +0 -0
  22. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe/variants.py +0 -0
  23. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe/visualization.py +0 -0
  24. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe_framework.egg-info/SOURCES.txt +0 -0
  25. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe_framework.egg-info/dependency_links.txt +0 -0
  26. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe_framework.egg-info/requires.txt +0 -0
  27. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/gpe_framework.egg-info/top_level.txt +0 -0
  28. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/setup.cfg +0 -0
  29. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/tests/test_core.py +0 -0
  30. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/tests/test_facts.py +0 -0
  31. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/tests/test_metrics.py +0 -0
  32. {gpe_framework-1.3.1 → gpe_framework-1.3.2}/tests/test_variants.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gpe-framework
3
- Version: 1.3.1
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
@@ -251,6 +251,7 @@ What it does not cover:
251
251
  - It holds for one explanation at a time. For the whole tree at once use `compile_explanations(explainer, simultaneous=True)`.
252
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.
253
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.
254
255
  - With imbalanced classes, high precision can just mean the base rate. Use `min_lift` to require the rule to beat it.
255
256
 
256
257
  ## 📦 Compiled Explanations
@@ -264,8 +265,11 @@ table = compile_explanations(explainer)
264
265
  explanation = table.explain(x)
265
266
  arrays = table.to_arrays() # leaf_ids, bit masks over the path, K, n
266
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
267
269
  ```
268
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
+
269
273
  ## 🔬 Method Properties
270
274
 
271
275
  1. **GPE-Core** — rules from subsets of the decision path, evaluated on real data rather than perturbations
@@ -200,6 +200,7 @@ What it does not cover:
200
200
  - It holds for one explanation at a time. For the whole tree at once use `compile_explanations(explainer, simultaneous=True)`.
201
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.
202
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.
203
204
  - With imbalanced classes, high precision can just mean the base rate. Use `min_lift` to require the rule to beat it.
204
205
 
205
206
  ## 📦 Compiled Explanations
@@ -213,8 +214,11 @@ table = compile_explanations(explainer)
213
214
  explanation = table.explain(x)
214
215
  arrays = table.to_arrays() # leaf_ids, bit masks over the path, K, n
215
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
216
218
  ```
217
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
+
218
222
  ## 🔬 Method Properties
219
223
 
220
224
  1. **GPE-Core** — rules from subsets of the decision path, evaluated on real data rather than perturbations
@@ -150,6 +150,24 @@ class AnchorsWrapper:
150
150
  }
151
151
  )
152
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
+
153
171
  def _parse_anchor_rules(
154
172
  self,
155
173
  anchor_exp,
@@ -164,8 +182,11 @@ class AnchorsWrapper:
164
182
  string first, so it may contain any characters.
165
183
  """
166
184
  conditions = []
167
- for j, text in zip(anchor_exp.features(), anchor_exp.names()):
168
- j = int(j)
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):
169
190
  name = self.feature_names[j]
170
191
  before, _, after = text.partition(name)
171
192
  if j in self.explainer.categorical_names and j not in self.explainer.ordinal_features:
@@ -45,7 +45,7 @@ Email: vvdehtiarov@gmail.com
45
45
  License: MIT
46
46
  """
47
47
 
48
- __version__ = "1.3.1"
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
 
@@ -353,6 +353,7 @@ class CertifiedGPE(GPEExplainer):
353
353
  base_rate_upper=upper,
354
354
  lift_lower_bound=None if upper is None else float(bound) - upper,
355
355
  meets_lift=None if upper is None else bool(float(bound) - upper >= self.min_lift),
356
+ confidence_bound_valid=trivial or (self.interval != 'wilson' and self.alpha_scheme != 'chain'),
356
357
  )
357
358
  precision = K / n if n else float('nan')
358
359
  return Explanation(
@@ -11,7 +11,7 @@ Author: Vladyslav Dehtiarov
11
11
 
12
12
  import math
13
13
  import time
14
- from dataclasses import dataclass, field
14
+ from dataclasses import dataclass, field, replace
15
15
  from typing import Any, Dict, List, Optional
16
16
 
17
17
  import numpy as np
@@ -20,7 +20,7 @@ from .certified import CertifiedGPE
20
20
  from .core import GPEExplainer, as_instance, as_matrix
21
21
  from .explanation import Certificate, Condition, Explanation, Rule
22
22
  from .novel_methods import GPEInformationTheoretic
23
- from .tree_utils import get_leaf_paths, representative_instance, simplify_conditions
23
+ from .tree_utils import get_leaf_paths, path_is_reachable, representative_instance, simplify_conditions
24
24
 
25
25
  _LEAF_DETERMINED = (GPEExplainer, GPEInformationTheoretic, CertifiedGPE)
26
26
 
@@ -48,11 +48,33 @@ class CompiledExplanations:
48
48
  entries: Leaf node ID -> CompiledEntry
49
49
  method: Name of the method that produced the rules
50
50
  simultaneous: Whether the certificates hold for all leaves at once
51
+ simplify: Whether the explainer merged repeated bounds of a feature
52
+ feature_names: Feature names of the explainer
53
+ unreachable_leaves: Leaves that no input reaches; they have no entry
51
54
  """
52
55
  model: Any
53
56
  entries: Dict[int, CompiledEntry] = field(default_factory=dict)
54
57
  method: str = "GPE"
55
58
  simultaneous: bool = False
59
+ simplify: bool = True
60
+ feature_names: Optional[List[str]] = None
61
+ unreachable_leaves: List[int] = field(default_factory=list)
62
+
63
+ def rule_from_mask(self, leaf: int, mask: Optional[int] = None) -> Rule:
64
+ """
65
+ Rebuild the rule of a leaf from its bit mask and the tree alone.
66
+
67
+ Args:
68
+ leaf: Leaf node ID
69
+ mask: Bit mask as in to_arrays(); the stored one by default
70
+
71
+ Returns:
72
+ The rule: the conditions of the stored entry, in depth order
73
+ """
74
+ entry = self.entries[int(leaf)]
75
+ path = get_leaf_paths(self.model, self.feature_names)[int(leaf)]
76
+ conditions = conditions_from_mask(path, entry.mask if mask is None else int(mask), self.simplify)
77
+ return Rule(conditions=conditions, prediction=entry.prediction)
56
78
 
57
79
  def explain(self, x: np.ndarray) -> Explanation:
58
80
  """Look up the explanation of an instance."""
@@ -91,7 +113,9 @@ class CompiledExplanations:
91
113
  Returns:
92
114
  Arrays sorted by leaf ID: leaf_ids, masks (uint64), and calibration
93
115
  counts K and n (uint32, zero without a certificate). A set bit d in a
94
- mask keeps the literal at depth d of that leaf's path.
116
+ mask keeps the literal at depth d of that leaf's path; decode it with
117
+ conditions_from_mask, which also restores how merged literals treat
118
+ missing values.
95
119
  """
96
120
  leaf_ids = np.array(sorted(self.entries), dtype=np.int64)
97
121
  depth = max((self.entries[int(leaf)].depth for leaf in leaf_ids), default=0)
@@ -138,7 +162,9 @@ def compile_explanations(
138
162
  each entry holds on its own, with probability 1 - delta.
139
163
 
140
164
  Returns:
141
- CompiledExplanations table
165
+ CompiledExplanations table. A leaf that no input reaches gets no entry
166
+ and is listed in unreachable_leaves; scikit-learn before 1.8 can grow
167
+ such leaves on data with missing values.
142
168
  """
143
169
  if type(explainer) not in _LEAF_DETERMINED:
144
170
  raise TypeError(
@@ -153,6 +179,8 @@ def compile_explanations(
153
179
 
154
180
  model = explainer.model
155
181
  paths = get_leaf_paths(model, explainer.feature_names)
182
+ unreachable = sorted(leaf for leaf, path in paths.items() if not path_is_reachable(path))
183
+ paths = {leaf: path for leaf, path in paths.items() if leaf not in unreachable}
156
184
 
157
185
  split = {}
158
186
  if simultaneous:
@@ -166,7 +194,13 @@ def compile_explanations(
166
194
  'n_classes': len(model.classes_),
167
195
  }
168
196
 
169
- table = CompiledExplanations(model=model, simultaneous=simultaneous)
197
+ table = CompiledExplanations(
198
+ model=model,
199
+ simultaneous=simultaneous,
200
+ simplify=bool(explainer.simplify),
201
+ feature_names=list(explainer.feature_names) if explainer.feature_names is not None else None,
202
+ unreachable_leaves=[int(leaf) for leaf in unreachable],
203
+ )
170
204
  for leaf, path in paths.items():
171
205
  x = representative_instance(model, path)
172
206
  if int(model.apply(x.reshape(1, -1))[0]) != leaf:
@@ -204,3 +238,42 @@ def _literal_mask(path, conditions: List[Condition]) -> int:
204
238
  else:
205
239
  raise RuntimeError(f"Literal {cond!r} is not on the path")
206
240
  return mask
241
+
242
+
243
+ def conditions_from_mask(path, mask: int, simplify: bool = True) -> List[Condition]:
244
+ """
245
+ Decode a bit mask into the conditions of a rule.
246
+
247
+ Bit d keeps the literal at depth d of the path. With simplify, that literal
248
+ stands for all bounds of its feature in its direction on the path: the kept
249
+ one is the tightest, and it accepts a missing value only if every one of them
250
+ does. Taking the literal as it is would let through missing values that an
251
+ earlier node of the path sends elsewhere.
252
+
253
+ Args:
254
+ path: Literals of a leaf as get_leaf_paths returns them
255
+ mask: Bit mask of the kept literals
256
+ simplify: Whether the rule was built from merged literals
257
+
258
+ Returns:
259
+ Conditions in depth order
260
+ """
261
+ literals = [literal for _, literal in path]
262
+ if mask >> len(literals):
263
+ raise ValueError(f"Mask {mask} has bits beyond the depth {len(literals)} of the path")
264
+
265
+ def group(cond: Condition):
266
+ direction = 'lower' if cond.operator in ('>', '>=') else 'upper' if cond.operator in ('<', '<=') else None
267
+ return cond.feature_index, cond.float32_input, direction
268
+
269
+ conditions = []
270
+ for depth, literal in enumerate(literals):
271
+ if not mask >> depth & 1:
272
+ continue
273
+ key = group(literal)
274
+ if simplify and key[2] is not None:
275
+ missing = all(other.matches_missing for other in literals if group(other) == key)
276
+ if missing != literal.matches_missing:
277
+ literal = replace(literal, matches_missing=missing)
278
+ conditions.append(literal)
279
+ return conditions
@@ -314,7 +314,9 @@ class Certificate:
314
314
  K: Calibration rows in the rule region that the model assigns to the class
315
315
  n: Calibration rows in the rule region
316
316
  lower_bound: Lower confidence bound on the rule's population precision.
317
- 1.0 for the full path, whose region lies inside one leaf.
317
+ 1.0 for the full path, whose region lies inside one leaf. With
318
+ alpha_scheme='chain' it is only the statistic of the last passed test:
319
+ see confidence_bound_valid.
318
320
  alpha: Level of the bound; None for the full path, which needs no test
319
321
  delta: Total error budget
320
322
  min_precision: Target precision tau
@@ -323,12 +325,22 @@ class Certificate:
323
325
  search: 'exact', 'greedy', 'chain' or 'none'
324
326
  family_size: Number of hypotheses on this path (alpha shows the level used)
325
327
  trivial: True when the rule is the full path
326
- guarantee: False for 'wilson', whose coverage holds only asymptotically
328
+ guarantee: The threshold is certified: with probability at least 1 - delta
329
+ over the calibration set the precision of the returned rule is at least
330
+ min_precision. False for 'wilson', whose coverage holds only asymptotically.
327
331
  base_rate: Share of calibration rows the model assigns to the class
328
332
  min_lift: Required additive lift gamma, if any
329
333
  base_rate_upper: Upper confidence bound on the class share (lift mode)
330
334
  lift_lower_bound: lower_bound - base_rate_upper (lift mode)
331
335
  meets_lift: Whether lift_lower_bound >= min_lift (lift mode)
336
+ confidence_bound_valid: lower_bound is a lower confidence bound of level
337
+ 1 - delta, valid whatever threshold it is compared with. False for
338
+ 'chain': fixed-sequence testing certifies the event
339
+ precision >= min_precision for the threshold fixed in advance, and the
340
+ statistic of its last passed test is not a confidence bound. False for
341
+ 'wilson'. True for the full path, whose precision is exactly 1.
342
+ Left as None, it is derived from the other fields, which is how
343
+ certificates stored before 1.3.2 are read.
332
344
  """
333
345
  K: int
334
346
  n: int
@@ -347,6 +359,18 @@ class Certificate:
347
359
  base_rate_upper: Optional[float] = None
348
360
  lift_lower_bound: Optional[float] = None
349
361
  meets_lift: Optional[bool] = None
362
+ confidence_bound_valid: Optional[bool] = None
363
+
364
+ def __post_init__(self):
365
+ if self.confidence_bound_valid is None:
366
+ self.confidence_bound_valid = bool(
367
+ self.trivial or (self.guarantee and self.alpha_scheme != 'chain')
368
+ )
369
+
370
+ @property
371
+ def threshold_certified(self) -> bool:
372
+ """Whether precision >= min_precision is certified at level 1 - delta (same as guarantee)."""
373
+ return self.guarantee
350
374
 
351
375
  def to_dict(self) -> Dict[str, Any]:
352
376
  """Convert to dictionary for serialization."""
@@ -186,22 +186,55 @@ def representative_instance(tree, path: List[Tuple[int, Condition]]) -> np.ndarr
186
186
 
187
187
  x = np.zeros(tree.tree_.n_features, dtype=np.float64)
188
188
  for j in set(lows) | set(highs):
189
- low, high = lows.get(j, -np.inf), highs.get(j, np.inf)
190
- if np.isfinite(high):
191
- value = np.float32(high)
192
- if float(value) > high:
193
- value = np.nextafter(value, np.float32(-np.inf))
194
- elif np.isfinite(low):
195
- value = np.float32(low)
196
- if float(value) <= low:
197
- value = np.nextafter(value, np.float32(np.inf))
198
- else:
199
- value = np.float32(0.0)
200
- fits = low < float(value) <= high and np.isfinite(value)
201
- x[j] = float(value) if fits else np.nan
189
+ value = _value_between(lows.get(j, -np.inf), highs.get(j, np.inf))
190
+ x[j] = np.nan if value is None else value
202
191
  return x
203
192
 
204
193
 
194
+ def _value_between(low: float, high: float) -> Optional[float]:
195
+ """A finite float32 value v with low < v <= high, or None when there is none."""
196
+ if np.isfinite(high):
197
+ value = np.float32(high)
198
+ if float(value) > high:
199
+ value = np.nextafter(value, np.float32(-np.inf))
200
+ elif np.isfinite(low):
201
+ value = np.float32(low)
202
+ if float(value) <= low:
203
+ value = np.nextafter(value, np.float32(np.inf))
204
+ else:
205
+ value = np.float32(0.0)
206
+ fits = low < float(value) <= high and np.isfinite(value)
207
+ return float(value) if fits else None
208
+
209
+
210
+ def path_is_reachable(path: List[Tuple[int, Condition]]) -> bool:
211
+ """
212
+ Whether any input satisfies every literal of a path.
213
+
214
+ A feature can be satisfied by a number between its bounds or, when all its
215
+ literals accept a missing value, by NaN. scikit-learn before 1.8 can grow a
216
+ tree on data with missing values that has leaves no input reaches: a node
217
+ sends NaN one way and a deeper node of the same branch keeps only NaN.
218
+
219
+ Args:
220
+ path: Literals of one leaf, as returned by get_leaf_paths
221
+
222
+ Returns:
223
+ False when the region of the path is empty
224
+ """
225
+ by_feature: Dict[int, List[Condition]] = {}
226
+ for _, literal in path:
227
+ by_feature.setdefault(literal.feature_index, []).append(literal)
228
+ for literals in by_feature.values():
229
+ if all(literal.matches_missing for literal in literals):
230
+ continue
231
+ low = max((c.threshold for c in literals if c.operator == '>'), default=-np.inf)
232
+ high = min((c.threshold for c in literals if c.operator != '>'), default=np.inf)
233
+ if _value_between(low, high) is None:
234
+ return False
235
+ return True
236
+
237
+
205
238
  def literal_importance(tree, node_id: int) -> float:
206
239
  """
207
240
  Weighted impurity decrease of a split, taken from the fitted tree alone.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gpe-framework
3
- Version: 1.3.1
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
@@ -251,6 +251,7 @@ What it does not cover:
251
251
  - It holds for one explanation at a time. For the whole tree at once use `compile_explanations(explainer, simultaneous=True)`.
252
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.
253
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.
254
255
  - With imbalanced classes, high precision can just mean the base rate. Use `min_lift` to require the rule to beat it.
255
256
 
256
257
  ## 📦 Compiled Explanations
@@ -264,8 +265,11 @@ table = compile_explanations(explainer)
264
265
  explanation = table.explain(x)
265
266
  arrays = table.to_arrays() # leaf_ids, bit masks over the path, K, n
266
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
267
269
  ```
268
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
+
269
273
  ## 🔬 Method Properties
270
274
 
271
275
  1. **GPE-Core** — rules from subsets of the decision path, evaluated on real data rather than perturbations
@@ -10,7 +10,7 @@ long_description = readme_path.read_text(encoding="utf-8") if readme_path.exists
10
10
 
11
11
  setup(
12
12
  name="gpe-framework",
13
- version="1.3.1",
13
+ version="1.3.2",
14
14
  author="Vladyslav Dehtiarov",
15
15
  author_email="vvdehtiarov@gmail.com",
16
16
  description="Greedy-Prune-Explain: Minimal local explanations for decision tree predictions",
@@ -86,6 +86,25 @@ def test_anchors_survive_hard_names_and_small_scales():
86
86
  assert non_empty
87
87
 
88
88
 
89
+ def test_anchors_match_each_name_to_its_feature_when_bounds_repeat():
90
+ """features() has one entry per bound, names() one per feature: the third condition used to be lost."""
91
+ pytest.importorskip("anchor")
92
+ tree, X_tr, X_te, names = rows_for_hard_names()
93
+ wrapper = AnchorsWrapper(tree, X_tr, feature_names=names, threshold=0.9)
94
+
95
+ class Seen:
96
+ def features(self):
97
+ return [2, 1, 1, 0, 0, 0]
98
+
99
+ def names(self):
100
+ return ["x(1) > -1.04", "hours per week > -575.63", "capital-gain <= -0.00"]
101
+
102
+ x = X_te[2].copy()
103
+ x[0], x[1], x[2] = -1e-4, 0.0, 0.0
104
+ conditions = wrapper._parse_anchor_rules(Seen(), x)
105
+ assert [c.feature_index for c in conditions] == [2, 1, 0]
106
+
107
+
89
108
  def test_shap_selects_the_features_that_matter():
90
109
  """Only feature 2 moves the prediction, so it must come first."""
91
110
  pytest.importorskip("shap")
@@ -19,11 +19,12 @@ from gpe import (
19
19
  GPEInformationTheoretic,
20
20
  GPEOptimal,
21
21
  compile_explanations,
22
+ conditions_from_mask,
22
23
  lower_bound,
23
24
  min_coverage,
24
25
  )
25
26
  from gpe.certified import _superset_sum, clopper_pearson_upper
26
- from gpe.explanation import Explanation, Rule
27
+ from gpe.explanation import Certificate, Explanation, Rule
27
28
  from gpe.tree_utils import get_decision_path, get_leaf_paths, simplify_conditions
28
29
 
29
30
  TAU = 0.95
@@ -41,6 +42,13 @@ def data():
41
42
  return tree, X_tr, X_cal, X_te
42
43
 
43
44
 
45
+ def same_conditions(a, b):
46
+ """The same conditions, whatever their order."""
47
+ def key(c):
48
+ return c.feature_index, c.operator, c.threshold, c.matches_missing, c.float32_input
49
+ return sorted(map(key, a)) == sorted(map(key, b)) and all(x in b for x in a)
50
+
51
+
44
52
  def counts(rule, X_cal, pred, c):
45
53
  mask = rule.evaluate_batch(X_cal)
46
54
  return int((pred[mask] == c).sum()), int(mask.sum())
@@ -249,6 +257,47 @@ class TestSearch:
249
257
  assert [conditions[i] for i in kept] == exp.rule.conditions
250
258
  assert shorter > 0
251
259
 
260
+ def test_chain_certifies_the_threshold_but_not_a_confidence_bound(self, data):
261
+ """The statistic of the last passed test is not a lower confidence bound."""
262
+ tree, _, X_cal, X_te = data
263
+ explainer = CertifiedGPE(tree, X_cal, alpha_scheme="chain")
264
+ shorter = 0
265
+ for x in X_te[:100]:
266
+ cert = explainer.explain(x).certificate
267
+ assert cert.guarantee and cert.threshold_certified
268
+ assert cert.confidence_bound_valid == cert.trivial
269
+ shorter += not cert.trivial
270
+ assert shorter > 0
271
+
272
+ @pytest.mark.parametrize("scheme", ["uniform", "layered"])
273
+ def test_simultaneous_schemes_give_a_confidence_bound(self, data, scheme):
274
+ tree, _, X_cal, X_te = data
275
+ explainer = CertifiedGPE(tree, X_cal, alpha_scheme=scheme)
276
+ for x in X_te[:50]:
277
+ cert = explainer.explain(x).certificate
278
+ assert cert.guarantee and cert.threshold_certified and cert.confidence_bound_valid
279
+
280
+ def test_wilson_certifies_nothing(self, data):
281
+ tree, _, X_cal, X_te = data
282
+ explainer = CertifiedGPE(tree, X_cal, interval="wilson")
283
+ shorter = 0
284
+ for x in X_te[:50]:
285
+ cert = explainer.explain(x).certificate
286
+ assert not cert.guarantee and not cert.threshold_certified
287
+ assert cert.confidence_bound_valid == cert.trivial
288
+ shorter += not cert.trivial
289
+ assert shorter > 0
290
+
291
+ @pytest.mark.parametrize("scheme", ["uniform", "chain"])
292
+ def test_certificate_stored_before_the_flag_reads_the_same(self, data, scheme):
293
+ tree, _, X_cal, X_te = data
294
+ explainer = CertifiedGPE(tree, X_cal, alpha_scheme=scheme)
295
+ for x in X_te[:30]:
296
+ cert = explainer.explain(x).certificate
297
+ stored = cert.to_dict()
298
+ assert stored.pop("confidence_bound_valid") == cert.confidence_bound_valid
299
+ assert Certificate.from_dict(stored) == cert
300
+
252
301
  def test_chain_uses_fewer_rows_than_uniform(self):
253
302
  assert lower_bound(59, 59, DELTA) >= TAU
254
303
  assert lower_bound(59, 59, DELTA / (2 ** 10 - 2)) < TAU
@@ -604,10 +653,24 @@ class TestCompile:
604
653
  table = compile_explanations(CertifiedGPE(tree, X_cal))
605
654
  arrays = table.to_arrays()
606
655
  paths = get_leaf_paths(tree)
656
+ merged = 0
607
657
  for leaf, mask in zip(arrays['leaf_ids'], arrays['masks']):
608
- literals = [lit for d, (_, lit) in enumerate(paths[int(leaf)]) if int(mask) >> d & 1]
609
- decoded = Rule(literals).evaluate_batch(X_cal)
610
- assert (decoded == table.entries[int(leaf)].rule.evaluate_batch(X_cal)).all()
658
+ path = paths[int(leaf)]
659
+ entry = table.entries[int(leaf)]
660
+ assert same_conditions(conditions_from_mask(path, int(mask)), entry.rule.conditions)
661
+ assert same_conditions(table.rule_from_mask(leaf).conditions, entry.rule.conditions)
662
+ assert table.rule_from_mask(leaf).prediction == entry.prediction
663
+ literals = [literal for _, literal in path]
664
+ merged += len(simplify_conditions(literals)) < len(literals)
665
+ full = conditions_from_mask(path, (1 << len(path)) - 1)
666
+ assert (Rule(full).evaluate_batch(X_cal) == Rule(literals).evaluate_batch(X_cal)).all()
667
+ assert merged > 0 # paths with repeated bounds of one feature are covered
668
+
669
+ def test_mask_beyond_the_path_is_rejected(self, data):
670
+ tree, _, X_cal, _ = data
671
+ leaf, path = next(iter(get_leaf_paths(tree).items()))
672
+ with pytest.raises(ValueError):
673
+ conditions_from_mask(path, 1 << len(path))
611
674
 
612
675
  def test_storage(self, data):
613
676
  tree, _, X_cal, _ = data
@@ -88,6 +88,13 @@ EXPLAINERS = {
88
88
  }
89
89
 
90
90
 
91
+ def same_conditions(a, b):
92
+ """The same conditions, whatever their order."""
93
+ def key(c):
94
+ return c.feature_index, c.operator, c.threshold, c.matches_missing, c.float32_input
95
+ return sorted(map(key, a)) == sorted(map(key, b)) and all(x in b for x in a)
96
+
97
+
91
98
  def rows_with_missing(X, count):
92
99
  return X[np.isnan(X).any(axis=1)][:count]
93
100
 
@@ -169,6 +176,75 @@ class TestMissingValues:
169
176
  assert compiled.rule.conditions == online.rule.conditions
170
177
  assert compiled.rule.evaluate(x)
171
178
 
179
+ @pytest.mark.parametrize("name", ["core", "certified"])
180
+ def test_masks_decode_to_rules_after_merging_with_missing_values(self, name):
181
+ """
182
+ A kept literal stands for all bounds of its feature on the path, and nodes on one path can route
183
+ NaN differently. Decoding the bit as the bare literal lets through rows the rule rejects.
184
+ """
185
+ from gpe import conditions_from_mask
186
+ from gpe.tree_utils import get_leaf_paths
187
+
188
+ mixed = bare_differs = 0
189
+ for seed in range(3):
190
+ rng = np.random.default_rng(seed)
191
+ X = rng.normal(size=(6000, 3))
192
+ y = ((X[:, 0] > 0) ^ (X[:, 1] > 0.3)).astype(int)
193
+ holes = rng.random(X.shape) < 0.25
194
+ y = np.where(holes[:, 0], rng.integers(0, 2, len(y)), y)
195
+ X[holes] = np.nan
196
+ tree = DecisionTreeClassifier(max_depth=10, random_state=seed).fit(X[:3000], y[:3000])
197
+ table = compile_explanations(EXPLAINERS[name](tree, X[3000:]))
198
+ arrays = table.to_arrays()
199
+ paths = get_leaf_paths(tree)
200
+ # scikit-learn before 1.8 grows leaves here that no input reaches
201
+ assert set(table.entries) | set(table.unreachable_leaves) == set(paths)
202
+ reached = tree.apply(X)
203
+ for leaf in table.unreachable_leaves:
204
+ assert not (reached == leaf).any()
205
+ assert not Rule(conditions=[c for _, c in paths[leaf]]).evaluate_batch(X).any()
206
+ for x in X[:300]:
207
+ assert table.explain(x).rule.evaluate(x)
208
+ for leaf, mask in zip(arrays["leaf_ids"], arrays["masks"]):
209
+ path, entry = paths[int(leaf)], table.entries[int(leaf)]
210
+ decoded = conditions_from_mask(path, int(mask))
211
+ assert same_conditions(decoded, entry.rule.conditions)
212
+ assert same_conditions(table.rule_from_mask(leaf).conditions, entry.rule.conditions)
213
+ bare = [literal for depth, (_, literal) in enumerate(path) if int(mask) >> depth & 1]
214
+ mixed += decoded != bare
215
+ bare_differs += not np.array_equal(Rule(bare).evaluate_batch(X), entry.rule.evaluate_batch(X))
216
+ # every bit set: the merged path, which selects exactly the leaf
217
+ full = conditions_from_mask(path, (1 << len(path)) - 1)
218
+ assert np.array_equal(Rule(full).evaluate_batch(X), tree.apply(X) == leaf)
219
+ assert mixed > 0 and bare_differs > 0
220
+
221
+ def test_path_is_reachable(self):
222
+ from gpe.tree_utils import path_is_reachable
223
+
224
+ def path(*literals):
225
+ return [(i, Condition(0, "f", op, threshold, matches_missing=missing))
226
+ for i, (op, threshold, missing) in enumerate(literals)]
227
+
228
+ assert path_is_reachable(path((">", 0.3, True), ("<=", 0.5, False)))
229
+ assert path_is_reachable(path((">", 0.5, True), ("<=", 0.3, True))) # only NaN, and both accept it
230
+ assert not path_is_reachable(path((">", 0.5, True), ("<=", 0.3, False)))
231
+ assert not path_is_reachable(path((">", 0.3, False), (">", np.inf, True))) # NaN sent away, then NaN only
232
+ assert path_is_reachable(path(("<=", np.inf, False), (">", 0.3, True)))
233
+ tight = float(np.float32(0.3))
234
+ assert not path_is_reachable(path((">", tight, False), ("<=", float(np.nextafter(np.float32(tight), np.float32(1))) - 1e-12, False)))
235
+
236
+ def test_mask_decoding_without_merging(self, missing):
237
+ from gpe import conditions_from_mask
238
+ from gpe.tree_utils import get_leaf_paths
239
+
240
+ tree, X_tr, _ = missing
241
+ table = compile_explanations(GPEExplainer(tree, X_train=X_tr, min_precision=TAU, simplify=False))
242
+ assert table.simplify is False
243
+ paths = get_leaf_paths(tree)
244
+ for leaf, entry in table.entries.items():
245
+ assert same_conditions(conditions_from_mask(paths[leaf], entry.mask, simplify=False), entry.rule.conditions)
246
+ assert same_conditions(table.rule_from_mask(leaf).conditions, entry.rule.conditions)
247
+
172
248
  def test_representative_reaches_each_leaf(self, missing):
173
249
  tree, _, _ = missing
174
250
  for leaf, path in get_leaf_paths(tree).items():
@@ -70,6 +70,14 @@ class TestSimplifyByBruteForce:
70
70
  same, kept = self.same_rows(conditions)
71
71
  assert same, (conditions, kept)
72
72
 
73
+ @pytest.mark.parametrize("loose, tight", [(True, False), (False, True), (True, True), (False, False)])
74
+ def test_missing_value_passes_only_if_every_source_accepts_it(self, loose, tight):
75
+ """Two nodes on one feature in one direction may route NaN differently: the tightest bound alone is not enough."""
76
+ sources = [Condition(0, "x", "<=", 1.0, matches_missing=loose), Condition(0, "x", "<=", 0.0, matches_missing=tight)]
77
+ same, kept = self.same_rows(sources)
78
+ assert same and len(kept) == 1
79
+ assert kept[0].threshold == 0.0 and kept[0].matches_missing == (loose and tight)
80
+
73
81
  def test_membership_condition_is_kept(self):
74
82
  conditions = [Condition(0, "x", "in", [0.0, 1.0]), Condition(0, "x", ">", -1.0)]
75
83
  same, kept = self.same_rows(conditions)
@@ -95,6 +103,32 @@ class TestPathRouting:
95
103
  assert tree_utils._path_nodes(tree, x)[-1] == leaves[i]
96
104
  assert get_decision_path(tree, x).evaluate(x)
97
105
 
106
+ @pytest.mark.parametrize("seed", range(5))
107
+ def test_merged_path_selects_the_leaf_when_nodes_route_missing_differently(self, seed):
108
+ if not hasattr(DecisionTreeClassifier(max_depth=1).fit([[0.0], [1.0]], [0, 1]).tree_, "missing_go_to_left"):
109
+ pytest.skip("scikit-learn without missing value support in trees")
110
+ rng = np.random.default_rng(seed)
111
+ X = rng.normal(size=(3000, 3))
112
+ y = ((X[:, 0] > 0) ^ (X[:, 1] > 0.3)).astype(int)
113
+ missing = rng.random(X.shape) < 0.25
114
+ y = np.where(missing[:, 0], rng.integers(0, 2, len(y)), y)
115
+ X[missing] = np.nan
116
+ tree = DecisionTreeClassifier(max_depth=10, random_state=seed).fit(X, y)
117
+ tree_, leaves, mixed = tree.tree_, tree.apply(X), 0
118
+ for leaf in np.unique(leaves):
119
+ x = X[np.argmax(leaves == leaf)]
120
+ nodes = tree_utils._path_nodes(tree, x)
121
+ accepts = {}
122
+ for parent, child in zip(nodes, nodes[1:]):
123
+ left = child == tree_.children_left[parent]
124
+ accepts.setdefault((tree_.feature[parent], left), set()).add(bool(tree_.missing_go_to_left[parent]) == left)
125
+ mixed += any(len(v) == 2 for v in accepts.values())
126
+ path = get_decision_path(tree, x).conditions
127
+ merged = simplify_conditions(path)
128
+ assert len(merged) <= len(path)
129
+ assert np.array_equal(Rule(conditions=merged).evaluate_batch(X), leaves == leaf)
130
+ assert mixed > 0 # the case under test does occur in these trees
131
+
98
132
  def test_each_step_follows_a_child(self):
99
133
  X, y = data()
100
134
  tree = DecisionTreeClassifier(max_depth=4, random_state=0).fit(X, y)
File without changes
File without changes
File without changes