Repository navigation
Conversation
|
Thank you for opening your first pull request to scikit-learn! 🎉 To help get your contribution reviewed, please make sure that:
|
|
Opened a PR with a proposed fix: The approach preserves DataFrame inputs during the feature-selection loop while keeping existing validation behavior unchanged. |
adrinjalali
left a comment
There was a problem hiding this comment.
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:
- The PR still calls
check_array, sovalidate_datakeeps raising on dtypes a capable estimator could handle — a datetime column, for instance, dies withDTypePromotionErrorbefore the loop is reached.skip_check_array=Trueresolves the whole class, which is what we agreed on in #30785. - The dataframe infra now goes through narwhals —
_num_featuresand_safe_indexingalready 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( |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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 | |||
There was a problem hiding this comment.
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."
There was a problem hiding this comment.
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.
|
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. |
adrinjalali
left a comment
There was a problem hiding this comment.
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?
|
Hi, |
|
@peehu-k nothing to be done, we need to wait for others to review. |
Reference Issues/PRs
Fixes #30785.
What does this implement/fix? Explain your changes.
SequentialFeatureSelector.fit()converts pandas DataFrames to NumPy arrays throughvalidate_data(), causing categorical dtypes to be lost before the feature-selection loop. This can break estimators that support non-numeric features when used insideSequentialFeatureSelector.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:
Any other comments?
This PR is an alternative implementation addressing the same issue discussed in #30799.