-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCarRacing_PPO.py
More file actions
410 lines (304 loc) · 17.2 KB
/
Copy pathCarRacing_PPO.py
File metadata and controls
410 lines (304 loc) · 17.2 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import os
import numpy as np
import pandas as pd
import time
import argparse
import os
import warnings
lr=None
env=None
eval_env=None
best_path=None
final_path=None
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import gym
from stable_baselines3 import PPO #PPO -> Proximal Policy Optimization
from stable_baselines3.common.vec_env import DummyVecEnv
from stable_baselines3.common.evaluation import evaluate_policy #to evaluate the model
from stable_baselines3.common.callbacks import EvalCallback
from stable_baselines3.common import type_aliases
from stable_baselines3.common.vec_env import DummyVecEnv, VecEnv, VecMonitor, is_vecenv_wrapped
def custom_evaluate_policy(
model: "type_aliases.PolicyPredictor",
env: Union[gym.Env, VecEnv],
n_eval_episodes: int = 10,
deterministic: bool = True,
render: bool = False,
callback: Optional[Callable[[Dict[str, Any], Dict[str, Any]], None]] = None,
reward_threshold: Optional[float] = None,
return_episode_rewards: bool = False,
warn: bool = True,
) -> Union[Tuple[float, float], Tuple[List[float], List[int]]]:
"""
Runs policy for ``n_eval_episodes`` episodes and returns average reward.
If a vector env is passed in, this divides the episodes to evaluate onto the
different elements of the vector env. This static division of work is done to
remove bias. See https://github.com/DLR-RM/stable-baselines3/issues/402 for more
details and discussion.
.. note::
If environment has not been wrapped with ``Monitor`` wrapper, reward and
episode lengths are counted as it appears with ``env.step`` calls. If
the environment contains wrappers that modify rewards or episode lengths
(e.g. reward scaling, early episode reset), these will affect the evaluation
results as well. You can avoid this by wrapping environment with ``Monitor``
wrapper before anything else.
:param model: The RL agent you want to evaluate. This can be any object
that implements a `predict` method, such as an RL algorithm (``BaseAlgorithm``)
or policy (``BasePolicy``).
:param env: The gym environment or ``VecEnv`` environment.
:param n_eval_episodes: Number of episode to evaluate the agent
:param deterministic: Whether to use deterministic or stochastic actions
:param render: Whether to render the environment or not
:param callback: callback function to do additional checks,
called after each step. Gets locals() and globals() passed as parameters.
:param reward_threshold: Minimum expected reward per episode,
this will raise an error if the performance is not met
:param return_episode_rewards: If True, a list of rewards and episode lengths
per episode will be returned instead of the mean.
:param warn: If True (default), warns user about lack of a Monitor wrapper in the
evaluation environment.
:return: Mean reward per episode, std of reward per episode.
Returns ([float], [int]) when ``return_episode_rewards`` is True, first
list containing per-episode rewards and second containing per-episode lengths
(in number of steps).
"""
is_monitor_wrapped = False
# Avoid circular import
from stable_baselines3.common.monitor import Monitor
if not isinstance(env, VecEnv):
env = DummyVecEnv([lambda: env]) # type: ignore[list-item, return-value]
is_monitor_wrapped = is_vecenv_wrapped(env, VecMonitor) or env.env_is_wrapped(Monitor)[0]
if not is_monitor_wrapped and warn:
warnings.warn(
"Evaluation environment is not wrapped with a ``Monitor`` wrapper. "
"This may result in reporting modified episode lengths and rewards, if other wrappers happen to modify these. "
"Consider wrapping environment first with ``Monitor`` wrapper.",
UserWarning,
)
n_envs = env.num_envs
episode_rewards = []
episode_lengths = []
episode_collisions = []
episode_collision_ratios = []
episode_tiles = []
episode_grass_ratios = []
episode_counts = np.zeros(n_envs, dtype="int")
# Divides episodes among different sub environments in the vector as evenly as possible
episode_count_targets = np.array([(n_eval_episodes + i) // n_envs for i in range(n_envs)], dtype="int")
current_rewards = np.zeros(n_envs)
current_lengths = np.zeros(n_envs, dtype="int")
observations = env.reset()
states = None
episode_starts = np.ones((env.num_envs,), dtype=bool)
while (episode_counts < episode_count_targets).any():
actions, states = model.predict(
observations, # type: ignore[arg-type]
state=states,
episode_start=episode_starts,
deterministic=deterministic,
)
new_observations, rewards, dones, infos = env.step(actions)
current_rewards += rewards
current_lengths += 1
for i in range(n_envs):
if episode_counts[i] < episode_count_targets[i]:
# unpack values so that the callback can access the local variables
reward = rewards[i]
done = dones[i]
info = infos[i]
episode_starts[i] = done
if callback is not None:
callback(locals(), globals())
if dones[i]:
if is_monitor_wrapped:
# Atari wrapper can send a "done" signal when
# the agent loses a life, but it does not correspond
# to the true end of episode
if "episode" in info.keys():
# Do not trust "done" with episode endings.
# Monitor wrapper includes "episode" key in info if environment
# has been wrapped with it. Use those rewards instead.
episode_rewards.append(info["episode"]["r"])
episode_lengths.append(info["episode"]["l"])
# Only increment at the real end of an episode
episode_counts[i] += 1
else:
episode_rewards.append(current_rewards[i])
episode_lengths.append(current_lengths[i])
if "num_obstacles" in infos[i].keys():
episode_collisions.append(infos[i]["num_collisions"])
episode_collision_ratios.append(infos[i]["num_collisions"] / infos[i]["num_obstacles"])
episode_tiles.append(infos[i]["tiles"])
episode_grass_ratios.append(infos[i]["grass_time"] / infos[i]["total_time"])
episode_counts[i] += 1
current_rewards[i] = 0
current_lengths[i] = 0
observations = new_observations
if render:
env.render()
mean_reward = np.mean(episode_rewards)
std_reward = np.std(episode_rewards)
mean_collisions = np.mean(episode_collisions)
mean_collision_ratios = np.mean(episode_collision_ratios)
mean_tiles = np.mean(episode_tiles)
mean_grass_ratios = np.mean(episode_grass_ratios)
if reward_threshold is not None:
assert mean_reward > reward_threshold, "Mean reward below threshold: " f"{mean_reward:.2f} < {reward_threshold:.2f}"
if return_episode_rewards:
return episode_rewards, episode_lengths
return mean_reward, std_reward, mean_collisions, mean_collision_ratios, mean_tiles, mean_grass_ratios
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--mode", type=int, help="Training/Testing_mode: 1.Default Turnrates \n 2.Default Obstacle probability/both \n 3.Manual Turnrates curriculum \n 4.Manual Obstacle probability curriculum \n 5.Manual Both curriculum \n 6.BO Turnrates curriculum \n 7.BO Obstacle probability curriculum \n 8.BO Both curriculum")
parser.add_argument("--train", type=str, help="Train/Test Train:True Test:False")
parser.add_argument("--ranges", type=float, nargs="+", help="Ranges found with Bayesian Optimization")
args = parser.parse_args()
log_path = os.path.join('./runs')
if args.train=="True":
if args.mode == 1:
from gym.wrappers.time_limit import TimeLimit
from envs.car_racing_default import CarRacingDefault
env = TimeLimit(CarRacingDefault(), max_episode_steps=1000)
eval_env = env
lr = 0.0005
best_path = './Training/Saved_Models/PPO_car_best_Model'
final_path = './Training/Saved_Models/PPO_Model_final.zip'
elif args.mode == 2:
from gym.wrappers.time_limit import TimeLimit
from envs.car_racing_obstacles import CarRacingObstacles
env = TimeLimit(CarRacingObstacles(), max_episode_steps=1000)
eval_env = env
lr = 0.0005
best_path = './Training/Saved_Models/PPO_car_best_Model_obstacles'
final_path = './Training/Saved_Models/PPO_Model_final__obstacles.zip'
elif args.mode == 3:
from gym.wrappers.time_limit import TimeLimit
from envs.TurnRates.car_racing_curriculum import CarRacingCurriculum
ranges = [230, 460, 756]
env = TimeLimit(CarRacingCurriculum(ranges), max_episode_steps=1000)
from gym.wrappers.time_limit import TimeLimit
from envs.TurnRates.car_racing_eval import CarRacingEval
eval_env = TimeLimit(CarRacingEval(), max_episode_steps=1000)
lr = 0.00025
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum'
final_path = './Training/Saved_Models/PPO_Model_final_curriculum.zip'
elif args.mode == 4:
from gym.wrappers.time_limit import TimeLimit
from envs.Obstacles.car_racing_obstacles_curriculum import CarRacingObstaclesCurriculum
ranges = [120, 240, 660]
env = TimeLimit(CarRacingObstaclesCurriculum(ranges), max_episode_steps=1000)
from gym.wrappers.time_limit import TimeLimit
from envs.Obstacles.car_racing_obstacles_eval import CarRacingObstaclesEval
eval_env = TimeLimit(CarRacingObstaclesEval(), max_episode_steps=1000)
lr = 0.000475
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum_obstacles'
final_path = './Training/Saved_Models/PPO_Model_final_curriculum_obstacles.zip'
elif args.mode == 5:
from gym.wrappers.time_limit import TimeLimit
from envs.Both.car_racing_obstacles_curriculum_both import CarRacingObstaclesCurriculumBoth
ranges = [198, 396, 775]
env = TimeLimit(CarRacingObstaclesCurriculumBoth(ranges), max_episode_steps=1000)
from gym.wrappers.time_limit import TimeLimit
from envs.Both.car_racing_obstacles_eval_both import CarRacingObstaclesEvalBoth
eval_env = TimeLimit(CarRacingObstaclesEvalBoth(), max_episode_steps=1000)
lr = 0.0002
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum_both'
final_path = './Training/Saved_Models/PPO_Model_final_curriculum_both.zip'
elif args.mode == 6:
from gym.wrappers.time_limit import TimeLimit
from envs.TurnRates.car_racing_curriculum import CarRacingCurriculum
ranges = [239, 442, 711]
if args.ranges:
ranges=args.ranges
env = TimeLimit(CarRacingCurriculum(ranges), max_episode_steps=1000)
from gym.wrappers.time_limit import TimeLimit
from envs.TurnRates.car_racing_eval import CarRacingEval
eval_env = TimeLimit(CarRacingEval(), max_episode_steps=1000)
lr = 0.00025
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum_BO'
final_path = './Training/Saved_Models/PPO_Model_final_curriculum_BO.zip'
elif args.mode == 7:
from gym.wrappers.time_limit import TimeLimit
from envs.Obstacles.car_racing_obstacles_curriculum import CarRacingObstaclesCurriculum
ranges = [101, 238, 670]
if args.ranges:
ranges=args.ranges
env = TimeLimit(CarRacingObstaclesCurriculum(ranges), max_episode_steps=1000)
from gym.wrappers.time_limit import TimeLimit
from envs.Obstacles.car_racing_obstacles_eval import CarRacingObstaclesEval
eval_env = TimeLimit(CarRacingObstaclesEval(), max_episode_steps=1000)
lr = 0.000475
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum_obstacles_BO'
final_path = './Training/Saved_Models/PPO_Model_final_curriculum_obstacles_BO.zip'
elif args.mode == 8:
from gym.wrappers.time_limit import TimeLimit
from envs.Both.car_racing_obstacles_curriculum_both import CarRacingObstaclesCurriculumBoth
ranges = [161, 418, 737]
if args.ranges:
ranges=args.ranges
env = TimeLimit(CarRacingObstaclesCurriculumBoth(ranges), max_episode_steps=1000)
from gym.wrappers.time_limit import TimeLimit
from envs.Both.car_racing_obstacles_eval_both import CarRacingObstaclesEvalBoth
eval_env = TimeLimit(CarRacingObstaclesEvalBoth(), max_episode_steps=1000)
lr = 0.0002
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum_both_BO'
final_path = './Training/Saved_Models/PPO_Model_final_curriculum_both_BO.zip'
log_path = os.path.join('./runs')
model = PPO('CnnPolicy', env=env, learning_rate=lr, n_steps=1000, batch_size=1000, verbose=0, seed=0,
tensorboard_log=log_path)
ppo_path = os.path.join(best_path)
eval_callback = EvalCallback(eval_env=eval_env, best_model_save_path=ppo_path,
n_eval_episodes=10,
eval_freq=50000, verbose=1,
deterministic=True, render=False)
model.learn(total_timesteps=1000000, callback=eval_callback)
ppo_path = os.path.join(final_path)
model.save(ppo_path)
elif args.train=="False":
if args.mode == 1:
from gym.wrappers.time_limit import TimeLimit
from envs.car_racing_default import CarRacingDefault
env = TimeLimit(CarRacingDefault(), max_episode_steps=1000)
eval_env = env
best_path = './Training/Saved_Models/PPO_car_best_Model/best_model.zip'
elif args.mode == 2:
from gym.wrappers.time_limit import TimeLimit
from envs.car_racing_obstacles import CarRacingObstacles
env = TimeLimit(CarRacingObstacles(), max_episode_steps=1000)
eval_env = env
best_path = './Training/Saved_Models/PPO_car_best_Model_obstacles/best_model.zip'
elif args.mode == 3:
from gym.wrappers.time_limit import TimeLimit
from envs.TurnRates.car_racing_eval import CarRacingEval
eval_env = TimeLimit(CarRacingEval(), max_episode_steps=1000)
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum/best_model.zip'
elif args.mode == 4:
from gym.wrappers.time_limit import TimeLimit
from envs.Obstacles.car_racing_obstacles_eval import CarRacingObstaclesEval
eval_env = TimeLimit(CarRacingObstaclesEval(), max_episode_steps=1000)
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum_obstacles/best_model.zip'
elif args.mode == 5:
from gym.wrappers.time_limit import TimeLimit
from envs.Both.car_racing_obstacles_eval_both import CarRacingObstaclesEvalBoth
eval_env = TimeLimit(CarRacingObstaclesEvalBoth(), max_episode_steps=1000)
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum_both/best_model.zip'
elif args.mode == 6:
from gym.wrappers.time_limit import TimeLimit
from envs.TurnRates.car_racing_eval import CarRacingEval
eval_env = TimeLimit(CarRacingEval(), max_episode_steps=1000)
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum_BO/best_model.zip'
elif args.mode == 7:
from gym.wrappers.time_limit import TimeLimit
from envs.Obstacles.car_racing_obstacles_eval import CarRacingObstaclesEval
eval_env = TimeLimit(CarRacingObstaclesEval(), max_episode_steps=1000)
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum_obstacles_BO/best_model.zip'
elif args.mode == 8:
from gym.wrappers.time_limit import TimeLimit
from envs.Both.car_racing_obstacles_eval_both import CarRacingObstaclesEvalBoth
eval_env = TimeLimit(CarRacingObstaclesEvalBoth(), max_episode_steps=1000)
best_path = './Training/Saved_Models/PPO_car_best_Model_curriculum_both_BO/best_model.zip'
ppo_path = os.path.join(best_path)
best_model = PPO.load(ppo_path, env=eval_env)
evalue = custom_evaluate_policy(best_model, eval_env, n_eval_episodes=500, render=False)
eval_env.close()
evalue