Views
No views yet
The trained PPO agent achieves a mean reward of 370.24 ± 8.90 on LunarLander-v2. This means it consistently lands successfully, demonstrating both high performance and stability across multiple episodes.
1from huggingface_sb3 import load_from_hub, package_to_hub
2from huggingface_hub import notebook_login
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
7import gymnasium as gym
8# First, we create our environment called LunarLander-v2
9env = gym.make("LunarLander-v2")
10# Then we reset this environment
11observation, info = env.reset()
12for _ in range(20):
13 # Take a random action
14 action = env.action_space.sample()
15 print("Action taken:", action)
16 # Do this action in the environment and get
17 # next_state, reward, terminated, truncated and info
18 observation, reward, terminated, truncated, info = env.step(action)
19 # If the game is terminated (in our case we land, crashed) or truncated (timeout)
20 if terminated or truncated:
21 # Reset the environment
22 print("Environment is reset")
23 observation, info = env.reset()
24env.close()
25
26# We create our environment with gym.make("<name_of_the_environment>")
27env = gym.make("LunarLander-v2")
28env.reset()
29print("_____OBSERVATION SPACE_____ \n")
30print("Observation Space Shape", env.observation_space.shape)
31print("Sample observation", env.observation_space.sample()) # Get a random observation
32print("\n _____ACTION SPACE_____ \n")
33print("Action Space Shape", env.action_space.n)
34print("Action Space Sample", env.action_space.sample()) # Take a random action
35
36env = make_vec_env('LunarLander-v2', n_envs=16)
37# Create environment
38env = gym.make('LunarLander-v2')
39# Instantiate the agent wuth policy
40model = PPO(
41 policy = 'MlpPolicy',
42 env = env,
43 n_steps = 1024,
44 batch_size = 64,
45 n_epochs = 4,
46 gamma = 0.999,
47 gae_lambda = 0.98,
48 ent_coef = 0.01,
49 verbose=1)
50# SOLUTION
51# Train it for 1,000,000 timesteps
52model.learn(total_timesteps=1000000)
53# Save the model
54model_name = "ppo-LunarLander-v2"
55model.save(model_name)
56
57#@title
58eval_env = Monitor(gym.make("LunarLander-v2", render_mode='rgb_array'))
59mean_reward, std_reward = evaluate_policy(model, eval_env, n_eval_episodes=10, deterministic=True)
60print(f"mean_reward={mean_reward:.2f} +/- {std_reward}")HuggingFace-Training "LunarLander Task" From Deep Reinforcement Learning Course.