Skip to content

ENH Remove unnecessary OOB computation when n_more_estimators == 0 #26318

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 11 commits into from
May 30, 2023
6 changes: 6 additions & 0 deletions doc/whats_new/v1.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,12 @@ Changelog
scikit-learn 1.3: retraining with scikit-learn 1.3 is required.
:pr:`25186` by :user:`Felipe Breve Siola <fsiola>`.

- |Efficiency| :class:`ensemble.RandomForestClassifier` and
:class:`ensemble.RandomForestRegressor` with `warm_start=True` now only
recomputes out-of-bag scores when there are actually more `n_estimators`
in subsequent `fit` calls.
:pr:`26318` by :user:`Joshua Choo Yun Keat <choo8>`.

- |Enhancement| :class:`ensemble.BaggingClassifier` and
:class:`ensemble.BaggingRegressor` expose the `allow_nan` tag from the
underlying estimator. :pr:`25506` by `Thomas Fan`_.
Expand Down
4 changes: 3 additions & 1 deletion sklearn/ensemble/_forest.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,9 @@ def fit(self, X, y, sample_weight=None):
# Collect newly grown trees
self.estimators_.extend(trees)

if self.oob_score:
if self.oob_score and (
n_more_estimators > 0 or not hasattr(self, "oob_score_")
):
y_type = type_of_target(y)
if y_type in ("multiclass-multioutput", "unknown"):
# FIXME: we could consider to support multiclass-multioutput if
Expand Down
22 changes: 22 additions & 0 deletions sklearn/ensemble/tests/test_forest.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@

from sklearn.tree._classes import SPARSE_SPLITTERS

from unittest.mock import patch

# toy sample
X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]
Expand Down Expand Up @@ -1470,6 +1471,27 @@ def test_warm_start_oob(name):
check_warm_start_oob(name)


@pytest.mark.parametrize("name", FOREST_CLASSIFIERS_REGRESSORS)
def test_oob_not_computed_twice(name):
# Check that oob_score is not computed twice when warm_start=True.
X, y = hastie_X, hastie_y
ForestEstimator = FOREST_ESTIMATORS[name]

est = ForestEstimator(
n_estimators=10, warm_start=True, bootstrap=True, oob_score=True
)

with patch.object(
est, "_set_oob_score_and_attributes", wraps=est._set_oob_score_and_attributes
) as mock_set_oob_score_and_attributes:
est.fit(X, y)

with pytest.warns(UserWarning, match="Warm-start fitting without increasing"):
est.fit(X, y)

mock_set_oob_score_and_attributes.assert_called_once()


def test_dtype_convert(n_classes=15):
classifier = RandomForestClassifier(random_state=0, bootstrap=False)

Expand Down