Skip to content

ENH Add categorical support for the forests - #34832

Merged
ogrisel merged 18 commits into
scikit-learn:mainfrom
adam2392:feat/cat-forest
Oct 16, 2026
Merged

ogrisel merged 18 commits into
scikit-learn:mainfrom
adam2392:feat/cat-forest

Conversation

@adam2392

@adam2392 adam2392 commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Towards: #33965

What does this implement/fix? Explain your changes.

Adds native categorical support to RandomForest* and ExtraTrees* via categorical_features, same idea as decision trees, and HGBT.

The forest encodes once, then passes the resolved bool mask into each tree so "from_dtype" / feature names are not dropped after X becomes a NumPy array. Trees fitted through the forest skip a second OrdinalEncoder pass when they already get that mask (check_input=False), which avoids an extra copy per tree under n_jobs. For forest categorical_features, default is "from_dtype" (aligned with HGBT).

This PR adds mostly documentation copy/pasted across RandomForest* and ExtraTrees* classes within sklearn/ensemble/.

IsolationForest categorical support is stacked in adam2392#13.

AI usage disclosure

I used AI assistance for:

  • Code generation (e.g., when writing an implementation or fixing a bug)
  • Test/benchmark generation
  • Documentation (including examples)
  • Research and understanding

Any other comments?

n/a

@github-actions github-actions Bot added module:ensemble CI:Linter failure The linter CI is failing on this PR labels Aug 28, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Sep 8, 2026
@adam2392 adam2392 changed the title Add categorical support for the forests ENH Add categorical support for the forests Sep 11, 2026
Enable native categorical splits in RandomForest, ExtraTrees, and
IsolationForest through the categorical_features parameter.
@adam2392
adam2392 marked this pull request as ready for review September 11, 2026 02:20
@cakedev0

Copy link
Copy Markdown
Member

🤩 It looks surprisingly clean/easy at first sight!! I'll try to take a deeper look soon!

@cakedev0 cakedev0 added this to Labs Sep 11, 2026
@cakedev0 cakedev0 moved this to PR waiting for reviews in Labs Sep 11, 2026

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

Thanks for the work, a few things to address, including one that might not be easy (but maybe it's not that hard 🤞 )

Comment thread sklearn/ensemble/tests/test_forest.py Resolved
Comment thread sklearn/ensemble/_iforest.py Resolved
Comment thread sklearn/ensemble/_iforest.py Resolved
@cakedev0 cakedev0 moved this from PR waiting for reviews to In progress in Labs Sep 11, 2026
Pass the resolved bool mask into base trees so from_dtype/name-based
categorical_features are not dropped after forest encoding, skip
per-tree OrdinalEncoder copies when check_input=False, and align
IsolationForest ensure_all_finite with the non-categorical path.
@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Sep 12, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Sep 12, 2026

@adam2392 adam2392 left a comment •

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.

From codex, I was trying to understand how big of a gap we have relative to HGBT. The main thing worth discussing is probably the "from_dtype" default that is present in HGBT, but not RF/ET. I think we can just support "from_dtype" since that's the default in HGBT, and there's nothing stopping us.

Everything else actually seems to match between RF + HGBT, which is great!

Matches trees (by design)

Forest categorical_features bullets match DecisionTree* / ExtraTree*: None, Boolean mask, integer indices, string names, "from_dtype", default None, missing values / np.nan, and unknown categories → missing.

Limits are mirrored by the base learner:

Forest Tree counterpart Documented limit
RandomForest DecisionTree(splitter="best") ≤255 categories; binary / single-output
ExtraTrees ExtraTree(splitter="random") ~16M categories; multiclass / multi-output supported

Runtime matches that story: the forest encodes once using the same OrdinalEncoder-style path as trees, keeps the original column order, and then passes the resolved Boolean mask into the trees. Sparse input with categorical features raises NotImplementedError, as it does for trees.

Does not match HGBT

Forest / Tree HGBT
Default None "from_dtype"
Capacity Fixed at 255 or ~16M max_bins (≤255)
Task limits in parameter docs RF: binary/single-output; Extra Trees: broader None (HGBT is its own model)
Internal layout Remaps categorical features back to their original order Keeps categorical features first via _is_categorical_remapped
Architecture Actual trees that can preprocess again TreeGrower operating on pre-binned data

Therefore, forests intentionally align with decision trees, not with HGBT’s "from_dtype"-by-default / max_bins behavior.

Documentation note

  1. is_categorical_ is documented only for RandomForestClassifier, although all four forest estimators set it.

Comment thread sklearn/ensemble/_forest.py Resolved
…check_input

BaseDecisionTree._fit inferred "X is already encoded" from
check_input=False combined with categorical_features being a bool
ndarray of the right shape. This heuristic is reachable from the
public fit() too, since check_input is a public parameter: calling
DecisionTreeClassifier(categorical_features=<bool mask>).fit(X, y,
check_input=False) on raw, unencoded data hits the same fast path and
crashes (TypeError at fit time, or AttributeError on a later normal
predict() since _preprocessor is left None).

Replace the heuristic with an explicit private categorical_counts
argument that only ensembles pass, and move the per-column category
count computation into _preprocess_X (computed once there) instead of
having every tree of an ensemble rescan the identical encoded X to
recompute it. Also guard the check_input=True predict path so it
doesn't call _preprocess_X when _preprocessor is None (already-encoded
tree), mirroring the guard already present on the check_input=False
path.

