Views
No views yet
1import gymnasium as gym
2
3from huggingface_sb3 import load_from_hub, package_to_hub
4from huggingface_hub import notebook_login # To log to our Hugging Face account to be able to upload models to the Hub.
5
6from stable_baselines3 import PPO
7from stable_baselines3.common.env_util import make_vec_env
8from stable_baselines3.common.evaluation import evaluate_policy
9from stable_baselines3.common.monitor import Monitor
10
11#------------------------
12# First, we create our environment called LunarLander-v2
13env = gym.make("LunarLander-v2")
14
15print("_____OBSERVATION SPACE_____ \n")
16print("Observation Space Shape", env.observation_space.shape)
17print("Sample observation", env.observation_space.sample()) # Get a random observation
18
19# Then we reset this environment
20observation, info = env.reset()
21
22#------------------------
23print("\n _____ACTION SPACE_____ \n")
24print("Action Space Shape", env.action_space.n)
25print("Action Space Sample", env.action_space.sample()) # Take a random action
26
27#------------------------
28# Create the environment
29env = make_vec_env('LunarLander-v2', n_envs=16)
30
31# Define a PPO MlpPolicy architecture
32# We use MultiLayerPerceptron (MLPPolicy) because the input is a vector,
33# if we had frames as input we would use CnnPolicy
34model = PPO('MlpPolicy', env, verbose=1)
35
36# Train it for 1,000,000 timesteps
37model.learn(total_timesteps=1000000)
38
39#------------------------
40# Specify file name for model and save the model to file
41model_name = "ppo-LunarLander-v2"
42model.save(model_name)
43
44#------------------------
45# Evaluate the agent
46# Create a new environment for evaluation
47eval_env = Monitor(gym.make("LunarLander-v2"))
48
49# Evaluate the model with 10 evaluation episodes and deterministic=True
50mean_reward, std_reward = evaluate_policy(model, eval_env, n_eval_episodes=10, deterministic=True)
51
52# Print the results
53print(f"mean_reward={mean_reward:.2f} +/- {std_reward}")
54
55#------------------------
56for _ in range(20):
57 # Take a random action
58 action = env.action_space.sample()
59 print("Action taken:", action)
60
61 # Do this action in the environment and get
62 # next_state, reward, terminated, truncated and info
63 observation, reward, terminated, truncated, info = env.step(action)
64
65 # If the game is terminated (in our case we land, crashed) or truncated (timeout)
66 if terminated or truncated:
67 # Reset the environment
68 print("Environment is reset")
69 observation, info = env.reset()
70
71env.close()
72...