Skip to content

Add a version of GenericUnivariateSelect/SelectPercentile/SelectKBest that allows input of X with missing values and y=None. #27609

Description

@34j

Describe the workflow you want to enable

  • Select features by the percentage of missing values of X
  • Select features only by statistical properties of X before y is available

Describe your proposed solution

Create a version with weaker X, y checks.

Describe alternatives you've considered, if relevant

class LooseGenericUnivariateSelect(GenericUnivariateSelect):
    def fit(self, X: Any, y: Any = None) -> Self:
        y = np.ones(X.shape[0])
        return super().fit(X, y)
    
    def _validate_data(self, X, y=None, *args, **kwargs):
        kwargs["force_all_finite"] = False
        kwargs.pop("multi_output", None)
        return super()._validate_data(X, y, *args, **kwargs)
    
    def _more_tags(self):
        return {"requires_y": False, "allow_nan": True}

Not sure if this code works properly.
2.
Bother to create an estimator that outputs the desired function in feature_importance_ and use SelectFromModel

Additional context

No response

Activity

  1. added
    Needs Triage
    on Oct 18, 2023
  2. betatim commented on Oct 19, 2023

    @betatim
    Member

    Thanks for creating the issue. Could you add a bit more context on use-cases where it would be useful to have this and maybe examples in the wild where this is being used. This will help to decide if we want to include this in scikit-learn.

  3. 34j commented on Oct 22, 2023

    @34j
    Author

    Select features by the percentage of missing values of X

    For example, if one wants to use both an estimator that allows NaNs and one that does not allow NaNs in a single complex Pipeline, NaNs need to be removed at some point; in certain fields where feature imputation is not prefered, something like feature_engine.DropMissingData can be used to remove rows that contain NaNs, but if for some reason a column is included where all values are NaN in X, all rows will be removed, so one may want to preliminarily remove some columns with such a transformer within a Pipeline.

    Select features only by statistical properties of X before y is available

    This could be used when you want to use a Pipeline for feature transformation, and then experiment with multiple estimators.
    When reducing features by their monotonicity or periodicity, y is unnecessary.

  4. removed
    Needs Triage
    on Nov 3, 2023
  5. glemaitre commented on Nov 3, 2023

    @glemaitre
    Member

    Select features by the percentage of missing values of X

    I am not sure that we will even advocate for dropping missing values. I am not convinced about this one.

  6. glemaitre commented on Nov 3, 2023

    @glemaitre
    Member

    Select features only by statistical properties of X before y is available

    Nothing prevent you to provide a function that does not use internally the y, ins't it?

  7. 34j commented on Nov 4, 2023

    @34j
    Author

    Isn't it a matter for the function, not these estimators, to determine if y is necessary in the first place? I don't think it is a good idea to reduce the availability of estimators by making such unnecessary checks. This shouldn't be such a big change to refuse.

    Select features only by statistical properties of X before y is available

    Nothing prevent you to provide a function that does not use internally the y, ins't it?

    This does not address the problem. Please read my statement again.

  8. 34j commented on Nov 4, 2023

    @34j
    Author

    Select features by the percentage of missing values of X

    I am not sure that we will even advocate for dropping missing values. I am not convinced about this one.

    When dealing with data that has a complex arrangement of missing values, the removal of missing values can be more difficult than one might imagine.

  9. glemaitre commented on Nov 4, 2023

    @glemaitre
    Member

    This does not address the problem. Please read my statement again.

    A code snippet would be better. Specifically, we overlooked that we validate y and None cannot be pass there. I assume that we could make y to be optional at fit and only validate if provided.

    Details
    import numpy as np
    from sklearn.feature_selection import GenericUnivariateSelect
    X = np.random.randn(100, 10)
    
    def func(X, y=None):
        return np.ones(X.shape[1])
    
    transformer = GenericUnivariateSelect(func, mode='k_best')
    X_new = transformer.fit(X, y=None)
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    Cell In[2], line 9
          6     return np.ones(X.shape[1])
          8 transformer = GenericUnivariateSelect(func, mode='k_best')
    ----> 9 X_new = transformer.fit(X, y=None)
    
    File ~/Documents/packages/scikit-learn/sklearn/base.py:1215, in _fit_context.<locals>.decorator.<locals>.wrapper(estimator, *args, **kwargs)
       1208     estimator._validate_params()
       1210 with config_context(
       1211     skip_parameter_validation=(
       1212         prefer_skip_nested_validation or global_skip_validation
       1213     )
       1214 ):
    -> 1215     return fit_method(estimator, *args, **kwargs)
    
    File ~/Documents/packages/scikit-learn/sklearn/feature_selection/_univariate_selection.py:501, in _BaseFilter.fit(self, X, y)
        483 @_fit_context(prefer_skip_nested_validation=True)
        484 def fit(self, X, y):
        485     """Run score function on (X, y) and get the appropriate features.
        486 
        487     Parameters
       (...)
        499         Returns the instance itself.
        500     """
    --> 501     X, y = self._validate_data(
        502         X, y, accept_sparse=["csr", "csc"], multi_output=True
        503     )
        505     self._check_params(X, y)
        506     score_func_ret = self.score_func(X, y)
    
    File ~/Documents/packages/scikit-learn/sklearn/base.py:583, in BaseEstimator._validate_data(self, X, y, reset, validate_separately, cast_to_ndarray, **check_params)
        580 self._check_feature_names(X, reset=reset)
        582 if y is None and self._get_tags()["requires_y"]:
    --> 583     raise ValueError(
        584         f"This {self.__class__.__name__} estimator "
        585         "requires y to be passed, but the target y is None."
        586     )
        588 no_val_X = isinstance(X, str) and X == "no_validation"
        589 no_val_y = y is None or isinstance(y, str) and y == "no_validation"
    
    ValueError: This GenericUnivariateSelect estimator requires y to be passed, but the target y is None.
  10. glemaitre commented on Nov 4, 2023

    @glemaitre
    Member

    When dealing with data that has a complex arrangement of missing values, the removal of missing values can be more difficult than one might imagine.

    To be more explicit, I think that we should leverage a bit more the following work in the documentation on the topic:

    In short, if you are using a strong learner, then the imputation techniques does not matter and leveraging the missing handling of random-forest or gradient boosting would be best. More advanced imputation techniques could be useful with simpler learner with a much higher cost.

    Regarding dropping the missing values does not seem wise because in real use-case, the missingness is usually MNAR (missing not at random) and potentially have a predictive power for your final task.

  11. glemaitre commented on Nov 4, 2023

    @glemaitre
    Member

    Something related to this feature request is the desired to drop constant feature as requested in OneHotEncoder: #27435

    Making these selectors unsupervised allow to not to have to create a new estimator. I still think that it could be useful to get a SelectThreshold filter in this case.

    I am going to implement those.

    /take

  12. glemaitre commented on Nov 4, 2023

    @glemaitre
    Member

    I open #27721

  13. glemaitre commented on Nov 4, 2023

    @glemaitre
    Member

    I subsequently open #27722 that build upon #27721

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