optuna_example.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """This example demonstrates the usage of Optuna with Ray Tune.
  2. It also checks that it is usable with a separate scheduler.
  3. Requires the Optuna library to be installed (`pip install optuna`).
  4. For an example of using an Optuna define-by-run function, see
  5. :doc:`/tune/examples/optuna_define_by_run_example`.
  6. """
  7. import time
  8. import ray
  9. from ray import tune
  10. from ray.tune.schedulers import AsyncHyperBandScheduler
  11. from ray.tune.search import ConcurrencyLimiter
  12. from ray.tune.search.optuna import OptunaSearch
  13. def evaluation_fn(step, width, height):
  14. return (0.1 + width * step / 100) ** (-1) + height * 0.1
  15. def easy_objective(config):
  16. # Hyperparameters
  17. width, height = config["width"], config["height"]
  18. for step in range(config["steps"]):
  19. # Iterative training function - can be any arbitrary training procedure
  20. intermediate_score = evaluation_fn(step, width, height)
  21. # Feed the score back back to Tune.
  22. tune.report({"iterations": step, "mean_loss": intermediate_score})
  23. time.sleep(0.1)
  24. def run_optuna_tune(smoke_test=False):
  25. algo = OptunaSearch()
  26. algo = ConcurrencyLimiter(algo, max_concurrent=4)
  27. scheduler = AsyncHyperBandScheduler()
  28. tuner = tune.Tuner(
  29. easy_objective,
  30. tune_config=tune.TuneConfig(
  31. metric="mean_loss",
  32. mode="min",
  33. search_alg=algo,
  34. scheduler=scheduler,
  35. num_samples=10 if smoke_test else 100,
  36. ),
  37. param_space={
  38. "steps": 100,
  39. "width": tune.uniform(0, 20),
  40. "height": tune.uniform(-100, 100),
  41. # This is an ignored parameter.
  42. "activation": tune.choice(["relu", "tanh"]),
  43. },
  44. )
  45. results = tuner.fit()
  46. print("Best hyperparameters found were: ", results.get_best_result().config)
  47. if __name__ == "__main__":
  48. import argparse
  49. parser = argparse.ArgumentParser()
  50. parser.add_argument(
  51. "--smoke-test", action="store_true", help="Finish quickly for testing"
  52. )
  53. args, _ = parser.parse_known_args()
  54. ray.init(configure_logging=False)
  55. run_optuna_tune(smoke_test=args.smoke_test)