Skip to content

Enable drop='constant' in OneHotEncoder #27435

Closed

Description

@ayaanhossain

Describe the workflow you want to enable

Currently the drop parameter in OneHotEncoder objects support {‘first’, ‘if_binary’, <array-of-features>, None} as potential choices, with a strong encouragement to use None to allow proper use of regularized linear modeling downstream. However, if there exists features that are constant for a data matrix then it would be really great if OneHotEncoder took care of dropping that feature entirely during coding. If all columns in the input matrix were constant perhaps an error could be raised during .fit(...) when this option was used for object initialization.

I would like to do the following.

>>> oh_encoder = OneHotEncoder(
    sparse_output=False,
    drop='constant',
    handle_unknown='ignore')

So that this were possible.

>>> X
array([['M', 'O', 'M'],
       ['M', 'A', 'N']], dtype='<U1')
>>> oh_encoder.fit_transform(X)
array([[0., 1., 0., 1.],
       [1., 0., 1., 0.]], dtype='float')
>>> oh_encoder.inverse_transform(oh_encoder.transform(X))
array([['M', 'O', 'M'],
       ['M', 'A', 'N']], dtype='<U1')

Please note that this is distinct from using drop='first' which would definitely remove the constant columns but also the first column for each feature group in the data matrix columns, which would be pretty crazy. Perhaps, instead of None this could become the default choice as well, as this encoding perfectly preserves all the information in the input data matrix.

Describe your proposed solution

It would be great to have drop='constant' as an option.

Describe alternatives you've considered, if relevant

I have considered writing my own OneHotEncoder, but it feels redudant and error prone to do so. I have also tried to specify the constant features per column via the drop=<array> method, but there are columns for which I set values to None (corresponding to the non-constant columns) but the object didn't like that.

Additional context

None.

Activity

  1. glemaitre commented on Sep 22, 2023

    @glemaitre
    Member

    I feel that our OneHotEncoder already has a lot of parameters. Since the feature being constant is not specific to the OneHotEncoder, I am thinking that we should not have the option into it. Indeed, I would prefer to have a specific transformer that only detect constant column seen at fit and drop them at transform. In this way, you could use this transformer ahead of several other transformation.

    Somehow it could also be useful in the context discussed in: #19547

  2. added
    Needs Decision
    and removed
    Needs Triage
    on Sep 22, 2023
  3. ayaanhossain commented on Sep 22, 2023

    @ayaanhossain
    Author

    Is there such a transformer available in the library that removes the constant columns and adds them back at the inverse_transform(...) time?

  4. ayaanhossain commented on Sep 22, 2023

    @ayaanhossain
    Author

    Part of the reason it would be great to have this within the OneHotEncoder object itself is that it automatically would take care of the removed offsets when going for get_feature_names_out for example.

  5. glemaitre commented on Sep 23, 2023

    @glemaitre
    Member

    Part of the reason it would be great to have this within the OneHotEncoder object itself is that it automatically would take care of the removed offsets when going for get_feature_names_out for example.

    Having a pipeline with such a transformer will also propagate the feature names in this manner.

  6. ayaanhossain commented on Oct 11, 2023

    @ayaanhossain
    Author

    I ended up sub classing OneHotEncoder which gets the job done as I intended. Code below.

    import numpy as np
    from sklearn.preprocessing import OneHotEncoder
    
    class SuperHotEncoder(OneHotEncoder):
        '''A modified OneHotEncoder that detects
        constant features and removes them prior
        to one-hot encoding.'''
    
        def __init__(
            self,
            categories='auto',
            sparse_output=True,
            dtype=np.float64,
            handle_unknown='ignore'):
            '''Initializer'''
            super().__init__(
                categories=categories,
                sparse_output=sparse_output,
                dtype=dtype,
                handle_unknown=handle_unknown)
            self.cc = None
    
        def fit(self, X, y=None):
            '''Model fit'''
            self.cc = None
            cc = np.where((X != X[0]).sum(axis=0) == 0)[0]
            if len(cc) > 0:
                self.cc = cc
                X = np.delete(X, cc, axis=1)
            return super().fit(X, y)
    
        def transform(self, X):
            '''Transform input'''
            cc = self.cc
            if not cc is None:
                X = np.delete(X, self.cc, axis=1)
            return super().transform(X)

    Since, I've solved the problem, I am open to closing this issue. However, I still do think a similar functionality within either the OneHotEncoder natively or with a separate preprocessor with appropriate support for inverse transformation would be appreciated.

  7. glemaitre commented on Nov 4, 2023

    @glemaitre
    Member

    I did not think of it at first but you can use the VarianceThreshold for this purpose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs DecisionNew Feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions