sb2rllib_rllib_example.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. """
  2. Example script on how to train, save, load, and test an RLlib agent.
  3. Equivalent script with stable baselines: sb2rllib_sb_example.py.
  4. Demonstrates transition from stable_baselines to Ray RLlib.
  5. Run example: python sb2rllib_rllib_example.py
  6. """
  7. import gym
  8. import ray
  9. import ray.rllib.agents.ppo as ppo
  10. # settings used for both stable baselines and rllib
  11. env_name = "CartPole-v1"
  12. train_steps = 10000
  13. learning_rate = 1e-3
  14. save_dir = "saved_models"
  15. # training and saving
  16. analysis = ray.tune.run(
  17. "PPO",
  18. stop={"timesteps_total": train_steps},
  19. config={
  20. "env": env_name,
  21. "lr": learning_rate
  22. },
  23. checkpoint_at_end=True,
  24. local_dir=save_dir,
  25. )
  26. # retrieve the checkpoint path
  27. analysis.default_metric = "episode_reward_mean"
  28. analysis.default_mode = "max"
  29. checkpoint_path = analysis.get_best_checkpoint(trial=analysis.get_best_trial())
  30. print(f"Trained model saved at {checkpoint_path}")
  31. # load and restore model
  32. agent = ppo.PPOTrainer(env=env_name)
  33. agent.restore(checkpoint_path)
  34. print(f"Agent loaded from saved model at {checkpoint_path}")
  35. # inference
  36. env = gym.make(env_name)
  37. obs = env.reset()
  38. for i in range(1000):
  39. action = agent.compute_single_action(obs)
  40. obs, reward, done, info = env.step(action)
  41. env.render()
  42. if done:
  43. print(f"Cart pole dropped after {i} steps.")
  44. break