-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathplay_car_racing_by_the_model.py
44 lines (35 loc) · 1.76 KB
/
play_car_racing_by_the_model.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
import argparse
import gym
from collections import deque
from CarRacingDQNAgent import CarRacingDQNAgent
from common_functions import process_state_image
from common_functions import generate_state_frame_stack_from_queue
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Play CarRacing by the trained model.')
parser.add_argument('-m', '--model', required=True, help='The `.h5` file of the trained model.')
parser.add_argument('-e', '--episodes', type=int, default=1, help='The number of episodes should the model plays.')
args = parser.parse_args()
train_model = args.model
play_episodes = args.episodes
env = gym.make('CarRacing-v0')
agent = CarRacingDQNAgent(epsilon=0) # Set epsilon to 0 to ensure all actions are instructed by the agent
agent.load(train_model)
for e in range(play_episodes):
init_state = env.reset()
init_state = process_state_image(init_state)
total_reward = 0
punishment_counter = 0
state_frame_stack_queue = deque([init_state]*agent.frame_stack_num, maxlen=agent.frame_stack_num)
time_frame_counter = 1
while True:
env.render()
current_state_frame_stack = generate_state_frame_stack_from_queue(state_frame_stack_queue)
action = agent.act(current_state_frame_stack)
next_state, reward, done, info = env.step(action)
total_reward += reward
next_state = process_state_image(next_state)
state_frame_stack_queue.append(next_state)
if done:
print('Episode: {}/{}, Scores(Time Frames): {}, Total Rewards: {:.2}'.format(e+1, play_episodes, time_frame_counter, float(total_reward)))
break
time_frame_counter += 1