Skip to content

FIX MultiOutputRegressor correctly ducktypes fitted estimators #19308

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/v0.24.rst
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ Changelog
`'use_encoded_value'` strategies.
:pr:`19234` by `Guillaume Lemaitre <glemaitre>`.

:mod:`sklearn.multioutput`
..........................

- |Fix| :class:`multioutput.MultiOutputRegressor` now works with estimators
that dynamically define `predict` during fitting, such as
:class:`ensemble.StackingRegressor`. :pr:`19308` by `Thomas Fan`_.

:mod:`sklearn.semi_supervised`
..............................

Expand Down
2 changes: 1 addition & 1 deletion sklearn/multioutput.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def predict(self, X):
Note: Separate models are generated for each predictor.
"""
check_is_fitted(self)
if not hasattr(self.estimator, "predict"):
if not hasattr(self.estimators_[0], "predict"):
raise ValueError("The base estimator should implement"
" a predict method")

Expand Down
18 changes: 18 additions & 0 deletions sklearn/tests/test_multioutput.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from sklearn import datasets
from sklearn.base import clone
from sklearn.datasets import make_classification
from sklearn.datasets import load_linnerud
from sklearn.ensemble import GradientBoostingRegressor, RandomForestClassifier
from sklearn.exceptions import NotFittedError
from sklearn.linear_model import Lasso
Expand All @@ -30,6 +31,7 @@
from sklearn.dummy import DummyRegressor, DummyClassifier
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.ensemble import StackingRegressor


def test_multi_target_regression():
Expand Down Expand Up @@ -658,3 +660,19 @@ def test_classifier_chain_tuple_invalid_order():

with pytest.raises(ValueError, match='invalid order'):
chain.fit(X, y)


def test_multioutputregressor_ducktypes_fitted_estimator():
"""Test that MultiOutputRegressor checks the fitted estimator for
predict. Non-regression test for #16549."""
X, y = load_linnerud(return_X_y=True)
stacker = StackingRegressor(
estimators=[("sgd", SGDRegressor(random_state=1))],
final_estimator=Ridge(),
cv=2
)

reg = MultiOutputRegressor(estimator=stacker).fit(X, y)

# Does not raise
reg.predict(X)