Skip to content

Make RFE/RFECV preserve pandas dataframes #28629

Closed

Description

@cleboo

Describe the workflow you want to enable

Hi!

I am currently using xgboost with some categorical features. To get that to work the categorical features have to be marked as such in the pandas dataframe:

df["my_cats"] = df["my_cats"].astype("string").astype("category")

The RFE(CV) implementation converts any input to a numpy array that can only contain numeric values which blocks me from using them with xgboost because the dtype information get's lost along the way.

So my proposal: make RFE and RFECV preserve pandas dataframes so the estimator that is used still has access to this information.

Describe your proposed solution

I was able to get this to work with the following quick-and-dirty changes:

# relax the data validation a little bit (dtype -> None, cast_to_ndarray -> False)
X, y = self._validate_data(
    X,
    y,
    accept_sparse="csc",
    ensure_min_features=2,
    force_all_finite=False,
    multi_output=True,
    dtype=None,
    cast_to_ndarray=False,
)

# make the fit command pandas compliant
estimator.fit(X.iloc[:, features], y, **fit_params)

# instead of
estimator.fit(X[:, features], y, **fit_params)

The second step is a hack of course and would have to be replaced depending on the input of X.

With these changes and a set_output(transform='pandas') i got the optimization to work.

Describe alternatives you've considered, if relevant

No response

Additional context

#17338 - similar problem with catboost.

