Skip to content

MNT Share X validation and categorical encoding between trees, forests and GB - #35181

Merged
ogrisel merged 17 commits into
scikit-learn:mainfrom
cakedev0:shared-validation-trees
Dec 1, 2026
Merged

ogrisel merged 17 commits into
scikit-learn:mainfrom
cakedev0:shared-validation-trees

Conversation

@cakedev0

@cakedev0 cakedev0 commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

Fixes #35221.

First part of the split of #35162. Follow-up of #34832 (categorical support in forests).

Follow-ups, for now as PRs in my fork on top of this branch (I'll open them here once this one is merged):

  • cakedev0#30: HGB uses the same helpers, which fixes 3 bugs when a categorical feature is not first.
  • cakedev0#32: categorical features and missing values in GB.

What does this implement/fix? Explain your changes.

Trees, forests and GB now share the same X validation and categorical encoding, in the new sklearn/tree/_preprocessing.py.

  • Trees: validation of X, y and sample_weight and encoding are done once in _validate_and_preprocess_input, then _fit_validated builds the tree.
  • Forests and GB: they reuse _validate_and_preprocess_input and call _fit_validated directly, so they don't need to know what kind of preprocessing trees do. The trees they fit don't validate y and sample_weight again. This saves check_array calls in each tree, which are costly when many trees are fitted in parallel threads.
  • Encoding: categorical columns are ordinal-encoded straight into an F-ordered array, in the original column order. No ColumnTransformer anymore: it outputs the categorical columns first, so the trees had to copy its output into a second array to restore the column order. Writing each encoded column into its place saves that copy and the hstack of the ColumnTransformer.
  • Extra trees: the criterion="absolute_error" restriction with categorical features is now only applied with splitter="best". Random categorical splits are evaluated exactly with absolute_error: test_split_impurity now checks them instead of skipping them. I updated the unreleased changelog entry of [ENH] ExtraTree: Add random splitting via deterministic hash to support up to 2**24 possible categories #33972.
  • Category limit: the error for too many categories now gives the feature index and its number of categories, instead of the internal encoded value (Categorical trees: error message and docstring state the wrong limit for categorical_features #35221). The docstrings now say 256 categories, which is the real limit with splitter="best".

AI usage disclosure

I used AI assistance for:

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

Benchmarks

Forest fit, 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 main → this PR
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 because check_array currently takes locks on free-threaded Python and you can get contention, see #35091 for more details (but not really needed to review this PR)

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.

cakedev0 and others added 3 commits October 19, 2026 18:20
…s and GB

Trees validate and encode X in _validate_and_preprocess_input, and build
the tree in _fit_validated. Forests and GB call _fit_validated directly,
so that X, y and sample_weight are validated once for all trees.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

Copy link
Copy Markdown

This PR exceeds the recommended size of 500 lines changed. Consider splitting it into smaller PRs to ease the review process. Please make sure you read our Contributing guide and in particular our Pull Request guidelines

@antoinebaker antoinebaker 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 PR @cakedev0 !

That's a meaty one ! I'll still trying to get familiar with the changes, so I'll need some time before making useful questions / suggestions / comments ;)

per feature. Extra trees also support multi-class / multi-output targets with
up to ``2**24 - 1`` categories via random hash splits.
per feature. Extra trees also support multi-class / multi-output targets and
`'absolute_error'`, with up to ``2**24 - 1`` categories via random hash splits.

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.

Do you mean criterion='absolute_error' ?

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.

Yes

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.

Should we add that explicitly in?

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.

Yes, done in c5a4714.

Comment on lines -1495 to +1347
.. versionadded:: 1.11
.. versionadded:: 1.10

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 guess the wrong version number was a typo in the previous PR ? Maybe you could make a quick doc PR (easy to review and merge for the release).

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

Hi, those are mainly questions to help me better understand the PR !

Comment thread sklearn/ensemble/_gb.py Resolved
Comment thread sklearn/tree/_classes.py Outdated
Comment on lines +575 to +577
"missing_values_in_feature_mask": np.isnan(
np.asarray(X.sum(axis=0)).ravel()
),

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 was wondering if there were a more effective to compute this. I asked cursor and apparently not !

@antoinebaker antoinebaker Oct 28, 2026 •

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.

But here we see (and also in _encode_categorical_features) that this is not very array API friendly.

For my own understanding, is the array API out of scope for the tree based estimators ? Is it because our code relies on the cython tree builders, so we are forced to numpy / scipy sparse arrays ?

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.

Array API is really out-of-scope for tree-based estimators.

Plugin system (with scikit-learn-intelex or cuML) is not, but it's not designed at all yet, and not decided either, so let's not plan for it. YAGNI.

Comment thread sklearn/tree/_classes.py
This is the case, for instance, for pandas and polars DataFrames.

For each categorical feature, there must be at most 255 unique
For each categorical feature, there must be at most 256 unique

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.

Was it just a typo in the last PR (here in the docstring and the error message) ? Or are the changes made in this PR necessary ?

I'm asking because if it's just a typo, you could do as for the version number a quick doc PR just for the release. But if it requires the refactoring, of course keep it in this PR.

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.

It was a copy-paste mistake (I think from the HGB docstring, where the limit is max_bins=255): with splitter="best", 256 categories work on main and 257 fail. The error message on main isn't great either: integers in [0, 255]. Found 256. refers to encoded values the user never sees.

Neither fix requires the refactoring. I'd keep them here as I hope this PR to be merged before 1.10.

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'd keep them here as I hope this PR to be merged before 1.10.

You're quite optimistic :)

Comment thread sklearn/tree/_preprocessing.py Outdated
_check_n_features(estimator, X, reset=False)

is_categorical = estimator.is_categorical_
X_out = np.empty((_num_samples(X), is_categorical.shape[0]), dtype, order="F")

@antoinebaker antoinebaker Oct 28, 2026 •

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 the preprocessed X is always a numpy F-order array. I guess this is not very array API compliant, but we probably don't care for tree based estimators.

BTW, why the F-order ? Is it for perfomance reasons in the tree builder ?

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.

The tree builder works with any layout. X is stored as a strided memoryview (const float32_t[:, :]). The builder only converts to F-order when it has to copy anyway (cast to float32):

elif X.dtype != np.float32:
# since we have to copy we will make it fortran for efficiency
X = np.asfortranarray(X, dtype=np.float32)

cdef const float32_t[:, :] X

So here I just align with existing behavior.

And also, for the few lines below, F-order is much faster. For the tree builder, sometimes it's faster sometimes it's not and it's quite hard to predict and outside the scope of this PR.

Comment thread sklearn/tree/_preprocessing.py Outdated
Comment on lines +127 to +141
def _get_n_categories(estimator):
"""Number of categories of each feature, -1 for numerical features.

Missing values are not counted as a category.
"""
n_categories = np.full(estimator.n_features_in_, -1, dtype=np.intp)
encoder = estimator._categorical_encoder
if encoder is not None:
for idx, categories in zip(
np.flatnonzero(estimator.is_categorical_), encoder.categories_
):
# OrdinalEncoder places np.nan last if missing values reach fit.
has_nan = len(categories) > 0 and is_scalar_nan(categories[-1])
n_categories[idx] = len(categories) - has_nan
return n_categories

@antoinebaker antoinebaker Oct 28, 2026 •

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.

My biggest question is about the general implementation.

Here the helper functions _encode_categorical_features, _validate_X and _get_n_categories ( called by the _validate_and_preprocess_input method) need to set attributes like
estimator._categorical_encoder and estimator.is_categorical_. Isn't it a bit weird to have a helper function mutate the estimator attributes, it feels more like a method ?

It seems that the same attributes are sometimes set elsewhere, for example self.is_categorical_ in BaseDecisionTree._fit_validated and _categorical_encoder = None in BaseDecisionTree.

Is it safe to have these attributes computed / updated in different places ?

Besides the code of _get_n_categories relies on the consistency of these attributes, for instance we better have estimator.is_categorical_ indices aligned with the encoder.categories_. And I guess the whole logic of the preprocessing relies on the consistency of these attributes.

Finally it seems that the estimator instance in these helper functions can be a DecisionTree, a RandomForest or a GradientBoosting ? Then are we sure they all follow the same "hidden API" with the same is_categorical_ or _categorical_encoder attributes ?

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.

PS: I don't have a strong opinion here. I'm just wondering if another design pattern would be better suited here. Perhaps a Mixin ?

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.

Thanks, good questions!

For helpers mutating the estimator, it's the same pattern as validate_data (which sets n_features_in_ and feature_names_in_), so I'm fine with it.

But I agree the "hidden API" was a problem and a Mixin is an excellent solution!
Forests and GB borrowed BaseDecisionTree._validate_and_preprocess_input, which relies on criterion, _categorical_encoder and optionally categorical_features without saying so. I moved it to a _TreeInputValidationMixin shared by BaseDecisionTree, BaseForest and BaseGradientBoosting, with this contract in its docstring (d5fd949).

@antoinebaker antoinebaker Oct 29, 2026 •

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.

Ah thanks, the code seems nicer with the Mixin!

Quick question: I was wondering why you left _fit_validated out of the Mixin. Is it because it's more of a DecisionTree method ? If I remember correctly it's called on the individual trees in forest and gbt.

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.

Quick suggestion: I think you can now make the helper functions _validate_X, _encode_categorical_features, _get_n_categories private methods of the Mixin (they all have estimator as first arg)

Quick note: is_categorical_ is still set in BaseDecisionTree._fit_validated:

self.is_categorical_ = is_categorical if has_categorical else None

Ideally we would like the Mixin to handle all the attributes management, not sure if it's possible though.

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 think you can now make the helper functions _validate_X, _encode_categorical_features, _get_n_categories private methods of the Mixin

Fair, I initially didn't do it because in the follow-up PR for HGB, HistGradientBoosting* also uses them but it has no criterion and still has its own validation flow.
So I split it in two mixins: _CategoricalEncodingMixin with the three helpers as methods, and _TreeInputValidationMixin inheriting from it and adding _validate_and_preprocess_input.

is_categorical_ is still set in BaseDecisionTree._fit_validated

I think it can't be avoided for the trees fitted by a forest or GB (as they get already encoded X, so _fit_validated is where they get their is_categorical_ from categorical_counts (same as on main).

For a standalone tree, it's set twice to the same value, which is a bit weird but fine I think.

I was wondering why you left _fit_validated out of the Mixin. Is it because it's more of a DecisionTree method ?

Yes: it calls the Cython tree builder. Forests and GB never call it themselves, they build sub-estimators (DecisionTrees) that they put in their estimators_ attribute.

The mixins only hold what all these estimators do on themselves: validate and encode their input.

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

some q's. sorry if you've already answered.

per feature. Extra trees also support multi-class / multi-output targets with
up to ``2**24 - 1`` categories via random hash splits.
per feature. Extra trees also support multi-class / multi-output targets and
`'absolute_error'`, with up to ``2**24 - 1`` categories via random hash splits.

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.

Should we add that explicitly in?

assert_array_equal(est.estimators_[0].is_categorical_, [True])
# Forest owns encoding; trees must not re-fit their own preprocessor.
assert est.estimators_[0]._preprocessor is None
assert est.estimators_[0]._categorical_encoder is None

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.

Omg the rename is so nice. Even tho I've read the code numerous times in the past, I always found myself asking "what the heck is a _processor again"?

@cakedev0 cakedev0 Nov 2, 2026 •

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.

Well, it's because now it's just a _categorical_encoder and not a ColumnTransformer.

Using a ColumnTransformer which actually is counter-productive for clarity of the code and performance as it forces to reorder the columns afterward. Also, using it was a bit what caused all the bugs fixed by cakedev0#30 in HGB (the fix is basically to use the common categories encoding helpers defined in this PR instead of the ColumnTransformer-based code).

Comment thread sklearn/ensemble/tests/test_forest.py Resolved
@pytest.mark.parametrize(
"sparse_container", COO_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS
)
def test_sparse_input_early_stopping(sparse_container):

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.

Was this a previous bug?

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.

No, it works on 1.9.1 for all sparse formats. It covers a new path: X is now validated (and converted to CSC) once, before the early stopping split, so the split output isn't validated again.

Comment thread sklearn/ensemble/_gb.py

if sample_weight_is_none:
y = self._encode_y(y=y, sample_weight=None)
sample_weight = np.ones(X.shape[0], dtype=np.float64)

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.

Is this just to be explicit?

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.

No, it's needed: _validate_and_preprocess_input keeps sample_weight=None (trees handle None), while on main GB called _check_sample_weight, which returns ones. Without it, subsample < 1, early stopping and loss="huber" crash.

Comment thread sklearn/ensemble/_forest.py Resolved
Comment thread sklearn/tree/tests/test_tree.py Resolved
cakedev0 added a commit to cakedev0/my-scikit-learn-backlog that referenced this pull request Nov 2, 2026
done: Blog: [blog#231](scikit-learn/blog#231) (match Substack's font size), merged
todo: move [blog#228](scikit-learn/blog#228) from Waiting to Now: address lorentzenchr's review and answer jjerphan on the OpenBLAS threading layers
todo: move [sklearn#35181](scikit-learn/scikit-learn#35181) from Now to Waiting, adam2392's and antoinebaker's questions answered
add: Maintenance: follow up on [sklearn#35254](scikit-learn/scikit-learn#35254): settle option B with dherrera1911 and betatim (LDA solvers disagree with custom priors)
add: Maintenance: follow up on [sklearn#35209](scikit-learn/scikit-learn#35209): newton-cg LogisticRegressionCV test fails on the macOS x86_64 wheels
add: Maintenance: re-review [sklearn#34619](scikit-learn/scikit-learn#34619) (faster PCA mle; jberg5 addressed my comments)
add: Benchmarks: review [benchmarks#142](probabl-ai/scikit-learn-benchmarks#142) (cuML config) with the results of the AWS L4 run
add: Upstream: upstream to OpenBLAS or close [cakedev0/OpenBLAS#3](cakedev0/OpenBLAS#3) and [cakedev0/OpenBLAS#4](cakedev0/OpenBLAS#4)
todo: since dates on [sklearn#35062](scikit-learn/scikit-learn#35062) and [sklearn#35053](scikit-learn/scikit-learn#35053), and virchan's question on the latter
todo: lorentzenchr's note on [sklearn#35029](scikit-learn/scikit-learn#35029) in the fork#38 line

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@MilindLate

Copy link
Copy Markdown

Reviewed the categorical features validation and docstring updates (#35221 consolidation):

  • The updated error message in _fit_validated clearly reports the feature index and its actual category count, removing the confusing reference to internal encoded values.
  • The distinction between splitter='best' (256 categories from bitset capacity) and splitter='random' (16,777,216 categories) is well-handled.
  • The docstrings across DecisionTreeClassifier, DecisionTreeRegressor, RandomForestClassifier, and RandomForestRegressor consistently state the 256 limit.
  • The tests in test_tree.py and test_forest.py properly check both the 256 valid boundary and the clear error message on exceeding it.

The consolidation of this validation into _fit_validated looks very clean and solid!

cakedev0 added a commit to cakedev0/my-scikit-learn-backlog that referenced this pull request Nov 3, 2026
done: HGB: get [sklearn#35216](scikit-learn/scikit-learn#35216) merged (binning crash on all-missing features, fixes [sklearn#35164](scikit-learn/scikit-learn#35164)), merged before I removed it
done: Trees: get [sklearn#34554](scikit-learn/scikit-learn#34554) merged (recursion PDP on categorical features)
drop: Threads: answer lesteve on [sklearn#35105](scikit-learn/scikit-learn#35105) (RFC deprecate `pre_dispatch`)
drop: Maintenance: follow up on [sklearn#35209](scikit-learn/scikit-learn#35209) (newton-cg test failing on the macOS x86_64 wheels)
drop: Benchmarks: review [benchmarks#142](probabl-ai/scikit-learn-benchmarks#142) (cuML benchmark config)
drop: Threads: review [sklearn#34729](scikit-learn/scikit-learn#34729) (inference methods don't modify the estimator)
drop: Linear: [sklearn#34793](scikit-learn/scikit-learn#34793) (Ridge centering trick for cholesky), benchmarks in [benchmarks#115](probabl-ai/scikit-learn-benchmarks#115) and [benchmarks#31](probabl-ai/scikit-learn-benchmarks#31)
drop: Upstream: sklearnex reports [sklearnex#3402](uxlfoundation/scikit-learn-intelex#3402), [sklearnex#3377](uxlfoundation/scikit-learn-intelex#3377), [sklearnex#3220](uxlfoundation/scikit-learn-intelex#3220)
drop: Upstream: [data-apis/array-api#976](data-apis/array-api#976) (why `stable=True` is the default for `xp.sort`)
drop: Upstream: dpnp reports [IntelPython/dpnp#3149](IntelPython/dpnp#3149) and [IntelPython/dpnp#3148](IntelPython/dpnp#3148)
drop: Threads: [sklearn#34736](scikit-learn/scikit-learn#34736) (oversubscription in `pairwise_distances`), out of the reported findings item
drop: KMeans: benchmarks [benchmarks#154](probabl-ai/scikit-learn-benchmarks#154), [benchmarks#160](probabl-ai/scikit-learn-benchmarks#160), [OpenBLAS#6105](OpenMathLib/OpenBLAS#6105) and [sklearn#17334](scikit-learn/scikit-learn#17334), out of the [sklearn#35193](scikit-learn/scikit-learn#35193) item
todo: move [joblib#1899](joblib/joblib#1899), [sklearn#35261](scikit-learn/scikit-learn#35261) and [sklearn#35053](scikit-learn/scikit-learn#35053) from Reviews to Now, [sklearn#35181](scikit-learn/scikit-learn#35181) to the top of Waiting (by hand in 03835dd)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cakedev0 cakedev0 moved this from PR in progress to PR waiting for reviews in Labs Nov 9, 2026
Comment thread sklearn/tree/_classes.py Resolved

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

Mostly LGTM now. I'll let others take another round of looks

@antoinebaker antoinebaker 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 again @cakedev0 for the PR, LGTM overall !

I feel we could improve the implementation (simplify the logic) but we should postpone to a future PR. Merging this PR will unblock your follow up PRs cakedev0#30 cakedev0#32. Besides the simplification (if still possible) will be easier to reason about after the follow up PRs are merged.

Comment thread sklearn/tree/_preprocessing.py Resolved
Comment thread sklearn/ensemble/_forest.py Resolved
@cakedev0

Copy link
Copy Markdown
Member Author

Thanks for the reviews @adam2392 and @antoinebaker!

Let's merge? (It contains some minor doc fixes, so we might as well merge it before the release I think)

@ogrisel
ogrisel enabled auto-merge (squash) December 1, 2026 10:04
@ogrisel

ogrisel commented Dec 1, 2026

Copy link
Copy Markdown
Member

I resolved the conflict in the changelog and marked as auto-merge since this PR already had two approvals.

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.

Categorical trees: error message and docstring state the wrong limit for categorical_features

5 participants