tune_basic_example.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """This example demonstrates basic Ray Tune random search and grid search."""
  2. import time
  3. import ray
  4. from ray import tune
  5. def evaluation_fn(step, width, height):
  6. time.sleep(0.1)
  7. return (0.1 + width * step / 100) ** (-1) + height * 0.1
  8. def easy_objective(config):
  9. # Hyperparameters
  10. width, height = config["width"], config["height"]
  11. for step in range(config["steps"]):
  12. # Iterative training function - can be any arbitrary training procedure
  13. intermediate_score = evaluation_fn(step, width, height)
  14. # Feed the score back back to Tune.
  15. tune.report({"iterations": step, "mean_loss": intermediate_score})
  16. if __name__ == "__main__":
  17. import argparse
  18. parser = argparse.ArgumentParser()
  19. parser.add_argument(
  20. "--smoke-test", action="store_true", help="Finish quickly for testing"
  21. )
  22. args, _ = parser.parse_known_args()
  23. ray.init(configure_logging=False)
  24. # This will do a grid search over the `activation` parameter. This means
  25. # that each of the two values (`relu` and `tanh`) will be sampled once
  26. # for each sample (`num_samples`). We end up with 2 * 50 = 100 samples.
  27. # The `width` and `height` parameters are sampled randomly.
  28. # `steps` is a constant parameter.
  29. tuner = tune.Tuner(
  30. easy_objective,
  31. tune_config=tune.TuneConfig(
  32. metric="mean_loss",
  33. mode="min",
  34. num_samples=5 if args.smoke_test else 50,
  35. ),
  36. param_space={
  37. "steps": 5 if args.smoke_test else 100,
  38. "width": tune.uniform(0, 20),
  39. "height": tune.uniform(-100, 100),
  40. "activation": tune.grid_search(["relu", "tanh"]),
  41. },
  42. )
  43. results = tuner.fit()
  44. print("Best hyperparameters found were: ", results.get_best_result().config)