Skip to content

FEA Categorical split support for DecisionTree*, and RandomForest* - #33354

Merged
adam2392 merged 138 commits into
scikit-learn:mainfrom
adam2392:nocats-v2
Jul 10, 2026
Merged

adam2392 merged 138 commits into
scikit-learn:mainfrom
adam2392:nocats-v2

Conversation

@adam2392

@adam2392 adam2392 commented Feb 22, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Supersedes #12866 #4899 and #7068 , #3346

Supersedes #29437 because the diff was too complicated relative to main.

Took some inspiration from: cakedev0#2, so I would say we should say this is co-authored with @cakedev0. Instead of only using a uint64_t to encode the bitset, I opt for uint64_t*, which future proofs our ability to handle much larger cardinality categories, which will be useful for the categorical support in ExtraTrees*.

What does this implement/fix? Explain your changes.

Implements splitting rules when categorical data is given in a decision tree classifier/regressor. For now, limits it to use the breiman shortcut to demonstrate the value and the main implementation changes. Downstream features (outlined in the next section) can be more simply added after this PR.

  • Tree data structures are moved to maintain the cimport/import sequence (ParentInfo, SplitRecord, Node) -> _utils.pxd
  • Adds partitioning of samples given a category (this complements nicely the partitioning of samples given a numerical threshold)
  • Adds splitting logic given a category
  • add deterministic unit-tests, performance tests, and basic error checks. The deterministic test for a tree I think is correct... Its very useful because it checks that we are tracking categorical splitting over multiple split nodes (at least 2 levels).
  • implemented the breiman shortcut.

Also ran this benchmark, which compares one-hot-encoding (OHE), ordinal (ord), and native-categorical support (cat); I had to group-encode rare categories to make this all fit within the constraint of "256" max categories:

There are two results worth looking at. The first is using default parameters where max_features = 'sqrt'. I shuffled up the categories after ordinal encoding.

categorical_benchmark

The second is where we fix max_features=None, so it samples all features:
categorical_benchmark

(Interestingly, if you order the categories by their occurrence, then the ordinal approach does quite well. This probably opens up a door of heuristics that we can later on add for categorical support. there is no 1 right-answer for everything, so I think it's totally reasonable).

Here, OHE is abysmally slow, and performance is essentially equivalent with native categorical support being on average the best. Surprisingly the ordinal strategy is quite good. It could be due to the fact that maybe I'm cutting categorical support down by group-encoding rare categories, which could be informative. It has ~10+x deeper trees, and almost 3-5x longer fittime.

Open TODO In a downstream PR

  1. [Feature] Add a bitset cache (i.e. a uint64_t memory view) that allows us to compute the category split as we traverse the tree for inference speedup
  2. [Feature] Brute-force search; expands categorical support to multi-class and multi-output problems
  3. [Refactor] Consolidate the goes_left operation to work at inference time too
  4. [Refactor] Understand the bitset operations and merge these with the HistGradientBoosting bitset operations
  5. [Feature] Implement categorical splitting for RandomSplitter for ExtraTrees. Pretty easy now that we have an arbitrary sized bitset, which we can expand to hold many categories in the case of a randomized tree
  6. [Feature] Add support for sparse categorical splitting with best and random splitter
  7. [Feature] Add support for categorical in exporting tree

Any other comments?

May be related to #24967

@adam2392 adam2392 changed the title Nocats v2 FEA Categorical split support for DecisionTree*, and RandomForest* Feb 22, 2026
@adam2392

Copy link
Copy Markdown
Member Author

I got bored over the weekend, so here is this feature I've been dying to get into scikit-learn! Yay snow.

@lorentzenchr

Copy link
Copy Markdown
Member

@cakedev0 Your review would help a lot.

[Feature] Add a bitset cache (i.e. a uint64_t memory view) that allows us to compute the category split as we traverse the tree for inference speedup

The HGBT uses bitsets, see sklearn/ensemble/_hist_gradient_boosting/_bitset.pyx. Maybe, one can put it into utils and reuse here.

@adam2392

Copy link
Copy Markdown
Member Author

Good point @lorentzenchr! I was hoping we can do that in a follow on PR to keep the diff relatively contained. I tried it in the previous PR but there's a lot of diff from moving things around essentially.

I.e. item 4 :p

@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Feb 22, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Feb 22, 2026
@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Feb 22, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Feb 22, 2026
@cakedev0

Copy link
Copy Markdown
Member

I will for sure give it a review. I took a quick look already and it looks pretty nice at first sight 👍 you took the best of our preceding PRs I think ^^ (though I don't fully remember them 😅 )

I took a look at the possible TODOs, and here is my opinon

  1. I don't really understand what it is (but probably should be done in an other PR as it's just an optimization)
  2. Let's do it in another PR.
  3. That sounds like a great idea! I think you can give it a try in this PR if you want, I don't think it will increase the diff too much. But it can also wait for another PR (let's not forget about it though! ^^).
  4. I agree that it's better for the diff to do it later (should be a quick merge just after this one)
  5. I don't have it clearly in mind, but if it's really easy / doesn't increase the diff much, maybe you can do it in this PR?
  6. Sparse can really wait I think ^^
  7. Let's do it in another PR (note: along with correctly handling the "missing go to left/right" display).

