A Proximal Policy Optimization (PPO) agent trained to land a spacecraft on the Moon using
Stable-Baselines3 and
Gymnasium.
Training time: ~8 minutes on Apple M-series CPU.
1from stable_baselines3 import PPO
2from huggingface_sb3 import load_from_hub
3from stable_baselines3.common.evaluation import evaluate_policy
4from stable_baselines3.common.monitor import Monitor
5import gymnasium as gym
6
7# Load from Hub
8checkpoint = load_from_hub(
9 repo_id="shivam3002/ppo-LunarLander-v3",
10 filename="ppo-LunarLander-v3.zip",
11)
12model = PPO.load(checkpoint)
13
14# Evaluate
15eval_env = Monitor(gym.make("LunarLander-v3", render_mode="human"))
16mean_reward, std_reward = evaluate_policy(
17 model, eval_env, n_eval_episodes=10, deterministic=True
18)
19print(f"mean_reward={mean_reward:.2f} +/- {std_reward:.2f}")
20eval_env.close()
1import gymnasium as gym
2from stable_baselines3 import PPO
3from huggingface_sb3 import load_from_hub
4
5checkpoint = load_from_hub("shivam3002/ppo-LunarLander-v3", "ppo-LunarLander-v3.zip")
6model = PPO.load(checkpoint)
7
8env = gym.make("LunarLander-v3", render_mode="human")
9obs, _ = env.reset()
10done = False
11total_reward = 0
12
13while not done:
14 action, _ = model.predict(obs, deterministic=True)
15 obs, reward, terminated, truncated, _ = env.step(action)
16 total_reward += reward
17 done = terminated or truncated
18
19print(f"Episode reward: {total_reward:.2f}")
20env.close()
1from stable_baselines3 import PPO
2from stable_baselines3.common.env_util import make_vec_env
3from stable_baselines3.common.evaluation import evaluate_policy
4from stable_baselines3.common.monitor import Monitor
5import gymnasium as gym
6
7# Vectorized training env
8env = make_vec_env("LunarLander-v3", n_envs=16)
9
10model = PPO(
11 policy="MlpPolicy",
12 env=env,
13 n_steps=1024,
14 batch_size=64,
15 n_epochs=4,
16 gamma=0.999,
17 gae_lambda=0.98,
18 ent_coef=0.01,
19 verbose=1,
20)
21
22model.learn(total_timesteps=1_000_000)
23model.save("ppo-LunarLander-v3")
24
25# Evaluate
26eval_env = Monitor(gym.make("LunarLander-v3", render_mode="rgb_array"))
27mean_reward, std_reward = evaluate_policy(model, eval_env, n_eval_episodes=10, deterministic=True)
28print(f"mean_reward={mean_reward:.2f} +/- {std_reward:.2f}")
gymnasium[box2d]>=1.0
stable-baselines3>=2.0
huggingface_sb3
torch