forked from flyyufelix/VizDoom-Keras-RL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
a2c.py
295 lines (225 loc) · 10.5 KB
/
a2c.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
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
#!/usr/bin/env python
from __future__ import print_function
import skimage as skimage
from skimage import transform, color, exposure
from skimage.viewer import ImageViewer
import random
from random import choice
import numpy as np
from collections import deque
import time
import json
from keras.models import model_from_json
from keras.models import Sequential, load_model, Model
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, Dense, Flatten, merge, MaxPooling2D, Input, AveragePooling2D, Lambda, Merge, Activation, Embedding
from keras.optimizers import SGD, Adam, rmsprop
from keras import backend as K
from vizdoom import DoomGame, ScreenResolution
from vizdoom import *
import itertools as it
from time import sleep
import tensorflow as tf
from networks import Networks
def preprocessImg(img, size):
img = np.rollaxis(img, 0, 3) # It becomes (640, 480, 3)
img = skimage.transform.resize(img, size)
img = skimage.color.rgb2gray(img)
return img
class A2CAgent:
def __init__(self, state_size, action_size):
# get size of state and action
self.state_size = state_size
self.action_size = action_size
self.value_size = 1
self.observe = 0
self.frame_per_action = 4
# These are hyper parameters for the Policy Gradient
self.gamma = 0.99
self.actor_lr = 0.0001
self.critic_lr = 0.0001
# Model for policy and critic network
self.actor = None
self.critic = None
# lists for the states, actions and rewards
self.states, self.actions, self.rewards = [], [], []
# Performance Statistics
self.stats_window_size= 50 # window size for computing rolling statistics
self.mavg_score = [] # Moving Average of Survival Time
self.var_score = [] # Variance of Survival Time
self.mavg_ammo_left = [] # Moving Average of Ammo used
self.mavg_kill_counts = [] # Moving Average of Kill Counts
# using the output of policy network, pick action stochastically (Stochastic Policy)
def get_action(self, state):
policy = self.actor.predict(state).flatten()
return np.random.choice(self.action_size, 1, p=policy)[0], policy
# Instead agent uses sample returns for evaluating policy
# Use TD(1) i.e. Monte Carlo updates
def discount_rewards(self, rewards):
discounted_rewards = np.zeros_like(rewards)
running_add = 0
for t in reversed(range(0, len(rewards))):
if rewards[t] != 0:
running_add = 0
running_add = running_add * self.gamma + rewards[t]
discounted_rewards[t] = running_add
return discounted_rewards
# save <s, a ,r> of each step
def append_sample(self, state, action, reward):
self.states.append(state)
self.rewards.append(reward)
self.actions.append(action)
# update policy network every episode
def train_model(self):
episode_length = len(self.states)
discounted_rewards = self.discount_rewards(self.rewards)
# Standardized discounted rewards
discounted_rewards -= np.mean(discounted_rewards)
if np.std(discounted_rewards):
discounted_rewards /= np.std(discounted_rewards)
else:
self.states, self.actions, self.rewards = [], [], []
print ('std = 0!')
return 0
update_inputs = np.zeros(((episode_length,) + self.state_size)) # Episode_lengthx64x64x4
# Episode length is like the minibatch size in DQN
for i in range(episode_length):
update_inputs[i,:,:,:] = self.states[i]
# Prediction of state values for each state appears in the episode
values = self.critic.predict(update_inputs)
# Similar to one-hot target but the "1" is replaced by Advantage Function i.e. discounted_rewards R_t - Value
advantages = np.zeros((episode_length, self.action_size))
for i in range(episode_length):
advantages[i][self.actions[i]] = discounted_rewards[i] - values[i]
actor_loss = self.actor.fit(update_inputs, advantages, nb_epoch=1, verbose=0)
critic_loss = self.critic.fit(update_inputs, discounted_rewards, nb_epoch=1, verbose=0)
self.states, self.actions, self.rewards = [], [], []
return actor_loss.history['loss'], critic_loss.history['loss']
def shape_reward(self, r_t, misc, prev_misc, t):
# Check any kill count
if (misc[0] > prev_misc[0]):
r_t = r_t + 1
if (misc[1] < prev_misc[1]): # Use ammo
r_t = r_t - 0.1
if (misc[2] < prev_misc[2]): # Loss HEALTH
r_t = r_t - 0.1
return r_t
def save_model(self, name):
self.actor.save_weights(name + "_actor.h5", overwrite=True)
self.critic.save_weights(name + "_critic.h5", overwrite=True)
def load_model(self, name):
self.actor.load_weights(name + "_actor.h5", overwrite=True)
self.critic.load_weights(name + "_critic.h5", overwrite=True)
if __name__ == "__main__":
# Avoid Tensorflow eats up GPU memory
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
K.set_session(sess)
game = DoomGame()
game.load_config("../../scenarios/defend_the_center.cfg")
game.set_sound_enabled(True)
game.set_screen_resolution(ScreenResolution.RES_640X480)
game.set_window_visible(False)
game.init()
# Maximum number of episodes
max_episodes = 1000000
game.new_episode()
game_state = game.get_state()
misc = game_state.game_variables # [KILLCOUNT, AMMO, HEALTH]
prev_misc = misc
action_size = game.get_available_buttons_size()
img_rows , img_cols = 64, 64
# Convert image into Black and white
img_channels = 4 # We stack 4 frames
state_size = (img_rows, img_cols, img_channels)
agent = A2CAgent(state_size, action_size)
agent.actor = Networks.actor_network(state_size, action_size, agent.actor_lr)
agent.critic = Networks.critic_network(state_size, agent.value_size, agent.critic_lr)
# Start training
GAME = 0
t = 0
max_life = 0 # Maximum episode life (Proxy for agent performance)
# Buffer to compute rolling statistics
life_buffer, ammo_buffer, kills_buffer = [], [], []
for i in range(max_episodes):
game.new_episode()
game_state = game.get_state()
misc = game_state.game_variables
prev_misc = misc
x_t = game_state.screen_buffer # 480 x 640
x_t = preprocessImg(x_t, size=(img_rows, img_cols))
s_t = np.stack(([x_t]*4), axis=2) # It becomes 64x64x4
s_t = np.expand_dims(s_t, axis=0) # 1x64x64x4
life = 0 # Episode life
while not game.is_episode_finished():
loss = 0 # Training Loss at each update
r_t = 0 # Initialize reward at time t
a_t = np.zeros([action_size]) # Initialize action at time t
x_t = game_state.screen_buffer
x_t = preprocessImg(x_t, size=(img_rows, img_cols))
x_t = np.reshape(x_t, (1, img_rows, img_cols, 1))
s_t = np.append(x_t, s_t[:, :, :, :3], axis=3)
# Sample action from stochastic softmax policy
action_idx, policy = agent.get_action(s_t)
a_t[action_idx] = 1
a_t = a_t.astype(int)
game.set_action(a_t.tolist())
skiprate = agent.frame_per_action # Frame Skipping = 4
game.advance_action(skiprate)
r_t = game.get_last_reward() # Each frame we get reward of 0.1, so 4 frames will be 0.4
# Check if episode is terminated
is_terminated = game.is_episode_finished()
if (is_terminated):
# Save max_life
if (life > max_life):
max_life = life
life_buffer.append(life)
ammo_buffer.append(misc[1])
kills_buffer.append(misc[0])
print ("Episode Finish ", prev_misc, policy)
else:
life += 1
game_state = game.get_state() # Observe again after we take the action
misc = game_state.game_variables
# Reward Shaping
r_t = agent.shape_reward(r_t, misc, prev_misc, t)
# Save trajactory sample <s, a, r> to the memory
agent.append_sample(s_t, action_idx, r_t)
# Update the cache
t += 1
prev_misc = misc
if (is_terminated and t > agent.observe):
# Every episode, agent learns from sample returns
loss = agent.train_model()
# Save model every 10000 iterations
if t % 10000 == 0:
print("Save model")
agent.save_model("models/a2c")
state = ""
if t <= agent.observe:
state = "Observe mode"
else:
state = "Train mode"
if (is_terminated):
# Print performance statistics at every episode end
print("TIME", t, "/ GAME", GAME, "/ STATE", state, "/ ACTION", action_idx, "/ REWARD", r_t, "/ LIFE", max_life, "/ LOSS", loss)
# Save Agent's Performance Statistics
if GAME % agent.stats_window_size == 0 and t > agent.observe:
print("Update Rolling Statistics")
agent.mavg_score.append(np.mean(np.array(life_buffer)))
agent.var_score.append(np.var(np.array(life_buffer)))
agent.mavg_ammo_left.append(np.mean(np.array(ammo_buffer)))
agent.mavg_kill_counts.append(np.mean(np.array(kills_buffer)))
# Reset rolling stats buffer
life_buffer, ammo_buffer, kills_buffer = [], [], []
# Write Rolling Statistics to file
with open("statistics/a2c_stats.txt", "w") as stats_file:
stats_file.write('Game: ' + str(GAME) + '\n')
stats_file.write('Max Score: ' + str(max_life) + '\n')
stats_file.write('mavg_score: ' + str(agent.mavg_score) + '\n')
stats_file.write('var_score: ' + str(agent.var_score) + '\n')
stats_file.write('mavg_ammo_left: ' + str(agent.mavg_ammo_left) + '\n')
stats_file.write('mavg_kill_counts: ' + str(agent.mavg_kill_counts) + '\n')
# Episode Finish. Increment game count
GAME += 1