forked from surajitsaikia27/SelfDrive_AI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrainAgent.py
More file actions
54 lines (37 loc) · 1.66 KB
/
TrainAgent.py
File metadata and controls
54 lines (37 loc) · 1.66 KB
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
49
50
51
52
53
54
from stable_baselines3 import PPO, SAC, ppo
from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel
channel = EngineConfigurationChannel()
from gym_unity.envs import UnityToGymWrapper
from mlagents_envs.environment import UnityEnvironment
import time,os
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.monitor import Monitor
from stable_baselines3.common.policies import ActorCriticPolicy
import math
env_name = "./UnityEnv"
speed = 15
env = UnityEnvironment(env_name,seed=1, side_channels=[channel])
channel.set_configuration_parameters(time_scale =speed)
env= UnityToGymWrapper(env, uint8_visual=False) # OpenAI gym interface created using UNITY
time_int = int(time.time())
# Diretories for storing results
log_dir = "stable_results/Euler_env_3{}/".format(time_int)
log_dirTF = "stable_results/tensorflow_log_Euler3{}/".format(time_int)
os.makedirs(log_dir, exist_ok=True)
env = Monitor(env, log_dir, allow_early_resets=True)
env = DummyVecEnv([lambda: env]) # The algorithms require a vectorized environment to run
model = PPO(ActorCriticPolicy, env, verbose=1, tensorboard_log=log_dirTF, device='cuda')
model.learn(int(200000)) # you can change the step size
time_int2 = int(time.time())
print('TIME TAKEN for training',time_int-time_int2)
# # save the model
model.save("Env_model")
# # # # # LOAD FOR TESTING
# del model
model = PPO.load("Env_model")
obs = env.reset()
# Test the agent for 1000 steps after training
for i in range(400):
action, states = model.predict(obs)
obs, rewards, done, info = env.step(action)
env.render()