bayesopt_example.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """This example demonstrates the usage of BayesOpt with Ray Tune.
  2. It also checks that it is usable with a separate scheduler.
  3. Requires the BayesOpt library to be installed (`pip install bayesian-optimization`).
  4. """
  5. import time
  6. from ray import tune
  7. from ray.tune.schedulers import AsyncHyperBandScheduler
  8. from ray.tune.search import ConcurrencyLimiter
  9. from ray.tune.search.bayesopt import BayesOptSearch
  10. def evaluation_fn(step, width, height):
  11. return (0.1 + width * step / 100) ** (-1) + height * 0.1
  12. def easy_objective(config):
  13. # Hyperparameters
  14. width, height = config["width"], config["height"]
  15. for step in range(config["steps"]):
  16. # Iterative training function - can be any arbitrary training procedure
  17. intermediate_score = evaluation_fn(step, width, height)
  18. # Feed the score back back to Tune.
  19. tune.report({"iterations": step, "mean_loss": intermediate_score})
  20. time.sleep(0.1)
  21. if __name__ == "__main__":
  22. import argparse
  23. parser = argparse.ArgumentParser()
  24. parser.add_argument(
  25. "--smoke-test", action="store_true", help="Finish quickly for testing"
  26. )
  27. args, _ = parser.parse_known_args()
  28. algo = BayesOptSearch(utility_kwargs={"kind": "ucb", "kappa": 2.5, "xi": 0.0})
  29. algo = ConcurrencyLimiter(algo, max_concurrent=4)
  30. scheduler = AsyncHyperBandScheduler()
  31. tuner = tune.Tuner(
  32. easy_objective,
  33. tune_config=tune.TuneConfig(
  34. metric="mean_loss",
  35. mode="min",
  36. search_alg=algo,
  37. scheduler=scheduler,
  38. num_samples=10 if args.smoke_test else 1000,
  39. ),
  40. run_config=tune.RunConfig(name="my_exp"),
  41. param_space={
  42. "steps": 100,
  43. "width": tune.uniform(0, 20),
  44. "height": tune.uniform(-100, 100),
  45. },
  46. )
  47. results = tuner.fit()
  48. print("Best hyperparameters found were: ", results.get_best_result().config)