Views
No views yet
1from stable_baselines3 import ...
2from huggingface_sb3 import load_from_hub
3import gymnasium as gym
4
5# First, we create our environment called LunarLander-v2
6env = gym.make("LunarLander-v3")
7
8# Then we reset this environment
9observation, info = env.reset()
10
11for _ in range(20):
12 # Take a random action
13 action = env.action_space.sample()
14 print("Action taken:", action)
15
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
20 # If the game is terminated (in our case we land, crashed) or truncated (timeout)
21 if terminated or truncated:
22 # Reset the environment
23 print("Environment is reset")
24 observation, info = env.reset()
25
26env.close()
27
28# We create our environment with gym.make("<name_of_the_environment>")
29env = gym.make("LunarLander-v3")
30env.reset()
31print("_____OBSERVATION SPACE_____ \n")
32print("Observation Space Shape", env.observation_space.shape)
33print("Sample observation", env.observation_space.sample()) # Get a random observation
34
35print("\n _____ACTION SPACE_____ \n")
36print("Action Space Shape", env.action_space.n)
37print("Action Space Sample", env.action_space.sample()) # Take a random action
38
39# Create the environment
40env = make_vec_env('LunarLander-v3', n_envs=16)
41
42model = PPO(
43 policy = 'MlpPolicy',
44 env = env,
45 n_steps = 1024,
46 batch_size = 64,
47 n_epochs = 4,
48 gamma = 0.999,
49 gae_lambda = 0.98,
50 ent_coef = 0.01,
51 verbose=1)
52
53#Train it for 1,050,000 timesteps
54
55model_name = "ppo-LunarLander-v3"
56model.learn(total_timesteps=1500000)
57model.save(model_name)
58
59eval_env = Monitor(gym.make("LunarLander-v3", render_mode='rgb_array'))
60mean_reward, std_reward = evaluate_policy(model, eval_env, n_eval_episodes=10, deterministic=True)
61print(f"mean_reward={mean_reward:.2f} +/- {std_reward}")
62...