Skip to content

Commit 3afe445

Browse files
mmschlkclaudeAdvueu963
authored
Fix path-dependent TreeSHAP dropping zero-cover subtrees entered by the explained point (#617)
* Fix path-dependent TreeSHAP dropping zero-cover subtrees entered by x The edge tree computed each cover ratio as w_child / w_parent, which is 0/0 below a zero-cover node. QuadratureTreeSHAP then clamped the resulting NaN to a 1e-300 cover and treated the subtree as unreachable. That is wrong when the explained point's routing enters the zero-cover node (NaN default routing, out-of-range values; common in CatBoost's oblivious trees) and a feature split below it is absent. Attributions came out wrong, and constant trees got nonzero Shapley values, violating the null-player axiom. A zero-cover node now splits its (zero) mass equally between its children, so the split weights at every node still sum to one. Edges into a zero-cover node keep ratio 0 and the existing c -> 0 limit. The Python reference converter mirrors the convention. The change covers QuadratureTreeSHAP at every order and index. LinearTreeSHAP still refuses zero-cover trees by design. Regression tests compare against a brute-force path-dependent game (SV and k-SII) on a hand-built tree and on the CatBoost model of the report, check the null-player axiom, and check that NaN XGBoost/LightGBM models and a CatBoost classifier don't regress. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0125eRFMU1m2QrufYkqwogbZ * Link PR in CHANGELOG entry Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0125eRFMU1m2QrufYkqwogbZ * Restore the zero-cover comment in QuadratureTreeSHAP after the main merge The merge of main brought back the pre-fix comment, which called zero-cover subtrees unreachable and said p_e is NaN inside them. Neither holds anymore: the edge tree now splits a zero-cover node's mass equally. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0125eRFMU1m2QrufYkqwogbZ * Add note on CatBoost * Add CatBoost Comment to AGENTS.md --------- Co-authored-by: Maximilian Muschalik <noreply@anthropic.com> Co-authored-by: Advueu963 <S.Thies@campus.lmu.de>
1 parent da6381c commit 3afe445

7 files changed

Lines changed: 248 additions & 4 deletions

File tree

