Repository navigation
Conversation
Enable native categorical splits in RandomForest, ExtraTrees, and IsolationForest through the categorical_features parameter.
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]>
…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]>
FIX Use an explicit categorical_counts arg instead of inferring from check_input
…to feat/cat-forest
The bagging hook is only needed for IsolationForest, so random forests and extra trees can land without it. Co-authored-by: Cursor <[email protected]>
Ship "from_dtype" as an option now and switch the default in 1.13, matching the HistGradientBoosting deprecation cycle. Co-authored-by: Cursor <[email protected]>
…ocessing trees do
Move validation and ordinal encoding of categorical features to sklearn/tree/_preprocessing.py, used by trees, forests, GB and HGB. Encoded columns are written directly into a Fortran-ordered array in the original column order, without ColumnTransformer. HGB no longer moves categorical features first, which fixes interaction_cst, partial dependence with method="recursion" and the cardinality error message when a categorical feature is not first. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Split the sample indices instead of X, bin X once with thresholds fitted on the training samples only (new sample_indices parameter of _BinMapper.fit), then split the binned data column by column. This avoids a float64 copy of X: peak memory is 2.3 to 4 times lower and fit is slightly faster. Fitted models are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Owner
Author
|
Possible follow-ups:
|
Owner
Author
|
@adam2392: heads-up about this PR. I'd like to open it on the official fork once yours (scikit-learn#34832) is merged. I think it's really good: removes a lot a duplication, adds features, fixes bugs, moves things towards unifying GB and HGB. |
…factor # Conflicts: # sklearn/ensemble/_forest.py # sklearn/ensemble/_gb.py # sklearn/ensemble/tests/test_forest.py # sklearn/tree/_classes.py
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TL;DR: this PR removes some code duplication, adds features, fixes bugs, improves performance and moves things towards unifying GB and HGB.
Reference Issues/PRs
Follow-up of scikit-learn#34832 (categorical support in forests). First step towards binning support for trees and towards unifying GB and HGB (scikit-learn#27873).
What does this implement/fix? Explain your changes.
Trees, forests,
GradientBoosting*andHistGradientBoosting*now share the same X validation and categorical encoding, in the newsklearn/tree/_preprocessing.py._check_categorical_featuresis moved there unchanged fromsklearn/utils/validation.py, with its tests, since_encode_categorical_featuresis its only caller.yandsample_weightand encoding are done once in_validate_and_preprocess_input, then_fit_validatedbuilds the tree. Forests call_fit_validateddirectly, so they don't need to know what kind of preprocessing trees do. Trees fitted by forests and GB don't validateyandsample_weightagain either. This savescheck_arraycalls in each tree, which are costly when many trees are fitted in parallel threads, especially on free-threaded Python (see META: lock contention can make thread-parallel code collapse on many-core machines (free-threading) scikit-learn/scikit-learn#35091).ColumnTransformeranymore. This saves time and memory, and fixes bugs in HGB, which moved categorical features first (see below).categorical_featuresand for missing values.predict_stagesnow uses the tree'sgoes_left.interaction_cstapplied to the wrong features,partial_dependence(method="recursion")computed for the wrong feature, and the cardinality error reporting the wrong feature index.sample_indicesparameter of_BinMapper.fit) and then splits the binned data column by column. This avoids a float64 copy of X. Fitted models are bit-identical.Excluding tests and changelogs: +651 / −754 lines, ~120 of them on each side being the move of
_check_categorical_features.AI usage disclosure
I used AI assistance for:
Some small benchmarks
yandsample_weight, on a 2 x 86-core Xeon 6787P (GIL Python 3.14.7,make_classificationwith 100k × 20, 688 trees, median of 9 fits):n_jobsExtraTreesClassifierExtraTreesClassifierRandomForestClassifierRandomForestClassifierOn free-threaded Python, the impact is much bigger on the first fit of a process and then less visible (see scikit-learn#35091 for why).
Any other comments?
check_input=False, a tree no longer checks thatyis a valid classification target. This only affects people who bypass validation on purpose.warm_startis not supported with categorical features in GB, same as forests.