Define best_iteration only if early stopping is used. (#9403)

* Define `best_iteration` only if early stopping is used.

This is the behavior specified by the document but not honored in the actual code.

- Don't set the attributes if there's no early stopping.
- Clean up the code for callbacks, and replace assertions with proper exceptions.
- Assign the attributes when early stopping `save_best` is used.
- Turn the attributes into Python properties.

---------

Co-authored-by: Philip Hyunsu Cho <chohyu01@cs.washington.edu>
This commit is contained in:
Jiaming Yuan
2023-07-24 12:43:35 +08:00
committed by GitHub
parent 01e00efc53
commit 851cba931e
10 changed files with 249 additions and 179 deletions

View File

@@ -173,7 +173,7 @@ class TestInplacePredict:
np.testing.assert_allclose(predt_from_dmatrix, predt_from_array)
with pytest.raises(ValueError):
booster.predict(test, iteration_range=(0, booster.best_iteration + 2))
booster.predict(test, iteration_range=(0, booster.num_boosted_rounds() + 2))
default = booster.predict(test)
@@ -181,7 +181,7 @@ class TestInplacePredict:
np.testing.assert_allclose(range_full, default)
range_full = booster.predict(
test, iteration_range=(0, booster.best_iteration + 1)
test, iteration_range=(0, booster.num_boosted_rounds())
)
np.testing.assert_allclose(range_full, default)