Skip to content

SimpleImputer does not drop a column full of np.nan even when keep_empty_feature=False #29827

Closed

Description

@glemaitre

The following code snippet lead to some surprises:

import numpy as np
from sklearn.datasets import load_iris
from sklearn.impute import SimpleImputer

X, y = load_iris(return_X_y=True)
X[:, 0] = np.nan

imputer = SimpleImputer(keep_empty_features=False, strategy="constant", fill_value=1)
X_trans = imputer.fit_transform(X)

assert X_trans.shape[1] == 3, f"X_trans contains {X.shape[1]} columns"
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[19], line 11
      8 imputer = SimpleImputer(keep_empty_features=False, strategy="constant", fill_value=1)
      9 X_trans = imputer.fit_transform(X)
---> 11 assert X_trans.shape[1] == 3, f"X_trans contains {X.shape[1]} columns"

AssertionError: X_trans contains 4 columns

Apparently this is something that we really wanted for backward compatibility when merging #24770:

@pytest.mark.parametrize("array_type", ["array", "sparse"])
@pytest.mark.parametrize("keep_empty_features", [True, False])
def test_simple_imputer_constant_keep_empty_features(array_type, keep_empty_features):
"""Check the behaviour of `keep_empty_features` with `strategy='constant'.
For backward compatibility, a column full of missing values will always be
fill and never dropped.
"""
X = np.array([[np.nan, 2], [np.nan, 3], [np.nan, 6]])
X = _convert_container(X, array_type)
fill_value = 10
imputer = SimpleImputer(
strategy="constant",
fill_value=fill_value,
keep_empty_features=keep_empty_features,
)
for method in ["fit_transform", "transform"]:
X_imputed = getattr(imputer, method)(X)
assert X_imputed.shape == X.shape
constant_feature = (
X_imputed[:, 0].toarray() if array_type == "sparse" else X_imputed[:, 0]
)
assert_array_equal(constant_feature, fill_value)

Now, I'm wondering if we should not deprecate this behaviour since the parameter keep_empty_feature allows to control whether or not we should drop the feature entirely.

So I would propose to warn for a change of behaviour when strategy="constant", keep_empty_feature=False, and that we detect that we have empty feature(s).

Activity

  1. added
    Needs Triage
    on Sep 10, 2024
  2. added and removed
    Needs Triage
    on Sep 10, 2024
  3. jeremiedbb commented on Sep 11, 2024

    @jeremiedbb
    Member

    It is kind of weird to have this behavior only for the constant strategy. I can't remember the motivation behind that and reading the original PR doesn't make it clearer.

    So I would propose to warn for a change of behaviour when strategy="constant", keep_empty_feature=False, and that we detect that we have empty feature(s).

    I'm okay with that.

    To go further, I'm wondering if we really want to keep the possibility to remove empty columns. It's been the source of many issues, especially when wrapped in a cross val. I feel like this should be handled separately. We don't have this option for any other preprocessor for instance.

  4. StefanieSenger commented on Sep 11, 2024

    @StefanieSenger
    Member

    I have come across another issue with keep_empty_feature in #29451 (open PR waiting for reviews, just linking for reference).
    keep_empty_feature is present in SimpleImputer, KNNImputer and IterativeImputer since version 1.2.

  5. glemaitre commented on Sep 11, 2024

    @glemaitre
    MemberAuthor

    Thanks @StefanieSenger I'll give a look at this PR.

    To go further, I'm wondering if we really want to keep the possibility to remove empty columns. It's been the source of many issues, especially when wrapped in a cross val. I feel like this should be handled separately. We don't have this option for any other preprocessor for instance.

    Now that we have the parameter this is maybe not worth to remove it. However, it might be wise to change the default to True to not step into the issue that you mentioned in cross-validation.

  6. StunningShield4504 commented on Sep 17, 2024

    @StunningShield4504
  7. ArthurCourselle commented on Sep 27, 2024

    @ArthurCourselle
    Contributor

    I am going to work on this issue.

  8. FMorgan-111 commented on Jul 4, 2026

    @FMorgan-111

    RepoPilot v2 could not complete an automatic fix.

    Reason: Infrastructure error during execution: Command '['git', 'clone', '--depth', '1', '--filter=blob:none', '--single-branch', 'https://x-access-token:@github.com/scikit-learn/scikit-learn.git', '/home/morganbest/.repopilot/repos/scikit-learn-scikit-learn']' timed out after 180 seconds

    Relevant files:

    • sklearn/impute/tests/test_impute.py: requested by planner next_checks; bm25 rerank score=103.945; matched issue terms: simpleimputer, does, not, drop, column, full; bm25 rerank score=109.411; matched issue terms: simpleimputer, does, not, drop, column, full
    • sklearn/impute/_base.py: path components match issue terms; bm25 rerank score=64.190; matched issue terms: simpleimputer, does, not, drop, column, full; bm25 rerank score=81.566; matched issue terms: simpleimputer, does, not, drop, column, full; bm25 rerank score=90.826; matched issue terms: simpleimputer, does, not, drop, column, full; bm25 rerank score=96.859; matched issue terms: simpleimputer, does, not, drop, column, full
    • sklearn/impute/_iterative.py: path components match issue terms; bm25 rerank score=52.597; matched issue terms: simpleimputer, not, drop, column, full, np; bm25 rerank score=67.669; matched issue terms: simpleimputer, not, drop, column, full, np; bm25 rerank score=76.024; matched issue terms: simpleimputer, not, drop, column, full, np; bm25 rerank score=79.833; matched issue terms: simpleimputer, not, drop, column, full, np
    • sklearn/impute/_knn.py: path components match issue terms; bm25 rerank score=42.480; matched issue terms: simpleimputer, not, column, np, nan, even; bm25 rerank score=58.419; matched issue terms: simpleimputer, not, column, np, nan, even; bm25 rerank score=65.370; matched issue terms: simpleimputer, not, column, np, nan, even; bm25 rerank score=69.623; matched issue terms: simpleimputer, not, column, np, nan, even
    • doc/conf.py: matched GitHub code search; bm25 rerank score=74.464; matched issue terms: does, not, full, nan, even, when; bm25 rerank score=72.096; matched issue terms: does, not, full, nan, even, when
    • examples/impute/plot_missing_values.py: path components match issue terms; bm25 rerank score=51.456; matched issue terms: simpleimputer, not, full, np, nan, feature; bm25 rerank score=53.585; matched issue terms: simpleimputer, not, full, np, nan, feature; bm25 rerank score=58.152; matched issue terms: simpleimputer, not, full, np, nan, feature

    Attempts:
    Attempt 1: success=False
    File: sklearn/impute/_base.py
    Result: execution_error
    Error:
    Command '['git', 'clone', '--depth', '1', '--filter=blob:none', '--single-branch', 'https://x-access-token:@github.com/scikit-learn/scikit-learn.git', '/home/morganbest/.repopilot/repos/scikit-learn-scikit-learn']' timed out after 180 seconds

    Token usage: 44247/100000

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions