Skip to content

FIX raise NotImplementedError for recursion PDP with categorical target features - #34554

Merged
adam2392 merged 9 commits into
scikit-learn:mainfrom
cakedev0:fix/pdp-recursion-categorical-target
Nov 3, 2026
Merged

adam2392 merged 9 commits into
scikit-learn:mainfrom
cakedev0:fix/pdp-recursion-categorical-target

Conversation

@cakedev0

@cakedev0 cakedev0 commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Follow-up from #33354, addresses #33354 (comment)

What does this implement/fix? Explain your changes.

BaseDecisionTree._compute_partial_dependence_recursion passed grid values straight to tree_.compute_partial_dependence, which routes categorical splits by casting the raw feature value to a bitset index. But categorical values are ordinal-encoded by _categorical_encoder at fit time, and predict/apply re-encode through _transform_categorical_features before reaching the tree — the recursion path never did. It silently returned wrong values whenever the raw categories didn't already coincide with their 0..n_categories-1 encoding.

As discussed in review, supporting this properly isn't trivial (the grid would need to go through the fitted encoder), so for now let's just raise a NotImplementedError for categorical target features.

While looking into this, found that HistGradientBoosting* has a related but distinct bug: _predictor.pyx::_compute_partial_dependence (the recursion tree walker) has no categorical branch at all, and grower.py never sets num_threshold for categorical splits, so recursion silently used a <= 0.0 split for any categorical target feature (not "correct by coincidence" like trees could be, just wrong). Applied the same fix there and parametrized the regression test over DecisionTreeRegressor, HistGradientBoostingRegressor and HistGradientBoostingClassifier.

AI usage disclosure

I used AI assistance for:

  • Code generation
  • Test update
  • Investigating the HGB bug
  • Writing this

`_compute_partial_dependence_recursion` routed grid points through the
tree's raw categorical bitset, but categorical splits are keyed on the
codes learned by `_categorical_encoder` at fit time (as used by
`predict`/`apply` via `_transform_categorical_features`). The recursion
path skipped that re-encoding, so it silently returned wrong values
whenever the raw categories didn't already coincide with their
0..n_categories-1 encoding.
cakedev0 added 4 commits July 23, 2026 11:35
Confirms method="brute" stays correct with categories that don't
coincide with their internal ordinal encoding (e.g. strings), unlike
the newly-restricted 'recursion' path.
…es in HGB

BaseHistGradientBoosting._compute_partial_dependence_recursion has the
same issue as trees, but worse: the Cython tree walker used by
recursion PDP (_predictor.pyx::_compute_partial_dependence) has no
categorical branch at all and num_threshold is never set for
categorical splits, so it silently used a "<= 0.0" split for any
categorical target feature.

Parametrized the categorical-target-feature NotImplementedError test
over DecisionTreeRegressor, HistGradientBoostingRegressor and
HistGradientBoostingClassifier.
@cakedev0
cakedev0 requested a review from adam2392 September 8, 2026 14:40

@adam2392 adam2392 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh yes I totally forgot about this comment. Thanks for taking the initiative for the fix!

@AnneBeyer AnneBeyer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't followed the discussion on how complex it would be to support categorical target features with recursion here, but throwing an error instead of returning wrong values definitely seems to be a valid quick fix.

One problem I see is that partial_dependence also has the (default) auto option, which is currently resolved irrespective of the nature of the features, and can thus result in the error being raised (maybe this means we also need a test that auto is resolved correctly i.e., without throwing an error?).
I think the check will need to be taken into account herel, as in that it should select brute in that case (and the docstring will need to be updated accordingly):

And since we need the check here anyway, we can also avoid the duplication and throw the error already here

if method == "recursion":

instead of in the estimator classes.

@AnneBeyer

AnneBeyer commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

This one is from Claude and I haven't looked into the categorical column handling in detail yet. Maybe you are faster in assessing whether this is a true bug and if it should be fixed within this PR or in a follow-up:

"HistGradientBoosting recursion still gives wrong results for numerical features. When any feature is categorical, HistGradientBoosting moves the categorical columns to the front internally, but recursion still looks features up by their original column position. The new check only blocks categorical target features, so these results are still silently wrong.

It has to be fixed inside HistGradientBoosting’s _compute_partial_dependence_recursion. Internally the model puts categorical columns first and keeps each group in its original order, so target_features needs to be mapped before the trees are walked:

if self.is_categorical_ is not None:
    remap = np.empty_like(order := np.argsort(~self.is_categorical_, kind="stable"))
    remap[order] = np.arange(order.size)
    target_features = remap[target_features]

This is best checked against self._preprocessor.output_indices_, rather than relying on the column order alone."

@cakedev0

Copy link
Copy Markdown
Member Author

When any feature is categorical, HistGradientBoosting moves the categorical columns to the front internally

