Skip to content

I think OneHotEncoder should be able to handle mixed data types #18073

Open

Description

@melgazar9

I think it's very practical to OneHotEncode columns that have mixed datatypes. Pandas (or some other dataframe reader) will unlikely read in the true datatype of every column correctly. Pandas reading in a column as an integer does not necessarily mean the column should be treated as an integer in sklearn.

Example: pandas will read in a column that contains codes of certain products (e.g. instrument_type will contain 10 integers in the dataset - 1000, 1001, ... 1009, NaN, and 'guitar'). There are only 12 categories. I cannot one hot encode this column unless I convert it to string (using .astype(str)). If there were no NaN this would still be a problem, but with NaN I can simple do a fillna('nan'), and then passed that to the final pipeline with FunctionTransformer. If only fitting something for exploratory purposes, the .astype(str) is a simple and quick solution. However, it is not efficient in a production pipeline. I found myself having to create a custom class that converts each column I want to OH encode to astype(str), so I can then implement the OH encoder in production even though pandas will interpret that column as an integer.

The solution for this would be to have an input parameter that allows OneHotEncoder (and OrdinalEncoder) to perform on columns with mixed datatypes. If the user does this when he/she shouldn't, that should be user error, but not decided by the sklearn package. What are the major reasons this hasn't bee implemented? Thoughts?

Code example

def na_impute(X, fill_value = 'nan', return_string = True):
        if return_string:
            return X.fillna(fill_value).astype(str)
        else:
            return X.fillna(fill_value)

oh_pipe = make_pipeline(
            FunctionTransformer(na_impute),
            OneHotEncoder(handle_unknown = 'ignore', sparse = False, drop = 'if_binary') # fails because drop = 'if_binary' and handle_unknown = 'ignore'
                           )

