You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
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 compliantestimator.fit(X.iloc[:, features], y, **fit_params)
# instead ofestimator.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
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_.
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:
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.
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.
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.
@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?
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.
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.
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.
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.)
Activity
glemaitre commentedon Mar 15, 2024
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_selectionshould make a copy ofXand use_safe_indexingto output based on the fitted attributesupport_.ogrisel commentedon Mar 19, 2024
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_indexingto handle either dataframes or arrays with the same code while making it possible to output the same output dtype when configuring `set_outputI had a look a the source:
SelectorMixin.transformmethod has apreserve_Xvariable that depends on both the type ofXand the output config:scikit-learn/sklearn/feature_selection/_base.py
Lines 97 to 109 in 69c1116
RFE(CV).fitmethod indeed always cast to arrays before passing this to the sub-estimator.I agree we should align the behavior of the
fitmethod with the logic implemented in theSelectorMixin.transformmethod.@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_selectionlater if we identify similar patterns.ogrisel commentedon Mar 19, 2024
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.
glemaitre commentedon Mar 19, 2024
By a copy, I mean that the underlying algorithm creating the
maskis 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.ogrisel commentedon Mar 19, 2024
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.cleboo commentedon Mar 26, 2024
Happy to - any pointers on how to write a test for this? I guess pandas should not become an explicit dependency here?
ogrisel commentedon Mar 27, 2024
You can take inspirations from other tests that have a soft dependency on pandas, e.g. on a linux/macos machine with bash / grep:
or alternatively use the "search in project files" feature of your IDE.
The most common idiom being to import pandas as follows in tests:
garciadias commentedon Jun 30, 2024
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.
Gabriel-Kissin commentedon Jul 4, 2024
+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:
Normal use of DecisionTreeClassifier (or any classifier) - works fine:
but using RFE to fit a DecisionTreeClassifier complains about feature names:
It shouldn't complain "UserWarning: X has feature names, but DecisionTreeClassifier was fitted without feature names".
clf.fitandclf.predictwere 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.Gabriel-Kissin commentedon Jul 4, 2024
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
Gabriel-Kissin commentedon Jul 4, 2024
One final thought: This issue is only relevant to
RFEandRFECV.sklearn.feature_selectionis 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.predictmethod at all, only a.transformmethod; onlyRFEandRFECVdo. Thus, issues with the fitted estimator used for prediction are only relevant toRFEandRFECV.(As I understand it, the reason only
RFEandRFECVimplement.predictis as follows:VarianceThresholdit is obvious - there is no model fitted which can predict.SequentialFeatureSelector, since it uses k-fold cross-validation there will beRFEandRFECVwhich 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 thesklearn.feature_selectionmodule, it would probably be overly pedantic to insist that only pure feature selection be performed here.)Kaynup commentedon Aug 21, 2026
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:
DataFrameinputs inRFEandRFECV, when appropriateX[:, features]with_safe_indexing(X, features, axis=1).I'll put together a PR shortly.