Repository navigation
ENH Add categorical support for the forests - #34832
Conversation
Enable native categorical splits in RandomForest, ExtraTrees, and IsolationForest through the categorical_features parameter.
bb22790 to
64ff7d9
Compare
|
🤩 It looks surprisingly clean/easy at first sight!! I'll try to take a deeper look soon! |
cakedev0
left a comment
There was a problem hiding this comment.
Thanks for the work, a few things to address, including one that might not be easy (but maybe it's not that hard 🤞 )
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.
Co-authored-by: Adam Li <[email protected]>
There was a problem hiding this comment.
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
is_categorical_is documented only forRandomForestClassifier, although all four forest estimators set it.
…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]>
Added in this commit the plan for deprecation cycle: f62b8b1 |
There was a problem hiding this comment.
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 👍
|
@thomasjpfan @ogrisel your review would make a difference for this PR. |
|
@adam2392 In your analysis, 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:
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). |
Co-authored-by: Cursor <[email protected]>
ogrisel
left a comment
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I'm doing this in a follow-up PR: adam2392#14, and for now, we can leave this alone(?)
There was a problem hiding this comment.
Basically, imo if our goal is alignment, I'll just copy/paste the behavior that HGBT has for warm-start
| - `"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. |
There was a problem hiding this comment.
There is a structure or grammatical problem in the sentence that starts with "The input must be a datafram..."
There was a problem hiding this comment.
Note that this problem is also present in the other classes' docstrings of this PR but also in the tree classes' docstrings.
fecfc29 to
de0f903
Compare
@ogrisel or @lorentzenchr I will let you merge and I can address the warm-start comment in adam2392#14? |
|
Wow, congrats! This is quite an achievement. I hope it will prove as user friendly improvement. |
Reference Issues/PRs
Towards: #33965
What does this implement/fix? Explain your changes.
Adds native categorical support to
RandomForest*andExtraTrees*viacategorical_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 afterXbecomes 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 undern_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:
Research and understandingAny other comments?
n/a