Views
No views yet
1import gymnasium
2
3from stable_baselines3 import PPO
4from stable_baselines3.common.env_util import make_vec_env
5from stable_baselines3.common.evaluation import evaluate_policy
6from stable_baselines3.common.monitor import Monitor
7from huggingface_sb3 import load_from_hub
8
9
10# Create the environment
11env = make_vec_env('LunarLander-v2', n_envs=16)
12
13# Define a PPO MlpPolicy architecture
14# We use MultiLayerPerceptron (MLPPolicy) because the input is a vector,
15# if we had frames as input we would use CnnPolicy
16model = PPO(
17 "MlpPolicy",
18 env = env,
19 n_steps = 1024,
20 batch_size = 64,
21 n_epochs = 4,
22 gamma = 0.999,
23 gae_lambda = 0.98,
24 ent_coef = 0.01,
25 verbose=1)
26
27# Train it for 1,000,000 timesteps
28model.learn(total_timesteps=1000000)
29# Specify file name for model and save the model to file
30model_name = "ppo-LunarLander-v2"
31model.save(model_name)
32
33# Evaluate the agent
34# Create a new environment for evaluation
35eval_env = Monitor(gym.make("LunarLander-v2"))
36
37# Evaluate the model with 10 evaluation episodes and deterministic=True
38mean_reward, std_reward = evaluate_policy(model=model, env=eval_env, n_eval_episodes=10, deterministic=True)
39
40# Print the results
41print(mean_reward)
42print(std_reward)
43...