Skip to content

Commit 2c7d8a1

Browse files
mmschlkclaudeAdvueu963
authored
Fix TreeExplainer class selection: class_index=0 on binary boosters, out-of-range indices, LightGBM default (#618)
* Fix TreeExplainer class_index=0 for binary gradient boosting classifiers Binary boosters (sklearn GradientBoosting/HistGradientBoosting, XGBoost, LightGBM, CatBoost) model a single raw output, the class-1 log-odds. The converters used class_label only to select per-class trees of multiclass models, so class_index=0 silently explained class 1. The converters now negate the leaf values (which already include the base score / init offset) and empty predictions for class_label=0 of a binary classifier, which fixes both shapiq backends. Woodelf ignores class_index for single-output models, so its result is negated as well. A class_index other than 0, 1 or None now raises a ValueError for these models. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0194yJ4YbD76pieP9CkpnvRv * Limit the LightGBM binary check to the model header Searching the whole model string scanned every tree of multiclass models, whose header has no match (+81 ms on a 10.9 MB model). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0194yJ4YbD76pieP9CkpnvRv * Move binary class selection into the C tree parsers The class-0 negation of binary boosters now lives where the parsers already select the class of multiclass models, instead of in a Python pass over the converted trees: - binary_class_sign (converter.hpp) returns the sign selecting class_label from the single raw output, raising std::invalid_argument (ValueError) for other labels. The XGBoost, LightGBM and CatBoost parsers apply it to the leaf values (including base score / bias) while filling them. A model is binary if it has one output and its serialized objective / loss is binary, or the caller passes the new optional is_classifier hint (custom objectives are not serialized as binary). - sklearn GB/HistGB, which have no C parser, fold the sign into the scaling and offset they already apply. - Converted trees carry TreeModel.negated_class_one, so the Woodelf path reads that flag instead of converting the model a second time. Conversion speed is unchanged against main. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0194yJ4YbD76pieP9CkpnvRv * Request class 1 from Woodelf when the trees negate it Woodelf ignores class_index for single-output models today. Asking for the class-1 output explicitly and negating it keeps class_index=0 correct if Woodelf later negates class 0 itself, instead of negating twice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0194yJ4YbD76pieP9CkpnvRv * Raise for class indices a tree model does not have Out-of-range class indices silently explained something else: multiclass XGBoost and LightGBM models converted to zero trees, and scikit-learn models read negative indices as counting from the last class. A shared check_class_label (conversion/common.py, cext/converter.hpp) now raises a ValueError with the same message everywhere, and convert_tree_model rejects negative labels, which the C parsers would read as "unspecified". The LightGBM parser kept the trees of all classes for an unspecified class, so class_index=None explained the sum of all class margins of a multiclass model; it now selects class 1, like the other parsers. A new test checks that the Woodelf backend explains the same class as the shapiq backend for every valid class_index of every supported family. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0194yJ4YbD76pieP9CkpnvRv * Update CHANGELOG --------- Co-authored-by: Maximilian Muschalik <noreply@anthropic.com> Co-authored-by: Santo Thies <49311372+Advueu963@users.noreply.github.com>
1 parent cbbffea commit 2c7d8a1

16 files changed

Lines changed: 730 additions & 84 deletions

File tree

‎AGENTS.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,20 @@ Boosting converters live in separate modules such as `xgboost.py`,
3737
predictors live in that transformed space. Converters must map feature
3838
indices and category codes back (see `_convert_hist_tree_predictor` in
3939
`src/shapiq/tree/conversion/sklearn.py`).
40+
- Binary boosters (sklearn GB/HistGB, XGBoost, LightGBM, CatBoost) have ONE raw output,
41+
the class-1 log-odds. `class_label=0` must negate it (leaves incl. base score / bias);
42+
the parsers do this via `binary_class_sign` in `conversion/cext/converter.hpp` (sklearn:
43+
`_binary_class_sign`) and flag the trees with `TreeModel.negated_class_one`. A model
44+
counts as binary if it has one output AND is a classifier: the serialized objective/loss
45+
says so, or Python passes `is_classifier` (custom objectives are not serialized as
46+
binary). Woodelf ignores `class_index` for single-output models (deliberately, to match
47+
shap), so `TreeExplainer._run_woodelf` requests class 1 and negates the result when the
48+
trees carry that flag.
49+
- `class_label` handling must agree across all converters AND Woodelf (which loads the
50+
original model itself): `None` = class 1, out-of-range / negative = `ValueError`
51+
(`check_class_label` in `conversion/common.py` and `cext/converter.hpp`). `-1` is the C
52+
parsers' "unspecified" sentinel, so negative labels are rejected in `convert_tree_model`.
53+
`test_woodelf_matches_shapiq_for_every_class_index` guards the agreement.
4054
- XGBoost routes in-set categorical values to the RIGHT ("yes") child;
4155
sklearn/LightGBM route them LEFT. The internal `TreeModel` convention is
4256
"in set -> left"; the XGBoost parser therefore swaps children at categorical

‎CHANGELOG.md‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
# Changelog
22

3-
## Unreleased
3+
## Development
44

55
### Bugfix
6-
6+
- `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.
7+
- `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.
78
- fixes `Game` passing integer or float 0/1 coalition arrays unchanged to `value_function`: games that use the coalitions as masks (e.g. `x[coalition]`, `~coalition`) silently computed wrong values, since integer arrays index positions `0`/`1` and `~` acts bitwise. `Game.__call__` (incl. `verbose=True`), `precompute`, and `compute` now always hand a boolean coalition matrix to `value_function`.
8-
### Bugfix
99
- fixes a bias in the cross-fitted MSR residual adjustment of `ProxySHAP` and `RegressionMSR` (`k_folds > 1`), so the estimates did not converge. Held-out residuals were scaled by `k_folds` and thus also stood in for the coalitions the fold's proxy was trained on.
1010
Folds are now split within each coalition size (complement pairs kept together), with training coalitions getting a weight of `1` and held-out coalitions a weight depending on how many unseen coalitions of their size exist.
1111

12-
1312
## v1.7.0 (2026-08-27)
1413

1514
### New and Improved Tree support.

‎src/shapiq/tree/base.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ class TreeModel:
6464
Currently not used by downstream algorithms.
6565
intercepts: Per-leaf intercept terms for linear-leaf tree models. Currently unused.
6666
coeffs: Per-leaf coefficient vectors for linear-leaf tree models. Currently unused.
67+
negated_class_one: Whether the tree models the class-0 log-odds of a binary classifier
68+
as the negated class-1 log-odds (the single raw output of binary boosters).
6769
6870
"""
6971

@@ -95,6 +97,7 @@ class TreeModel:
9597
intercepts: NDArray[np.floating]
9698
coeffs: NDArray[np.floating]
9799
input_precision: InputPrecision = "float64"
100+
negated_class_one: bool = False
98101

99102
def __init__(
100103
self,
@@ -123,6 +126,7 @@ def __init__(
123126
cat_start: NDArray[np.int_] | None = None,
124127
cat_size: NDArray[np.int_] | None = None,
125128
input_precision: InputPrecision = "float64",
129+
negated_class_one: bool = False, # noqa: FBT001, FBT002
126130
) -> None:
127131
"""Initialize the :class:`TreeModel`.
128132
@@ -168,6 +172,9 @@ def __init__(
168172
thresholds at prediction time: ``"float32"`` for XGBoost and CatBoost (inputs
169173
are cast before routing, see :meth:`cast_input`), ``"float64"`` otherwise.
170174
Defaults to ``"float64"``.
175+
negated_class_one: Whether the tree models the class-0 log-odds of a binary
176+
classifier as the negated class-1 log-odds. Set by the converters for
177+
``class_label=0``; the leaf values are already negated. Defaults to ``False``.
171178
"""
172179
self.children_left = children_left
173180
self.children_right = children_right
@@ -229,6 +236,7 @@ def __init__(
229236
msg = f"input_precision must be 'float64' or 'float32', got {input_precision!r}."
230237
raise ValueError(msg)
231238
self.input_precision = input_precision
239+
self.negated_class_one = negated_class_one
232240
# setup empty prediction
233241
if empty_prediction is None:
234242
self.compute_empty_prediction()

‎src/shapiq/tree/conversion/catboost.py‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,14 +49,16 @@ def parse_catboost_json_model(
4949
5050
Args:
5151
model_json: CatBoost JSON model as a dictionary.
52-
class_label: For multiclass classifiers, the class index to extract. ``None`` is passed
53-
to the C++ parser as ``-1`` and defaults to class ``1`` for multiclass CatBoost
54-
models. It is ignored for regression/binary trees.
52+
class_label: For classifiers, the class index to explain. ``None`` is passed to the
53+
C++ parser as ``-1`` and defaults to class ``1``. For binary classifiers
54+
(``Logloss``/``CrossEntropy``), ``0`` negates the class-``1`` log-odds. It is
55+
ignored for regression trees.
5556
5657
Returns:
5758
A list of ``TreeModel`` instances, one per CatBoost tree.
5859
"""
5960
byte_array = json.dumps(model_json, separators=(",", ":")).encode("utf-8")
61+
# without a model object, binary classifiers are identified by their loss
6062
return _mark_float32_input(
6163
parse_catboost_json_treemodels(byte_array, -1 if class_label is None else class_label)
6264
)
@@ -69,13 +71,17 @@ def convert_catboost_model(
6971
"""Convert a CatBoost model to the unified internal tree format used by shapiq.
7072
7173
The converter uses CatBoost's JSON export and currently supports numeric
72-
``FloatFeature`` splits. For multiclass CatBoost models, pass ``class_label`` to
73-
select the raw margin for one class. If ``class_label`` is ``None``, the C++ parser
74-
defaults to class ``1`` for multiclass models.
74+
``FloatFeature`` splits. For CatBoost classifiers, pass ``class_label`` to select the
75+
raw margin for one class; ``None`` defaults to class ``1``. Binary classifiers model the
76+
class-``1`` log-odds, so ``class_label=0`` negates the trees.
7577
"""
7678
byte_array = _catboost_model_to_json_bytes(model)
7779
return _mark_float32_input(
78-
parse_catboost_json_treemodels(byte_array, -1 if class_label is None else class_label)
80+
parse_catboost_json_treemodels(
81+
byte_array,
82+
-1 if class_label is None else class_label,
83+
isinstance(model, CatBoostClassifier),
84+
)
7985
)
8086

8187

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

Lines changed: 64 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ struct CatBoostJsonModel
2121
std::vector<CatBoostObliviousTree> trees;
2222
std::vector<double> bias_values{0.0};
2323
double scaling = 1.0;
24+
std::string loss_function; // model_info.params.loss_function.type, empty if absent
2425
};
2526

2627
class JsonStream
@@ -209,6 +210,56 @@ class JsonStream
209210
}
210211
}
211212

