-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathgym_ddpg.py
221 lines (147 loc) · 5 KB
/
gym_ddpg.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
import gym
import time
import logging
import shutil
import os
import sys
import tensorflow as tf
import gc
gc.enable()
from modules.ddpg import *
from modules.env_utils import *
# Save video rendering every Xth game played
def multiples_video_schedule(episode_id):
return episode_id % 100 == 0 # and episode_id>0
#return episode_id % 200 == 0
print
print "Usage:"
print " ",sys.argv[0]," [optional: path_to_ckpt_file] [optional: True/False test mode]"
print
print
outdir = "gym_results"
ENV_NAME = 'Pendulum-v0' # BipedalWalker-v2
TOTAL_FRAMES = 200000 ## TRAIN
MAX_TRAINING_STEPS = 500 ## MAX STEPS BEFORE RESETTING THE ENVIRONMENT
TESTING_GAMES = 100 # no. of games to average on during testing
MAX_TESTING_STEPS = 500 #5 minutes '/3' because gym repeating the last action 3-4 times already!
TRAIN_AFTER_FRAMES = 1000
epoch_size = 5000 # every how many frames to test
"""
ENV_NAME = 'BipedalWalker-v2'
TOTAL_FRAMES = 20000000 ## TRAIN
MAX_TRAINING_STEPS = 2000 ## MAX STEPS BEFORE RESETTING THE ENVIRONMENT
TESTING_GAMES = 100 # no. of games to average on during testing
MAX_TESTING_STEPS = 2000 #5 minutes '/3' because gym repeating the last action 3-4 times already!
TRAIN_AFTER_FRAMES = 50000
epoch_size = 50000 # every how many frames to test
"""
MAX_NOOP_START = 0
LOG_DIR = outdir+'/'+ENV_NAME+'/logs/'
if os.path.isdir(LOG_DIR):
shutil.rmtree(LOG_DIR)
journalist = tf.train.SummaryWriter(LOG_DIR)
# Build environment
env = gym.make(ENV_NAME)
# Initialize Tensorflow session
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
session = tf.InteractiveSession(config=config)
# Create DQN agent
agent = DDPG(state_size=env.observation_space.shape,
action_size=env.action_space.shape[0],
session=session,
summary_writer = journalist,
exploration_period = 20000,
minibatch_size = 64,
discount_factor = 0.97,
experience_replay_buffer = 500000,
target_qnet_update_frequency = 1000,
initial_exploration_epsilon = 0.2,
final_exploration_epsilon = 0.2)#,
# reward_clipping = 1.0)
session.run(tf.initialize_all_variables())
journalist.add_graph(session.graph)
saver = tf.train.Saver(tf.all_variables())
env.monitor.start(outdir+'/'+ENV_NAME,force = True, video_callable=multiples_video_schedule)
logger = logging.getLogger()
logging.disable(logging.INFO)
# If an argument is supplied, load the specific checkpoint.
test_mode = False
if len(sys.argv)>=2:
print sys.argv[1]
saver.restore(session, sys.argv[1])
if len(sys.argv)==3:
test_mode = bool(sys.argv[2])
num_frames = 0
num_games = 0
current_game_frames = 0
last_time = time.time()
last_frame_count = 0.0
state = env.reset()
agent.noise.reset()
while num_frames <= TOTAL_FRAMES+1:
if test_mode:
env.render()
num_frames += 1
current_game_frames += 1
# Pick action given current state
if not test_mode:
action = agent.action(state, training = True)
else:
action = agent.action(state, training = False)
if current_game_frames < MAX_NOOP_START:
action = 0
# Perform the selected action on the environment
next_state,reward,done,_ = env.step(action)
# Store experience
if current_game_frames >= MAX_NOOP_START:
agent.store(state,action,reward,next_state,done)
state = next_state
# Train agent
if num_frames>=TRAIN_AFTER_FRAMES:
agent.train()
if done or current_game_frames > MAX_TRAINING_STEPS:
state = env.reset()
agent.noise.reset()
current_game_frames = 0
num_games += 1
# Print an update
if num_frames % epoch_size == 0:
new_time = time.time()
diff = new_time - last_time
last_time = new_time
elapsed_frames = num_frames - last_frame_count
last_frame_count = num_frames
print "frames: ",num_frames," games: ",num_games," speed: ",(elapsed_frames/diff)," frames/second"
# Save the network's parameters after every epoch
if num_frames % epoch_size == 0 and num_frames > TRAIN_AFTER_FRAMES:
saver.save(session, outdir+"/"+ENV_NAME+"/model_"+str(num_frames/1000)+"k.ckpt")
print
print "epoch: frames=",num_frames," games=",num_games
## Testing -- it's kind of slow, so we're only going to test every 2 epochs
if num_frames % (2*epoch_size) == 0 and num_frames > TRAIN_AFTER_FRAMES:
total_reward = 0
avg_steps = 0
for i in xrange(TESTING_GAMES):
state = env.reset()
agent.noise.reset()
frm = 0
while frm < MAX_TESTING_STEPS:
frm += 1
#env.render()
action = agent.action(state, training = False) # direct action for test
state,reward,done,_ = env.step(action)
total_reward += reward
if done:
break
avg_steps += frm
avg_reward = float(total_reward)/TESTING_GAMES
str_ = session.run( tf.scalar_summary('test reward ('+str(epoch_size/1000)+'k)', avg_reward) )
journalist.add_summary(str_, num_frames) #np.round(num_frames/epoch_size)) # in no. of epochs, as in Mnih
print ' --> EVALUATION AVERAGE REWARD: ',avg_reward,' avg steps: ',(avg_steps/TESTING_GAMES)
state = env.reset()
agent.noise.reset()
env.monitor.close()
journalist.close()
## Save the final network
saver.save(session, outdir+"/"+ENV_NAME+"/final.ckpt")