Skip to content

ValueError raised by FeatureUnion._set_output with FunctionTransform that outputs a pandas Series in scikit-learn version 1.6 #31318

Closed

Description

@Bilalbrahimi

Describe the bug

Hello,

I'm currently working with scikit-learn version 1.6, and I encountered a regression that wasn't present in version 1.4.

The following minimal code computes two features — the cumulative mean of age and weight grouped by id. Each transformation function returns a pandas.Series:

When I run this code with scikit-learn 1.6, I get the following error:

After investigation, I found that the issue occurs because each transformer returns a Series, not a DataFrame. If I update the functions to return DataFrame objects instead, the error disappears.

Interestingly, in scikit-learn 1.4, the same code works correctly even when the functions return Series.

Do you have any explanation for why this changed between version 1.4 and 1.6 ?

Thanks in advance for your help!

Steps/Code to Reproduce

import pandas as pd
from sklearn.pipeline import FunctionTransformer, FeatureUnion
import numpy as np

def compute_cumulative_mean_age(df: pd.DataFrame) -> pd.Series:
    return (
        df["age"]
        .astype(float)
        .groupby(df["id"])
        .expanding()
        .mean()
        .droplevel(level="id")
        .reindex(df.index)
        .rename("cumulative_mean_age")
    )

def compute_cumulative_mean_weight(df: pd.DataFrame) -> pd.Series:
    return (
        df["poids"]
        .astype(float)
        .groupby(df["id"])
        .expanding()
        .mean()
        .droplevel(level="id")
        .reindex(df.index)
        .rename("cumulative_mean_weight")
    )

def compute_features(df: pd.DataFrame) -> pd.DataFrame:
    feature_union = FeatureUnion(
        [
            ("cumulative_mean_age", FunctionTransformer(compute_cumulative_mean_age)),
            ("cumulative_mean_weight", FunctionTransformer(compute_cumulative_mean_weight))
        ]
    ).set_output(transform="pandas")

    return feature_union.fit_transform(X=df).astype(float)

def transform(df: pd.DataFrame) -> pd.DataFrame:
    return compute_features(df)

if __name__ == "__main__":
    np.random.seed(42)
    df = pd.DataFrame({
        'id': [1, 2, 3, 1, 4, 5, 6, 6, 7, 8],
        'age': np.random.randint(18, 70, size=10),
        'poids': np.random.randint(50, 100, size=10)
    })

    print(transform(df))

Expected Results