213+
// Calls on_key(key) for every key of the next JSON object; on_key must consume the value.
214+
// A value that is not an object is skipped.
215+
template <typename OnKey>
216+
void forEachKey(OnKey on_key)
217+
{
218+
skipWhitespace();
219+
if (pos >= size || data[pos] != '{')
220+
{
221+
skipValue();
222+
return;
223+
}
224+
expect('{');
225+
if (consume('}'))
226+
return;
227+
while (true)
228+
{
229+
std::string key = readString();
230+
expect(':');
231+
on_key(key);
232+
if (consume('}'))
233+
return;
234+
expect(',');
235+
}
236+
}
237+
238+
// Reads the training loss, model_info.params.loss_function.type.
239+
void parseModelInfo(CatBoostJsonModel &model)
240+
{
241+
forEachKey([&](const std::string &info_key) {
242+
if (info_key != "params")
243+
{
244+
skipValue();
245+
return;
246+
}
247+
forEachKey([&](const std::string &params_key) {
248+
if (params_key != "loss_function")
249+
{
250+
skipValue();
251+
return;
252+
}
253+
forEachKey([&](const std::string &loss_key) {
254+
if (loss_key == "type")
255+
model.loss_function = readString();
256+
else
257+
skipValue();
258+
});
259+
});
260+
});
261+
}
262+
212263
void parseScaleAndBias(CatBoostJsonModel &model)
213264
{
214265
expect('[');
@@ -381,6 +432,8 @@ class JsonStream
381432
expect(':');
382433
if (key == "features_info")
383434
parseFeaturesInfo(model);
435+
else if (key == "model_info")
436+
parseModelInfo(model);
384437
else if (key == "scale_and_bias")
385438
parseScaleAndBias(model);
386439
else if (key == "oblivious_trees")
@@ -450,10 +503,12 @@ static void fill_catboost_tree_node(
450503
tree.node_sample_weights[node_id] = tree.node_sample_weights[left_child] + tree.node_sample_weights[right_child];
451504
}
452505

453-
ParsedForest parse_catboost_json_to_forest(const char *json_data, size_t json_size, int class_label)
506+
// is_classifier: the caller knows the model is a classifier even if its loss is a custom one.
507+
ParsedForest parse_catboost_json_to_forest(const char *json_data, size_t json_size, int class_label, bool is_classifier)
454508
{
455509
JsonStream stream(json_data, json_size);
456510
CatBoostJsonModel model = stream.parseModel();
511+
bool binary_loss = model.loss_function == "Logloss" || model.loss_function == "CrossEntropy";
457512

458513
ParsedForest forest;
459514
size_t tree_count = model.trees.size();
@@ -473,11 +528,15 @@ ParsedForest parse_catboost_json_to_forest(const char *json_data, size_t json_si
473528
effective_class_label = 0;
474529
else if (effective_class_label < 0)
475530
effective_class_label = 1;
476-
if (effective_class_label < 0 || effective_class_label >= class_count)
477-
throw std::runtime_error("CatBoost class_label is outside the available class range.");
531+
check_class_label(effective_class_label, class_count);
478532
if (static_cast<size_t>(effective_class_label) >= model.bias_values.size())
479533
throw std::runtime_error("CatBoost scale_and_bias does not contain the selected class bias.");
480534
double bias_per_tree = model.bias_values[static_cast<size_t>(effective_class_label)] / static_cast<double>(tree_count == 0 ? 1 : tree_count);
535+
// a binary classifier has a single raw output, the class-1 log-odds
536+
double class_sign = (class_count == 1 && (is_classifier || binary_loss)) ? binary_class_sign(class_label) : 1.0;
537+
forest.negated_class_one = class_sign < 0.0;
538+
double scaling = class_sign * model.scaling;
539+
double bias = class_sign * bias_per_tree;
481540

482541
std::vector<double> leaf_values(leaf_count);
483542
for (uint64_t i = 0; i < leaf_count; ++i)
@@ -507,12 +566,12 @@ ParsedForest parse_catboost_json_to_forest(const char *json_data, size_t json_si
507566
if (depth == 0)
508567
{
509568
parsed_tree.node_ids[0] = 0;
510-
parsed_tree.values[0] = model.scaling * leaf_values[0] + bias_per_tree;
569+
parsed_tree.values[0] = scaling * leaf_values[0] + bias;
511570
parsed_tree.node_sample_weights[0] = leaf_weights[0];
512571
}
513572
else
514573
{
515-
fill_catboost_tree_node(cat_tree.splits, leaf_values, leaf_weights, model.nan_treatments, parsed_tree, depth, internal_count, 0, 0, model.scaling, bias_per_tree);
574+
fill_catboost_tree_node(cat_tree.splits, leaf_values, leaf_weights, model.nan_treatments, parsed_tree, depth, internal_count, 0, 0, scaling, bias);
516575
}
517576
forest.trees.push_back(std::move(parsed_tree));
518577
}

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

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,8 @@ static PyObject *forest_to_treemodel_list(const ParsedForest &forest, const char
265265
Py_DECREF(result);
266266
return NULL;
267267
}
268-
if (PyDict_SetItemString(kwargs, "decision_type", decision_type) < 0)
268+
if (PyDict_SetItemString(kwargs, "decision_type", decision_type) < 0 ||
269+
(forest.negated_class_one && PyDict_SetItemString(kwargs, "negated_class_one", Py_True) < 0))
269270
{
270271
Py_DECREF(decision_type);
271272
Py_DECREF(kwargs);
@@ -709,6 +710,14 @@ static PyObject *create_edge_tree_arrays(PyObject *self, PyObject *args)
709710
}
710711

711712

713+
// Raises a C++ parser exception as a Python exception: invalid arguments (e.g. an invalid
714+
// class_label) as ValueError, everything else as RuntimeError.
715+
static void set_parser_error(const std::exception &exc)
716+
{
717+
PyObject *type = dynamic_cast<const std::invalid_argument *>(&exc) ? PyExc_ValueError : PyExc_RuntimeError;
718+
PyErr_SetString(type, exc.what());
719+
}
720+
712721
static PyObject *parse_xgboost_ubjson(PyObject *self, PyObject *args)
713722
{
714723
(void)self;
@@ -727,7 +736,8 @@ static PyObject *parse_xgboost_ubjson(PyObject *self, PyObject *args)
727736
static_cast<const uint8_t *>(ubjson_buffer.buf),
728737
static_cast<size_t>(ubjson_buffer.len),
729738
class_label,
730-
margin_base_score);
739+
margin_base_score,
740+
false);
731741

732742
PyObject *node_ids = forest_field_to_pylist<int64_t>(forest, &ParsedTreeArrays::node_ids, NPY_INT64);
733743
PyObject *feature_ids = forest_field_to_pylist<int64_t>(forest, &ParsedTreeArrays::feature_ids, NPY_INT64);
@@ -778,7 +788,7 @@ static PyObject *parse_xgboost_ubjson(PyObject *self, PyObject *args)
778788
catch (const std::exception &exc)
779789
{
780790
PyBuffer_Release(&ubjson_buffer);
781-
PyErr_SetString(PyExc_RuntimeError, exc.what());
791+
set_parser_error(exc);
782792
return NULL;
783793
}
784794
}
@@ -789,9 +799,10 @@ static PyObject *parse_xgboost_ubjson_treemodels(PyObject *self, PyObject *args)
789799
Py_buffer ubjson_buffer;
790800
int class_label = -1;
791801
double margin_base_score = 0.0;
802+
int is_classifier = 0;
792803
ubjson_buffer.buf = NULL;
793804

794-
if (!PyArg_ParseTuple(args, "y*id", &ubjson_buffer, &class_label, &margin_base_score))
805+
if (!PyArg_ParseTuple(args, "y*id|p", &ubjson_buffer, &class_label, &margin_base_score, &is_classifier))
795806
{
796807
return NULL;
797808
}
@@ -802,7 +813,8 @@ static PyObject *parse_xgboost_ubjson_treemodels(PyObject *self, PyObject *args)
802813
static_cast<const uint8_t *>(ubjson_buffer.buf),
803814
static_cast<size_t>(ubjson_buffer.len),
804815
class_label,
805-
margin_base_score);
816+
margin_base_score,
817+
is_classifier != 0);
806818
PyObject *result = forest_to_treemodel_list(forest, "<", true);
807819
if (!result)
808820
{
@@ -815,7 +827,7 @@ static PyObject *parse_xgboost_ubjson_treemodels(PyObject *self, PyObject *args)
815827
catch (const std::exception &exc)
816828
{
817829
PyBuffer_Release(&ubjson_buffer);
818-
PyErr_SetString(PyExc_RuntimeError, exc.what());
830+
set_parser_error(exc);
819831
return NULL;
820832
}
821833
}
@@ -825,9 +837,10 @@ static PyObject *parse_lightgbm_string_treemodels(PyObject *self, PyObject *args
825837
(void)self;
826838
Py_buffer model_string_buffer;
827839
int class_label = -1;
840+
int is_classifier = 0;
828841
model_string_buffer.buf = NULL;
829842

830-
if (!PyArg_ParseTuple(args, "y*i", &model_string_buffer, &class_label))
843+
if (!PyArg_ParseTuple(args, "y*i|p", &model_string_buffer, &class_label, &is_classifier))
831844
{
832845
return NULL;
833846
}
@@ -837,7 +850,8 @@ static PyObject *parse_lightgbm_string_treemodels(PyObject *self, PyObject *args
837850
ParsedForest forest = parse_lightgbm_text_to_forest(
838851
static_cast<const char *>(model_string_buffer.buf),
839852
static_cast<size_t>(model_string_buffer.len),
840-
class_label);
853+
class_label,
854+
is_classifier != 0);
841855
PyObject *result = forest_to_treemodel_list(forest, "<=", false);
842856
if (!result)
843857
{
@@ -850,7 +864,7 @@ static PyObject *parse_lightgbm_string_treemodels(PyObject *self, PyObject *args
850864
catch (const std::exception &exc)
851865
{
852866
PyBuffer_Release(&model_string_buffer);
853-
PyErr_SetString(PyExc_RuntimeError, exc.what());
867+
set_parser_error(exc);
854868
return NULL;
855869
}
856870
}
@@ -860,24 +874,25 @@ static PyObject *parse_catboost_json_treemodels(PyObject *self, PyObject *args)
860874
(void)self;
861875
Py_buffer json_buffer;
862876
int class_label = -1;
877+
int is_classifier = 0;
863878
json_buffer.buf = NULL;
864879

865-
if (!PyArg_ParseTuple(args, "y*i", &json_buffer, &class_label))
880+
if (!PyArg_ParseTuple(args, "y*i|p", &json_buffer, &class_label, &is_classifier))
866881
{
867882
return NULL;
868883
}
869884

870885
try
871886
{
872-
ParsedForest forest = parse_catboost_json_to_forest(static_cast<const char *>(json_buffer.buf), static_cast<size_t>(json_buffer.len), class_label);
887+
ParsedForest forest = parse_catboost_json_to_forest(static_cast<const char *>(json_buffer.buf), static_cast<size_t>(json_buffer.len), class_label, is_classifier != 0);
873888
PyObject *result = forest_to_treemodel_list(forest, "<=", false);
874889
PyBuffer_Release(&json_buffer);
875890
return result;
876891
}
877892
catch (const std::exception &exc)
878893
{
879894
PyBuffer_Release(&json_buffer);
880-
PyErr_SetString(PyExc_RuntimeError, exc.what());
895+
set_parser_error(exc);
881896
return NULL;
882897
}
883898
}

0 commit comments

Comments
 (0)