‎AGENTS.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,20 @@ Boosting converters live in separate modules such as `xgboost.py`,
6464
predictors live in that transformed space. Converters must map feature
6565
indices and category codes back (see `_convert_hist_tree_predictor` in
6666
`src/shapiq/tree/conversion/sklearn.py`).
67+
- Zero-cover nodes are NOT always unreachable: the explained point's routing can enter
68+
one (NaN default routing, out-of-range values; common in CatBoost's oblivious trees),
69+
often only partway down after cover-weighting an absent feature above it. The
70+
path-dependent cover ratio below a zero-cover node is defined in ONE place,
71+
`create_edge_tree_arrays` in `src/shapiq/tree/conversion/cext/cext.cc` (equal split,
72+
1/2 per child), mirrored by the Python reference
73+
`tests/.../tests_tree_explainer/conversion_reference.py`; keep the two in sync.
74+
- Path-dependent SVs of CatBoost models do NOT match CatBoost's native `ShapValues`
75+
(observed 2026-10-13, gaps up to ~0.1), and that is expected: path-dependent SHAP depends
76+
on the level order of an oblivious tree. shapiq puts `splits[0]` (the first split chosen in
77+
training) at the root (`fill_catboost_tree_node` in `conversion/cext/catboost_json.cc`), and
78+
CatBoost walks the levels in reverse. Both match a brute-force reference for their order to
79+
1e-15. CatBoost also adds the explained pool's leaf counts to the model's leaf weights when a
80+
zero-weight leaf has a non-zero value, so its base value can change with the batch.
6781
- Binary boosters (sklearn GB/HistGB, XGBoost, LightGBM, CatBoost) have ONE raw output,
6882
the class-1 log-odds. `class_label=0` must negate it (leaves incl. base score / bias);
6983
the parsers do this via `binary_class_sign` in `conversion/cext/converter.hpp` (sklearn:

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727

2828
### Bugfix
2929

30+
- fixes path-dependent `TreeExplainer`/`QuadratureTreeSHAP` dropping the mass of a zero-cover subtree whenever the explained point's routing enters it (e.g. through NaN default routing or a value outside the training range, which is common in CatBoost's oblivious trees). Below such a node the cover ratio was `0/0` and the subtree was treated as unreachable, which gave wrong Shapley values and interactions and nonzero attributions on constant trees (violating the null-player axiom); efficiency was unaffected. A zero-cover node now splits its (zero) mass equally among its children, so its split weights still sum to one. [#617](https://github.com/mmschlk/shapiq/pull/617)
3031
- `InterventionalTreeSHAPIQ(weight_fn=...)` dropped the terms whose interaction size equals `|E| + |R|`, so custom weights never reproduced a built-in index.
3132
- `TreeExplainer` with `class_index=0` on binary gradient boosting classifiers (scikit-learn `GradientBoostingClassifier` and `HistGradientBoostingClassifier`, `XGBClassifier`, `LGBMClassifier`, `CatBoostClassifier`) silently returned the class-1 explanation in both `mode="pathdependent"` and `mode="interventional"`, including the Woodelf fast path. It now explains the class-0 log-odds, which are the negated class-1 log-odds: the values and the `baseline_value` are the negation of the `class_index=1` explanation. `class_index=None` still explains class 1.
3233
- `TreeExplainer` with `class_index=None` on a multiclass LightGBM model explained the sum of the raw margins of all classes; it now explains class 1, like for the other libraries.

‎src/shapiq/tree/conversion/cext/catboost_json.cc‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,9 @@ static void fill_catboost_tree_node(
486486
uint64_t right_child = (level + 1 == depth)
487487
? internal_count + right_leaf_index
488488
: (uint64_t{1} << (level + 1)) - 1 + right_leaf_index;
489+
// splits[0] (CatBoost's first split chosen in training) becomes the root.
490+
// This choice is made consistently with other tree models, but not with CatBoost's own ShapValues, which walk the levels in reverse.
491+
// Both are exact for their order, but path-dependent SHAP values depend on the order of the splits. Interventional does not depend on the order of the splits, so it is consistent with CatBoost's own ShapValues.
489492
const CatBoostSplit &split = splits[level];
490493

491494
fill_catboost_tree_node(splits, leaf_values, leaf_weights, nan_treatments, tree, depth, internal_count, level + 1, leaf_index, scaling, bias);

‎src/shapiq/tree/conversion/cext/cext.cc‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -615,7 +615,12 @@ static PyObject *create_edge_tree_arrays(PyObject *self, PyObject *args)
615615
throw std::runtime_error("EdgeTree feature id is outside the dense feature range.");
616616

617617
last_feature_node[node_id] = 1;
618-
double weight = node_sample_weight[node_id] / node_sample_weight[parent_id];
618+
// A zero-cover parent has no data to split by (the ratio would be 0/0); it splits
619+
// its mass equally, so the weights at every split still sum to one. This matters
620+
// when the explained point's routing enters the zero-cover node (NaN default
621+
// routing, out-of-range values) and a feature split below it is absent.
622+
double parent_weight = node_sample_weight[parent_id];
623+
double weight = parent_weight > 0.0 ? node_sample_weight[node_id] / parent_weight : 0.5;
619624
split_weights[node_id] = weight;
620625
prod_weight *= weight;
621626
double p_e = 1.0 / weight;

‎src/shapiq/tree/quadrature/computer.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,8 +185,11 @@ def __init__(
185185
empty_prediction += float(tree_empty)
186186
max_features_per_path = max(max_features_per_path, int(edge_tree.edge_heights.max()))
187187
max_depth = max(max_depth, int(edge_tree.max_depth))
188-
# a zero-cover subtree gets a tiny positive cover, which realizes its zero
189-
# contribution without 0/0 factors (p_e is inf on its entry edge, NaN inside)
188+
# an edge into a zero-cover node has cover ratio 0 (p_e = inf, and inf again down a
189+
# same-feature chain through it); a tiny positive cover realizes the limit c -> 0
190+
# without 0/0 factors. The edge tree splits a zero-cover node's (zero) mass equally
191+
# among its children: x's routing may still enter such a node (NaN default routing,
192+
# out-of-range values), and features absent below it are then weighted 1/2.
190193
with np.errstate(divide="ignore"):
191194
c_acc = np.where(
192195
np.isfinite(edge_tree.p_e_values) & (edge_tree.p_e_values > 0),

‎tests/shapiq/tests_unit/tests_explainer/tests_tree_explainer/conversion_reference.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,8 @@ def recursive_search(
9595
feature_id = features[parents[node_id]]
9696
last_feature_node_in_path[node_id] = True
9797

98-
weight = node_sample_weight[node_id] / node_sample_weight[parents[node_id]]
98+
parent_weight = node_sample_weight[parents[node_id]]
99+
weight = node_sample_weight[node_id] / parent_weight if parent_weight > 0 else 0.5
99100
split_weights[node_id] = weight
100101
prod_weight *= weight
101102
p_e = 1 / weight

‎tests/shapiq/tests_unit/tests_explainer/tests_tree_explainer/test_tree_quadrature.py‎

Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,223 @@ def test_zero_cover_subtree_contributes_nothing(implementation):
303303
LinearTreeSHAP(dead_tree)
304304

305305

306+
# ------------------------ zero-cover nodes on the explained path ------------------------
307+
308+
309+
def _path_dependent_value(trees, x: np.ndarray, coalition: set[int]) -> float:
310+
"""Brute-force path-dependent game ``v(S)`` of an ensemble (sum over its trees).
311+
312+
Follows ``x`` at splits on features in ``S`` and otherwise averages the children by cover
313+
(weights summing to one). A zero-cover node splits equally, the convention of the edge
314+
tree (:func:`~shapiq.tree.conversion.edges.create_edge_tree`).
315+
"""
316+
317+
def visit(tree, x_tree: np.ndarray, node: int) -> float:
318+
if tree.leaf_mask[node]:
319+
return float(tree.values[node])
320+
feature = int(tree.feature_map_internal_original[int(tree.features[node])])
321+
left, right = int(tree.children_left[node]), int(tree.children_right[node])
322+
if feature in coalition:
323+
child = left if tree.goes_left(node, x_tree[feature]) else right
324+
return visit(tree, x_tree, child)
325+
w_left = float(tree.node_sample_weight[left])
326+
w_right = float(tree.node_sample_weight[right])
327+
share = w_left / (w_left + w_right) if w_left + w_right > 0 else 0.5
328+
return share * visit(tree, x_tree, left) + (1 - share) * visit(tree, x_tree, right)
329+
330+
return sum(
331+
visit(tree, tree.cast_input(np.asarray(x, dtype=np.float64)), int(tree.root_node_id))
332+
for tree in trees
333+
)
334+
335+
336+
def _brute_force(trees, x: np.ndarray, index: str, order: int):
337+
"""Exact interaction values of the brute-force path-dependent game."""
338+
from shapiq.game_theory.exact import ExactComputer
339+
340+
n_players = x.shape[0]
341+
table = {
342+
subset: _path_dependent_value(trees, x, set(subset))
343+
for subset in powerset(range(n_players))
344+
}
345+
346+
def game(coalitions: np.ndarray) -> np.ndarray:
347+
return np.array([table[tuple(np.flatnonzero(c))] for c in coalitions])
348+
349+
return ExactComputer(game, n_players=n_players)(index, order)
350+
351+
352+
def _assert_matches_brute_force(trees, x: np.ndarray, implementation: str = "cpp") -> None:
353+
"""QuadratureTreeSHAP equals the brute-force game for SV and order-2 k-SII."""
354+
for index, order in (("SV", 1), ("k-SII", 2)):
355+
reference = _brute_force(trees, x, index, order)
356+
result = _explain(
357+
QuadratureTreeSHAP(trees, index=index, max_order=order), x, implementation
358+
)
359+
for interaction in _all_interactions(x.shape[0], 1, order):
360+
assert result[interaction] == pytest.approx(reference[interaction], abs=1e-10), (
361+
index,
362+
interaction,
363+
)
364+
365+
366+
def _zero_cover_entered_by_x(tree, x: np.ndarray) -> bool:
367+
"""Whether ``x``'s routing at some split selects a zero-cover internal child.
368+
369+
Coalitions containing that split's feature then carry positive mass into the zero-cover
370+
node (cover-weighting further up only scales it), so the split ratios below it matter.
371+
"""
372+
x_tree = tree.cast_input(np.asarray(x, dtype=np.float64))
373+
for node in np.flatnonzero(~tree.leaf_mask):
374+
feature = int(tree.feature_map_internal_original[int(tree.features[node])])
375+
go_left = tree.goes_left(int(node), x_tree[feature])
376+
child = int(tree.children_left[node] if go_left else tree.children_right[node])
377+
if not tree.leaf_mask[child] and tree.node_sample_weight[child] == 0:
378+
return True
379+
return False
380+
381+
382+
def _zero_cover_on_path_tree(leaf_values=(1.0, 4.0, 10.0)) -> dict:
383+
"""Root splits feature 0; its right child has zero cover and splits feature 1.
384+
385+
``x = [1, 5]`` (or ``x_0 = NaN``, routed right) reaches the zero-cover node, below
386+
which feature 1 decides between two leaves with different values.
387+
"""
388+
left, dead_left, dead_right = leaf_values
389+
return {
390+
"children_left": np.asarray([1, -1, 3, -1, -1]),
391+
"children_right": np.asarray([2, -1, 4, -1, -1]),
392+
"children_missing": np.asarray([2, -1, 3, -1, -1]),
393+
"features": np.asarray([0, -2, 1, -2, -2]),
394+
"thresholds": np.asarray([0.0, -2, 0.0, -2, -2]),
395+
"node_sample_weight": np.asarray([100.0, 100.0, 0.0, 0.0, 0.0]),
396+
"values": np.asarray([0.0, left, 0.0, dead_left, dead_right]),
397+
}
398+
399+
400+
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
401+
@pytest.mark.parametrize("x", [[1.0, 5.0], [np.nan, 5.0]], ids=["out-of-range", "nan-routing"])
402+
def test_zero_cover_node_on_explained_path(x, implementation):
403+
"""A zero-cover node entered by ``x``'s routing splits absent features equally.
404+
405+
Regression test: the edge tree's cover ratio below a zero-cover node was ``0/0``, and
406+
the subtree's mass was dropped as if it were unreachable. With the equal-split
407+
convention ``v({0}) = (4 + 10) / 2 = 7``, ``v({}) = v({1}) = 1`` and ``v({0, 1}) = 10``,
408+
so ``SV = (7.5, 1.5)``; dropping the subtree gave ``(4, 5)``.
409+
"""
410+
from shapiq.tree.validation import validate_tree_model
411+
412+
x = np.asarray(x)
413+
trees = validate_tree_model(_zero_cover_on_path_tree())
414+
assert _zero_cover_entered_by_x(trees[0], x)
415+
result = _explain(QuadratureTreeSHAP(trees, index="SV"), x, implementation)
416+
assert result.baseline_value == pytest.approx(1.0)
417+
assert result[(0,)] == pytest.approx(7.5, abs=1e-12)
418+
assert result[(1,)] == pytest.approx(1.5, abs=1e-12)
419+
_assert_matches_brute_force(trees, x, implementation)
420+
421+
422+
@pytest.mark.parametrize("implementation", IMPLEMENTATIONS)
423+
@pytest.mark.parametrize("index", ["SV", "k-SII", "BII"])
424+
@pytest.mark.parametrize("x", [[1.0, 5.0], [np.nan, -5.0], [-1.0, 5.0]])
425+
def test_zero_cover_constant_tree_is_null_player(x, index, implementation):
426+
"""A constant tree attributes nothing, even when ``x``'s routing enters a zero-cover node."""
427+
explainer = QuadratureTreeSHAP(
428+
_zero_cover_on_path_tree(leaf_values=(3.0, 3.0, 3.0)), index=index, max_order=2
429+
)
430+
result = _explain(explainer, np.asarray(x), implementation)
431+
assert result.baseline_value == pytest.approx(3.0)
432+
for interaction in _all_interactions(2, 1, 2):
433+
assert result[interaction] == pytest.approx(0.0, abs=1e-12)
434+
435+
436+
def _catboost_zero_cover_model():
437+
"""The CatBoost regressor of the bug report: NaNs in feature 1, oblivious depth-3 trees."""
438+
catboost = pytest.importorskip("catboost")
439+
rng = np.random.default_rng(0)
440+
n = 400
441+
X = np.column_stack(
442+
[rng.integers(0, 6, n), rng.normal(size=n), rng.normal(size=n), rng.integers(0, 4, n)]
443+
).astype(float)
444+
X[rng.random(n) < 0.15, 1] = np.nan
445+
y = (X[:, 0] % 3) + np.nan_to_num(X[:, 1]) * X[:, 2] + (X[:, 3] == 2)
446+
model = catboost.CatBoostRegressor(
447+
iterations=5, depth=3, random_seed=0, verbose=0, allow_writing_files=False
448+
)
449+
return model.fit(X, y)
450+
451+
452+
_ZERO_COVER_INSTANCES = [[2.0, np.nan, 0.5, 2.0], [2.0, -1.0, 3.0, 2.0]]
453+
454+
455+
@pytest.mark.parametrize("x", _ZERO_COVER_INSTANCES)
456+
def test_catboost_zero_cover_on_path_matches_brute_force(x):
457+
"""Every tree of the bug report's CatBoost model, and the ensemble, match brute force."""
458+
from shapiq.tree.validation import validate_tree_model
459+
460+
x = np.asarray(x)
461+
trees = validate_tree_model(_catboost_zero_cover_model())
462+
# precondition: x's routing enters a zero-cover node (otherwise this tests nothing new)
463+
assert any(_zero_cover_entered_by_x(tree, x) for tree in trees)
464+
for tree in trees:
465+
_assert_matches_brute_force([tree], x)
466+
_assert_matches_brute_force(trees, x)
467+
# the default TreeExplainer path agrees
468+
explainer = TreeExplainer(trees, index="SV", max_order=1)
469+
reference = _brute_force(trees, x, "SV", 1)
470+
assert np.allclose(
471+
explainer.explain(x).get_n_order_values(1),
472+
reference.get_n_order_values(1),
473+
atol=1e-10,
474+
)
475+
476+
477+
@pytest.mark.parametrize("x", _ZERO_COVER_INSTANCES)
478+
def test_catboost_zero_cover_constant_tree_is_null_player(x):
479+
"""Constant-valued copies of the CatBoost trees get all-zero Shapley values."""
480+
from shapiq.tree.validation import validate_tree_model
481+
482+
x = np.asarray(x)
483+
for tree in validate_tree_model(_catboost_zero_cover_model()):
484+
tree.values[:] = 1.0
485+
values = TreeExplainer([tree], index="SV", max_order=1).explain(x)
486+
assert np.allclose(values.get_n_order_values(1), 0.0, atol=1e-12)
487+
488+
489+
def _nan_dataset() -> tuple[np.ndarray, np.ndarray]:
490+
rng = np.random.default_rng(1)
491+
n = 300
492+
X = rng.normal(size=(n, 4))
493+
y = X[:, 0] + X[:, 1] * X[:, 2] + (X[:, 3] > 0)
494+
X[rng.random(n) < 0.2, 0] = np.nan
495+
X[rng.random(n) < 0.2, 1] = np.nan
496+
return X, y
497+
498+
499+
@pytest.mark.parametrize("library", ["xgboost", "lightgbm", "catboost"])
500+
def test_nan_models_match_brute_force(library):
501+
"""No regression on NaN-routing XGBoost/LightGBM regressors and a CatBoost classifier."""
502+
from shapiq.tree.validation import validate_tree_model
503+
504+
X, y = _nan_dataset()
505+
if library == "xgboost":
506+
xgboost = pytest.importorskip("xgboost")
507+
model = xgboost.XGBRegressor(n_estimators=5, max_depth=3, random_state=0).fit(X, y)
508+
elif library == "lightgbm":
509+
lightgbm = pytest.importorskip("lightgbm")
510+
model = lightgbm.LGBMRegressor(
511+
n_estimators=5, num_leaves=8, random_state=0, verbose=-1
512+
).fit(X, y)
513+
else:
514+
catboost = pytest.importorskip("catboost")
515+
model = catboost.CatBoostClassifier(
516+
iterations=5, depth=3, random_seed=0, verbose=0, allow_writing_files=False
517+
).fit(X, y > np.median(y))
518+
trees = validate_tree_model(model)
519+
for x in (X[0], np.array([np.nan, np.nan, 0.3, -0.2]), np.array([9.0, -9.0, 9.0, -9.0])):
520+
_assert_matches_brute_force(trees, x)
521+
522+
306523
def test_output_holds_only_co_occurring_interactions():
307524
"""A depth-3 tree on 200 features reports at most one triple per path and reads absent pairs as zero."""
308525
rng = np.random.default_rng(0)

0 commit comments

Comments
 (0)