Activity

  1. glemaitre commented on Mar 15, 2024

    @glemaitre
    Member

    I'm almost sure that we got another issue about the topic. I could only find #25560 but there is a major difference here, we do not apply any transformation on the input data and thus only select them.

    Therefore, I think that all estimators in feature_selection should make a copy of X and use _safe_indexing to output based on the fitted attribute support_.

  2. removed
    Needs Triage
    on Mar 15, 2024
  3. ogrisel commented on Mar 19, 2024

    @ogrisel
    Member

    I think that all estimators in feature_selection should make a copy of X and use safe_indexing to output based on the fitted attribute support.

    I don't understand why you would want to make a copy if there is no inplace modification of the original input datastructure.

    But I agree that we should use _safe_indexing to handle either dataframes or arrays with the same code while making it possible to output the same output dtype when configuring `set_output

    I had a look a the source:

    • the SelectorMixin.transform method has a preserve_X variable that depends on both the type of X and the output config:
      output_config_dense = _get_output_config("transform", estimator=self)["dense"]
      preserve_X = output_config_dense != "default" and _is_pandas_df(X)
      # note: we use _safe_tags instead of _get_tags because this is a
      # public Mixin.
      X = self._validate_data(
      X,
      dtype=None,
      accept_sparse="csr",
      force_all_finite=not _safe_tags(self, key="allow_nan"),
      cast_to_ndarray=not preserve_X,
      reset=False,
      )
    • the RFE(CV).fit method indeed always cast to arrays before passing this to the sub-estimator.

    I agree we should align the behavior of the fit method with the logic implemented in the SelectorMixin.transform method.

    @cleboo would you be interested in working on a PR? You can start with RFE and RFECV alone and then we could open follow-up PRs for other estimators under sklearn.feature_selection later if we identify similar patterns.

  4. ogrisel commented on Mar 19, 2024

    @ogrisel
    Member

    Also, we might want to add polars support as well but we can do that in a follow-up PR to make the review process more lightweight.

  5. glemaitre commented on Mar 19, 2024

    @glemaitre
    Member

    I don't understand why you would want to make a copy if there is no inplace modification of the original input datastructure.

    By a copy, I mean that the underlying algorithm creating the mask is most probably expecting working on NumPy array. We could always make sure that the underlying algorithm does not required specifically a NumPy array in which case, we then don't even need the conversion and the associated copy.

  6. ogrisel commented on Mar 19, 2024

    @ogrisel
    Member

    Alright, thanks for the clarification. Indeed there are several occurrences of array-specific indexing such as X[:, features] in the RFE(CV) source code and all of them should be replaced by _safe_indexing.

  7. cleboo commented on Mar 26, 2024

    @cleboo
    Author

    @cleboo would you be interested in working on a PR? You can start with RFE and RFECV alone and then we could open follow-up PRs for other estimators under sklearn.feature_selection later if we identify similar patterns.

    Happy to - any pointers on how to write a test for this? I guess pandas should not become an explicit dependency here?

  8. ogrisel commented on Mar 27, 2024

    @ogrisel
    Member

    You can take inspirations from other tests that have a soft dependency on pandas, e.g. on a linux/macos machine with bash / grep:

    git grep pandas | grep test
    

    or alternatively use the "search in project files" feature of your IDE.

    The most common idiom being to import pandas as follows in tests:

    pd = pytest.importorskip("pandas")
  9. garciadias commented on Jun 30, 2024

    @garciadias

    Hi @cleboo, Have you made any progress on this? I would love to see this problem solved as well. If you are working on a solution, let me know, and I would try to help you.

  10. Gabriel-Kissin commented on Jul 4, 2024

    @Gabriel-Kissin

    +1. I came here to post a separate issue, but will add here instead as I suspect same root cause and will be solved together.

    Setup:

    from sklearn.datasets import load_iris
    import sklearn.linear_model
    import sklearn.feature_selection
    import sklearn.model_selection
    import sklearn.tree
    
    iris = load_iris(as_frame=True)
    X = iris['data']
    y = iris['target']
    
    X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, test_size=30)
    
    from sklearn import set_config
    set_config(transform_output = "pandas")

    Normal use of DecisionTreeClassifier (or any classifier) - works fine:

    clf = sklearn.tree.DecisionTreeClassifier()
    
    clf.fit(X_train,y_train)
    print(clf.predict(X_test))
    print(clf.feature_names_in_)
    [1 1 0 0 1 1 2 0 0 2 2 2 2 1 1 1 2 1 1 0 2 1 1 1 0 1 2 2 1 2]
    ['sepal length (cm)' 'sepal width (cm)' 'petal length (cm)' 'petal width (cm)']
    

    but using RFE to fit a DecisionTreeClassifier complains about feature names:

    • not just DecisionTreeClassifier - other models also - the issue is with RFE
    • not just RFE, also RFECV
    clf = sklearn.feature_selection.RFE(
            estimator=sklearn.tree.DecisionTreeClassifier(),
            # estimator=sklearn.linear_model.LogisticRegression(),
            n_features_to_select=2
            ).set_output(transform='pandas')
    
    clf.fit(X_train,y_train)
    print(clf.transform(X_test)[:1])
    print(clf.predict(X_test))
    print(clf.feature_names_in_)
    print(clf.estimator_.feature_names_in_)
        petal length (cm)  petal width (cm)
    85                4.5               1.6
    [1 1 0 0 1 1 2 0 0 2 2 2 2 1 1 1 2 1 1 0 2 1 1 1 0 1 2 2 1 2]
    ['sepal length (cm)' 'sepal width (cm)' 'petal length (cm)'
     'petal width (cm)']
    ... /sklearn/base.py:486: UserWarning: X has feature names, but DecisionTreeClassifier was fitted without feature names
      warnings.warn(
    AttributeError: 'DecisionTreeClassifier' object has no attribute 'feature_names_in_'
    

    It shouldn't complain "UserWarning: X has feature names, but DecisionTreeClassifier was fitted without feature names". clf.fit and clf.predict were both run on dataframes with feature names.

    In a nutshell, RFE and RFECV implement both transform and predict. Transform returns X after feature selection; and predict does the transform and then uses the fitted estimator to predict. The above cell output shows that transform retains feature names, the output is a dataframe like the input. However predict complains about feature names, because when RFE(CV) fits the estimator it does so without feature names. And feature_names_in_ works for the RFE but not for the estimator, for the same reason.

  11. Gabriel-Kissin commented on Jul 4, 2024

    @Gabriel-Kissin

    A temporary workaround which I imagine will solve the OP's issue is to make a pipeline of the RFE and then a new classifier. The RFE will be responsible for transforming the X to Xt, which it does preserving dataframe status. The new classifier will then use Xt for fitting and predicting, in both cases receiving a dataframe. I.e. instead of using the classifier which RFE returns, which loses feature names (and categorical cols), we just use RFE for the transform and then fit a new classifer to handle the predict.

    So

    import sklearn.pipeline
    
    estimator = sklearn.tree.DecisionTreeClassifier()
    # estimator = sklearn.linear_model.LogisticRegression()
    
    rfe = sklearn.feature_selection.RFE(
            estimator=estimator,
            n_features_to_select=2
            ).set_output(transform='pandas')
    
    clf = sklearn.pipeline.make_pipeline(rfe, estimator)
    clf.fit(X_train,y_train)
    print(clf[0].transform(X_test)[:1])
    print(clf.predict(X_test))
    print(clf.feature_names_in_)
    print(clf[0].get_feature_names_out())
    print(clf[1].feature_names_in_)
        petal length (cm)  petal width (cm)
    85                4.5               1.6
    [1 1 0 0 1 1 2 0 0 2 2 2 2 1 1 1 2 1 1 0 2 1 1 1 0 1 2 2 1 2]
    ['sepal length (cm)' 'sepal width (cm)' 'petal length (cm)' 'petal width (cm)']
    ['petal length (cm)' 'petal width (cm)']
    ['petal length (cm)' 'petal width (cm)']
    
    • the classifier has the feature names as desired
    • this would presumably also work for OP's issue by preserving categorical columns.
  12. Gabriel-Kissin commented on Jul 4, 2024

    @Gabriel-Kissin

    One final thought: This issue is only relevant to RFE and RFECV. sklearn.feature_selection is a set of feature selection approaches - i.e. essentially their job is to transform the input data by selecting some features, not to predict. Indeed, the vast majority do not implement a .predict method at all, only a .transform method; only RFE and RFECV do. Thus, issues with the fitted estimator used for prediction are only relevant to RFE and RFECV.

    (As I understand it, the reason only RFE and RFECV implement .predict is as follows:

    • In cases like VarianceThreshold it is obvious - there is no model fitted which can predict.
    • With SequentialFeatureSelector, since it uses k-fold cross-validation there will be $k$ models fitted using the required $m$ features, so there is no obvious choice about which of the $k$ models to use for prediction. (Shame the models aren't kept in some attribute though).
    • It is only RFE and RFECV which fit one and only one model, and as such it is only this feature selection method which should arguably incorporate the fitted model and use that for predictions, rather than requiring a new model to be fitted on transformed data. While this means a slight inconsistency across the sklearn.feature_selection module, it would probably be overly pedantic to insist that only pure feature selection be performed here.)
  13. Kaynup commented on Aug 21, 2026

    @Kaynup
    Contributor

    Hello @ogrisel @glemaitre,

    I would like to work on this issue as my first contribution to scikit-learn.

    I've checked the current codebase and plan to follow the approach as discussed above:

    • preserving the DataFrame inputs in RFE and RFECV, when appropriate
    • also as you said, replace array-specific slicing X[:, features] with _safe_indexing(X, features, axis=1).
    • add test coverage for both

    I'll put together a PR shortly.

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

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions