bohb_example.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #!/usr/bin/env python
  2. """This example demonstrates the usage of BOHB with Ray Tune.
  3. Requires the HpBandSter and ConfigSpace libraries to be installed
  4. (`pip install hpbandster ConfigSpace`).
  5. """
  6. import json
  7. import os
  8. import time
  9. import numpy as np
  10. import ray
  11. from ray import tune
  12. from ray.tune import Trainable
  13. from ray.tune.schedulers.hb_bohb import HyperBandForBOHB
  14. from ray.tune.search.bohb import TuneBOHB
  15. class MyTrainableClass(Trainable):
  16. """Example agent whose learning curve is a random sigmoid.
  17. The dummy hyperparameters "width" and "height" determine the slope and
  18. maximum reward value reached.
  19. """
  20. def setup(self, config):
  21. self.timestep = 0
  22. def step(self):
  23. self.timestep += 1
  24. v = np.tanh(float(self.timestep) / self.config.get("width", 1))
  25. v *= self.config.get("height", 1)
  26. time.sleep(0.1)
  27. # Here we use `episode_reward_mean`, but you can also report other
  28. # objectives such as loss or accuracy.
  29. return {"episode_reward_mean": v}
  30. def save_checkpoint(self, checkpoint_dir):
  31. path = os.path.join(checkpoint_dir, "checkpoint")
  32. with open(path, "w") as f:
  33. f.write(json.dumps({"timestep": self.timestep}))
  34. def load_checkpoint(self, checkpoint_dir):
  35. path = os.path.join(checkpoint_dir, "checkpoint")
  36. with open(path, "r") as f:
  37. self.timestep = json.loads(f.read())["timestep"]
  38. if __name__ == "__main__":
  39. import sys
  40. if sys.version_info >= (3, 12):
  41. # TuneBOHB is not compatible with Python 3.12
  42. sys.exit(0)
  43. ray.init(num_cpus=8)
  44. config = {
  45. "iterations": 100,
  46. "width": tune.uniform(0, 20),
  47. "height": tune.uniform(-100, 100),
  48. "activation": tune.choice(["relu", "tanh"]),
  49. }
  50. # Optional: Pass the parameter space yourself
  51. # import ConfigSpace as CS
  52. # config_space = CS.ConfigurationSpace()
  53. # config_space.add_hyperparameter(
  54. # CS.UniformFloatHyperparameter("width", lower=0, upper=20))
  55. # config_space.add_hyperparameter(
  56. # CS.UniformFloatHyperparameter("height", lower=-100, upper=100))
  57. # config_space.add_hyperparameter(
  58. # CS.CategoricalHyperparameter(
  59. # "activation", choices=["relu", "tanh"]))
  60. max_iterations = 10
  61. bohb_hyperband = HyperBandForBOHB(
  62. time_attr="training_iteration",
  63. max_t=max_iterations,
  64. reduction_factor=2,
  65. stop_last_trials=False,
  66. )
  67. bohb_search = TuneBOHB(
  68. # space=config_space, # If you want to set the space manually
  69. )
  70. bohb_search = tune.search.ConcurrencyLimiter(bohb_search, max_concurrent=4)
  71. tuner = tune.Tuner(
  72. MyTrainableClass,
  73. run_config=tune.RunConfig(
  74. name="bohb_test", stop={"training_iteration": max_iterations}
  75. ),
  76. tune_config=tune.TuneConfig(
  77. metric="episode_reward_mean",
  78. mode="max",
  79. scheduler=bohb_hyperband,
  80. search_alg=bohb_search,
  81. num_samples=32,
  82. ),
  83. param_space=config,
  84. )
  85. results = tuner.fit()
  86. print("Best hyperparameters found were: ", results.get_best_result().config)