forked from tensorforce/tensorforce
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_tutorial_code.py
More file actions
500 lines (409 loc) · 14.8 KB
/
test_tutorial_code.py
File metadata and controls
500 lines (409 loc) · 14.8 KB
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# Copyright 2017 reinforce.io. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import logging
import unittest
logging.getLogger('tensorflow').disabled = True
class TestTutorialCode(unittest.TestCase):
"""
Validation of random code snippets as to be notified when old blog posts need to be changed.
"""
class MyClient(object):
def __init__(self, *args, **kwargs):
pass
def get_state(self):
import numpy as np
return np.random.rand(10)
def execute(self, action):
pass
def test_reinforceio_homepage(self):
"""
Code example from the homepage and README.md.
"""
from tensorforce.agents import TRPOAgent
# Create a Trust Region Policy Optimization agent
agent = TRPOAgent(
states=dict(shape=(10,), type='float'),
actions=dict(type='int', num_actions=2),
network=[dict(type='dense', size=50), dict(type='dense', size=50)],
update_mode=dict(
unit='episodes',
batch_size=1,
frequency=1
),
memory=dict(
type='latest',
include_next_states=False,
capacity=100
)
)
# Get new data from somewhere, e.g. a client to a web app
client = TestTutorialCode.MyClient('http://127.0.0.1', 8080)
# Poll new state from client
state = client.get_state()
# Get prediction from agent, execute
action = agent.act(states=state)
reward = client.execute(action)
# Add experience, agent automatically updates model according to batch size
agent.observe(reward=reward, terminal=False)
agent.close()
def test_blogpost_introduction(self):
"""
Test of introduction blog post examples.
"""
import tensorflow as tf
### DQN agent example
from tensorforce.agents import DQNAgent
# Network is an ordered list of layers
network_spec = [dict(type='dense', size=32), dict(type='dense', size=32)]
# Define a state
states = dict(shape=(10,), type='float')
# Define an action
actions = dict(type='int', num_actions=5)
agent = DQNAgent(
states=states,
actions=actions,
network=network_spec,
update_mode=dict(
unit='timesteps',
batch_size=1,
frequency=1
),
memory=dict(
type='latest',
include_next_states=True,
capacity=100
),
target_sync_frequency=10
)
agent.close()
### Code block: multiple states
states = dict(
image=dict(shape=(64, 64, 3), type='float'),
caption=dict(shape=(20,), type='int')
)
# DQN does not support multiple states. Omit test for now.
# agent = DQNAgent(config=config)
### Code block: DQN observer function
def observe(self, reward, terminal):
super(DQNAgent, self).observe(reward, terminal)
if self.timestep >= self.first_update \
and self.timestep % self.target_update_frequency == 0:
self.model.update_target()
### Code block: Network config JSON
network_json = """
[
{
"type": "conv2d",
"size": 32,
"window": 8,
"stride": 4
},
{
"type": "conv2d",
"size": 64,
"window": 4,
"stride": 2
},
{
"type": "flatten"
},
{
"type": "dense",
"size": 512
}
]
"""
### Test json
import json
network_spec = json.loads(network_json)
### Code block: Modified dense layer
modified_dense = """
[
{
"type": "dense",
"size": 64,
"bias": false,
"activation": "selu",
"l2_regularization": 0.001
}
]
"""
### Test json
network_spec = json.loads(modified_dense)
### Code block: Own layer type
from tensorforce.core.networks import Layer
class BatchNormalization(Layer):
def __init__(self, variance_epsilon=1e-6, scope='batchnorm', summary_labels=None):
super(BatchNormalization, self).__init__(scope=scope, summary_labels=summary_labels)
self.variance_epsilon = variance_epsilon
def tf_apply(self, x, update):
mean, variance = tf.nn.moments(x, axes=tuple(range(x.shape.ndims - 1)))
return tf.nn.batch_normalization(
x=x,
mean=mean,
variance=variance,
offset=None,
scale=None,
variance_epsilon=self.variance_epsilon
)
### Test own layer
states = dict(shape=(10,), type='float')
network_spec = [
{'type': 'dense', 'size': 32},
{'type': BatchNormalization, 'variance_epsilon': 1e-9}
]
agent = DQNAgent(
states=states,
actions=actions,
network=network_spec,
update_mode=dict(
unit='timesteps',
batch_size=8,
frequency=4
),
memory=dict(
type='replay',
include_next_states=True,
capacity=100
)
)
agent.close()
### Code block: Own network builder
from tensorforce.core.networks import Network
class CustomNetwork(Network):
def tf_apply(self, x, internals, update, return_internals=False):
image = x['image'] # 64x64x3-dim, float
caption = x['caption'] # 20-dim, int
initializer = tf.random_normal_initializer(mean=0.0, stddev=0.01, dtype=tf.float32)
# CNN
weights = tf.get_variable(name='W1', shape=(3, 3, 3, 16), initializer=initializer)
image = tf.nn.conv2d(image, filter=weights, strides=(1, 1, 1, 1), padding='SAME')
image = tf.nn.relu(image)
image = tf.nn.max_pool(image, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1), padding='SAME')
weights = tf.get_variable(name='W2', shape=(3, 3, 16, 32), initializer=initializer)
image = tf.nn.conv2d(image, filter=weights, strides=(1, 1, 1, 1), padding='SAME')
image = tf.nn.relu(image)
image = tf.nn.max_pool(image, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1), padding='SAME')
image = tf.reshape(image, shape=(-1, 16 * 16, 32))
image = tf.reduce_mean(image, axis=1)
# LSTM
weights = tf.get_variable(name='W3', shape=(30, 32), initializer=initializer)
caption = tf.nn.embedding_lookup(params=weights, ids=caption)
lstm = tf.contrib.rnn.LSTMCell(num_units=32)
caption, _ = tf.nn.dynamic_rnn(cell=lstm, inputs=caption, dtype=tf.float32)
caption = tf.reduce_mean(caption, axis=1)
# Combination
if return_internals:
return tf.multiply(image, caption), list()
else:
return tf.multiply(image, caption)
### Test own network builder
states = dict(
image=dict(shape=(64, 64, 3), type='float'),
caption=dict(shape=(20,), type='int')
)
agent = DQNAgent(
states=states,
actions=actions,
network=CustomNetwork,
memory=dict(
type='replay',
include_next_states=True,
capacity=100
)
)
agent.close()
### Code block: LSTM function
from tensorforce.core.networks import Layer
class Lstm(Layer):
def __init__(self, size, scope='lstm', summary_labels=()):
self.size = size
super(Lstm, self).__init__(scope=scope, summary_labels=summary_labels)
def tf_apply(self, x, update, state):
state = tf.contrib.rnn.LSTMStateTuple(c=state[:, 0, :], h=state[:, 1, :])
self.lstm_cell = tf.contrib.rnn.LSTMCell(num_units=self.size)
x, state = self.lstm_cell(inputs=x, state=state)
state = tf.stack(values=(state.c, state.h), axis=1)
return x, dict(state=state)
def internals_spec(self):
return dict(state=dict(
type='float',
shape=(2, self.size),
initialization='zeros'
))
### Test LSTM
states = dict(shape=(10,), type='float')
network_spec = [
{'type': 'flatten'},
{'type': Lstm, 'size': 10}
]
agent = DQNAgent(
states=states,
actions=actions,
network=network_spec,
update_mode=dict(
unit='timesteps',
batch_size=100,
frequency=4
),
memory=dict(
type='replay',
include_next_states=True,
capacity=100
)
)
agent.close()
### Preprocessing configuration
states = dict(shape=(84, 84, 3), type='float')
states_preprocessing_spec = [
dict(
type='image_resize',
width=84,
height=84
),
dict(
type='grayscale'
),
dict(
type='normalize'
)
# sequence preprocessing is temporarily broken
# ,
# dict(
# type='sequence',
# length=4
# )
]
### Test preprocessing configuration
agent = DQNAgent(
states=states,
actions=actions,
network=network_spec,
memory=dict(
type='replay',
include_next_states=True,
capacity=100
),
target_sync_frequency=50,
states_preprocessing=states_preprocessing_spec
)
agent.close()
### Code block: Continuous action exploration
exploration = dict(
type='ornstein_uhlenbeck',
sigma=0.1,
mu=0.0,
theta=0.1
)
### Test continuous action exploration
agent = DQNAgent(
states=states,
actions=actions,
network=network_spec,
memory=dict(
type='replay',
include_next_states=True,
capacity=100
),
actions_exploration=exploration
)
agent.close()
### Code block: Discrete action exploration
exploration = dict(
type='epsilon_decay',
initial_epsilon=1.0,
final_epsilon=0.01,
timesteps=1e6
)
### Test discrete action exploration
agent = DQNAgent(
states=states,
actions=actions,
network=network_spec,
memory=dict(
type='replay',
include_next_states=True,
capacity=100
),
actions_exploration=exploration
)
agent.close()
def test_blogpost_introduction_runner(self):
from tensorforce.tests.minimal_test import MinimalTest
from tensorforce.agents import DQNAgent
from tensorforce.execution import Runner
environment = MinimalTest(specification={'int': ()})
network_spec = [
dict(type='dense', size=32)
]
agent = DQNAgent(
states=environment.states,
actions=environment.actions,
network=network_spec,
memory=dict(
type='replay',
include_next_states=True,
capacity=100
),
target_sync_frequency=50
)
runner = Runner(agent=agent, environment=environment)
def episode_finished(runner):
if runner.episode % 100 == 0:
print(sum(runner.episode_rewards[-100:]) / 100)
return runner.episode < 100 \
or not all(reward >= 1.0 for reward in runner.episode_rewards[-100:])
# runner.run(episodes=1000, episode_finished=episode_finished)
runner.run(episodes=10, episode_finished=episode_finished) # Only 10 episodes for this test
runner.close()
### Code block: next
agent = DQNAgent(
states=environment.states,
actions=environment.actions,
network=network_spec,
memory=dict(
type='replay',
include_next_states=True,
capacity=100
),
target_sync_frequency=50
)
# max_episodes = 1000
max_episodes = 10 # Only 10 episodes for this test
max_timesteps = 2000
episode = 0
episode_rewards = list()
while True:
state = environment.reset()
agent.reset()
timestep = 0
episode_reward = 0
while True:
action = agent.act(states=state)
state, terminal, reward = environment.execute(actions=action)
agent.observe(terminal=terminal, reward=reward)
timestep += 1
episode_reward += reward
if terminal or timestep == max_timesteps:
break
episode += 1
episode_rewards.append(episode_reward)
if all(reward >= 1.0 for reward in episode_rewards[-100:]) or episode == max_episodes:
break
agent.close()
environment.close()