Skip to content

FIX Keeps namedtuple's class when transform returns a tuple #26121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/whats_new/v1.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,9 @@ Changelog
- |Feature| A `__sklearn_clone__` protocol is now available to override the
default behavior of :func:`base.clone`. :pr:`24568` by `Thomas Fan`_.

- |Fix| :class:`base.TransformerMixin` now currently keeps a namedtuple's class
if `transform` returns a namedtuple. :pr:`26121` by `Thomas Fan`_.

:mod:`sklearn.calibration`
..........................

Expand Down
7 changes: 6 additions & 1 deletion sklearn/utils/_set_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,15 @@ def wrapped(self, X, *args, **kwargs):
data_to_wrap = f(self, X, *args, **kwargs)
if isinstance(data_to_wrap, tuple):
# only wrap the first output for cross decomposition
return (
return_tuple = (
_wrap_data_with_container(method, data_to_wrap[0], X, self),
*data_to_wrap[1:],
)
# Support for namedtuples `_make` is a documented API for namedtuples:
# https://docs.python.org/3/library/collections.html#collections.somenamedtuple._make
if hasattr(type(data_to_wrap), "_make"):
return type(data_to_wrap)._make(return_tuple)
return return_tuple

return _wrap_data_with_container(method, data_to_wrap, X, self)

Expand Down
21 changes: 21 additions & 0 deletions sklearn/utils/tests/test_set_output.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pytest
from collections import namedtuple

import numpy as np
from scipy.sparse import csr_matrix
Expand Down Expand Up @@ -292,3 +293,23 @@ def test_set_output_pandas_keep_index():

X_trans = est.transform(X)
assert_array_equal(X_trans.index, ["s0", "s1"])


class EstimatorReturnTuple(_SetOutputMixin):
def __init__(self, OutputTuple):
self.OutputTuple = OutputTuple

def transform(self, X, y=None):
return self.OutputTuple(X, 2 * X)


def test_set_output_named_tuple_out():
"""Check that namedtuples are kept by default."""
Output = namedtuple("Output", "X, Y")
X = np.asarray([[1, 2, 3]])
est = EstimatorReturnTuple(OutputTuple=Output)
X_trans = est.transform(X)

assert isinstance(X_trans, Output)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shall we check the names as well?

assert_array_equal(X_trans.X, X)
assert_array_equal(X_trans.Y, 2 * X)