Repository navigation
Description
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
[-]Bug sur la version 1.6 sklearn[/-][+]Bug in scikit-learn version 1.6[/+]glemaitre commentedon May 7, 2025
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 useset_output(transform="default"), then you will get an array of shape(20,)where I would argue that theFeatureUnionfailed.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
FunctionTransformerbeing 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 thevalidateparameter but for the output.glemaitre commentedon May 7, 2025
@jeremiedbb @ogrisel do you have any thoughts regarding if
FunctionTransformershould 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.
[-]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[/+][-]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[/+]ogrisel commentedon May 19, 2025
Note that the mentioned code already raises 2 informative warnings before raising the final exception:
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.
ogrisel commentedon May 19, 2025
Here is a minimal reproducer:
Note that the
FeatureUnionrequires 2 series, otherwise there are no exceptions, only the warnings.ogrisel commentedon May 19, 2025
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:Instead,
FeatureUnionshould raise an explicit error message to make it explicit that some transformers output 1d data-structures instead of the expected 2d.ogrisel commentedon May 19, 2025
I think the
FeatureUnion._hstackmethod should be changed to raise an informative error message if some elements inXsare not 2D data-structures. We should also check that their.shape[0]match the expected number of samples measured on theXparameter passed toFeatureUnion.transformorFeatureUnion.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.
[-]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[/+][-]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[/+]Ahsan-Imam commentedon Jun 22, 2025
hello i am Ahsan , i am new to open source , i would like to contribute .
Nafeessidd1 commentedon Jul 3, 2025
/take
MohammedSaim-Quadri commentedon Jul 6, 2025
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!
Nafeessidd1 commentedon Jul 6, 2025
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!
FIX FeatureUnion._set_output for pandas Series (scikit-learn#31318)
FIX FeatureUnion: handle pandas Series outputs (closes scikit-learn#3…
zhanglll-yh commentedon Jul 17, 2025
That 's quite wierd,how does"work by chance" happned?
zhanglll-yh commentedon Jul 17, 2025
I tried that code on version 1.4,same as 1.6,don't work as well.
Hassan9255 commentedon Jul 18, 2025
want to contribute
FIX Add validation for FeatureUnion transformer outputs (#31318) (#31559
FIX Add validation for FeatureUnion transformer outputs (scikit-learn…
FIX Add validation for FeatureUnion transformer outputs (scikit-learn…
FIX Add validation for FeatureUnion transformer outputs (#31318) (#31559