forked from louisnino/RLcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tutorial_AC.py
338 lines (279 loc) · 13.1 KB
/
tutorial_AC.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
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
"""
Actor-Critic
-------------
It uses TD-error as the Advantage.
Actor Critic History
----------------------
A3C > DDPG > AC
Advantage
----------
AC converge faster than Policy Gradient.
Disadvantage (IMPORTANT)
------------------------
The Policy is oscillated (difficult to converge), DDPG can solve
this problem using advantage of DQN.
Reference
----------
paper: https://papers.nips.cc/paper/1786-actor-critic-algorithms.pdf
View more on MorvanZhou's tutorial page: https://morvanzhou.github.io/tutorials/
Environment
------------
CartPole-v0: https://gym.openai.com/envs/CartPole-v0
A pole is attached by an un-actuated joint to a cart, which moves along a
frictionless track. The system is controlled by applying a force of +1 or -1
to the cart. The pendulum starts upright, and the goal is to prevent it from
falling over.
A reward of +1 is provided for every timestep that the pole remains upright.
The episode ends when the pole is more than 15 degrees from vertical, or the
cart moves more than 2.4 units from the center.
Prerequisites
--------------
tensorflow >=2.0.0a0
tensorlayer >=2.0.0
To run
------
python tutorial_AC.py --train/test
"""
import argparse
import time
import gym
import numpy as np
import tensorflow as tf
import tensorlayer as tl
tl.logging.set_verbosity(tl.logging.DEBUG)
np.random.seed(2)
tf.random.set_seed(2) # reproducible
# add arguments in command --train/test
parser = argparse.ArgumentParser(description='Train or test neural net motor controller.')
parser.add_argument('--train', dest='train', action='store_true', default=True)
parser.add_argument('--test', dest='test', action='store_true', default=False)
print(parser.parse_args())
args = parser.parse_args()
##################### hyper parameters ####################
OUTPUT_GRAPH = False
MAX_EPISODE = 3000 # number of overall episodes for training
DISPLAY_REWARD_THRESHOLD = 100 # renders environment if running reward is greater then this threshold
MAX_EP_STEPS = 1000 # maximum time step in one episode
RENDER = False # rendering wastes time
LAMBDA = 0.9 # reward discount in TD error
LR_A = 0.001 # learning rate for actor
LR_C = 0.01 # learning rate for critic
############################### Actor-Critic ####################################
class Actor(object):
def __init__(self, n_features, n_actions, lr=0.001):
# 创建Actor网络
def get_model(inputs_shape):
ni = tl.layers.Input(inputs_shape, name='state')
nn = tl.layers.Dense(
n_units=30, act=tf.nn.relu6, W_init=tf.random_uniform_initializer(0, 0.01), name='hidden'
)(ni)
nn = tl.layers.Dense(
n_units=10, act=tf.nn.relu6, W_init=tf.random_uniform_initializer(0, 0.01), name='hidden2'
)(nn)
nn = tl.layers.Dense(n_units=n_actions, name='actions')(nn)
return tl.models.Model(inputs=ni, outputs=nn, name="Actor")
self.model = get_model([None, n_features])
self.model.train()
self.optimizer = tf.optimizers.Adam(lr)
# Actor学习
def learn(self, s, a, td):
with tf.GradientTape() as tape:
_logits = self.model(np.array([s]))
## 带权重更新。
_exp_v = tl.rein.cross_entropy_reward_loss(logits=_logits, actions=[a], rewards=td[0])
grad = tape.gradient(_exp_v, self.model.trainable_weights)
self.optimizer.apply_gradients(zip(grad, self.model.trainable_weights))
return _exp_v
# 按照分布随机动作。
def choose_action(self, s):
_logits = self.model(np.array([s]))
_probs = tf.nn.softmax(_logits).numpy()
return tl.rein.choice_action_by_probs(_probs.ravel()) # sample according to probability distribution
# 贪婪算法。
def choose_action_greedy(self, s):
_logits = self.model(np.array([s])) # logits: probability distribution of actions
_probs = tf.nn.softmax(_logits).numpy()
return np.argmax(_probs.ravel())
def save_ckpt(self): # save trained weights
tl.files.save_npz(self.model.trainable_weights, name='model_actor.npz')
def load_ckpt(self): # load trained weights
tl.files.load_and_assign_npz(name='model_actor.npz', network=self.model)
class Critic(object):
def __init__(self, n_features, lr=0.01):
# 创建Critic网络。
def get_model(inputs_shape):
ni = tl.layers.Input(inputs_shape, name='state')
nn = tl.layers.Dense(
n_units=30, act=tf.nn.relu6, W_init=tf.random_uniform_initializer(0, 0.01), name='hidden'
)(ni)
nn = tl.layers.Dense(
n_units=5, act=tf.nn.relu, W_init=tf.random_uniform_initializer(0, 0.01), name='hidden2'
)(nn)
nn = tl.layers.Dense(n_units=1, act=None, name='value')(nn)
return tl.models.Model(inputs=ni, outputs=nn, name="Critic")
self.model = get_model([1, n_features])
self.model.train()
self.optimizer = tf.optimizers.Adam(lr)
# Critic学习
def learn(self, s, r, s_):
v_ = self.model(np.array([s_]))
with tf.GradientTape() as tape:
v = self.model(np.array([s]))
## [敲黑板]计算TD-error
## TD_error = r + lambd * V(newS) - V(S)
td_error = r + LAMBDA * v_ - v
loss = tf.square(td_error)
grad = tape.gradient(loss, self.model.trainable_weights)
self.optimizer.apply_gradients(zip(grad, self.model.trainable_weights))
return td_error
def save_ckpt(self): # save trained weights
tl.files.save_npz(self.model.trainable_weights, name='model_critic.npz')
def load_ckpt(self): # load trained weights
tl.files.load_and_assign_npz(name='model_critic.npz', network=self.model)
if __name__ == '__main__':
'''
choose environment
1. Openai gym:
env = gym.make()
2. DeepMind Control Suite:
env = dm_control2gym.make()
'''
env = gym.make('CartPole-v1')
# dm_control2gym.create_render_mode('example mode', show=True, return_pixel=False, height=240, width=320, camera_id=-1, overlays=(),
# depth=False, scene_option=None)
# env = dm_control2gym.make(domain_name="cartpole", task_name="balance")
env.seed(2) # reproducible
# env = env.unwrapped
N_F = env.observation_space.shape[0]
# N_A = env.action_space.shape[0]
N_A = env.action_space.n
print("observation dimension: %d" % N_F) # 4
print("observation high: %s" % env.observation_space.high) # [ 2.4 , inf , 0.41887902 , inf]
print("observation low : %s" % env.observation_space.low) # [-2.4 , -inf , -0.41887902 , -inf]
print("num of actions: %d" % N_A) # 2 : left or right
actor = Actor(n_features=N_F, n_actions=N_A, lr=LR_A)
# we need a good teacher, so the teacher should learn faster than the actor
critic = Critic(n_features=N_F, lr=LR_C)
## 训练部分
if args.train:
t0 = time.time()
for i_episode in range(MAX_EPISODE):
# episode_time = time.time()
s = env.reset().astype(np.float32)
t = 0 # number of step in this episode
all_r = [] # rewards of all steps
while True:
if RENDER: env.render()
a = actor.choose_action(s)
s_new, r, done, info = env.step(a)
s_new = s_new.astype(np.float32)
# [敲黑板],我们希望在濒死状态,可以减去一个大reward。让智能体学习如何力挽狂澜。
if done: r = -20
# these may helpful in some tasks
# if abs(s_new[0]) >= env.observation_space.high[0]:
# # cart moves more than 2.4 units from the center
# r = -20
# reward for the distance between cart to the center
# r -= abs(s_new[0]) * .1
all_r.append(r)
# Critic学习,并计算出td-error
td_error = critic.learn(
s, r, s_new
) # learn Value-function : gradient = grad[r + lambda * V(s_new) - V(s)]
# actor学习
try:
for _ in range(1):
actor.learn(s, a, td_error) # learn Policy : true_gradient = grad[logPi(s, a) * td_error]
except KeyboardInterrupt: # if Ctrl+C at running actor.learn(), then save model, or exit if not at actor.learn()
actor.save_ckpt()
critic.save_ckpt()
# logging
s = s_new
t += 1
if done or t >= MAX_EP_STEPS:
ep_rs_sum = sum(all_r)
if 'running_reward' not in globals():
running_reward = ep_rs_sum
else:
running_reward = running_reward * 0.95 + ep_rs_sum * 0.05
# start rending if running_reward greater than a threshold
# if running_reward > DISPLAY_REWARD_THRESHOLD: RENDER = True
# print("Episode: %d reward: %f running_reward %f took: %.5f" % \
# (i_episode, ep_rs_sum, running_reward, time.time() - episode_time))
print('Episode: {}/{} | Episode Reward: {:.4f} | Running Time: {:.4f}'\
.format(i_episode, MAX_EPISODE, ep_rs_sum, time.time()-t0 ))
# Early Stopping for quick check
if t >= MAX_EP_STEPS:
print("Early Stopping")
s = env.reset().astype(np.float32)
rall = 0
while True:
env.render()
# a = actor.choose_action(s)
a = actor.choose_action_greedy(s) # Hao Dong: it is important for this task
s_new, r, done, info = env.step(a)
s_new = np.concatenate((s_new[0:N_F], s[N_F:]), axis=0).astype(np.float32)
rall += r
s = s_new
if done:
print("reward", rall)
s = env.reset().astype(np.float32)
rall = 0
break
actor.save_ckpt()
critic.save_ckpt()
## 测试部分
if args.test:
actor.load_ckpt()
critic.load_ckpt()
t0 = time.time()
for i_episode in range(MAX_EPISODE):
episode_time = time.time()
s = env.reset().astype(np.float32)
t = 0 # number of step in this episode
all_r = [] # rewards of all steps
while True:
if RENDER: env.render()
a = actor.choose_action(s)
s_new, r, done, info = env.step(a)
s_new = s_new.astype(np.float32)
if done: r = -20
# these may helpful in some tasks
# if abs(s_new[0]) >= env.observation_space.high[0]:
# # cart moves more than 2.4 units from the center
# r = -20
# reward for the distance between cart to the center
# r -= abs(s_new[0]) * .1
all_r.append(r)
s = s_new
t += 1
if done or t >= MAX_EP_STEPS:
ep_rs_sum = sum(all_r)
if 'running_reward' not in globals():
running_reward = ep_rs_sum
else:
running_reward = running_reward * 0.95 + ep_rs_sum * 0.05
# start rending if running_reward greater than a threshold
# if running_reward > DISPLAY_REWARD_THRESHOLD: RENDER = True
# print("Episode: %d reward: %f running_reward %f took: %.5f" % \
# (i_episode, ep_rs_sum, running_reward, time.time() - episode_time))
print('Episode: {}/{} | Episode Reward: {:.4f} | Running Time: {:.4f}'\
.format(i_episode, MAX_EPISODE, ep_rs_sum, time.time()-t0 ))
# Early Stopping for quick check
if t >= MAX_EP_STEPS:
print("Early Stopping")
s = env.reset().astype(np.float32)
rall = 0
while True:
env.render()
# a = actor.choose_action(s)
a = actor.choose_action_greedy(s) # Hao Dong: it is important for this task
s_new, r, done, info = env.step(a)
s_new = np.concatenate((s_new[0:N_F], s[N_F:]), axis=0).astype(np.float32)
rall += r
s = s_new
if done:
print("reward", rall)
s = env.reset().astype(np.float32)
rall = 0
break