Thanks to visit codestin.com
Credit goes to github.com

Skip to content

API add named_transformers attribute to FeatureUnion #20331

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 15 commits into from
Oct 25, 2022
4 changes: 4 additions & 0 deletions doc/whats_new/v1.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,10 @@ Changelog
be used when one of the transformers in the :class:`pipeline.FeatureUnion` is
`"passthrough"`. :pr:`24058` by :user:`Diederik Perdok <diederikwp>`

- |Enhancement| The :class:`FeatureUnion` class now has a `named_transformers`
attribute for accessing transformers by name.
:pr:`20331` by :user:`Christopher Flynn <crflynn>`.

:mod:`sklearn.preprocessing`
............................

Expand Down
13 changes: 13 additions & 0 deletions sklearn/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -959,6 +959,14 @@ class FeatureUnion(TransformerMixin, _BaseComposition):

Attributes
----------
named_transformers : :class:`~sklearn.utils.Bunch`
Dictionary-like object, with the following attributes.
Read-only attribute to access any transformer parameter by user
given name. Keys are transformer names and values are
transformer parameters.

.. versionadded:: 1.2

n_features_in_ : int
Number of features seen during :term:`fit`. Only defined if the
underlying first transformer in `transformer_list` exposes such an
Expand Down Expand Up @@ -1017,6 +1025,11 @@ def set_output(self, transform=None):
_safe_set_output(step, transform=transform)
return self

@property
def named_transformers(self):
# Use Bunch object to improve autocomplete
return Bunch(**dict(self.transformer_list))

def get_params(self, deep=True):
"""Get parameters for this estimator.

Expand Down
13 changes: 13 additions & 0 deletions sklearn/tests/test_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,19 @@ def test_feature_union():
fs.fit(X, y)


def test_feature_union_named_transformers():
"""Check the behaviour of `named_transformers` attribute."""
transf = Transf()
noinvtransf = NoInvTransf()
fs = FeatureUnion([("transf", transf), ("noinvtransf", noinvtransf)])
assert fs.named_transformers["transf"] == transf
assert fs.named_transformers["noinvtransf"] == noinvtransf

# test named attribute
assert fs.named_transformers.transf == transf
assert fs.named_transformers.noinvtransf == noinvtransf


def test_make_union():
pca = PCA(svd_solver="full")
mock = Transf()
Expand Down