-
Notifications
You must be signed in to change notification settings - Fork 50
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
feat: New surrogate models API #669
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
346fda9
Adding the interface for contributing new surrogate models in Syne Tune
jgolebiowski 1fd0885
Adding the interface for contributing new surrogate models in Syne Tune
jgolebiowski ce5c525
Fixed an accidental change
jgolebiowski 1ab7b52
Adressing PR comments
jgolebiowski bd29fbd
Adressing PR comments v2
jgolebiowski bf829b0
Replacing * with -
jgolebiowski 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 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
syne_tune/optimizer/schedulers/searchers/bayesopt/models/sklearn_estimator.py
This file contains 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 @@ | ||
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"). | ||
# You may not use this file except in compliance with the License. | ||
# A copy of the License is located at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# or in the "license" file accompanying this file. This file is distributed | ||
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
# express or implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
from syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.tuning_job_state import ( | ||
TuningJobState, | ||
) | ||
from syne_tune.optimizer.schedulers.searchers.bayesopt.models.estimator import ( | ||
Estimator, | ||
transform_state_to_data, | ||
) | ||
from syne_tune.optimizer.schedulers.searchers.bayesopt.sklearn.estimator import ( | ||
SklearnEstimator, | ||
) | ||
from syne_tune.optimizer.schedulers.searchers.bayesopt.models.sklearn_predictor import ( | ||
SklearnPredictorWrapper, | ||
) | ||
from syne_tune.optimizer.schedulers.searchers.bayesopt.tuning_algorithms.base_classes import ( | ||
Predictor, | ||
) | ||
|
||
|
||
class SklearnEstimatorWrapper(Estimator): | ||
""" | ||
Wrapper class for the sklearn estimators to be used with BayesianOptimizationSearcher | ||
""" | ||
|
||
def __init__(self, contributed_estimator: SklearnEstimator, *args, **kwargs): | ||
super().__init__(*args, **kwargs) | ||
self.contributed_estimator = contributed_estimator | ||
|
||
@property | ||
def normalize_targets(self) -> bool: | ||
""" | ||
:return: Should targets in ``state`` be normalized before fitting the estimator | ||
""" | ||
return self.contributed_estimator.normalize_targets | ||
|
||
def fit_from_state( | ||
self, state: TuningJobState, update_params: bool = False | ||
) -> Predictor: | ||
""" | ||
Creates a | ||
:class:`~syne_tune.optimizer.schedulers.searchers.bayesopt.tuning_algorithms.base_classes.Predictor` | ||
object based on data in ``state``. | ||
|
||
If the model also has hyperparameters, these are learned iff | ||
``update_params == True``. Otherwise, these parameters are not changed, | ||
but only the posterior state is computed. | ||
|
||
If your surrogate model is not Bayesian, or does not have hyperparameters, | ||
you can ignore the ``update_params`` argument, | ||
|
||
:param state: Current data model parameters are to be fit on, and the | ||
posterior state is to be computed from | ||
:param update_params: See above | ||
:return: Predictor, wrapping the posterior state | ||
""" | ||
data = transform_state_to_data( | ||
state=state, normalize_targets=self.normalize_targets | ||
) | ||
contributed_predictor = self.contributed_estimator.fit( | ||
data.features, data.targets, update_params=update_params | ||
) | ||
return SklearnPredictorWrapper( | ||
contributed_predictor=contributed_predictor, state=state | ||
) |
83 changes: 83 additions & 0 deletions
83
syne_tune/optimizer/schedulers/searchers/bayesopt/models/sklearn_predictor.py
This file contains 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,83 @@ | ||
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"). | ||
# You may not use this file except in compliance with the License. | ||
# A copy of the License is located at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# or in the "license" file accompanying this file. This file is distributed | ||
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
# express or implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
from typing import Optional, List, Dict | ||
|
||
import numpy as np | ||
|
||
from syne_tune.optimizer.schedulers.searchers.bayesopt.datatypes.tuning_job_state import ( | ||
TuningJobState, | ||
) | ||
from syne_tune.optimizer.schedulers.searchers.bayesopt.models.model_base import ( | ||
BasePredictor, | ||
) | ||
from syne_tune.optimizer.schedulers.searchers.bayesopt.sklearn.predictor import ( | ||
SklearnPredictor, | ||
) | ||
|
||
|
||
class SklearnPredictorWrapper(BasePredictor): | ||
""" | ||
Wrapper class for the sklearn estimators to be used with ContributedEstimatorWrapper | ||
""" | ||
|
||
def __init__( | ||
self, | ||
contributed_predictor: SklearnPredictor, | ||
state: TuningJobState, | ||
active_metric: Optional[str] = None, | ||
): | ||
super().__init__(state, active_metric) | ||
self.contributed_predictor = contributed_predictor | ||
|
||
def predict(self, inputs: np.ndarray) -> List[Dict[str, np.ndarray]]: | ||
""" | ||
Returns signals which are statistics of the predictive distribution at | ||
input points ``inputs``. By default: | ||
|
||
* "mean": Predictive means. | ||
* "std": Predictive stddevs, shape ``(n,)`` | ||
|
||
This function relies on the assigned ContributedPredictor to execute the predictions | ||
|
||
:param inputs: Input points, shape ``(n, d)`` | ||
:return: List of ``dict`` with keys :meth:`keys_predict`, of length 1 | ||
""" | ||
|
||
mean, std = self.contributed_predictor.predict(inputs) | ||
outputs = {"mean": mean} | ||
if std is not None: | ||
outputs["std"] = std | ||
return [outputs] | ||
|
||
def backward_gradient( | ||
self, input: np.ndarray, head_gradients: List[Dict[str, np.ndarray]] | ||
) -> List[np.ndarray]: | ||
""" | ||
Computes the gradient :math:`\nabla f(x)` for an acquisition | ||
function :math:`f(x)`, where :math:`x` is a single input point. This | ||
is using reverse mode differentiation, the head gradients are passed | ||
by the acquisition function. The head gradients are | ||
:math:`\partial_k f`, where :math:`k` runs over the statistics | ||
returned by :meth:`predict` for the single input point :math:`x`. | ||
The shape of head gradients is the same as the shape of the | ||
statistics. | ||
|
||
:param input: Single input point :math:`x`, shape ``(d,)`` | ||
:param head_gradients: See above | ||
:return: Gradient :math:`\nabla f(x)` (one-length list) | ||
""" | ||
return [ | ||
self.contributed_predictor.backward_gradient( | ||
input=input, head_gradients=head_gradients | ||
) | ||
] |
12 changes: 12 additions & 0 deletions
12
syne_tune/optimizer/schedulers/searchers/bayesopt/sklearn/__init__.py
This file contains 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,12 @@ | ||
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"). | ||
# You may not use this file except in compliance with the License. | ||
# A copy of the License is located at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# or in the "license" file accompanying this file. This file is distributed | ||
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
# express or implied. See the License for the specific language governing | ||
# permissions and limitations under the License. |
44 changes: 44 additions & 0 deletions
44
syne_tune/optimizer/schedulers/searchers/bayesopt/sklearn/estimator.py
This file contains 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,44 @@ | ||
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"). | ||
# You may not use this file except in compliance with the License. | ||
# A copy of the License is located at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# or in the "license" file accompanying this file. This file is distributed | ||
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
# express or implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
import numpy as np | ||
|
||
from syne_tune.optimizer.schedulers.searchers.bayesopt.sklearn.predictor import ( | ||
SklearnPredictor, | ||
) | ||
|
||
|
||
class SklearnEstimator: | ||
""" | ||
Base class for the sklearn Estimators | ||
""" | ||
|
||
def fit( | ||
self, X: np.ndarray, y: np.ndarray, update_params: bool | ||
) -> SklearnPredictor: | ||
""" | ||
Implements :meth:`fit_from_state`, given transformed data. | ||
|
||
:param X: Training data in ndarray of shape (n_samples, n_features) | ||
:param y: Target values in ndarray of shape (n_samples,) | ||
:param update_params: Should model (hyper)parameters be updated? | ||
:return: Predictor, wrapping the posterior state | ||
""" | ||
raise NotImplementedError() | ||
|
||
@property | ||
def normalize_targets(self) -> bool: | ||
""" | ||
:return: Should targets in ``state`` be normalized before calling | ||
:meth:`fit`? | ||
""" | ||
return False |
56 changes: 56 additions & 0 deletions
56
syne_tune/optimizer/schedulers/searchers/bayesopt/sklearn/predictor.py
This file contains 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,56 @@ | ||
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"). | ||
# You may not use this file except in compliance with the License. | ||
# A copy of the License is located at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# or in the "license" file accompanying this file. This file is distributed | ||
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either | ||
# express or implied. See the License for the specific language governing | ||
# permissions and limitations under the License. | ||
from typing import Tuple, List, Dict | ||
|
||
import numpy as np | ||
|
||
|
||
class SklearnPredictor: | ||
""" | ||
Base class for the sklearn predictors | ||
""" | ||
|
||
def predict( | ||
self, X: np.ndarray, return_std: bool = True | ||
) -> Tuple[np.ndarray, np.ndarray]: | ||
""" | ||
Returns signals which are statistics of the predictive distribution at | ||
input points ``inputs``. | ||
|
||
|
||
:param inputs: Input points, shape ``(n, d)`` | ||
:return: Tuple with the following entries: | ||
* "mean": Predictive means in shape of ``(n,)`` | ||
* "std": Predictive stddevs, shape ``(n,)`` | ||
""" | ||
|
||
raise NotImplementedError() | ||
|
||
def backward_gradient( | ||
self, input: np.ndarray, head_gradients: List[Dict[str, np.ndarray]] | ||
) -> np.ndarray: | ||
""" | ||
Computes the gradient :math:`\nabla f(x)` for an acquisition | ||
function :math:`f(x)`, where :math:`x` is a single input point. This | ||
is using reverse mode differentiation, the head gradients are passed | ||
by the acquisition function. The head gradients are | ||
:math:`\partial_k f`, where :math:`k` runs over the statistics | ||
returned by :meth:`predict` for the single input point :math:`x`. | ||
The shape of head gradients is the same as the shape of the | ||
statistics. | ||
|
||
:param input: Single input point :math:`x`, shape ``(d,)`` | ||
:param head_gradients: See above | ||
:return: Gradient :math:`\nabla f(x)` | ||
""" | ||
raise NotImplementedError() |
This file contains 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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why remove this one? I thought this is something we wanted to have
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
EstimatorWrapper now implements this function, its a rename + move rather than a removal.