Skip to content

FIX SequentialFeatureSelector/RFE/RFECV preserve DataFrame container type - #34227

Open
peehu-k wants to merge 15 commits into
scikit-learn:mainfrom
peehu-k:fix/sfs-dataframe-passthrough
Open

peehu-k wants to merge 15 commits into
scikit-learn:mainfrom
peehu-k:fix/sfs-dataframe-passthrough

Conversation

@peehu-k

@peehu-k peehu-k commented Jun 9, 2026

Copy link
Copy Markdown

Reference Issues/PRs

Fixes #30785.

What does this implement/fix? Explain your changes.

SequentialFeatureSelector.fit() converts pandas DataFrames to NumPy arrays through validate_data(), causing categorical dtypes to be lost before the feature-selection loop. This can break estimators that support non-numeric features when used inside SequentialFeatureSelector.

This PR preserves the original DataFrame container during the feature-selection loop while keeping the existing validation behavior for other input types. It also replaces direct column indexing with _safe_indexing() for container-agnostic column selection.

A non-regression test is added to verify that DataFrame inputs are passed through to the underlying estimator during cross-validation.

First time contributor introduction

Hi! I'm a student and a first-time contributor to scikit-learn. I became interested in contributing while investigating issue #30785 and tracing the behavior through the feature-selection code path.

AI usage disclosure

I used AI assistance for:

  • Research and understanding

Any other comments?

This PR is an alternative implementation addressing the same issue discussed in #30799.

@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown

Thank you for opening your first pull request to scikit-learn! 🎉

To help get your contribution reviewed, please make sure that:

  • You have filled out the pull request template. - The pull request addresses an existing issue that is ready for
    contribution (e.g. not tagged as "Needs Triage", "Needs Decision", ...).
    If you are proposing a new feature, please open an issue to discuss it first.
  • There are no other open pull requests already targeting the same issue. - You have followed the pull request checklist.
    In particular, linting and tests should pass.

@github-actions github-actions Bot added module:feature_selection CI:Linter failure The linter CI is failing on this PR labels Jun 9, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Jun 9, 2026
@peehu-k

peehu-k commented Jun 9, 2026

Copy link
Copy Markdown
Author

Opened a PR with a proposed fix:

#34227

The approach preserves DataFrame inputs during the feature-selection loop while keeping existing validation behavior unchanged.

@peehu-k peehu-k closed this Jun 9, 2026
@peehu-k peehu-k reopened this Jun 9, 2026

@adrinjalali adrinjalali left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution.

This is a claude review, reviewed by me:


Thanks for digging into this. The diagnosis is right — check_array(dtype="numeric") silently collapses a mixed categorical/numeric frame to an object array and drops the categorical dtype — and the move to _safe_indexing is the correct direction. I confirmed the fix works end-to-end with HistGradientBoostingRegressor(categorical_features="from_dtype").

The main change needed: we don't have to keep X_original and branch on hasattr(..., "iloc"). validate_data already supports skip_check_array=True, which leaves X untouched while still setting n_features_in_/feature_names_in_. Combined with _num_features for the count, the whole X_original/X_loop machinery goes away and the fix stops being pandas-specific:

X = validate_data(self, X, skip_check_array=True)
n_features = _num_features(X)
if n_features < 2:
    raise ValueError(
        f"Found array with {n_features} feature(s) while a minimum of 2 is required."
    )

then use X (with _safe_indexing) everywhere and drop X_original/X_loop.

Two reasons this matters beyond style:

  1. The PR still calls check_array, so validate_data keeps raising on dtypes a capable estimator could handle — a datetime column, for instance, dies with DTypePromotionError before the loop is reached. skip_check_array=True resolves the whole class, which is what we agreed on in #30785.
  2. The dataframe infra now goes through narwhals — _num_features and _safe_indexing already handle polars and pyarrow generically. hasattr(X_original, "iloc") only catches pandas, so a polars frame would still be flattened to numpy.

One thing to call out in the PR description: dropping ensure_all_finite/accept_sparse delegates finiteness and sparse handling to the underlying estimator. That's the intent of a meta-estimator and matches the issue discussion, but it should be stated so reviewers know it's deliberate. The ensure_min_features=2 check is our own invariant, so keep it explicitly as above.

