Skip to content

ENH Share X validation and categorical encoding across trees, forests, GB and HGB - #18

Closed
cakedev0 wants to merge 32 commits into
mainfrom
trees-validation-refactor
Closed

cakedev0 wants to merge 32 commits into
mainfrom
trees-validation-refactor

Conversation

@cakedev0

@cakedev0 cakedev0 commented Sep 29, 2026 •

Copy link
Copy Markdown
Owner

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* and HistGradientBoosting* now share the same X validation and categorical encoding, in the new sklearn/tree/_preprocessing.py. _check_categorical_features is moved there unchanged from sklearn/utils/validation.py, with its tests, since _encode_categorical_features is its only caller.

  • Trees & forests: validation of X, y and sample_weight and encoding are done once in _validate_and_preprocess_input, then _fit_validated builds the tree. Forests call _fit_validated directly, so they don't need to know what kind of preprocessing trees do. Trees fitted by forests and GB don't validate y and sample_weight again either. This saves check_array calls 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).
  • Encoding: categorical columns are ordinal-encoded straight into an F-ordered array, in the original column order. No ColumnTransformer anymore. This saves time and memory, and fixes bugs in HGB, which moved categorical features first (see below).
  • GB: uses the same helpers, which adds support for categorical_features and for missing values. predict_stages now uses the tree's goes_left.
  • HGB: uses the same helpers too, so categorical features are no longer moved first. This fixes 3 bugs when a categorical feature is not the first column: interaction_cst applied to the wrong features, partial_dependence(method="recursion") computed for the wrong feature, and the cardinality error reporting the wrong feature index.
  • HGB early stopping: the internal validation split now splits indices, bins X once (bin mapper fitted on the training samples only, via a new sample_indices parameter 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:

  • Code generation (closely guided)
  • Test/benchmark generation
  • Documentation (changelogs)

Some small benchmarks

  1. HGB fit, early stopping with the internal validation split, 20 iterations:
n × d fit time (before → after) peak RSS above X (before → after)
1M × 20 0.77 → 0.73 s 260 → 112 MB
1M × 100 2.49 → 2.24 s 1015 → 261 MB
3M × 50 4.12 → 3.90 s 1498 → 364 MB
  1. Forest fit without the per-tree validation of y and sample_weight, on a 2 x 86-core Xeon 6787P (GIL Python 3.14.7, make_classification with 100k × 20, 688 trees, median of 9 fits):
n_jobs before → after
ExtraTreesClassifier 172 (one socket) 1.93 → 1.54 s
ExtraTreesClassifier 344 2.55 → 1.94 s
RandomForestClassifier 172 (one socket) 4.22 → 4.02 s
RandomForestClassifier 344 7.40 → 6.43 s

On 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?

  • With check_input=False, a tree no longer checks that y is a valid classification target. This only affects people who bypass validation on purpose.
  • GB now accepts NaN in any feature, and unknown categories at predict time are treated as missing values (same as trees/forests/HGB).
  • warm_start is not supported with categorical features in GB, same as forests.
  • Possible follow-up: HGB validation doesn't have to force the dtype to float64. It could keep the dtype of the input (maybe just enforce float) and let the bin mapper handle both float32 and float64 (should be straightforward). This would save a copy of X for float32 inputs.

adam2392 and others added 25 commits September 10, 2026 22:19
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.
…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
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]>
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]>
@cakedev0

Copy link
Copy Markdown
Owner Author

Possible follow-ups:

  • HGB: validation don't have force dtype to float64. It could keep the dtype of the input (maybe just enforce float) and let the bin mapper handle both float32 and float64 (should be straightforward). This could save a copy of X.

@cakedev0

Copy link
Copy Markdown
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
@cakedev0
cakedev0 changed the base branch from feat/cat-forest to main October 17, 2026 06:52
@cakedev0 cakedev0 closed this Oct 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants