Skip to content

Imputer can change the number of features #10671

Closed

Description

@mfeurer

Description

When building a pipeline which contains an imputer and a one hot encoder with an array marking the categorical features, the imputer can remove columns (in case they're completely missing) which makes the one hot encoder crash.

Steps/Code to Reproduce

import numpy as np

import sklearn.pipeline
import sklearn.preprocessing

X = [[np.NaN, 1], [np.NaN, np.NaN]]

imp = sklearn.preprocessing.Imputer()
ohe = sklearn.preprocessing.OneHotEncoder(categorical_features=[False, True])
pipeline = sklearn.pipeline.Pipeline([('imp', imp), ('ohe', ohe)])

print(pipeline.fit_transform(X))

Expected Results

Not 100% sure, but either no exception or an argument to the imputer which configures the behavior in such cases (similar to one hot encoding where one can specify how to handle unknowns).

Actual Results

Traceback (most recent call last):
  File "/home/feurerm/projects/[...]/auto-sklearn/bug.py", line 12, in <module>
    print(pipeline.fit_transform(X))
  File "/home/feurerm/miniconda3_4.3.30/envs/[...]/lib/python3.6/site-packages/sklearn/pipeline.py", line 283, in fit_transform
    return last_step.fit_transform(Xt, y, **fit_params)
  File "/home/feurerm/miniconda3_4.3.30/envs/[...]/lib/python3.6/site-packages/sklearn/preprocessing/data.py", line 2019, in fit_transform
    self.categorical_features, copy=True)
  File "/home/feurerm/miniconda3_4.3.30/envs/[...]/lib/python3.6/site-packages/sklearn/preprocessing/data.py", line 1820, in _transform_selected
    sel[np.asarray(selected)] = True
IndexError: boolean index did not match indexed array along dimension 0; dimension is 1 but corresponding boolean dimension is 2

Versions

Linux-4.4.0-112-generic-x86_64-with-debian-stretch-sid
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 18:10:19) 
[GCC 7.2.0]
NumPy 1.14.0
SciPy 1.0.0
Scikit-Learn 0.19.1

Activity

  1. jnothman commented on Feb 22, 2018

    @jnothman
    Member
  2. nok commented on Feb 22, 2018

    @nok
    Contributor

    In that case the result of the Imputer (with default params) is [[1.] [1.]] of shape (2, 1) which forces the mentioned exception in the OneHotEncoder. The nan columns will be dropped imputation.py#L340-L341.

  3. nok commented on Feb 23, 2018

    @nok
    Contributor

    I added an initial PR for a discussion and further suggestions.

  4. mfeurer commented on Feb 23, 2018

    @mfeurer
    Author

    @jnothman the issue is not how the one hot encoder does not handle missing values, but that it expects more features than there will be present due to the imputer dropping one.

    How would this look like with the proposed ColumnTransformer? Like this?

    ColumnTransformer(
        [Pipeline(Imputer(), OneHotEncoder()), [categorical_features],
        [Pipeline(Imputer()), [numerical_features],
    )

    If yes, the problem might actually already be solved in the master branch by employing a different construct in the pipeline.

    However, it could still be a good idea to not drop the column in the Imputer(), but by making the dropping explicit by a VarianceThreshold()? Thanks a lot @nok for going ahead and creating a PR for this.

  5. amueller commented on Feb 26, 2018

    @amueller
    Member

    @mfeurer How do you like the ColumnTransformer solution? It also allows different strategies for imputation and scaling on the categorical and numerical features, which I think is something you usually want.

  6. mfeurer commented on Feb 27, 2018

    @mfeurer
    Author

    I'm fine with that solution as well, great that it's already solved. And having different imputation will actually be a good thing!

  7. nok commented on Feb 27, 2018

    @nok
    Contributor

    Nice solution, thanks for your feedback @amueller . So we can take the open PR #10678 back I guess?

  8. mitar commented on Feb 28, 2019

    @mitar
    Contributor

    This turned out to be quite a problem for us. The issue is that if imputer deletes columns then it is not really possible to map input columns to output columns.

    I would ask that this is reopened and that there is some way for imputer to communicate which columns have been removed. Not sure what would be the best API for this though.

  9. irodionzaytsev commented on Apr 20, 2020

    @irodionzaytsev
  10. rth commented on Apr 20, 2020

    @rth
    Member

    I would ask that this is reopened and that there is some way for imputer to communicate which columns have been removed. Not sure what would be the best API for this though.

    Thanks for the feedback @mitar . Could you comment why the above solution using ColumnTransformer transformer doesn't work for you? In the long term this should also be solved by propagating feature names (likely in 0.24).

    This is why I hate sklearn

    @irodionzaytsev This is not an acceptable way of communicating on the issue tracker. Please be constructive.

  11. mitar commented on Apr 21, 2020

    @mitar
    Contributor

    Could you comment why the above solution using ColumnTransformer transformer doesn't work for you?

    It does not work for us, because our problem is not with one-hot encoding, but with simply knowing which data comes from where. In our case we have metadata attached to every column. So if put X categorical columns into a ColumnTransformer and apply Imputer currently it is not necessary that X columns are returned, so we do not know how to map metadata to output columns. So ColumnTransformer does not really help in our case. That is just a workaround for one-hot encoding to not crash. But if you are doing anything else, it is still problematic.

    In the long term this should also be solved by propagating feature names (likely in 0.24).

    Yea, I heard about that solution, but the problem there is that Pandas DataFrame allows non-unique column names. So what happens if such DataFrame is used an input?

  12. rth commented on Apr 21, 2020

    @rth
    Member

    Yes, I agree that even if feature names are implemented it's still a behavior that can lead to issues in the code, and there should be an easy way to opt-out.

    Let's continue the discussion in #16426 that's about the same issue, there is also an associated PR that looks to be in a good shape.

  13. mitar commented on Apr 21, 2020

    @mitar
    Contributor

    Thanks!

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions