Repository navigation
Description
In sklearn.preprocessing._encoders._BaseEncoder, columns with pd.Categorical dtype are converted to arrays.
| Xi = check_array(Xi, ensure_2d=False, dtype=None, |
If the categories ordering is explicitly specified by the user to the constructor of OneHotEncoder or OrdinalEncoder, then this is fine... but if 'auto' is used, lexicographic ordering will be assumed, disregarding the encoding order determined by the Categorical dtype.
I propose that we raise a warning if:
- a feature passed to OneHotEncoder or OrdinalEncoder has a Pandas Categorical dtype (is there a way to duck type this?)
- the categories for that feature are 'auto'
- the lexicographically sorted features do not match the feature's
dtype.categoriesordering.
The warning might be something like UserWarning("'auto' categories is used, but the Categorical dtype provided is not consistent with the automatic lexicographic ordering")... or else something more intelligible.
We may change this warning to a FutureWarning with "From version 0.24 the category ordering specified by a Categorical dtype will be respected in encoders."
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDiscussion
Activity
harsh020 commentedon Sep 16, 2019
@jnothman Hi, I am a bit new to open source and would like to work on this issue, if available.
Let me know if I got things correct,
if any of the above point hold true we need to raise warning.
Few queries,
__init__, or duringfitor the_fitof the base class.Few queries in general, if you don't mind answering them -
Thanks.
jnothman commentedon Sep 16, 2019
harsh020 commentedon Sep 17, 2019
@jnothman Thanks.
Just one more thing the last point
Do we have lexicographically sorted feature list? And what is feature's
dtype.categories(is it theself.categories_list that we are finding?)Thanks.
jnothman commentedon Sep 18, 2019
harsh020 commentedon Sep 18, 2019
scikit-learn/sklearn/preprocessing/_encoders.py
Line 85 in 03ea20d
@jnothman Hey, I thought of doing it as -
In the lines above in line 85, within the if condition we can just check whether the other two conditions are true, that is whether
X_list[i]is a categorical dtype and then we can checkcatsvariable has same order as that ofX_list[i]'sdtype.category.Is it a feasible approach?
Thanks.
amueller commentedon Sep 18, 2019
I agree with the proposed behavior, but I doubt this issue will be easy ;) [also this issue is tagged easy and moderate?]
harsh020 commentedon Sep 19, 2019
@amueller Thanks for the heads up, I won't be opening any PR until I make sure that the approach is correct and get it reviewed by you guys.
And from your reply I think that this approach won't be any good. Still working on it.
Thanks.
harsh020 commentedon Sep 19, 2019
@jnothman I was going through the
check_arrayfunction, please correct me if wrong, the function converts any type of object passed to it to an array of features withstringvalues.If, so I think we need to verify the three conditions to raise the warning in the
check_arrayfunction itself.Thanks.
jnothman commentedon Sep 21, 2019
thomasjpfan commentedon Oct 23, 2019
It would be nice to have support for this now and not wait till 0.24. Is adding option in
categoriesa good idea? (I do not have a good idea what this new option would be called.categories=use-pandas-categories-if-avaliable?)jnothman commentedon Oct 23, 2019
jorisvandenbossche commentedon Oct 28, 2019
This duplicates #12086 somewhat, there is some discussion there as well (but basically what @jnothman is proposing here to introduce a warning for it). Will close the other issue.
I agree with @thomasjpfan that it would be nice to already have the new behaviour now, but I was wondering if we cannot combine that we the changes in OrdinalEncoder for strings with
categories='sort' / 'auto'? For example, if people specifycategories='auto', we use the order of the categorical dtype, ifcategories='sort', we lexicographically sort them (the current behaviour).That way it could also be possible to raise a warning in the default case, but having a way for users to both have the new behaviour or keep the old behaviour and silence the warning.
BTW, I don't think that the actual implementation to use the categorical dtype's categories should be very hard (there is actually a PR for this: #13351), as the required preparatory work to handle a DataFrame column by column is already done (#13253).
23 remaining items
adrinjalali commentedon Aug 22, 2021
Doesn't seem like we'd get this in time. Moving to 2.0
amueller commentedon Jan 22, 2024
is there a current/ recent issue tracking the support for pd.categorical? So it was added to hgb, not not anywhere else, right?
I feel like there should be a consistent story, and a lot of conversation has happened over the last .. 5 years? but I can't finda current status or summary.
I saw #24967, and some related thoughts in #27947, but I haven't seen anything more recent?
glemaitre commentedon Jan 22, 2024
We have a related PR that wants to leverage this feature: #27911
amueller commentedon Jan 22, 2024
Thanks, that's quite interesting, but also somewhat orthogonal. I was thinking more about the API surface. Currently a user doesn't know whether categorical features are treated correctly or not in a model without reading the documentation of each model and default hyper-parameters. Passing categoricals encoded as integers and with categorical dtype to
LogisticRegression,RandomForestClassifierandHistogramGradientBoostingClassifierhas very different results.glemaitre commentedon Jan 23, 2024
Indeed, we did not got the discussion.
HistGradientBoostingis the first model that handle categorical feature in a "native manner". I assume that we could have something similar for all tree-based approach avoiding. You get missing values and categorical handling without the need of preprocessing.For linear model, we got kind of backward by deprecating
normalizeparameter and totally rely on theColumnTransformer. The fact that you need to handle both numerical + categorical + missing values make those models trickier.The pattern of using the
TableVectorizerfromskrubs(https://skrub-data.org/stable/generated/skrub.TableVectorizer.html#skrub.TableVectorizer) could be a way to simplify such pipeline and the same pattern could also potentially used with tree-based models but I'm not sure if this necessary when one deals only with numerical and categorical (when dates come to play then it could be useful).But I rather think that we should have the discussion on that topic.
lorentzenchr commentedon May 28, 2026
Update as of scikit-learn 1.9
HistGradientBoostingClassifierand regressor have the init parametercategorical_featuresand this natively supports categorical features with up to 255 categories per feature.DecisionTreeClassifier,RandomForestClassifier,GradientBoostingClassifier, ..) will have the samecategorical_featuresin the future, once FEA Categorical split support forDecisionTree*, andRandomForest*#33354 and follow-ups are merged.Note
This approach works by either detecting a categorical dtype of features or by ordinal-encoding features and then specifying their positions.
Current Problems
#18894 demonstrates that the above outlined solution still has problems, in particular for more than 255 categories. One needs:
OrdinalEncoderand then later somehow infer their position which is non-trivial.Summary for
OrdinalEncoderUse cases
For the first use case, ordering of the categories has no effect on the predictions of the fitted estimator (apart from randomness). For display and inspection purposes, having control over the order might be desirable.
For the second use, having control over the ordering is necessary.
Concluding Suggestion:
OrdinalEncoder(categories="auto")should use given order of dtype if available.ThibaultDECO commentedon Jun 22, 2026
Is there any update on this issue?
cakedev0 commentedon Aug 17, 2026
I just saw this issue. My PR #34678 should close it I guess, or at least partially close it? (I don't have the time to read all this thread sorry).
@lorentzenchr do you still think that? I think I agree.
lcrmorin commentedon Aug 24, 2026
I was interested in the initial issue, so read it all... @thomasjpfan @ogrisel read through #15050 and #15396. Looks like it stalled on time, not disagreement - #15396 had real review before you closed it planning a cat.codes rewrite, and @ogrisel's default-behavior suggestion never got picked up. Now, #34678 may already fix this as a side effect of pd.factorize(sort=True) on Categorical dtype. Would a dedicated solution still be needed ?
lorentzenchr commentedon Sep 9, 2026
I would prefer the order as given by the dtype. But more important is to test and document it.