# Keep the original container; validate_data may convert DataFrames
# to numpy, which would lose non-numeric dtypes.
X_original = X
X = validate_data(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use skip_check_array=True here instead of converting and then keeping X_original:

X = validate_data(self, X, skip_check_array=True)
n_features = _num_features(X)

This leaves X as-is (a DataFrame stays a DataFrame) while still setting n_features_in_/feature_names_in_, so the X_original/X_loop machinery below isn't needed. _num_features (narwhals-aware) replaces X.shape[1], which won't work once X is no longer guaranteed to be an array.

This drops ensure_min_features=2, ensure_all_finite and accept_sparse: keep the min-features check explicitly (it's our own invariant), the other two are fine to delegate to the estimator.

n_features = X.shape[1]
# Pass the original container to the estimator for DataFrames so that
# non-numeric dtypes are preserved; use the validated array otherwise.
X_loop = X_original if hasattr(X_original, "iloc") else X

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only catches pandas. Our dataframe handling moved to narwhals, so _num_features/_safe_indexing already support polars and pyarrow — a polars frame would fall into the else branch and get flattened to numpy, losing its dtypes. With skip_check_array=True above, this line goes away entirely.

if self.direction == "backward":
candidate_mask = ~candidate_mask
X_new = X[:, candidate_mask]
X_new = _safe_indexing(X, candidate_mask, axis=1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the right call — works for ndarray, sparse csc, and any narwhals-supported frame. I verified the boolean-mask axis=1 path on all three.


received_types = []

class TypeRecordingEstimator(BaseEstimator):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only checks that the container type reaches the estimator. A stronger non-regression test uses an estimator that actually consumes the categorical dtype, so it fails on main for the real reason:

from sklearn.ensemble import HistGradientBoostingRegressor
est = HistGradientBoostingRegressor(
    categorical_features="from_dtype", random_state=0
)
SequentialFeatureSelector(
    est, n_features_to_select=2, direction=direction, cv=2
).fit(X, y)

I confirmed this raises on main and passes with the fix. A datetime-column case would also lock in the broader guarantee that we no longer reject dtypes the estimator can handle.

@@ -0,0 +1,3 @@
- :class:`feature_selection.SequentialFeatureSelector` now passes pandas
DataFrames to the underlying estimator unchanged during cross-validation,
preserving non-numeric dtypes. No newline at end of file

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing trailing newline. Also, once the fix is container-agnostic (see the skip_check_array note), reword so it's not pandas-specific, e.g.: "now passes the input to the underlying estimator without converting it to a NumPy array, preserving non-numeric dtypes such as categorical columns."

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review.

I updated the implementation to use validate_data(..., skip_check_array=True) and removed the X_original / X_loop logic.

The implementation now preserves dataframe-like containers while using _num_features and _safe_indexing throughout. I also restored the estimator validation behavior required by the common estimator checks, and the full CI suite is now passing.

@peehu-k

peehu-k commented Jun 10, 2026

Copy link
Copy Markdown
Author

Thanks for the detailed review and for verifying the behavior with HistGradientBoostingRegressor.

The points about skip_check_array=True and narwhals support make sense. I'll rework the implementation to use validate_data(..., skip_check_array=True), replace X.shape[1] with _num_features(X), remove the X_original/X_loop logic, and update the test to use HistGradientBoostingRegressor with categorical_features="from_dtype".

I'll also update the changelog wording accordingly.

@github-actions github-actions Bot added the CI:Linter failure The linter CI is failing on this PR label Jun 10, 2026
@github-actions github-actions Bot removed the CI:Linter failure The linter CI is failing on this PR label Jun 10, 2026
@adrinjalali adrinjalali changed the title FIX SequentialFeatureSelector preserves DataFrame container type FIX SequentialFeatureSelector/RFE/RFECV preserve DataFrame container type Jun 12, 2026

@adrinjalali adrinjalali left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Investigating this, I realised we can make validate_data quite nicer, have a common test via a new estimator flag, and also fix RFE/RFECV, which also had a few issues detected by the new test.

So the scope of the PR ended up expanding, and I've pushed the fixes to it.

@thomasjpfan this is what I mentioned yesterday where indexing after validate_data was raised.

@OmarManzoor maybe you could have a look?

@peehu-k

peehu-k commented Jun 17, 2026

Copy link
Copy Markdown
Author

Hi,
Just checking in on this PR. I noticed all the CI checks have completed. Please let me know if there’s anything else you’d like me to do or if any further changes are needed. Thanks!

@adrinjalali

Copy link
Copy Markdown
Member

@peehu-k nothing to be done, we need to wait for others to review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SequentialFeatureSelector fails on text features even though the estimator supports them

2 participants