forked from Farama-Foundation/HighwayEnv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sb3_highway_ppo.py
48 lines (44 loc) · 1.52 KB
/
sb3_highway_ppo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import gym
import torch as th
from stable_baselines3 import PPO
from torch.distributions import Categorical
import torch
import torch.nn as nn
import numpy as np
from torch.nn import functional as F
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
from stable_baselines3.common.vec_env import SubprocVecEnv
import highway_env
# ==================================
# Main script
# ==================================
if __name__ == "__main__":
train = True
if train:
n_cpu = 6
batch_size = 64
env = make_vec_env("highway-fast-v0", n_envs=n_cpu, vec_env_cls=SubprocVecEnv)
model = PPO("MlpPolicy",
env,
policy_kwargs=dict(net_arch=[dict(pi=[256, 256], vf=[256, 256])]),
n_steps=batch_size * 12 // n_cpu,
batch_size=batch_size,
n_epochs=10,
learning_rate=5e-4,
gamma=0.8,
verbose=2,
tensorboard_log="highway_ppo/")
# Train the agent
model.learn(total_timesteps=int(2e4))
# Save the agent
model.save("highway_ppo/model")
model = PPO.load("highway_ppo/model")
env = gym.make("highway-fast-v0")
for _ in range(5):
obs = env.reset()
done = False
while not done:
action, _ = model.predict(obs)
obs, reward, done, info = env.step(action)
env.render()