Traceback (most recent call last):
  File "C:\Users\XXX\PycharmProjects\fraude_detection_pec_audio\tmp.py", line 73, in <module>
    print(transform(df=df))
          ^^^^^^^^^^^^^^^^
  File "C:\Users\XXX\PycharmProjects\fraude_detection_pec_audio\tmp.py", line 55, in transform
    return compute_features(
           ^^^^^^^^^^^^^^^^^
  File "C:\Users\XXX\PycharmProjects\fraude_detection_pec_audio\tmp.py", line 45, in compute_features
    .fit_transform(
     ^^^^^^^^^^^^^^
  File "C:\Users\XXX\PycharmProjects\fraude_detection_pec_audio\.venv\Lib\site-packages\sklearn\utils\_set_output.py", line 332, in wrapped
    return _wrap_data_with_container(method, data_to_wrap, X, self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\XXX\PycharmProjects\fraude_detection_pec_audio\.venv\Lib\site-packages\sklearn\utils\_set_output.py", line 307, in _wrap_data_with_container
    return adapter.create_container(
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\XXX\PycharmProjects\fraude_detection_pec_audio\.venv\Lib\site-packages\sklearn\utils\_set_output.py", line 135, in create_container
    X_output = _create_pandas_dataframe_from_non_pandas_container(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\XXX\PycharmProjects\fraude_detection_pec_audio\.venv\Lib\site-packages\sklearn\utils\fixes.py", line 428, in _create_pandas_dataframe_from_non_pandas_container
    return pd.DataFrame(X, index=index, copy=copy)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\XXX\PycharmProjects\fraude_detection_pec_audio\.venv\Lib\site-packages\pandas\core\frame.py", line 722, in __init__
    mgr = ndarray_to_mgr(
          ^^^^^^^^^^^^^^^
  File "C:\Users\XXX\PycharmProjects\fraude_detection_pec_audio\.venv\Lib\site-packages\pandas\core\internals\construction.py", line 349, in ndarray_to_mgr
    _check_values_indices_shape_match(values, index, columns)
  File "C:\Users\XXX\PycharmProjects\fraude_detection_pec_audio\.venv\Lib\site-packages\pandas\core\internals\construction.py", line 420, in _check_values_indices_shape_match
    raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
ValueError: Shape of passed values is (20, 1), indices imply (10, 1)

Actual Results

    raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
ValueError: Shape of passed values is (20, 1), indices imply (10, 1)

Versions

sklearn: 1.6.0
numpy: 1.26.4
pandas: 1.5.3

Activity

  1. added
    Needs Triage
    on May 6, 2025
  2. changed the title [-]Bug sur la version 1.6 sklearn[/-] [+]Bug in scikit-learn version 1.6[/+] on May 6, 2025
  3. glemaitre commented on May 7, 2025

    @glemaitre
    Member

    I would argue that the previous beahviour worked by chance but it was a bug. Scikit-learn transformers API expect to return an array of shape (n_samples, n_features). Having a single dimension is really ambiguous because we cannot guess if it is a single sample or a single feature. For instance, if you use set_output(transform="default"), then you will get an array of shape (20,) where I would argue that the FeatureUnion failed.

    So here, I think that the fact that we raise an error is actually fine. The error message is a bit tricky thought. The fact it does not raise with set_output(transform="default") is actually annoying I think.

    So one way would be to validate the output of FunctionTransformer being sure it should be 2-D. However, we sometime want this transformer to be lenient so I wonder if the behaviour should be driven by a parameter, similarly to the validate parameter but for the output.

  4. removed
    Needs Triage
    on May 7, 2025
  5. glemaitre commented on May 7, 2025

    @glemaitre
    Member

    @jeremiedbb @ogrisel do you have any thoughts regarding if FunctionTransformer should be permissive regarding the shape of the output or if we should strictly follow the API of other transformers.

    I'm thinking that we usually want this transformer to be permissive on the input side.

  6. changed the title [-]Bug in scikit-learn version 1.6[/-] [+]ValueError raised by _set_output on FunctionTransform that outputs a pandas Series in scikit-learn version 1.6[/+] on May 19, 2025
  7. changed the title [-]ValueError raised by _set_output on FunctionTransform that outputs a pandas Series in scikit-learn version 1.6[/-] [+]ValueError raised by `_set_output` with `FunctionTransform` that outputs a pandas `Series` in scikit-learn version 1.6[/+] on May 19, 2025
  8. ogrisel commented on May 19, 2025

    @ogrisel
    Member

    Note that the mentioned code already raises 2 informative warnings before raising the final exception:

    /Users/ogrisel/code/scikit-learn/sklearn/preprocessing/_function_transformer.py:311: UserWarning: When `set_output` is configured to be 'pandas', `func` should return a pandas DataFrame to follow the `set_output` API  or `feature_names_out` should be defined.
      warnings.warn(warn_msg.format("pandas"))
    /Users/ogrisel/code/scikit-learn/sklearn/preprocessing/_function_transformer.py:311: UserWarning: When `set_output` is configured to be 'pandas', `func` should return a pandas DataFrame to follow the `set_output` API  or `feature_names_out` should be defined.
      warnings.warn(warn_msg.format("pandas"))

    The function transformer should not return a pandas series but a pandas dataframe.

    Maybe we could change this to accept series and automatically wrap them as dataframes because there is no ambiguity in this particular case.

    If not, I agree that we should at least improve the error message.

    Let me try to simplify the reproducer to make it minimal.

  9. ogrisel commented on May 19, 2025

    @ogrisel
    Member

    Here is a minimal reproducer:

    import pandas as pd
    from sklearn.preprocessing import FunctionTransformer
    from sklearn.pipeline import FeatureUnion
    
    
    data = pd.DataFrame(dict(a=range(3), b=range(3)))
    FeatureUnion(
        [
            ("a", FunctionTransformer(lambda df: df["a"])),
            ("b", FunctionTransformer(lambda df: df["b"])),  # exception not raised if you remove this line.
        ]
    ).set_output(transform="pandas").fit_transform(data)

    Note that the FeatureUnion requires 2 series, otherwise there are no exceptions, only the warnings.

  10. ogrisel commented on May 19, 2025

    @ogrisel
    Member

    Actually, here is the real bug in my opinion: if you remove the .set_output("pandas") from the above snippet, the code works without failing or raising warnings but outputs meaningless results:

    import pandas as pd
    from sklearn.preprocessing import FunctionTransformer
    from sklearn.pipeline import FeatureUnion
    
    
    data = pd.DataFrame(dict(a=range(3), b=range(3)))
    FeatureUnion(
        [
            ("a", FunctionTransformer(lambda df: df["a"])),
            ("b", FunctionTransformer(lambda df: df["b"])),
        ]
    ).fit_transform(data)
    array([0, 1, 2, 0, 1, 2])
    

    Instead, FeatureUnion should raise an explicit error message to make it explicit that some transformers output 1d data-structures instead of the expected 2d.

  11. ogrisel commented on May 19, 2025

    @ogrisel
    Member

    I think the FeatureUnion._hstack method should be changed to raise an informative error message if some elements in Xs are not 2D data-structures. We should also check that their .shape[0] match the expected number of samples measured on the X parameter passed to FeatureUnion.transform or FeatureUnion.fit_transform.

    EDIT: the error message of the exception should mention the name of the transformer that generated invalid output shapes along with the observed shape and the expected number of data points.

  12. changed the title [-]ValueError raised by `_set_output` with `FunctionTransform` that outputs a pandas `Series` in scikit-learn version 1.6[/-] [+]ValueError raised by `FeatureUnion._set_output` with `FunctionTransform` that outputs a pandas `Series` in scikit-learn version 1.6[/+] on May 19, 2025
  13. changed the title [-]ValueError raised by `FeatureUnion._set_output` with `FunctionTransform` that outputs a pandas `Series` in scikit-learn version 1.6[/-] [+]`ValueError` raised by `FeatureUnion._set_output` with `FunctionTransform` that outputs a pandas `Series` in scikit-learn version 1.6[/+] on May 19, 2025
  14. added
    good first issue
    on Jun 16, 2025
  15. Ahsan-Imam commented on Jun 22, 2025

    @Ahsan-Imam

    hello i am Ahsan , i am new to open source , i would like to contribute .

  16. Nafeessidd1 commented on Jul 3, 2025

    @Nafeessidd1

    /take

  17. MohammedSaim-Quadri commented on Jul 6, 2025

    @MohammedSaim-Quadri

    Hi @Nafeessidd1 , I noticed you've claimed this issue recently. I'm new to open source and was interested in contributing. Would you be open to collaborating, or should I look for another issue? No worries either way — thanks!

  18. Nafeessidd1 commented on Jul 6, 2025

    @Nafeessidd1

    Hi! @MohammedSaim-Quadri 👋 Thanks for reaching out — and welcome to open source! I'd be more than happy to collaborate on this issue or any other issue. Let’s work on it together and split things up if needed. Feel free to share your thoughts or let me know if you’ve already started exploring a solution. Looking forward to working with you!

  19. added a commit that references this issue on Jul 16, 2025
    a2671d8
  20. zhanglll-yh commented on Jul 17, 2025

    @zhanglll-yh

    I would argue that the previous beahviour worked by chance but it was a bug. Scikit-learn transformers API expect to return an array of shape (n_samples, n_features). Having a single dimension is really ambiguous because we cannot guess if it is a single sample or a single feature. For instance, if you use set_output(transform="default"), then you will get an array of shape (20,) where I would argue that the FeatureUnion failed.

    So here, I think that the fact that we raise an error is actually fine. The error message is a bit tricky thought. The fact it does not raise with set_output(transform="default") is actually annoying I think.

    So one way would be to validate the output of FunctionTransformer being sure it should be 2-D. However, we sometime want this transformer to be lenient so I wonder if the behaviour should be driven by a parameter, similarly to the validate parameter but for the output.

    That 's quite wierd,how does"work by chance" happned?

  21. zhanglll-yh commented on Jul 17, 2025

    @zhanglll-yh

    I tried that code on version 1.4,same as 1.6,don't work as well.

  22. Hassan9255 commented on Jul 18, 2025

    @Hassan9255

    want to contribute

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

    Buggood first issue

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions