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

Skip to content

ENH Adds FeatureUnion.__getitem__ to access transformers #25093

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
Dec 6, 2022
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
6 changes: 6 additions & 0 deletions doc/whats_new/v1.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ Changelog
:pr:`123456` by :user:`Joe Bloggs <joeongithub>`.
where 123456 is the *pull request* number, not the issue number.

:mod:`sklearn.pipeline`
.......................
- |Feature| :class:`pipeline.FeatureUnion` can now use indexing notation (e.g.
`feature_union["scalar"]`) to access transformers by name. :pr:`25093` by
`Thomas Fan`_.

Code and Documentation Contributors
-----------------------------------

Expand Down
6 changes: 6 additions & 0 deletions sklearn/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -1286,6 +1286,12 @@ def _sk_visual_block_(self):
names, transformers = zip(*self.transformer_list)
return _VisualBlock("parallel", transformers, names=names)

def __getitem__(self, name):
"""Return transformer with name."""
if not isinstance(name, str):
raise KeyError("Only string keys are supported")
return self.named_transformers[name]


def make_union(*transformers, n_jobs=None, verbose=False):
"""Construct a FeatureUnion from the given transformers.
Expand Down
29 changes: 29 additions & 0 deletions sklearn/tests/test_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -1658,3 +1658,32 @@ def test_feature_union_set_output():
assert isinstance(X_trans, pd.DataFrame)
assert_array_equal(X_trans.columns, union.get_feature_names_out())
assert_array_equal(X_trans.index, X_test.index)


def test_feature_union_getitem():
"""Check FeatureUnion.__getitem__ returns expected results."""
scalar = StandardScaler()
pca = PCA()
union = FeatureUnion(
[
("scalar", scalar),
("pca", pca),
("pass", "passthrough"),
("drop_me", "drop"),
]
)
assert union["scalar"] is scalar
assert union["pca"] is pca
assert union["pass"] == "passthrough"
assert union["drop_me"] == "drop"


@pytest.mark.parametrize("key", [0, slice(0, 2)])
def test_feature_union_getitem_error(key):
"""Raise error when __getitem__ gets a non-string input."""

union = FeatureUnion([("scalar", StandardScaler()), ("pca", PCA())])

msg = "Only string keys are supported"
with pytest.raises(KeyError, match=msg):
union[key]