IsolationForest (via BaggingClassifier/Regressor's generic
_parallel_build_estimators) relied on the same check_input=False
heuristic through the public estimator.fit(), so it now calls the
private estimator._fit() directly with a categorical_counts array
subset/reordered to match the sampled features.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@adam2392

Copy link
Copy Markdown
Member Author

Let's just do the two-release deprecation cycle for the categorical_features="from_dtype" parameter (though I'm a bit afraid to bother all RFs users with a warning... happy to have other opinions on this one).

Added in this commit the plan for deprecation cycle: f62b8b1

@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Sep 23, 2026

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

This looks ready to me 🎉 nice work thanks!

I was worried the deprecation cycle / future warning would spam every single user for the duration of one release, but we can limit firing the future warning to dataframes with a least one categorical column (which is likely very rare for an all numerical dataframe), so it's totally fine and I'm convinced it's the way to go 👍

@lorentzenchr

Copy link
Copy Markdown
Member

@thomasjpfan @ogrisel your review would make a difference for this PR.

@lorentzenchr

Copy link
Copy Markdown
Member

@adam2392 In your analysis, the "Internal layout" is different from HGBT. Would we have advantages if they were aligned?
@cakedev0 What about your proof of concept cakedev0#18?

@cakedev0

Copy link
Copy Markdown
Member

the "Internal layout" is different from HGBT. Would we have advantages if they were aligned?

The "internal layout" of HGB causes a few minor bugs when fitted with categorical values. My PR cakedev0#18 aligns it with how we do it in trees/forests, which fixes 3 bugs:

  • interaction_cst applied to the wrong features
  • partial_dependence(method="recursion") computed for the wrong feature
  • the cardinality error reporting the wrong feature index.

About my PR cakedev0#18: it's a bit more than a proof of concept, it maybe still needs a bit of polishing but I've put quite some effort & thoughts into it, even though it's heavily AI assisted. It's a follow-up of this PR and I'm very happy with it, I think it's a great improvement of the code base (less lines of logic/less duplication, more features, less bugs).

@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Oct 15, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Oct 16, 2026

@ogrisel ogrisel 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 did a review and overall LGTM for merge once the following minor things are addressed.

I hope that a follow-up based on cakedev0#18 will help futher improve the consistency of missing value handling among tree-based models by factorizing common logic in more maintainable code.

has_categorical = False

if has_categorical and self.warm_start and getattr(self, "estimators_", None):
raise ValueError(

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.

Note that we could try to re-encode and check whether or not the resulting encoding is consistent with the previous fit or not, and only raise when this is not the case.

I am fine to do that as a follow and just add a TODO inline comment for now if you agree that this is a good plan.

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.

I'm doing this in a follow-up PR: adam2392#14, and for now, we can leave this alone(?)

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.

Basically, imo if our goal is alignment, I'll just copy/paste the behavior that HGBT has for warm-start

Comment thread sklearn/ensemble/_forest.py Resolved
Comment thread sklearn/ensemble/_forest.py Outdated
- `"from_dtype"`: dataframe columns with dtype "Categorical" and "Enum" are
considered to be categorical features. The input must be a dataframe that
is supported by narwhals (or supports it): :func:`narwhals.from_native` must
work. This is the case, for instance, for pandas and polars DataFrames.

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.

There is a structure or grammatical problem in the sentence that starts with "The input must be a datafram..."

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.

Note that this problem is also present in the other classes' docstrings of this PR but also in the tree classes' docstrings.

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.

Resolved: de0f903

@adam2392

Copy link
Copy Markdown
Member Author

Note that we could try to re-encode and check whether or not the resulting encoding is consistent with the previous fit or not, and only raise when this is not the case.

I am fine to do that as a follow and just add a TODO inline comment for now if you agree that this is a good plan.

@ogrisel or @lorentzenchr I will let you merge and I can address the warm-start comment in adam2392#14?

@ogrisel
ogrisel enabled auto-merge (squash) October 16, 2026 17:04
@ogrisel
ogrisel merged commit 85593ca into scikit-learn:main Oct 16, 2026
35 checks passed
@github-project-automation github-project-automation Bot moved this from PR waiting for reviews to Done in Labs Oct 16, 2026
@lorentzenchr

Copy link
Copy Markdown
Member

Wow, congrats! This is quite an achievement. I hope it will prove as user friendly improvement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

module:ensemble 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.

5 participants