forked from harvitronix/reinforcement-learning-car
-
Notifications
You must be signed in to change notification settings - Fork 0
/
learning.py
217 lines (172 loc) · 6.66 KB
/
learning.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
from flat_game import carmunk
import numpy as np
import random
import csv
from nn import neural_net, LossHistory
import os.path
import timeit
NUM_INPUT = 3
GAMMA = 0.9 # Forgetting.
TUNING = False # If False, just use arbitrary, pre-selected params.
def train_net(model, params):
filename = params_to_filename(params)
observe = 1000 # Number of frames to observe before training.
epsilon = 1
train_frames = 1000000 # Number of frames to play.
batchSize = params['batchSize']
buffer = params['buffer']
# Just stuff used below.
max_car_distance = 0
car_distance = 0
t = 0
data_collect = []
replay = [] # stores tuples of (S, A, R, S').
loss_log = []
# Create a new game instance.
game_state = carmunk.GameState()
# Get initial state by doing nothing and getting the state.
_, state = game_state.frame_step((2))
# Let's time it.
start_time = timeit.default_timer()
# Run the frames.
while t < train_frames:
t += 1
car_distance += 1
# Choose an action.
if random.random() < epsilon or t < observe:
action = np.random.randint(0, 3) # random
else:
# Get Q values for each action.
qval = model.predict(state, batch_size=1)
action = (np.argmax(qval)) # best
# Take action, observe new state and get our treat.
reward, new_state = game_state.frame_step(action)
# Experience replay storage.
replay.append((state, action, reward, new_state))
# If we're done observing, start training.
if t > observe:
# If we've stored enough in our buffer, pop the oldest.
if len(replay) > buffer:
replay.pop(0)
# Randomly sample our experience replay memory
minibatch = random.sample(replay, batchSize)
# Get training values.
X_train, y_train = process_minibatch(minibatch, model)
# Train the model on this batch.
history = LossHistory()
model.fit(
X_train, y_train, batch_size=batchSize,
nb_epoch=1, verbose=0, callbacks=[history]
)
loss_log.append(history.losses)
# Update the starting state with S'.
state = new_state
# Decrement epsilon over time.
if epsilon > 0.1 and t > observe:
epsilon -= (1/train_frames)
# We died, so update stuff.
if reward == -500:
# Log the car's distance at this T.
data_collect.append([t, car_distance])
# Update max.
if car_distance > max_car_distance:
max_car_distance = car_distance
# Time it.
tot_time = timeit.default_timer() - start_time
fps = car_distance / tot_time
# Output some stuff so we can watch.
print("Max: %d at %d\tepsilon %f\t(%d)\t%f fps" %
(max_car_distance, t, epsilon, car_distance, fps))
# Reset.
car_distance = 0
start_time = timeit.default_timer()
# Save the model every 25,000 frames.
if t % 25000 == 0:
model.save_weights('saved-models/' + filename + '-' +
str(t) + '.h5',
overwrite=True)
print("Saving model %s - %d" % (filename, t))
# Log results after we're done all frames.
log_results(filename, data_collect, loss_log)
def log_results(filename, data_collect, loss_log):
# Save the results to a file so we can graph it later.
with open('results/sonar-frames/learn_data-' + filename + '.csv', 'w') as data_dump:
wr = csv.writer(data_dump)
wr.writerows(data_collect)
with open('results/sonar-frames/loss_data-' + filename + '.csv', 'w') as lf:
wr = csv.writer(lf)
for loss_item in loss_log:
wr.writerow(loss_item)
def process_minibatch(minibatch, model):
"""This does the heavy lifting, aka, the training. It's super jacked."""
X_train = []
y_train = []
# Loop through our batch and create arrays for X and y
# so that we can fit our model at every step.
for memory in minibatch:
# Get stored values.
old_state_m, action_m, reward_m, new_state_m = memory
# Get prediction on old state.
old_qval = model.predict(old_state_m, batch_size=1)
# Get prediction on new state.
newQ = model.predict(new_state_m, batch_size=1)
# Get our best move. I think?
maxQ = np.max(newQ)
y = np.zeros((1, 3))
y[:] = old_qval[:]
# Check for terminal state.
if reward_m != -500: # non-terminal state
update = (reward_m + (GAMMA * maxQ))
else: # terminal state
update = reward_m
# Update the value for the action we took.
y[0][action_m] = update
X_train.append(old_state_m.reshape(NUM_INPUT,))
y_train.append(y.reshape(3,))
X_train = np.array(X_train)
y_train = np.array(y_train)
return X_train, y_train
def params_to_filename(params):
return str(params['nn'][0]) + '-' + str(params['nn'][1]) + '-' + \
str(params['batchSize']) + '-' + str(params['buffer'])
def launch_learn(params):
filename = params_to_filename(params)
print("Trying %s" % filename)
# Make sure we haven't run this one.
if not os.path.isfile('results/sonar-frames/loss_data-' + filename + '.csv'):
# Create file so we don't double test when we run multiple
# instances of the script at the same time.
open('results/sonar-frames/loss_data-' + filename + '.csv', 'a').close()
print("Starting test.")
# Train.
model = neural_net(NUM_INPUT, params['nn'])
train_net(model, params)
else:
print("Already tested.")
if __name__ == "__main__":
if TUNING:
param_list = []
nn_params = [[164, 150], [256, 256],
[512, 512], [1000, 1000]]
batchSizes = [40, 100, 400]
buffers = [10000, 50000]
for nn_param in nn_params:
for batchSize in batchSizes:
for buffer in buffers:
params = {
"batchSize": batchSize,
"buffer": buffer,
"nn": nn_param
}
param_list.append(params)
for param_set in param_list:
launch_learn(param_set)
else:
nn_param = [164, 150]
params = {
"batchSize": 100,
"buffer": 50000,
"nn": nn_param
}
model = neural_net(NUM_INPUT, nn_param)
train_net(model, params)