Repository navigation
MNT Share X validation and categorical encoding between trees, forests and GB - #35181
Conversation
…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]>
…_impurity Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
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 |
…o many Co-Authored-By: Claude Opus 5.5 <[email protected]>
antoinebaker
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
Do you mean criterion='absolute_error' ?
There was a problem hiding this comment.
Should we add that explicitly in?
| .. versionadded:: 1.11 | ||
| .. versionadded:: 1.10 |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
Hi, those are mainly questions to help me better understand the PR !
| "missing_values_in_feature_mask": np.isnan( | ||
| np.asarray(X.sum(axis=0)).ravel() | ||
| ), |
There was a problem hiding this comment.
I was wondering if there were a more effective to compute this. I asked cursor and apparently not !
There was a problem hiding this comment.
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 ?
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I'd keep them here as I hope this PR to be merged before 1.10.
You're quite optimistic :)
| _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") |
There was a problem hiding this comment.
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 ?
There was a problem hiding this comment.
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):
scikit-learn/sklearn/tree/_tree.pyx
Lines 125 to 127 in d685424
scikit-learn/sklearn/tree/_partitioner.pxd
Line 107 in d685424
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.
| 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 |
There was a problem hiding this comment.
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 ?
There was a problem hiding this comment.
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 ?
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 NoneIdeally we would like the Mixin to handle all the attributes management, not sure if it's possible though.
There was a problem hiding this comment.
I think you can now make the helper functions
_validate_X,_encode_categorical_features,_get_n_categoriesprivate 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 inBaseDecisionTree._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_validatedout 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.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed-validation-trees
Co-Authored-By: Claude Opus 5.5 <[email protected]>
adam2392
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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"?
There was a problem hiding this comment.
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).
| @pytest.mark.parametrize( | ||
| "sparse_container", COO_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS | ||
| ) | ||
| def test_sparse_input_early_stopping(sparse_container): |
There was a problem hiding this comment.
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.
|
|
||
| if sample_weight_is_none: | ||
| y = self._encode_y(y=y, sample_weight=None) | ||
| sample_weight = np.ones(X.shape[0], dtype=np.float64) |
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hangelog Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
|
Reviewed the categorical features validation and docstring updates (#35221 consolidation):
The consolidation of this validation into |
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]>
adam2392
left a comment
There was a problem hiding this comment.
Mostly LGTM now. I'll let others take another round of looks
There was a problem hiding this comment.
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.
Co-authored-by: antoinebaker <[email protected]>
|
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) |
|
I resolved the conflict in the changelog and marked as auto-merge since this PR already had two approvals. |
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):
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.yandsample_weightand encoding are done once in_validate_and_preprocess_input, then_fit_validatedbuilds the tree._validate_and_preprocess_inputand call_fit_validateddirectly, so they don't need to know what kind of preprocessing trees do. The trees they fit don't validateyandsample_weightagain. This savescheck_arraycalls in each tree, which are costly when many trees are fitted in parallel threads.ColumnTransformeranymore: 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 thehstackof theColumnTransformer.criterion="absolute_error"restriction with categorical features is now only applied withsplitter="best". Random categorical splits are evaluated exactly withabsolute_error:test_split_impuritynow 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.splitter="best".AI usage disclosure
I used AI assistance for:
Benchmarks
Forest fit, 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 because
check_arraycurrently 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 thatyis a valid classification target. This only affects people who bypass validation on purpose.