Views
No views yet
1from huggingface_sb3 import load_from_hub
2from stable_baselines3 import PPO
3from stable_baselines3.common.env_util import make_vec_env
4from stable_baselines3.common.evaluation import evaluate_policy
5
6# Download checkpoint
7checkpoint = load_from_hub("araffin/ppo-LunarLander-v2", "ppo-LunarLander-v2.zip")
8# Load the model
9model = PPO.load(checkpoint)
10
11env = make_vec_env("LunarLander-v2", n_envs=1)
12
13# Evaluate
14print("Evaluating model")
15mean_reward, std_reward = evaluate_policy(
16 model,
17 env,
18 n_eval_episodes=20,
19 deterministic=True,
20)
21print(f"Mean reward = {mean_reward:.2f} +/- {std_reward:.2f}")
22
23# Start a new episode
24obs = env.reset()
25
26try:
27 while True:
28 action, _states = model.predict(obs, deterministic=True)
29 obs, rewards, dones, info = env.step(action)
30 env.render()
31except KeyboardInterrupt:
32 pass1from stable_baselines3 import PPO
2from stable_baselines3.common.env_util import make_vec_env
3from stable_baselines3.common.callbacks import EvalCallback
4
5# Create the environment
6env_id = "LunarLander-v2"
7n_envs = 16
8env = make_vec_env(env_id, n_envs=n_envs)
9
10# Create the evaluation envs
11eval_envs = make_vec_env(env_id, n_envs=5)
12
13# Adjust evaluation interval depending on the number of envs
14eval_freq = int(1e5)
15eval_freq = max(eval_freq // n_envs, 1)
16
17# Create evaluation callback to save best model
18# and monitor agent performance
19eval_callback = EvalCallback(
20 eval_envs,
21 best_model_save_path="./logs/",
22 eval_freq=eval_freq,
23 n_eval_episodes=10,
24)
25
26# Instantiate the agent
27# Hyperparameters from https://github.com/DLR-RM/rl-baselines3-zoo
28model = PPO(
29 "MlpPolicy",
30 env,
31 n_steps=1024,
32 batch_size=64,
33 gae_lambda=0.98,
34 gamma=0.999,
35 n_epochs=4,
36 ent_coef=0.01,
37 verbose=1,
38)
39
40# Train the agent (you can kill it before using ctrl+c)
41try:
42 model.learn(total_timesteps=int(5e6), callback=eval_callback)
43except KeyboardInterrupt:
44 pass
45
46# Load best model
47model = PPO.load("logs/best_model.zip")