-
Notifications
You must be signed in to change notification settings - Fork 2
/
a3c.py
286 lines (221 loc) · 10.1 KB
/
a3c.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
import numpy as np
import tensorflow as tf
import tflearn
GAMMA = 0.99
A_DIM = 6
ENTROPY_WEIGHT = 0.5
ENTROPY_EPS = 1e-6
S_INFO = 4
class ActorNetwork(object):
"""
Input to the network is the state, output is the distribution
of all actions.
"""
def __init__(self, sess, state_dim, action_dim, learning_rate):
self.sess = sess
self.s_dim = state_dim
self.a_dim = action_dim
self.lr_rate = learning_rate
# Create the actor network
self.inputs, self.out = self.create_actor_network()
# Get all network parameters
self.network_params = \
tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='actor')
# Set all network parameters
self.input_network_params = []
for param in self.network_params:
self.input_network_params.append(
tf.placeholder(tf.float32, shape=param.get_shape()))
self.set_network_params_op = []
for idx, param in enumerate(self.input_network_params):
self.set_network_params_op.append(self.network_params[idx].assign(param))
# Selected action, 0-1 vector
self.acts = tf.placeholder(tf.float32, [None, self.a_dim])
# This gradient will be provided by the critic network
self.act_grad_weights = tf.placeholder(tf.float32, [None, 1])
# Compute the objective (log action_vector and entropy)
self.obj = tf.reduce_sum(tf.multiply(
tf.log(tf.reduce_sum(tf.multiply(self.out, self.acts),
reduction_indices=1, keep_dims=True)),
-self.act_grad_weights)) \
+ ENTROPY_WEIGHT * tf.reduce_sum(tf.multiply(self.out,
tf.log(self.out + ENTROPY_EPS)))
# Combine the gradients here
self.actor_gradients = tf.gradients(self.obj, self.network_params)
# Optimization Op
self.optimize = tf.train.RMSPropOptimizer(self.lr_rate).\
apply_gradients(zip(self.actor_gradients, self.network_params))
def create_actor_network(self):
with tf.variable_scope('actor'):
inputs = tflearn.input_data(shape=[None, self.s_dim[0], self.s_dim[1]])
split_0 = tflearn.fully_connected(inputs[:, 0:1, -1], 128, activation='relu')
split_1 = tflearn.fully_connected(inputs[:, 1:2, -1], 128, activation='relu')
split_2 = tflearn.conv_1d(inputs[:, 2:3, :], 128, 4, activation='relu')
split_3 = tflearn.conv_1d(inputs[:, 3:4, :], 128, 4, activation='relu')
split_4 = tflearn.conv_1d(inputs[:, 4:5, :A_DIM], 128, 4, activation='relu')
split_5 = tflearn.fully_connected(inputs[:, 4:5, -1], 128, activation='relu')
split_2_flat = tflearn.flatten(split_2)
split_3_flat = tflearn.flatten(split_3)
split_4_flat = tflearn.flatten(split_4)
merge_net = tflearn.merge([split_0, split_1, split_2_flat, split_3_flat, split_4_flat, split_5], 'concat')
dense_net_0 = tflearn.fully_connected(merge_net, 128, activation='relu')
out = tflearn.fully_connected(dense_net_0, self.a_dim, activation='softmax')
return inputs, out
def train(self, inputs, acts, act_grad_weights):
self.sess.run(self.optimize, feed_dict={
self.inputs: inputs,
self.acts: acts,
self.act_grad_weights: act_grad_weights
})
def predict(self, inputs):
return self.sess.run(self.out, feed_dict={
self.inputs: inputs
})
def get_gradients(self, inputs, acts, act_grad_weights):
return self.sess.run(self.actor_gradients, feed_dict={
self.inputs: inputs,
self.acts: acts,
self.act_grad_weights: act_grad_weights
})
def apply_gradients(self, actor_gradients):
return self.sess.run(self.optimize, feed_dict={
i: d for i, d in zip(self.actor_gradients, actor_gradients)
})
def get_network_params(self):
return self.sess.run(self.network_params)
def set_network_params(self, input_network_params):
self.sess.run(self.set_network_params_op, feed_dict={
i: d for i, d in zip(self.input_network_params, input_network_params)
})
class CriticNetwork(object):
"""
Input to the network is the state and action, output is V(s).
On policy: the action must be obtained from the output of the Actor network.
"""
def __init__(self, sess, state_dim, learning_rate):
self.sess = sess
self.s_dim = state_dim
self.lr_rate = learning_rate
# Create the critic network
self.inputs, self.out = self.create_critic_network()
# Get all network parameters
self.network_params = \
tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='critic')
# Set all network parameters
self.input_network_params = []
for param in self.network_params:
self.input_network_params.append(
tf.placeholder(tf.float32, shape=param.get_shape()))
self.set_network_params_op = []
for idx, param in enumerate(self.input_network_params):
self.set_network_params_op.append(self.network_params[idx].assign(param))
# Network target V(s)
self.td_target = tf.placeholder(tf.float32, [None, 1])
# Temporal Difference, will also be weights for actor_gradients
self.td = tf.subtract(self.td_target, self.out)
# Mean square error
self.loss = tflearn.mean_square(self.td_target, self.out)
# Compute critic gradient
self.critic_gradients = tf.gradients(self.loss, self.network_params)
# Optimization Op
self.optimize = tf.train.RMSPropOptimizer(self.lr_rate).\
apply_gradients(zip(self.critic_gradients, self.network_params))
def create_critic_network(self):
with tf.variable_scope('critic'):
inputs = tflearn.input_data(shape=[None, self.s_dim[0], self.s_dim[1]])
split_0 = tflearn.fully_connected(inputs[:, 0:1, -1], 128, activation='relu')
split_1 = tflearn.fully_connected(inputs[:, 1:2, -1], 128, activation='relu')
split_2 = tflearn.conv_1d(inputs[:, 2:3, :], 128, 4, activation='relu')
split_3 = tflearn.conv_1d(inputs[:, 3:4, :], 128, 4, activation='relu')
split_4 = tflearn.conv_1d(inputs[:, 4:5, :A_DIM], 128, 4, activation='relu')
split_5 = tflearn.fully_connected(inputs[:, 4:5, -1], 128, activation='relu')
split_2_flat = tflearn.flatten(split_2)
split_3_flat = tflearn.flatten(split_3)
split_4_flat = tflearn.flatten(split_4)
merge_net = tflearn.merge([split_0, split_1, split_2_flat, split_3_flat, split_4_flat, split_5], 'concat')
dense_net_0 = tflearn.fully_connected(merge_net, 128, activation='relu')
out = tflearn.fully_connected(dense_net_0, 1, activation='linear')
return inputs, out
def train(self, inputs, td_target):
return self.sess.run([self.loss, self.optimize], feed_dict={
self.inputs: inputs,
self.td_target: td_target
})
def predict(self, inputs):
return self.sess.run(self.out, feed_dict={
self.inputs: inputs
})
def get_td(self, inputs, td_target):
return self.sess.run(self.td, feed_dict={
self.inputs: inputs,
self.td_target: td_target
})
def get_gradients(self, inputs, td_target):
return self.sess.run(self.critic_gradients, feed_dict={
self.inputs: inputs,
self.td_target: td_target
})
def apply_gradients(self, critic_gradients):
return self.sess.run(self.optimize, feed_dict={
i: d for i, d in zip(self.critic_gradients, critic_gradients)
})
def get_network_params(self):
return self.sess.run(self.network_params)
def set_network_params(self, input_network_params):
self.sess.run(self.set_network_params_op, feed_dict={
i: d for i, d in zip(self.input_network_params, input_network_params)
})
def compute_gradients(s_batch, a_batch, r_batch, terminal, actor, critic):
"""
batch of s, a, r is from samples in a sequence
the format is in np.array([batch_size, s/a/r_dim])
terminal is True when sequence ends as a terminal state
"""
assert s_batch.shape[0] == a_batch.shape[0]
assert s_batch.shape[0] == r_batch.shape[0]
ba_size = s_batch.shape[0]
v_batch = critic.predict(s_batch)
R_batch = np.zeros(r_batch.shape)
if terminal:
R_batch[-1, 0] = 0 # terminal state
else:
R_batch[-1, 0] = v_batch[-1, 0] # boot strap from last state
for t in reversed(xrange(ba_size - 1)):
R_batch[t, 0] = r_batch[t] + GAMMA * R_batch[t + 1, 0]
td_batch = R_batch - v_batch
actor_gradients = actor.get_gradients(s_batch, a_batch, td_batch)
critic_gradients = critic.get_gradients(s_batch, R_batch)
return actor_gradients, critic_gradients, td_batch
def discount(x, gamma):
"""
Given vector x, computes a vector y such that
y[i] = x[i] + gamma * x[i+1] + gamma^2 x[i+2] + ...
"""
out = np.zeros(len(x))
out[-1] = x[-1]
for i in reversed(xrange(len(x)-1)):
out[i] = x[i] + gamma*out[i+1]
assert x.ndim >= 1
# More efficient version:
# scipy.signal.lfilter([1],[1,-gamma],x[::-1], axis=0)[::-1]
return out
def compute_entropy(x):
"""
Given vector x, computes the entropy
H(x) = - sum( p * log(p))
"""
H = 0.0
for i in xrange(len(x)):
if 0 < x[i] < 1:
H -= x[i] * np.log(x[i])
return H
def build_summaries():
td_loss = tf.Variable(0.)
tf.summary.scalar("TD_loss", td_loss)
eps_total_reward = tf.Variable(0.)
tf.summary.scalar("Eps_total_reward", eps_total_reward)
avg_entropy = tf.Variable(0.)
tf.summary.scalar("Avg_entropy", avg_entropy)
summary_vars = [td_loss, eps_total_reward, avg_entropy]
summary_ops = tf.summary.merge_all()
return summary_ops, summary_vars