Skip to content

Missing features removal with SimpleImputer #16426

Closed

Description

@vitorsrg

Code sample

In the sample code below, a column is removed from the dataset during the pipeline

>>> from sklearn.impute import SimpleImputer
>>> import numpy as np
>>> imp = SimpleImputer()
>>> imp.fit([[0, np.nan], [1, np.nan]])
>>> imp.transform([[0, np.nan], [1, 1]])
array([[0.],
       [1.]])

Problem description

Currently sklearn.impute.SimpleImputer silently removes features that are np.nan on every training sample.

This may cause further issues on pipelines because the dataset's shape has changed, e.g.

dataset[:, columns_to_impute_with_median] = imp.fit_transform(dataset[:, columns_to_impute_with_median])

Possible solutions

For the problematic features, either keep their values if valid or impute the fill_value during transform. I suggest adding a new parameter to trigger this behaviour with a warning highlighting the referred features.

As I'm willing to implement this feature, I look forward advices.

Activity

  1. rth commented on Feb 11, 2020

    @rth
    Member

    Thanks for the report!

    Currently sklearn.impute.SimpleImputer silently removes features that are np.nan on every training sample.

    That's a fairly surprising (and I think undocumented) behavior. Though I imagine keeping columns with all 0s (or other fill_value) is not very helpful either, for most use cases (putting aside API consistency).

    It's also seems dependent on the strategy,

    from sklearn.impute import SimpleImputer
    
    >>> X = pd.DataFrame({'a': [1, np.nan], 'b': [np.nan, np.nan]})
    >>> SimpleImputer(strategy='median').fit_transform(X)
    array([[1.],
           [1.]])
    >>> SimpleImputer(strategy='constant').fit_transform(X)
    array([[1., 0.],
           [0., 0.]])

    TBH, I have mixed feeling between documenting it as is, fixing as a bug, or adding an optional parameter to switch between these two behaviors as you suggest. Maybe other reviewers have stronger options about it.

  2. jnothman commented on Feb 12, 2020

    @jnothman
    Member
  3. glemaitre commented on Feb 14, 2020

    @glemaitre
    Member

    This behaviour ring the bell. We should check the behaviour across the different imputers.

  4. vitorsrg commented on Feb 17, 2020

    @vitorsrg
    Author

    The expected behaviour could be to keep the NaN, so we can use another SimpleImputer(strategy='constant') after trying to impute with the mean:

    >>> from sklearn.impute import SimpleImputer
    >>> import numpy as np
    
    >>> train = [[0, np.nan], [1, np.nan]]
    >>> test = [[0, np.nan], [1, 1]]
    
    >>> imp1 = SimpleImputer(strategy='mean')
    >>> imp2 = SimpleImputer(strategy='constant')
    
    >>> imp1.fit(train)
    >>> imp2.fit(train)
    
    >>> imp1.transform(test)
    array([[0. np.nan], 
           [1. 1.]])
    >>> imp2.transform(imp1.transform(test))
    array([[0., 0.],
           [1., 1.]])
  5. glemaitre commented on Feb 17, 2020

    @glemaitre
    Member

    Regarding the over imputer, I meant the KNNImputer and IterativeImputer. I recall a discussion about this in the IterativeImputer. If we are going to change the behaviour it would need to be consistent. I did not have time to look at it yet.

  6. micahjsmith commented on Feb 21, 2020

    @micahjsmith
    Contributor

    chiming in to agree that my expected behavior in the original post is that the column with all np.nan should be passed through. Never would I expect the column to be silently dropped. Thanks to all for looking into this.

  7. jnothman commented on Feb 23, 2020

    @jnothman
    Member
  8. jnothman commented on Feb 23, 2020

    @jnothman
    Member
  9. glemaitre commented on Feb 23, 2020

    @glemaitre
    Member

    FYI, the behaviour is consistent across imputers:

    from sklearn.impute import SimpleImputer
    from sklearn.impute import KNNImputer
    from sklearn.experimental import enable_iterative_imputer
    from sklearn.impute import IterativeImputer
    import numpy as np
    
    for Imputer in [SimpleImputer, KNNImputer, IterativeImputer]:
        imp = Imputer()
        imp.fit([[0, np.nan], [1, np.nan]])
        X_trans = imp.transform([[0, np.nan], [1, 1]])
        print(imp.__class__.__name__)
        print(X_trans)
    SimpleImputer
    [[0.]
     [1.]]
    KNNImputer
    [[0.]
     [1.]]
    IterativeImputer
    [[0.]
     [1.]]
    

    If we are going to change the behaviour, it needs to be shared between all imputers.

  10. added
    Moderate
    on Feb 26, 2020
  11. 3 remaining items

  12. mitar commented on Apr 22, 2020

    @mitar
    Contributor

    I am glad this got reopened, as I was commenting on #10671 about this as well.

    I think I see value in columns being removed, because this assures the property that after calling imputer you do not have any missing values. This is an important precondition for many models so it is useful to know that you can call something (an imputer) and be assured it (the property that there are no missing values) holds after calling.

    So despite having problems with this behavior, I think this should not be changed: I think both keeping a column with all nans is problematic, and also changing a default is problematic (because it breaks the important property). Keeping nans is problematic because it is still hard for one to know which column is the column which has been kept and not imputed. We are currently (because of this bug) trying to workaround by checking for all-nan columns before calling imputer, but it is fragile because any change in logic of the imputer will throw our detection off which means that we will miss some cases. This is tricky also because what is nan is configurable. If we just keep columns around, we would still have to have this workaround detection implemented.

    I think a better, simpler, and backwards compatible solution is to simple expose a public attribute on the imputer, which after fitting tells how input columns map to output columns, based on column indices. So something like column_map_ which would be a dict from input column indices to output. If some column is dropped, the output column index would be None.

    So one can after fitting inspect and quickly determine if any and which columns are being dropped.

  13. vitorsrg commented on Apr 22, 2020

    @vitorsrg
    Author

    Particularly, I don't think that "sometimes changing the schema, based on the input" is a role of an imputer. Sure, those missing values might cause problems downstream, but changing the schema may break the pipeline itself.

    Nonetheless, the PR preserves the default behaviour and I'll add a is_missing_ field (like statistics_ ).

  14. mitar commented on Apr 22, 2020

    @mitar
    Contributor

    Particularly, I don't think that "sometimes changing the schema, based on the input" is a role of an imputer.

    I think this is just two types of assertions we have here. One assertion (A) is "output schema is the same as input schema" and the other one (B) is "if input has missing values, output does not have them anymore". Now, the question is how those interact. If there were no missing values, then it is easy to say A should hold. If there were some missing values, A can still hold. The question is what to do if there are just missing values. Which of two assertions should prevail. A or B in that case?

    You are saying that imputer's job is not for B to prevail, but for A to ensured for any reason. But I think it is hard to not claim also the opposite, that the nature of the imputer is to assure B, even if it is at the cost of A.

    is_missing_

    This could also be a way to do it, but can you be more precise what you mean with this and what exactly would be semantic of it, and what would be stored there?

  15. vitorsrg commented on Apr 22, 2020

    @vitorsrg
    Author

    One assertion (A) is "output schema is the same as input schema"

    Yes, I advocate for this one, because:

    1. Different imputation strategies may have distinct undefined behaviours
    2. Feature housekeeping and policies are indeed important, but are more specific to each problem: e.g. some algorithms may fail with nans, other may use it directly

    Regarding the is_missing_ field, the user may use it to construct the mapping, but it is intrinsically a mask:

    imp.is_missing_ = np.isnan(X).all(axis=0)
    X[:, ~imp.is_missing_] = imp.transform(X)
    
  16. mitar commented on Apr 22, 2020

    @mitar
    Contributor

    Let's maybe name it is_empty_.

  17. jnothman commented on Apr 23, 2020

    @jnothman
    Member
  18. rth commented on Apr 23, 2020

    @rth
    Member

    I don't see how this leading to a user friendly API, and I don't see why we
    can't have an option to uphold both properties A and B by imputing empty
    columns with a constant value.

    +1 And if one doesn't desire B then one could always pass fill_missing_features=np.nan (or any other paceholder for missing values) in #16695 to keep a columns with missing values and do something with it later.

  19. mitar commented on Apr 24, 2020

    @mitar
    Contributor

    If one anyway wants to drop the column with all all missing values (but just wants to know what is being dropped) I do not think it is reasonable to first fill it with a constant just to be dropped.

    But I do not mind details here. What I really would like to see is an attribute like is_empty_ which tells which columns have been a special case (dropped, filled as a constant, left as is, whatever).

  20. hsorsky commented on Sep 6, 2022

    @hsorsky
    Contributor

    Another point on this in favour of NOT dropping columns of all NaNs at fit time is that it makes calculation of output feature names (via get_feature_names_out) possible pre-fit, assuming we pass in a valid input_features.

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

    EnhancementModeratemodule:impute

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions