Skip to content

SequentialFeatureSelector is not working with ColumnTransformer #25711

Open

Description

@Crispy13

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: 128

Activity

  1. added
    Needs Triage
    on Feb 27, 2023
  2. ogrisel commented on Mar 2, 2023

    @ogrisel
    Member

    Thanks for the reproducer. I confirm I reproduce the exact same problem with scikit-learn's main branch.

  3. added
    Moderate
    and removed
    Needs Triage
    on Mar 2, 2023
  4. glemaitre commented on Mar 8, 2023

    @glemaitre
    Member

    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. SequentialFeatureSelector will alter the ordering and the column. Thus, one should alter the column indices passed to the ColumnTransformer to only treat the columns provided by the SequentialFeatureSelector.

    If we have str then we could always come back first to the indices and make the previous change.

    Where things become really complicated is that ColumnTransformer is usually inside a Pipeline and we would therefore need to introspect such a Pipeline and understand how columns are propagated in order to filter/map the right columns. It could become even harder if you have 2 ColumnTransformers 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.

  5. Charlie-XIAO commented on Mar 23, 2023

    @Charlie-XIAO
    Contributor

    Hi, I'm pretty interested in this issue but I'm not sure if the following would work. Currently in _get_best_new_feature_score of SequentialFeatureSelector, we call cross_val_score for each column of X and pass in the original estimator. Maybe here we can check whether estimator involves any ColumnTransformer, and modify their columns accordingly. Then we pass the new estimator to cross_val_score instead of the original one. If the estimator is a Pipeline, we check each of its steps. If there are Pipelines inside Pipelines, we recursively check (and possibly modify) them. For instance in this case, we have

    Pipeline(steps=[('Preprocessing',
                     ColumnTransformer(remainder='passthrough',
                                       transformers=[('num',
                                                      Pipeline(steps=[('Imputer',
                                                                       SimpleImputer(strategy='median')),
                                                                      ('StdScalar',
                                                                       StandardScaler())]),
                                                      [0, 1, 2])])),
                    ('Classifier', KNeighborsClassifier())])
    

    Since in each iteration we call cross_val_score on a single column of X, we pass the new estimator like

    Pipeline(steps=[('Preprocessing',
                     ColumnTransformer(remainder='passthrough',
                                       transformers=[('num',
                                                      Pipeline(steps=[('Imputer',
                                                                       SimpleImputer(strategy='median')),
                                                                      ('StdScalar',
                                                                       StandardScaler())]),
                                                      [0])])),
                    ('Classifier', KNeighborsClassifier())])
    

    so 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.

  6. thomasjpfan commented on May 4, 2023

    @thomasjpfan
    Member

    Once we update ColumnTransformer to not call _validate_data and generically slice the data, then we can do the following. Note that the code does not work yet.

    ct = make_column_transformer(
          (
              StandardScaler(),
              make_column_selector(dtype_include="number")
          ),
          (
              OneHotEncoder(),
              make_column_selector(dtype_include="category")
          )
    )
    selector_pipe = make_pipeline(ct, LogisticRegression())
    selector = SequentialFeatureSelector(selector_pipe, n_features_to_select="auto")
    selector.fit(X, y)

    Overall, the ColumnTransformer needs to be generic enough to handle different feature subsets. This can be done using make_column_selector or a callable for selecting columns.

  7. hyugai commented on Apr 11, 2024

    @hyugai

    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.

  8. hemant2186 commented on Jul 8, 2026

    @hemant2186

    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?

  9. satyashry commented on Jul 8, 2026

    @satyashry

    can i take this task on?

  10. arham766 commented on Jul 10, 2026

    @arham766

    I dug into this on main and the failure has two independent layers:

    1. SequentialFeatureSelector.fit converts X to a numpy array up front (_sequential.py#L238-L244), so column names and dtypes are gone before any candidate subset reaches cross_val_score.
    2. Each candidate subset is then sliced positionally (X_new = X[:, candidate_mask], L319), so a ColumnTransformer configured against the original X (e.g. columns [0, 1, 2]) receives a narrower matrix and _get_column_indices raises IndexError: 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. ColumnTransformer can nowadays handle varying feature subsets when given callables; SFS just never lets it see the dataframe (his snippet currently dies with ValueError: could not convert string to float because of the upfront conversion).

    A minimal fix makes that endorsed pattern work: skip the array conversion when X is a pandas dataframe (validate_data(..., skip_check_array=True) — the same mechanism SelectorMixin.transform already uses to preserve dataframes) and slice candidate subsets with _safe_indexing(X, candidate_mask, axis=1). With that change, the make_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 existing feature_selection test suite passing.

    I'd like to open a PR with this change plus regression tests if this direction sounds right.

  11. added a commit that references this issue on Jul 10, 2026
    e8f347f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugModerate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions