-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdqn.py
More file actions
296 lines (234 loc) · 8.51 KB
/
Copy pathdqn.py
File metadata and controls
296 lines (234 loc) · 8.51 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
<<<<<<< HEAD
=======
<<<<<<< HEAD
>>>>>>> a5c2fc7961c043221138ed8771d55c24576bc46e
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.callbacks import TensorBoard
from keras.optimizers import Adam
<<<<<<< HEAD
from keras.models import load_model
import tensorflow as tf
=======
>>>>>>> a5c2fc7961c043221138ed8771d55c24576bc46e
from collections import deque
import numpy as np
import time
import random
<<<<<<< HEAD
input_shape = (4,)
REPLAY_MEMORY_SIZE = 50_000
MIN_REPLAY_MEMORY_SIZE = 2_000
MINIBATCH_SIZE = 1_024
=======
input_shape = (2,)
REPLAY_MEMORY_SIZE = 50_000
MIN_REPLAY_MEMORY_SIZE = 1_000
MINIBATCH_SIZE = 64
>>>>>>> a5c2fc7961c043221138ed8771d55c24576bc46e
DISCOUNT = 0.99
UPDATE_TARGET_EVERY = 5
MAX_SIZE = 15
<<<<<<< HEAD
class ModifiedTensorBoard(TensorBoard):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.step = 1
self.writer = tf.summary.FileWriter(self.log_dir)
def set_model(self, model):
pass
def on_epoch_end(self, epoch, logs=None):
self.update_stats(**logs)
def on_batch_end(self, batch, logs=None):
pass
def on_train_end(self, _):
pass
def update_stats(self, **stats):
self._write_logs(stats, self.step)
class DQNAgent:
def __init__(self, name):
self.name = name
=======
MODEL_NAME = "4x4x2"
class ModifiedTensorBoard(TensorBoard):
# Overriding init to set initial step and writer (we want one log file for all .fit() calls)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.step = 1
self.writer = tf.summary.FileWriter(self.log_dir)
# Overriding this method to stop creating default log writer
def set_model(self, model):
pass
# Overrided, saves logs with our step number
# (otherwise every .fit() will start writing from 0th step)
def on_epoch_end(self, epoch, logs=None):
self.update_stats(**logs)
# Overrided
# We train for one batch only, no need to save anything at epoch end
def on_batch_end(self, batch, logs=None):
pass
# Overrided, so won't close writer
def on_train_end(self, _):
pass
# Custom method for saving own metrics
# Creates writer, writes custom metrics and closes writer
def update_stats(self, **stats):
self._write_logs(stats, self.step)
class DQNAgent:
def __init__(self):
>>>>>>> a5c2fc7961c043221138ed8771d55c24576bc46e
self.model = self.create_model()
self.target_model = self.create_model()
self.target_model.set_weights(self.model.get_weights())
self.replay_memory = deque(maxlen=REPLAY_MEMORY_SIZE)
<<<<<<< HEAD
self.tensorboard = ModifiedTensorBoard(log_dir=f'boards/{self.name}')
=======
self.tensorboard = ModifiedTensorBoard(log_dir=f"boards/{MODEL_NAME}-{int(time.time())}")
>>>>>>> a5c2fc7961c043221138ed8771d55c24576bc46e
self.target_update_counter = 0
def create_model(self):
model = Sequential()
<<<<<<< HEAD
model.add(Dense(3, input_shape=input_shape, activation="relu"))
=======
model.add(Dense(4, input_shape=input_shape))
model.add(Activation("relu"))
model.add(Dense(4))
model.add(Activation("relu"))
model.add(Dropout(0.2))
>>>>>>> a5c2fc7961c043221138ed8771d55c24576bc46e
model.add(Dense(2, activation="linear"))
model.compile(loss="mse", optimizer=Adam(lr=0.001), metrics=['accuracy'])
return model
<<<<<<< HEAD
def load(self, path):
self.model = load_model(path)
=======
def update_replay_memory(self, transition):
self.replay_memory.append(transition)
def get_qs(self, state):
return self.model_predict(np.array(state).reshape(-1, *state.shape) / MAX_SIZE)[0]
def train(self, terminal_state, step):
if len(self.replay_memory) < MIN_REPLAY_MEMORY_SIZE: return
minibatch = random.sample(self.replay_memory, MINIBATCH_SIZE)
current_states = np.array([transition[0] for transition in minibatch]) / MAX_SIZE
current_qs_list = self.model.predict(current_states)
new_current_states = np.array([transition[3] for transition in minibatch]) / MAX_SIZE
future_qs_list = self.target_model.predict(new_current_states)
X = []
y = []
for index, (current_state, action, reward, new_current_state, done) in enumerate(minibatch):
if not done:
max_future_q = np.max(future_qs_list[index])
new_q = reward + DISCOUNT * max_future_q
else:
new_q = reward
current_qs = current_qs_list[index]
current_qs[action] = new_q
X.append(current_state)
y.append(current_qs)
self.model.fit(np.array(X) / MAX_SIZE, np.array(y), batch_size=MINIBATCH_SIZE, verbose=0, shuffle=False, callbacks=[self.tensorboard] if terminal_state else None)
# Update target_model
if terminal_state:
self.target_update_counter += 1
if self.target_update_counter > UPDATE_TARGET_EVERY:
self.target_model.set_weights(self.model.get_weights())
=======
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.callbacks import TensorBoard
from keras.optimizers import Adam
from collections import deque
import numpy as np
import time
import random
input_shape = (2,)
REPLAY_MEMORY_SIZE = 50_000
MIN_REPLAY_MEMORY_SIZE = 1_000
MINIBATCH_SIZE = 64
DISCOUNT = 0.99
UPDATE_TARGET_EVERY = 5
MAX_SIZE = 15
MODEL_NAME = "4x4x2"
class ModifiedTensorBoard(TensorBoard):
# Overriding init to set initial step and writer (we want one log file for all .fit() calls)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.step = 1
self.writer = tf.summary.FileWriter(self.log_dir)
# Overriding this method to stop creating default log writer
def set_model(self, model):
pass
# Overrided, saves logs with our step number
# (otherwise every .fit() will start writing from 0th step)
def on_epoch_end(self, epoch, logs=None):
self.update_stats(**logs)
# Overrided
# We train for one batch only, no need to save anything at epoch end
def on_batch_end(self, batch, logs=None):
pass
# Overrided, so won't close writer
def on_train_end(self, _):
pass
# Custom method for saving own metrics
# Creates writer, writes custom metrics and closes writer
def update_stats(self, **stats):
self._write_logs(stats, self.step)
class DQNAgent:
def __init__(self):
self.model = self.create_model()
self.target_model = self.create_model()
self.target_model.set_weights(self.model.get_weights())
self.replay_memory = deque(maxlen=REPLAY_MEMORY_SIZE)
self.tensorboard = ModifiedTensorBoard(log_dir=f"boards/{MODEL_NAME}-{int(time.time())}")
self.target_update_counter = 0
def create_model(self):
model = Sequential()
model.add(Dense(4, input_shape=input_shape))
model.add(Activation("relu"))
model.add(Dense(4))
model.add(Activation("relu"))
model.add(Dropout(0.2))
model.add(Dense(2, activation="linear"))
model.compile(loss="mse", optimizer=Adam(lr=0.001), metrics=['accuracy'])
return model
>>>>>>> a5c2fc7961c043221138ed8771d55c24576bc46e
def update_replay_memory(self, transition):
self.replay_memory.append(transition)
def get_qs(self, state):
<<<<<<< HEAD
return self.model.predict(np.array(state).reshape(-1, *state.shape) / MAX_SIZE)[0]
=======
return self.model_predict(np.array(state).reshape(-1, *state.shape) / MAX_SIZE)[0]
>>>>>>> a5c2fc7961c043221138ed8771d55c24576bc46e
def train(self, terminal_state, step):
if len(self.replay_memory) < MIN_REPLAY_MEMORY_SIZE: return
minibatch = random.sample(self.replay_memory, MINIBATCH_SIZE)
current_states = np.array([transition[0] for transition in minibatch]) / MAX_SIZE
current_qs_list = self.model.predict(current_states)
new_current_states = np.array([transition[3] for transition in minibatch]) / MAX_SIZE
future_qs_list = self.target_model.predict(new_current_states)
X = []
y = []
for index, (current_state, action, reward, new_current_state, done) in enumerate(minibatch):
if not done:
max_future_q = np.max(future_qs_list[index])
new_q = reward + DISCOUNT * max_future_q
else:
new_q = reward
current_qs = current_qs_list[index]
current_qs[action] = new_q
X.append(current_state)
y.append(current_qs)
self.model.fit(np.array(X) / MAX_SIZE, np.array(y), batch_size=MINIBATCH_SIZE, verbose=0, shuffle=False, callbacks=[self.tensorboard] if terminal_state else None)
# Update target_model
if terminal_state:
self.target_update_counter += 1
if self.target_update_counter > UPDATE_TARGET_EVERY:
self.target_model.set_weights(self.model.get_weights())
<<<<<<< HEAD
=======
>>>>>>> d7063b3b83a5f01b86467f8c0c906e4a4acd70b5
>>>>>>> a5c2fc7961c043221138ed8771d55c24576bc46e
self.target_update_counter = 0