Activity

  1. jnothman commented on Aug 4, 2020

    @jnothman
    Member

    I think this is a problem for how you read in the data; it's not Scikit-learn's job to help you ingest your data correctly.

  2. melgazar9 commented on Aug 4, 2020

    @melgazar9
    Author

    I agree that sklearn is not responsible for how I read in the data. My concern is, why are we preventing one hot encoding on columns with mixed data types? After fit transform there will only be 0s and 1s. I don't think mixed data types should prevent OHE or ordinal encoding from fitting or transforming.

    To put this in context, I'm reading in data with thousands of columns, so I wrote a function that detects the highly cardinal features, numerical features, and OH features. The OHE breaks if I don't call those OH variables astype(str) before calling fit. This is a bit annoying because to use ColumnTransformer now I have to either write a simple custom fit transform that converts the input variables to astype(str), or just put that single line in a function and use FunctionTransformer.

  3. jnothman commented on Aug 4, 2020

    @jnothman
    Member
  4. amueller commented on Aug 5, 2020

    @amueller
    Member

    Can you give a minimum example to reproduce? Where does it actually brake? Scikit-learn works on numpy level, not pandas, and handling this kind of type conversion in numpy is quite tricky. We might move towards more direct support of pandas in OneHotEncoder, but we're not there yet (afaik).

  5. melgazar9 commented on Aug 6, 2020

    @melgazar9
    Author

    Hey thanks for the response. Below is a reproducible example of what I sklearn is doing vs what I think sklearn should at the very least consider changing.

    df = pd.DataFrame({'col1': [0,1,2,3,np.nan, 5,6,7,8,9], 
                       'col2': ['hi', 'bye', 'hi', 'hi', 'bye', 'hi', 'hi', 'bye', 'hi', 'hi'],
                       'col3': [1001, 1002, 1001, 'guitar', 1005, 1002, 1005, 'guitar', 1001, 1002],
                       'col4': ['strings', 'drums', np.nan, 'strings', 'strings', 'drums', 'strings', 'drums', 'strings', 'drums'],
                       'col5': [0,1,2,3,5,6,7,8,9,10]
                       })
    
    [print(col, df[col].dtype) for col in df.columns]
    
    OneHotEncoder(sparse = False).fit_transform(df[['col1']]) # fail because np.nan - this is fine
    OneHotEncoder(sparse = False).fit_transform(df[['col1']].astype(str)) # pass because astype(str) - so all values are the same dtype
    OneHotEncoder(sparse = False).fit_transform(df[['col2']]) # pass because all values are astype(str) - so all values are the same dtype
    
    
    ###### I think this should be fixed ######
    OneHotEncoder(sparse = False).fit_transform(df[['col3']]) # failed because col3 has different datatypes...
    ######
    OneHotEncoder(sparse = False).fit_transform(df[['col3']].astype(str)) # pass because col3 converted to astype(str) - so all values are the same dtype
    OneHotEncoder(sparse = False).fit_transform(df[['col5']]) # pass because col5 is all of the same datatype
    
    ######
    # In practice
    ######
    
    oh_vars = ['col2', 'col3', 'col4']
    
    def na_impute(X, fill_value = 'nan', return_string = True):
        if return_string:
            return X.fillna(fill_value).astype(str)
        else:
            return X.fillna(fill_value)
    
        
    ###### Passes ######
    oh_pipe = make_pipeline(
        FunctionTransformer(na_impute),
    #             SimpleImputer(strategy='constant', fill_value='missing'),
        OneHotEncoder(handle_unknown = 'ignore', sparse = False)
    )
    
    feature_transformer = ColumnTransformer(
        transformers=[
            ('oh_encoder', oh_pipe, oh_vars)
        ],
        remainder = 'drop',
        n_jobs=-1).fit(df.drop('col1', axis=1), df['col1'])
    
    ###### Fails ######
    oh_pipe = make_pipeline(
        SimpleImputer(strategy='constant', fill_value='missing'),
        OneHotEncoder(handle_unknown = 'ignore', sparse = False)
    )
    
    feature_transformer = ColumnTransformer(
        transformers=[
            ('oh_encoder', oh_pipe, oh_vars)
        ],
        remainder = 'drop',
        n_jobs=-1).fit(df.drop('col1', axis=1), df['col1'])
    

    Since col2, col3, and col4 are clearly categorical variables, I may want to OH encode them. For me to do that I'd need to convert them all to astype(str) first, which is actually a bit of a pain in a production system. The reason it's a pain is because I'll need to use some other method (say FunctionTransformer), which does not have the get_feature_names attribute. So when fitting a model I will need to write extra code to map the feature names. If the either (or both) the OHE or SimpleImputer accepts mixed datatypes then there is no need for FunctionTransformer or the na_impute function at all. However neither accept mixed datatypes so it is just extra effort that many data scientists need to take in order to apply fit to columns with mixed datatypes.

  6. ogrisel commented on Nov 9, 2020

    @ogrisel
    Member

    The reason it's a pain is because I'll need to use some other method (say FunctionTransformer), which does not have the get_feature_names attribute.

    We should definitely add an option to FunctionTransformer to make it possible to implement get_feature_names for element wise functions that implement a one-to-one mapping (which is very often the case in practice).

    For the other case, FunctionTransformer could accept another optional callable constructor argument that makes it possible for the user to specify how to compute output feature names given input feature names.

  7. ogrisel commented on Nov 9, 2020

    @ogrisel
    Member

    @melgazar9 has for your example, why not specify two different transformers for integer encoded categorical variables (without nan values) and string encoded categorical variables (possibly with nan values treated as categories)?

  8. melgazar9 commented on Nov 9, 2020

    @melgazar9
    Author

    @ogrisel - Hey I would love for there to be a get_feature_names attribute to column transformer. As far as the oh encoder suggestion, that is definitely a reasonable solution in a small project. However, when there are tens of thousands of features and I want to automatically detect and transform the categorical features this solution would require me to manually figure out which features are categorical / numeric.

    Someone above mentioned I should know all of my features and read the data in properly in pandas. That is true, unless you're dealing with tens of thousands of features and are expected to turn around a ML model in a matter of a few weeks. Nobody has time to go through 10k features and figure out which variables are categorical and which are numeric, let alone in a few weeks.

    An example is when you have a column of T-shirt sizes XS-S-M-L-XL-NaN encoded in a column as integers 1-2-3-4-5-NaN. Say I read this data frame in with pandas, and pandas calls that column dtype int64 without the NaN (and with the NaN it defaults to float64). Say again now I want to one-hot encode this column since there are less than 10 distinct categories. This will throw and error. I think this error defeats the purpose of automation.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions