-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Create simple example and doc for naive early stopping #1476
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
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
fedd75b
Create simple example and doc for naive early stopping
eddiebergman 901236c
Fix doc, pass through SMAC callbacks directly
eddiebergman 249318e
Fix `isinstance` check
eddiebergman 893131f
Add test for early stopping
eddiebergman 450d8b1
Fix signature of early stopping example/test
eddiebergman 3a4776c
Fix doc build
eddiebergman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
from __future__ import annotations | ||
|
||
from typing import Callable, Union | ||
|
||
from smac.callbacks import IncorporateRunResultCallback | ||
from smac.optimizer.smbo import SMBO | ||
from smac.runhistory.runhistory import RunInfo, RunValue | ||
|
||
SMACCallback = Callable[[SMBO, RunInfo, RunValue, float], Union[bool, None]] | ||
|
||
|
||
class SmacRunCallback(IncorporateRunResultCallback): | ||
def __init__(self, f: SMACCallback): | ||
self.f = f | ||
|
||
def __call__( | ||
self, | ||
smbo: SMBO, | ||
run_info: RunInfo, | ||
result: RunValue, | ||
time_left: float, | ||
) -> bool | None: | ||
""" | ||
Parameters | ||
---------- | ||
smbo: SMBO | ||
The SMAC SMBO object | ||
|
||
run_info: RunInfo | ||
Information about the run completed | ||
|
||
result: RunValue | ||
The results of the run | ||
|
||
time_left: float | ||
How much time is left for the remaining runs | ||
|
||
Returns | ||
------- | ||
bool | None | ||
If False is returned, the optimization loop will stop | ||
""" | ||
return self.f(smbo, run_info, result, time_left) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
75 changes: 75 additions & 0 deletions
75
examples/40_advanced/example_early_stopping_and_callbacks.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
""" | ||
============================ | ||
Early stopping and Callbacks | ||
============================ | ||
|
||
The example below shows how we can use the ``get_trials_callback`` parameter of | ||
auto-sklearn to implement an early-stopping mechanism through a callback. | ||
|
||
These callbacks give access to the result of each model + hyperparameter configuration | ||
optimized by SMAC, the underlying optimizer for autosklearn. By checking the cost of | ||
a result, we can implement a simple yet effective early stopping mechanism! | ||
|
||
Do note however, this does not provide any access to the ensembles that autosklearn | ||
produces, only the individual models. You may wish to perform a more sophisticated | ||
early stopping mechanism such that there are enough good models for autosklearn to build | ||
and ensemble with. This is here to provide a simple example. | ||
""" | ||
from pprint import pprint | ||
|
||
import sklearn.datasets | ||
import sklearn.metrics | ||
|
||
import autosklearn.classification | ||
|
||
from smac.optimizer.smbo import SMBO | ||
from smac.runhistory.runhistory import RunInfo, RunValue | ||
|
||
|
||
############################################################################ | ||
# Build and fit a classifier | ||
# ========================== | ||
def callback( | ||
smbo: SMBO, | ||
run_info: RunInfo, | ||
result: RunValue, | ||
time_left: float, | ||
) -> bool: | ||
"""Stop early if we get a very low cost value for a single run""" | ||
# You can find out the parameters in the SMAC documentation | ||
# https://automl.github.io/SMAC3/main/ | ||
if result.cost <= 0.02: | ||
print("Stopping!") | ||
print(run_info) | ||
print(result) | ||
return False | ||
|
||
|
||
X, y = sklearn.datasets.load_breast_cancer(return_X_y=True) | ||
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split( | ||
X, y, random_state=1 | ||
) | ||
|
||
automl = autosklearn.classification.AutoSklearnClassifier( | ||
time_left_for_this_task=120, per_run_time_limit=30, get_trials_callback=callback | ||
) | ||
automl.fit(X_train, y_train, dataset_name="breast_cancer") | ||
|
||
############################################################################ | ||
# View the models found by auto-sklearn | ||
# ===================================== | ||
|
||
print(automl.leaderboard()) | ||
|
||
############################################################################ | ||
# Print the final ensemble constructed by auto-sklearn | ||
# ==================================================== | ||
|
||
pprint(automl.show_models(), indent=4) | ||
|
||
########################################################################### | ||
# Get the Score of the final ensemble | ||
# =================================== | ||
|
||
predictions = automl.predict(X_test) | ||
print("Accuracy score:", sklearn.metrics.accuracy_score(y_test, predictions)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
from __future__ import annotations | ||
|
||
from typing import TYPE_CHECKING, Callable | ||
|
||
if TYPE_CHECKING: | ||
import numpy as np | ||
from smac.optimizer.smbo import SMBO | ||
from smac.runhistory.runhistory import RunInfo, RunValue | ||
|
||
from autosklearn.automl import AutoMLClassifier | ||
|
||
|
||
def test_early_stopping( | ||
make_automl_classifier: Callable[..., AutoMLClassifier], | ||
make_sklearn_dataset: Callable[..., tuple[np.ndarray, ...]], | ||
) -> None: | ||
""" | ||
Expects | ||
------- | ||
* Should early after fitting 2 models | ||
""" | ||
|
||
def callback( | ||
smbo: SMBO, | ||
run_info: RunInfo, | ||
result: RunValue, | ||
time_left: float, | ||
) -> bool: | ||
if int(result.additional_info["num_run"]) >= 2: | ||
return False | ||
|
||
automl = make_automl_classifier(get_trials_callback=callback) | ||
|
||
X_train, Y_train, X_test, Y_test = make_sklearn_dataset("iris") | ||
automl.fit(X_train, Y_train) | ||
|
||
assert len(automl.runhistory_.data) == 2 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.