One thing that concerns me, and that we'll need to address before really publicizing the categorical support is the risk of over-fitting, see cakedev0#2 (comment). But I think it's fine to address it later, in another PR.

Also, I'd appreciate that we merge #32119 first, it's been opened for a while and it will have some conflicts with this one... (nothing hard to solve, but still...). If have some boredom left, can you give it a review? 😉

@cakedev0

cakedev0 commented Feb 23, 2026 •

Copy link
Copy Markdown
Member

Can you copy the adapted test_split.py from here? I'd like to have this test to continue covering the split logic entirely.

@ogrisel

ogrisel commented Feb 23, 2026 •

Copy link
Copy Markdown
Member

(Interestingly, if you order the categories by their occurrence, then the ordinal approach does quite well. This probably opens up a door of heuristics that we can later on add for categorical support. there is no 1 right-answer for everything, so I think it's totally reasonable).

I think we should add an option for ordinal encoding by number of occurrences in the training set (independently of this PR), see: #32161. Feel free to say so there so that we can remove the "Needs decision: include features" label and unleash the flow of contributors ;)

@cakedev0 cakedev0 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.

Here is a first pass, many small things, no big blockers. I'll let you clean up, add the split tests, and fix the CI before making a second path.

Comment thread sklearn/tree/meson.build Resolved
Comment thread sklearn/tree/_utils.pyx Resolved
Comment thread sklearn/tree/_tree.pyx Resolved
Comment thread sklearn/tree/_tree.pyx Resolved
Comment thread sklearn/tree/_tree.pyx Resolved
Comment thread sklearn/tree/_partitioner.pyx Resolved
Comment thread sklearn/ensemble/_forest.py Resolved
Comment thread sklearn/tree/_classes.py Resolved
Comment thread sklearn/tree/_splitter.pyx Resolved
Comment thread sklearn/tree/_splitter.pxd Resolved

@lorentzenchr lorentzenchr 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.

LGTM, finally - after yeeeeeeeeears! Thanks @adam2392 for pushing it.

2 remarks:

  • Now it's +1'478 -195 loc changed (at some point it was more than +1800).
  • I expect the follow-up work for random forests and gradient boosting to be not that trivial. Some (private) API is needed to pass the cat encoding to the trees and skip validation there.

@lorentzenchr

Copy link
Copy Markdown
Member

@thomasjpfan @cakedev0 @adam2392 If there is anything else you want to add, I leave it unmerged for a few days.

@adam2392

adam2392 commented Jul 3, 2026 •

Copy link
Copy Markdown
Member Author

Now it's +1'478 -195 loc changed (at some point it was more than +1800).

Yes thank you and @cakedev0 and @thomasjpfan very much for the reviews, and ideas throughout this long process. And also @adrinjalali for the historical work!

I expect the follow-up work for random forests and gradient boosting to be not that trivial. Some (private) API is needed to pass the cat encoding to the trees and skip validation there.

Yep. I think RF is the logical next step, and then some fast-follow-up work outlined in #33965 . Somewhere there, I can consolidate the design to use ColumnTransformer to make the design at a high-level look very similar to HGBT.

@adam2392

adam2392 commented Jul 3, 2026

Copy link
Copy Markdown
Member Author

@thomasjpfan @cakedev0 @adam2392 If there is anything else you want to add, I leave it unmerged for a few days.

I'll ping @scikit-learn/core-devs actually since this is so "big" and "new". Tho if you have comments that require me to refactor things here... I kindly ask maybe that I can do it as a follow-up :p.

@cakedev0 cakedev0 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.

LGTM, I think we can merge by the end of the week.

One minor catch from codex, but it can be fixed in another PR if you don't have time this week @adam2392.

The fact that the behavior is aligned with HGB is great (as we ultimately want to merge GB with HGB, at least publicly) and makes me confident this PR can be safely merged and that the API/decisions will remain stable.


About the subsequent work, I agree with @lorentzenchr about that:

I expect the follow-up work for random forests and gradient boosting to be not that trivial. Some (private) API is needed to pass the cat encoding to the trees and skip validation there.

I'd like to try implementing histograming in decision trees before doing this, as it will have the same kind of API need to be exposed in RF/GB. And doing both at the same time might help in finding a better design.

assert r2 > 0.99


def test_partial_dependence_recursion_decision_tree_categorical_target_feature():

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.

This test breaks / this feature is not implemented for categorical features that don't map to their encoding.

It's really not trivial to support categorical support in BaseDecisionTree._compute_partial_dependence_recursion, so let's just raise a not implemented error.

@adam2392

adam2392 commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

I'd like to try implementing histograming in decision trees before doing this, as it will have the same kind of API need to be exposed in RF/GB. And doing both at the same time might help in finding a better design.

I think I looked into this, and seems hard. We want to store the data as uint type within the Cython code. WDYT? Maybe we can continue the discussion in #33965

@adam2392

Copy link
Copy Markdown
Member Author

Going to merge this tmr!

@adam2392
adam2392 merged commit b8e52fc into scikit-learn:main Jul 10, 2026
33 checks passed
@github-project-automation github-project-automation Bot moved this from In progress to Done in Labs Jul 10, 2026
@lorentzenchr

Copy link
Copy Markdown
Member

Finally 🎉 🚀 🌲

@adam2392 Very minor note (more a remark on history): While not written as governance it is custom in scikit-learn that a reviewer merges.

@adam2392

adam2392 commented Jul 13, 2026 •

Copy link
Copy Markdown
Member Author

@adam2392 Very minor note (more a remark on history): While not written as governance it is custom in scikit-learn that a reviewer merges.

Ah didn't know that. But TIL. Thanks for the note!

I got trigger happy

@lorentzenchr

Copy link
Copy Markdown
Member

I got trigger happy

Me too!

@h-vetinari

Copy link
Copy Markdown
image

Apologies for the exaggeration, obviously it took only a tad over 11 years since #4899 😜

No but seriously: thanks and congrats 🥳🤩

@lorentzenchr

Copy link
Copy Markdown
Member

Well, someone with the endurance to finish it has to do the work.

This feature is in good company alongside with

  • gap safe screening rules, see this blog post (more than 10 years)
  • Whittaker-Henderson smoothing in scipy 1.18 (more than 100 years old!)

prady0t pushed a commit to prady0t/scikit-learn that referenced this pull request Sep 2, 2026
scikit-learn#33354)

Co-authored-by: Adam Li <[email protected]>
Co-authored-by: Arthur Lacote <[email protected]>
Co-authored-by: Christian Lorentzen <[email protected]>
Co-authored-by: Thomas J. Fan <[email protected]>
@jeremiedbb jeremiedbb mentioned this pull request Sep 8, 2026
14 tasks done
MilindLate pushed a commit to MilindLate/scikit-learn that referenced this pull request Oct 31, 2026
…-learn#35221)

- Docstring incorrectly stated 'at most 255 unique categories'. The
  actual limit is 256 with splitter='best' (bitset capacity) and
  16,777,216 with splitter='random'. The ordinal encoding added in
  scikit-learn#33354 means raw input values are no longer required to be in any
  specific range; only the *number* of unique categories is limited.

- Error message referred to encoded value range [0, 255] which is an
  internal implementation detail, not a property of the user's data.
  Replaced with a clear, actionable message:
    'Categorical feature N has K categories, but at most M are
     supported with splitter=...'

Fixes scikit-learn#35221
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Transformer for nominal categories, with the goal of improving category support in decision trees

8 participants