Skip to content

FIX Allows pipeline to pass through feature names #21351

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
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
7 changes: 7 additions & 0 deletions doc/whats_new/v1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ Fixed models
and `radius_neighbors`, due to handling of explicit zeros in `bsr` and `dok`
:term:`sparse graph` formats. :pr:`21199` by `Thomas Fan`_.

:mod:`sklearn.pipeline`
.......................

- |Fix| :meth:`pipeline.Pipeline.get_feature_names_out` correctly passes feature
names out from one step of a pipeline to the next. :pr:`21351` by
`Thomas Fan`_.

.. _changes_1_0:

Version 1.0.0
Expand Down
5 changes: 3 additions & 2 deletions sklearn/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,15 +746,16 @@ def get_feature_names_out(self, input_features=None):
feature_names_out : ndarray of str objects
Transformed feature names.
"""
feature_names_out = input_features
for _, name, transform in self._iter():
if not hasattr(transform, "get_feature_names_out"):
raise AttributeError(
"Estimator {} does not provide get_feature_names_out. "
"Did you mean to call pipeline[:-1].get_feature_names_out"
"()?".format(name)
)
feature_names = transform.get_feature_names_out(input_features)
return feature_names
feature_names_out = transform.get_feature_names_out(feature_names_out)
return feature_names_out

@property
def n_features_in_(self):
Expand Down
21 changes: 21 additions & 0 deletions sklearn/tests/test_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -1517,3 +1517,24 @@ def fit(self, X, y):
check_is_fitted(pipeline)
pipeline.fit(iris.data, iris.target)
check_is_fitted(pipeline)


def test_pipeline_get_feature_names_out_passes_names_through():
"""Check that pipeline passes names through.

Non-regresion test for #21349.
"""
X, y = iris.data, iris.target

class AddPrefixStandardScalar(StandardScaler):
def get_feature_names_out(self, input_features=None):
names = super().get_feature_names_out(input_features=input_features)
return np.asarray([f"my_prefix_{name}" for name in names], dtype=object)

pipe = make_pipeline(AddPrefixStandardScalar(), StandardScaler())
pipe.fit(X, y)

input_names = iris.feature_names
feature_names_out = pipe.get_feature_names_out(input_names)

assert_array_equal(feature_names_out, [f"my_prefix_{name}" for name in input_names])