-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #6 from fugue-project/0.0.3.1
add bayesian search
- Loading branch information
Showing
9 changed files
with
266 additions
and
35 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
from typing import Any, Dict, Tuple, Set | ||
|
||
from fugue_tune.tunable import Tunable | ||
from fugue_tune.tuner import ObjectiveRunner | ||
from fugue_tune.space import StochasticExpression, Rand, Choice | ||
from hyperopt import fmin, tpe, hp, Trials, STATUS_OK | ||
import numpy as np | ||
|
||
|
||
class HyperoptRunner(ObjectiveRunner): | ||
def __init__(self, max_iter: int, seed: int = 0): | ||
self._max_iter = max_iter | ||
self._seed = seed | ||
|
||
def run( | ||
self, tunable: Tunable, kwargs: Dict[str, Any], hp_keys: Set[str] | ||
) -> Dict[str, Any]: | ||
static_params, stochastic_params = self._split(kwargs) | ||
keys = list(stochastic_params.keys()) | ||
|
||
def obj(args) -> Dict[str, Any]: | ||
params = {k: v for k, v in zip(keys, args)} | ||
tunable.run(**static_params, **params) | ||
hp = {k: v for k, v in tunable.hp.items() if k in hp_keys} | ||
return { | ||
"loss": tunable.error, | ||
"status": STATUS_OK, | ||
"error": tunable.error, | ||
"hp": hp, | ||
"metadata": tunable.metadata, | ||
} | ||
|
||
trials = Trials() | ||
fmin( | ||
obj, | ||
space=list(stochastic_params.values()), | ||
algo=tpe.suggest, | ||
max_evals=self._max_iter, | ||
trials=trials, | ||
show_progressbar=False, | ||
rstate=np.random.RandomState(self._seed), | ||
) | ||
|
||
return { | ||
"error": trials.best_trial["result"]["error"], | ||
"hp": trials.best_trial["result"]["hp"], | ||
"metadata": trials.best_trial["result"]["metadata"], | ||
} | ||
|
||
def _split(self, kwargs: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: | ||
static_params: Dict[str, Any] = {} | ||
stochastic_params: Dict[str, Any] = {} | ||
for k, v in kwargs.items(): | ||
if isinstance(v, StochasticExpression): | ||
if isinstance(v, Rand): | ||
stochastic_params[k] = self.convert_rand(k, v) | ||
elif isinstance(v, Choice): | ||
stochastic_params[k] = self.convert_choice(k, v) | ||
else: | ||
raise NotImplementedError(v) # pragma: no cover | ||
else: | ||
static_params[k] = v | ||
return static_params, stochastic_params | ||
|
||
def convert_rand(self, k: str, v: Rand) -> Any: | ||
if v.q is None and not v.log and not v.normal: | ||
return hp.uniform(k, v.start, v.end) | ||
raise NotImplementedError(k, v) # pragma: no cover | ||
|
||
def convert_choice(self, k: str, v: Choice) -> Any: | ||
return hp.choice(k, v.values) |
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
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
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 |
---|---|---|
@@ -1,4 +1,4 @@ | ||
. | ||
.[all] | ||
|
||
# test requirements | ||
pre-commit | ||
|
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
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
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,41 @@ | ||
import pandas as pd | ||
|
||
from fugue_tune.convert import tunable | ||
from fugue_tune.hyperopt import HyperoptRunner | ||
from fugue_tune.space import Choice, Rand, Space, Grid | ||
|
||
from typing import Dict, Any | ||
from fugue import FugueWorkflow | ||
from fugue_tune.tuner import Tuner | ||
|
||
|
||
def test_run(): | ||
@tunable() | ||
def func(df: pd.DataFrame, a: float, b: float, c: int) -> Dict[str, Any]: | ||
return {"error": a * a + b * b + df.shape[0] + c, "metadata": {"d": 1}} | ||
|
||
pdf = pd.DataFrame([[0]], columns=["a"]) | ||
runner = HyperoptRunner(100, seed=3) | ||
|
||
res = runner.run( | ||
func, dict(df=pdf, b=Rand(-100, 100), a=10, c=Choice(1, -1)), {"a", "b", "c"} | ||
) | ||
assert res["error"] < 103.0 | ||
assert res["hp"]["a"] == 10 | ||
assert abs(res["hp"]["b"]) < 3.0 | ||
assert res["hp"]["c"] == -1 | ||
assert len(res) == 3 | ||
assert res["metadata"] == {"d": 1} | ||
|
||
|
||
def test_wf(): | ||
@tunable() | ||
def func(a: float, b: float, c: int) -> float: | ||
return a * a + b * b + c | ||
|
||
t = Tuner() | ||
with FugueWorkflow() as dag: | ||
space = t.space_to_df( | ||
dag, Space(a=Grid(1, 2), b=Rand(-100, 100), c=Choice(1, -1)) | ||
) | ||
t.tune(space, func, objective_runner=HyperoptRunner(100, seed=3)).show() |
Oops, something went wrong.