Repository navigation
Open
Description
Describe the bug
Please see the code.
Steps/Code to Reproduce
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.compose import ColumnTransformer
import pandas as pd
import numpy as np
# dummy data
N = 100
dummy_x = pd.DataFrame(
np.random.randn(N,3),
columns = list('abc'),
)
dummy_y = pd.DataFrame(
np.random.choice([0,1], size= (N,1)),
columns = ['label'],
)
num_pipeline = Pipeline([
('imputer', SimpleImputer(strategy="median")),
('std_scaler', StandardScaler()),
])
ct_parts = [
('num', num_pipeline, [0,1,2]),
]
data_preparation_pipe = ColumnTransformer(ct_parts, remainder='passthrough')
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.ensemble import GradientBoostingClassifier
model = Pipeline(
[
# ('data_prep', num_pipeline),
('data_prep', data_preparation_pipe),
('ML', GradientBoostingClassifier()),
]
)
sfs = SequentialFeatureSelector(
model,
)
sfs.fit(dummy_x, dummy_y)Expected Results
No error
Actual Results
Traceback (most recent call last):
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3460, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "/tmp/ipykernel_3433582/3663298101.py", line 1, in <module>
sfs.fit(dummy_x, dummy_y)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/feature_selection/_sequential.py", line 268, in fit
new_feature_idx, new_score = self._get_best_new_feature_score(
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/feature_selection/_sequential.py", line 299, in _get_best_new_feature_score
scores[feature_idx] = cross_val_score(
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/model_selection/_validation.py", line 515, in cross_val_score
cv_results = cross_validate(
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/model_selection/_validation.py", line 285, in cross_validate
_warn_or_raise_about_fit_failures(results, error_score)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/model_selection/_validation.py", line 367, in _warn_or_raise_about_fit_failures
raise ValueError(all_fits_failed_message)
ValueError:
All the 5 fits failed.
It is very likely that your model is misconfigured.
You can try to debug the error by setting error_score='raise'.
Below are more details about the failures:
--------------------------------------------------------------------------------
5 fits failed with the following error:
Traceback (most recent call last):
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/utils/__init__.py", line 416, in _get_column_indices
idx = _safe_indexing(np.arange(n_columns), key)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/utils/__init__.py", line 356, in _safe_indexing
return _array_indexing(X, indices, indices_dtype, axis=axis)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/utils/__init__.py", line 185, in _array_indexing
return array[key] if axis == 0 else array[:, key]
IndexError: index 1 is out of bounds for axis 0 with size 1
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/model_selection/_validation.py", line 686, in _fit_and_score
estimator.fit(X_train, y_train, **fit_params)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/pipeline.py", line 401, in fit
Xt = self._fit(X, y, **fit_params_steps)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/pipeline.py", line 359, in _fit
X, fitted_transformer = fit_transform_one_cached(
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/joblib/memory.py", line 349, in __call__
return self.func(*args, **kwargs)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/pipeline.py", line 893, in _fit_transform_one
res = transformer.fit_transform(X, y, **fit_params)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/utils/_set_output.py", line 142, in wrapped
data_to_wrap = f(self, X, *args, **kwargs)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/compose/_column_transformer.py", line 724, in fit_transform
self._validate_column_callables(X)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/compose/_column_transformer.py", line 426, in _validate_column_callables
transformer_to_input_indices[name] = _get_column_indices(X, columns)
File "/software/anaconda3/envs/TOSC_ML/lib/python3.10/site-packages/sklearn/utils/__init__.py", line 418, in _get_column_indices
raise ValueError(
ValueError: all features must be in [0, 0] or [-1, 0]Versions
System:
python: 3.10.9 | packaged by conda-forge | (main, Feb 2 2023, 20:20:04) [GCC 11.3.0]
executable: /software/anaconda3/envs/TOSC_ML/bin/python
machine: Linux-4.18.0-305.3.1.el8.x86_64-x86_64-with-glibc2.28
Python dependencies:
sklearn: 1.2.1
pip: 23.0
setuptools: 67.3.2
numpy: 1.23.5
scipy: 1.10.0
Cython: None
pandas: 1.5.3
matplotlib: 3.7.0
joblib: 1.2.0
threadpoolctl: 3.1.0
Built with OpenMP: True
threadpoolctl info:
user_api: blas
internal_api: openblas
prefix: libopenblas
filepath: /software/anaconda3/envs/TOSC_ML/lib/libopenblasp-r0.3.21.so
version: 0.3.21
threading_layer: pthreads
architecture: Zen
num_threads: 128
user_api: openmp
internal_api: openmp
prefix: libgomp
filepath: /software/anaconda3/envs/TOSC_ML/lib/libgomp.so.1.0.0
version: None
num_threads: 128Reacted by avm19, pascal456, NoPenguinsLand and Saloni Malpani
Activity
ogrisel commentedon Mar 2, 2023
Thanks for the reproducer. I confirm I reproduce the exact same problem with scikit-learn's
mainbranch.glemaitre commentedon Mar 8, 2023
I don't really see an easy fix here.
Let's consider only integral indices. We defined the indices of the column to be treated in the column transformer depending on the original
X.SequentialFeatureSelectorwill alter the ordering and the column. Thus, one should alter the column indices passed to theColumnTransformerto only treat the columns provided by theSequentialFeatureSelector.If we have
strthen we could always come back first to the indices and make the previous change.Where things become really complicated is that
ColumnTransformeris usually inside aPipelineand we would therefore need to introspect such aPipelineand understand how columns are propagated in order to filter/map the right columns. It could become even harder if you have 2ColumnTransformers one after the other (since it is quite possible with pandas output).I forsee a lot of magical trick to make this use case work.
Charlie-XIAO commentedon Mar 23, 2023
Hi, I'm pretty interested in this issue but I'm not sure if the following would work. Currently in
_get_best_new_feature_scoreofSequentialFeatureSelector, we callcross_val_scorefor each column ofXand pass in the originalestimator. Maybe here we can check whetherestimatorinvolves anyColumnTransformer, and modify theircolumnsaccordingly. Then we pass the newestimatortocross_val_scoreinstead of the original one. If theestimatoris aPipeline, we check each of itssteps. If there arePipelines insidePipelines, we recursively check (and possibly modify) them. For instance in this case, we haveSince in each iteration we call
cross_val_scoreon a single column ofX, we pass the newestimatorlikeso that there wouldn't be
IndexError. Would this be a valid (and feasible) approach? Though I've contributed to this project I'm still quite new, so please bear with me if I'm not understanding this issue correctly.thomasjpfan commentedon May 4, 2023
Once we update
ColumnTransformerto not call_validate_dataand generically slice the data, then we can do the following. Note that the code does not work yet.Overall, the
ColumnTransformerneeds to be generic enough to handle different feature subsets. This can be done usingmake_column_selectoror a callable for selecting columns.hyugai commentedon Apr 11, 2024
Hi, I think the problem is that SFS uses only the subset of X_train, for example we call it X_train_subset, and those do not share the same shape due to the SFS algorithm. The solution is that you may wanna try creating a customed transformer (there are lots of tutorial on this) which can detect categorical and numerical column to transform.
Hope my opinion will be helpful.
hemant2186 commentedon Jul 8, 2026
Hi! I'm interested in working on this issue.
From reading the discussion, it seems the challenge is that SequentialFeatureSelector subsets the input features while ColumnTransformer still expects the original column indices.
I'd like to investigate whether this can be addressed by adapting how column selections are mapped during feature selection, while keeping the solution compatible with nested pipelines and callable selectors.
Before I start implementing anything, is this issue still open for contributions, and would that direction be consistent with the current design?
satyashry commentedon Jul 8, 2026
can i take this task on?
arham766 commentedon Jul 10, 2026
I dug into this on
mainand the failure has two independent layers:SequentialFeatureSelector.fitconvertsXto a numpy array up front (_sequential.py#L238-L244), so column names and dtypes are gone before any candidate subset reachescross_val_score.X_new = X[:, candidate_mask], L319), so aColumnTransformerconfigured against the originalX(e.g. columns[0, 1, 2]) receives a narrower matrix and_get_column_indicesraisesIndexError: index 1 is out of bounds.For hard-coded positional indices (the original reproducer) I agree with @glemaitre that there is no well-defined fix: once SFS drops features, "column 1" of a subset is ambiguous, and remapping specs through arbitrarily nested pipelines isn't tractable.
But the pattern @thomasjpfan sketched in #25711 (comment) — callable selectors like
make_column_selector— fails for reason (1) alone.ColumnTransformercan nowadays handle varying feature subsets when given callables; SFS just never lets it see the dataframe (his snippet currently dies withValueError: could not convert string to floatbecause of the upfront conversion).A minimal fix makes that endorsed pattern work: skip the array conversion when
Xis a pandas dataframe (validate_data(..., skip_check_array=True)— the same mechanismSelectorMixin.transformalready uses to preserve dataframes) and slice candidate subsets with_safe_indexing(X, candidate_mask, axis=1). With that change, themake_column_selector-based pipeline from the discussion fits fine, and each candidate subset reaches the inner estimator with its original column names and dtypes. I've verified this locally with the existingfeature_selectiontest suite passing.I'd like to open a PR with this change plus regression tests if this direction sounds right.
FIX preserve pandas dataframes in SequentialFeatureSelector