-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassignment2.py
More file actions
312 lines (280 loc) · 8.97 KB
/
Copy pathassignment2.py
File metadata and controls
312 lines (280 loc) · 8.97 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
''' Assignment: Planning & Reinforcement Learning Assignment 2
By: Justus Hübotter (2617135), Florence van der Voort (2652198), Stefan Wijtsma (2575874)
Created @ April 2019'''
import main
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
plt.style.use('ggplot')
RUNS = 100
EPISODES = 3000
LEARNING_RATE = 0.1
def task8():
print('TASK 8:')
print(f'{RUNS} Runs of Q learning on {EPISODES} episodes.')
results = {}
time = {}
for i in [0.01, 0.1]:
for j in [1., 0.999]:
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.q_learning(R, Q, V, states, actions, lr=LEARNING_RATE, epsilon=i, e_decay=j, n_episodes=EPISODES)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'epsilon = %.2f, decay = %.3f' % (i, j): run})
time.update({'epsilon = %.2f, decay = %.3f' % (i, j): runtimes})
for k, v in time.items():
print(k)
print('Mean runtime [ms] +- SE: %.2f (+- %.2f)' % (np.mean(v), np.std(v)/np.sqrt(RUNS)))
print()
print('Task 8 complete.')
print()
return results
def task9():
print('TASK 9:')
print(f'{RUNS} Runs of Soft Max exploration strategy on {EPISODES} episodes.')
results = {}
time = {}
for i in [1.0, 20.0, 50.0]:
for j in [1., 0.999]:
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.soft_max(R, Q, V, states, actions, lr=LEARNING_RATE, temperature=i, t_decay=j, n_episodes=EPISODES)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'temp = %.1f, decay = %.3f' % (i, j): run})
time.update({'temp = %.1f, decay = %.3f' % (i, j): runtimes})
for k, v in time.items():
print(k)
print('Mean runtime [ms] +- SE: %.2f (+- %.2f)' % (np.mean(v), np.std(v)/np.sqrt(RUNS)))
print()
print('Task 9 complete.')
print()
return results
def task10():
print('TASK 10:')
print(f'{RUNS} Runs of SARSA on {EPISODES} episodes.')
results = {}
time = {}
for i in [0.01, 0.1]:
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.sarsa(R, Q, V, states, actions, lr=LEARNING_RATE, epsilon=i, n_episodes=EPISODES)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'epsilon = %.3f' % i: run})
time.update({'epsilon = %.2f' % i: runtimes})
for k, v in time.items():
print(k)
print('Mean runtime [ms] +- SE: %.2f (+- %.2f)' % (np.mean(v), np.std(v)/np.sqrt(RUNS)))
print()
print('Task 10 complete.')
print()
return results
def task11():
# THIS FUNCTION IS NOT DONE AND WILL NOT YIELD THE EXPECTED OUTPUT!
print('TASK 11:')
print(f'{RUNS} Runs of Q learning with experience replay on {EPISODES} episodes.')
results = {}
time = {}
for i in [0.01, 0.1]:
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.q_learning_er(R, Q, V, states, actions, lr=LEARNING_RATE, epsilon=i, n_episodes=EPISODES)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'epsilon = %.3f' % i: run})
time.update({'epsilon = %.2f' % i: runtimes})
print('Task 11 complete.')
print()
return results
def task12():
print('TASK 12:')
print(f'{RUNS} Runs of Q learning with eligibility traces on {EPISODES} episodes.')
results = {}
time = {}
for i in [0.01, 0.1]:
for j in [0.5, 1.]:
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.q_learning_et(R, Q, V, states, actions, lr=LEARNING_RATE, epsilon=i, n_episodes=EPISODES, lamb=j)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'epsilon = %.3f, lambda = %.1f' % (i,j): run})
time.update({'epsilon = %.3f, lambda = %.1f' % (i,j): runtimes})
for k, v in time.items():
print(k)
print('Mean runtime [ms] +- SE: %.2f (+- %.2f)' % (np.mean(v), np.std(v)/np.sqrt(RUNS)))
print()
print('Task 12 complete.')
print()
return results
def task14c():
print('TASK 14c:')
print(f'{RUNS} Runs of double Q learning on {EPISODES} episodes.')
results = {}
time = {}
for i in [0.01, 0.1]:
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.double_q_learning(R, Q, V, states, actions, lr=LEARNING_RATE, epsilon=i, n_episodes=EPISODES)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'epsilon = %.3f' % i: run})
time.update({'epsilon = %.2f' % i: runtimes})
for k, v in time.items():
print(k)
print('Mean runtime [ms] +- SE: %.2f (+- %.2f)' % (np.mean(v), np.std(v)/np.sqrt(RUNS)))
print()
print('Task 14c complete.')
print()
return results
def comparison():
print('COMPARISON:')
print(f'{RUNS} Runs of all algorithms on {EPISODES} episodes.')
results = {}
time = {}
i = 0.01
t = 20
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.soft_max(R, Q, V, states, actions, lr=LEARNING_RATE, temperature=t, n_episodes=EPISODES)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'Soft Max': run})
time.update({'Soft Max': runtimes})
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.q_learning(R, Q, V, states, actions, lr=LEARNING_RATE, epsilon=i, n_episodes=EPISODES)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'Q Learning': run})
time.update({'Q Learning': runtimes})
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.double_q_learning(R, Q, V, states, actions, lr=LEARNING_RATE, epsilon=i, n_episodes=EPISODES)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'Double Q Learning': run})
time.update({'Double Q Learning': runtimes})
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.q_learning_et(R, Q, V, states, actions, lr=LEARNING_RATE, epsilon=i, n_episodes=EPISODES)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'Q Learning ET': run})
time.update({'Q Learning ET': runtimes})
run = []
runtimes = []
for k in range(RUNS):
R, Q, V, states, actions = main.initialize(init=0)
#print('Run', k+1)
Gs, runtime = main.q_learning(R, Q, V, states, actions, lr=LEARNING_RATE, epsilon=i, n_episodes=EPISODES)
run.append(Gs)
runtimes.append(runtime)
#print('\n\n')
results.update({'SARSA': run})
time.update({'SARSA': runtimes})
for k, v in time.items():
print(k)
print('Mean runtime [ms] +- SE: %.2f (+- %.2f)' % (np.mean(v), np.std(v)/np.sqrt(RUNS)))
print()
print('Task 14c complete.')
print()
return results
def plot_results(results, title, savefig=True, smoothing=10):
fig, ax = plt.subplots(1)
for k, v in results.items():
Y = np.array(v)
M = Y.mean(axis=0)
M = pd.Series(M).rolling(window=smoothing, min_periods=1).mean().values #.iloc[smoothing-1:].values
S = Y.std(axis=0) / np.sqrt(RUNS)
X = np.arange(1,len(M)+1)
ax.plot(X, M, label=k)
#ax.fill_between(X, M-S, M+S, alpha=0.5)
#ax.fill_between(X, Y.min(axis=0), Y.max(axis=0), alpha=0.2)
plt.title('Performance of ' + title)
plt.xlabel('Episodes')
plt.ylabel('Mean cumulative reward')
plt.legend()
plt.tight_layout()
if savefig:
plt.savefig('%s_r%i_e%i.png' % (title, RUNS, EPISODES))
else:
plt.show()
def save_results(results, name, a=[9, 99, 999, 1999, EPISODES-1]):
dict_of_df = {k: pd.DataFrame(np.array(v).T) for k,v in results.items()}
df = pd.concat(dict_of_df, axis=1)
df.loc[a].reindex().to_csv('%s_r%i_e%i.csv' % (name, RUNS, EPISODES), index=False, sep=';',mode='w')
if __name__ == '__main__':
results = task8()
plot_results(results, 'Q Learning')
save_results(results, 'Q Learning')
input('Press ENTER to continue')
results = comparison()
plot_results(results, 'Comparison')
save_results(results, 'Comparison')
print('\n\n', 100 * '#', '\n\n')
results = task9()
plot_results(results, 'Soft Max')
save_results(results, 'Soft Max')
input('Press ENTER to continue')
print('\n\n', 100 * '#', '\n\n')
results = task10()
plot_results(results, 'SARSA')
save_results(results, 'SARSA')
input('Press ENTER to continue')
print('\n\n', 100 * '#', '\n\n')
results = task11()
plot_results(results, 'Q Learning ER')
save_results(results, 'Q Learning ER')
input('Press ENTER to continue')
print('\n\n', 100 * '#', '\n\n')
results = task12()
plot_results(results, 'Q Learning ET')
save_results(results, 'Q Learning ET')
input('Press ENTER to continue')
print('\n\n', 100 * '#', '\n\n')
results = task14c()
plot_results(results, 'Double Q Learning')
save_results(results, 'Double Q Learning')