True and a cause of many bugs. I have a PR ready to fix that (preserve feature order like it's done in trees/forests). So I think we can ignore that for this PR and let my other PR take care of this case.

…back to brute for auto

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cakedev0

Copy link
Copy Markdown
Member Author

Very good catch and idea for the auto option!! Thanks! I did as you suggested, it's fairly clean & natural 🎉

Comment on lines +613 to +622
if _determine_key_type(features, accept_slice=False) == "int":
# _get_column_indices() supports negative indexing. Here, we limit
# the indexing to be positive. The upper bound will be checked
# by _get_column_indices()
if np.any(np.less(features, 0)):
raise ValueError(f"all features must be in [0, {X.shape[1] - 1}]")

features_indices = np.asarray(
_get_column_indices(X, features), dtype=np.intp, order="C"
).ravel()

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part is moved from below, because I need it to determine has_categorical_target.

@AnneBeyer AnneBeyer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update, LGTM now!

@AnneBeyer

Copy link
Copy Markdown
Member

ping @adam2392, could you please merge this?

cakedev0 added a commit to cakedev0/my-scikit-learn-backlog that referenced this pull request Nov 3, 2026
todo: move [sklearn#35216](scikit-learn/scikit-learn#35216) from Now to Waiting, the test was already there, approved by lesteve with auto-merge
add: Trees: get [sklearn#34554](scikit-learn/scikit-learn#34554) merged (recursion PDP on categorical features; approved)
add: Threads: review [sklearn#34729](scikit-learn/scikit-learn#34729) (inference methods don't modify the estimator; ev-br on the SplineTransformer mutation)
todo: lucyleeow approved [sklearn#35215](scikit-learn/scikit-learn#35215)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@adam2392
adam2392 merged commit ac396ae into scikit-learn:main Nov 3, 2026
38 checks passed
cakedev0 added a commit to cakedev0/my-scikit-learn-backlog that referenced this pull request Nov 3, 2026
done: HGB: get [sklearn#35216](scikit-learn/scikit-learn#35216) merged (binning crash on all-missing features, fixes [sklearn#35164](scikit-learn/scikit-learn#35164)), merged before I removed it
done: Trees: get [sklearn#34554](scikit-learn/scikit-learn#34554) merged (recursion PDP on categorical features)
drop: Threads: answer lesteve on [sklearn#35105](scikit-learn/scikit-learn#35105) (RFC deprecate `pre_dispatch`)
drop: Maintenance: follow up on [sklearn#35209](scikit-learn/scikit-learn#35209) (newton-cg test failing on the macOS x86_64 wheels)
drop: Benchmarks: review [benchmarks#142](probabl-ai/scikit-learn-benchmarks#142) (cuML benchmark config)
drop: Threads: review [sklearn#34729](scikit-learn/scikit-learn#34729) (inference methods don't modify the estimator)
drop: Linear: [sklearn#34793](scikit-learn/scikit-learn#34793) (Ridge centering trick for cholesky), benchmarks in [benchmarks#115](probabl-ai/scikit-learn-benchmarks#115) and [benchmarks#31](probabl-ai/scikit-learn-benchmarks#31)
drop: Upstream: sklearnex reports [sklearnex#3402](uxlfoundation/scikit-learn-intelex#3402), [sklearnex#3377](uxlfoundation/scikit-learn-intelex#3377), [sklearnex#3220](uxlfoundation/scikit-learn-intelex#3220)
drop: Upstream: [data-apis/array-api#976](data-apis/array-api#976) (why `stable=True` is the default for `xp.sort`)
drop: Upstream: dpnp reports [IntelPython/dpnp#3149](IntelPython/dpnp#3149) and [IntelPython/dpnp#3148](IntelPython/dpnp#3148)
drop: Threads: [sklearn#34736](scikit-learn/scikit-learn#34736) (oversubscription in `pairwise_distances`), out of the reported findings item
drop: KMeans: benchmarks [benchmarks#154](probabl-ai/scikit-learn-benchmarks#154), [benchmarks#160](probabl-ai/scikit-learn-benchmarks#160), [OpenBLAS#6105](OpenMathLib/OpenBLAS#6105) and [sklearn#17334](scikit-learn/scikit-learn#17334), out of the [sklearn#35193](scikit-learn/scikit-learn#35193) item
todo: move [joblib#1899](joblib/joblib#1899), [sklearn#35261](scikit-learn/scikit-learn#35261) and [sklearn#35053](scikit-learn/scikit-learn#35053) from Reviews to Now, [sklearn#35181](scikit-learn/scikit-learn#35181) to the top of Waiting (by hand in 03835dd)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

module:inspection module:tree Quick Review For PRs that are quick to review size/M Waiting for Second Reviewer First reviewer is done, need a second one!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants