-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
518 lines (444 loc) · 17 KB
/
index.html
File metadata and controls
518 lines (444 loc) · 17 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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
<!DOCTYPE html>
<html lang="en" hola_ext_inject="disabled"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Friendly qLearning</title>
<!-- jquery and jqueryui -->
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<link href="external/jquery-ui.min.css" rel="stylesheet">
<script src="external/jquery-ui.min.js"></script>
<!--google analytics-->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-72311215-5', 'auto');
ga('send', 'pageview');
</script>
<!-- bootstrap -->
<script src="external/bootstrap.min.js"></script>
<link href="external/bootstrap.min.css" rel="stylesheet">
<!--math notation-->
<script type="text/javascript" async
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
<!-- d3js -->
<script type="text/javascript" src="external/d3.min.js"></script>
<!-- markdown -->
<script type="text/javascript" src="external/marked.js"></script>
<script type="text/javascript" src="external/highlight.pack.js"></script>
<link rel="stylesheet" href="external/highlight_default.css">
<script>hljs.initHighlightingOnLoad();</script>
<style type="text/css"></style>
<link href="./external/style.css" rel="stylesheet">
<!-- rljs -->
<script type="text/javascript" src="lib/rl.js"></script>
<!-- flotjs -->
<script src="external/jquery.flot.min.js"></script>
<!-- environment dynamics -->
<script src="friendly.js"></script>
<script type="application/javascript">
var canvas, ctx;
var agentView = false;
var humanControls = false;
// Draw everything
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.lineWidth = 1;
var agents = w.agents;
// draw walls in environment
ctx.strokeStyle = "rgb(0,0,0)";
ctx.beginPath();
for(var i=0,n=w.walls.length;i<n;i++) {
var q = w.walls[i];
ctx.moveTo(q.p1.x, q.p1.y);
ctx.lineTo(q.p2.x, q.p2.y);
}
ctx.stroke();
// draw agents
// color agent based on reward it is experiencing at the moment // and type of agent
var reward_color = 0;
var atype_color = 0;
ctx.strokeStyle = "rgb(0,0,0)";
for(var i=0,n=agents.length;i<n;i++) {
var a = agents[i];
// draw agents sight
for(var ei=0,ne=a.eyes.length;ei<ne;ei++) {
var e = a.eyes[ei];
var sr = e.sensed_proximity;
if(e.sensed_type === -1) { ctx.strokeStyle = "rgb(200,200,200)"; } // nothing
if(e.sensed_type === 0) { ctx.strokeStyle = "rgb(100,100,100)"; } // wall
if(e.sensed_type === 1) { ctx.strokeStyle = "rgb(150,150,200)"; } // poison lover
if(e.sensed_type === 2) { ctx.strokeStyle = "rgb(150,150,255)"; } // apple lover
if(e.sensed_type === 3) { ctx.strokeStyle = "rgb(255,150,150)"; } // apples
if(e.sensed_type === 4) { ctx.strokeStyle = "rgb(150,255,150)"; } // poison
if(e.sensed_type === 5) { ctx.strokeStyle = "rgb(220,220,220)"; } // poison
ctx.lineWidth=2;
ctx.beginPath();
ctx.moveTo(a.op.x, a.op.y);
ctx.lineTo(a.op.x + sr * Math.sin(a.oangle + e.angle),
a.op.y + sr * Math.cos(a.oangle + e.angle));
ctx.stroke();
// set agent body color
reward_color = a.last_reward*100;
if(a.type === 1) { ctx.fillStyle = "rgb(150,0,0)"; } // likes apples
if(a.type === 2) { ctx.fillStyle = "rgb(0,150,0)"; } // likes poison
ctx.strokeStyle = "rgb(200,200,200)";
ctx.lineWidth=1;
// draw agents body
ctx.beginPath();
ctx.arc(a.op.x, a.op.y, a.rad, 0, Math.PI*2, true);
ctx.fill();
ctx.stroke();
}
}
// draw items
ctx.strokeStyle = "rgb(0,0,0)";
if(!agentView) {
for(var i=0,n=w.items.length;i<n;i++) {
var it = w.items[i];
if(it.type === 3) ctx.fillStyle = "rgb(255, 150, 150)"; //apple
if(it.type === 4) ctx.fillStyle = "rgb(150, 255, 150)"; //poison
if(it.type === 5) ctx.fillStyle = "rgb(220, 220, 220)"; //flipme
ctx.beginPath();
ctx.arc(it.p.x, it.p.y, it.rad, 0, Math.PI*2, true);
ctx.fill();
ctx.stroke();
}
}
}
// Tick the world
var smooth_reward_history = []; // [][];
var smooth_reward = [];
var flott = 0;
function tick() {
if(simspeed === 3) {
for(var k=0;k<200;k++) {
w.tick();
}
} else {
w.tick();
}
draw();
updateStats();
flott += 1;
for(i=0; i<w.agents.length; i++) {
var rew = w.agents[i].last_reward;
if(!smooth_reward[i]) { smooth_reward[i] = 0; }
smooth_reward[i] = smooth_reward[i] * 0.999 + rew * 0.001;
if(flott === 50) {
// record smooth reward
if(smooth_reward_history[i].length >= nflot) {
smooth_reward_history[i] = smooth_reward_history[i].slice(1);
}
smooth_reward_history[i].push(smooth_reward[i]);
}
}
if(flott === 50) {
flott = 0;
}
var agent = w.agents[0];
if(typeof agent.expi !== 'undefined') {
$("#expi").html(agent.expi);
}
if(typeof agent.tderror !== 'undefined') {
$("#tde").html(agent.tderror.toFixed(3));
}
}
// flot stuff
var nflot = 1000;
function initFlot() {
var container = $("#flotreward");
var res = getFlotRewards(0);
var res1 = getFlotRewards(1);
series = [{
data: res,
lines: {fill: true}
}, {
data: res1,
lines: {fill: true}
}];
var plot = $.plot(container, series, {
grid: {
borderWidth: 1,
minBorderMargin: 20,
labelMargin: 10,
backgroundColor: {
colors: ["#FFF", "#e4f4f4"]
},
margin: {
top: 10,
bottom: 10,
left: 10,
}
},
xaxis: {
min: 0,
max: nflot
},
yaxis: {
min: -0.10,
max: 0.10
}
});
setInterval(function(){
for(var i=0; i<w.agents.length; i++) {
series[i].data = getFlotRewards(i);
}
plot.setData(series);
plot.draw();
}, 100);
}
function getFlotRewards(agentId) {
// zip rewards into flot data
var res = [];
if(agentId >= w.agents.length || !smooth_reward_history[agentId]) {
return res;
}
for(var i=0,n=smooth_reward_history[agentId].length;i<n;i++) {
res.push([i, smooth_reward_history[agentId][i]]);
}
return res;
}
var simspeed = 2;
function goveryfast() {
window.clearInterval(current_interval_id);
current_interval_id = setInterval(tick, 0);
skipdraw = true;
simspeed = 3;
}
function gofast() {
window.clearInterval(current_interval_id);
current_interval_id = setInterval(tick, 0);
skipdraw = true;
simspeed = 2;
}
function gonormal() {
window.clearInterval(current_interval_id);
current_interval_id = setInterval(tick, 30);
skipdraw = false;
simspeed = 1;
}
function goslow() {
window.clearInterval(current_interval_id);
current_interval_id = setInterval(tick, 200);
skipdraw = false;
simspeed = 0;
}
function saveAgent() {
var json = {};
for(var b=0,nb=w.agents.length;b<nb;b++) {
var agent_i = {};
agent_i['brain_' + b] = w.agents[b].brain.toJSON();
agent_i['type_' + b] = w.agents[b].type;
json['agent_' + b] = agent_i;
}
$("#mysterybox").fadeIn();
$("#mysterybox").val(JSON.stringify(json));
}
function resetAgent() {
eval($("#agentspec").val())
w.agents = [];
for(var k = 0; k < 2; k++) {
var a = new Agent();
a.brain = new RL.DQNAgent(env, spec); // give agent a TD brain
w.agents.push(a);
}
}
function loadAgents() {
$.getJSON( "agentzoo/flipme.json", function( data ) {
console.log(data);
var agent0 = w.agents[0].brain;
agent0.fromJSON(data.agent_0.brain_0); // cross your fingers...
w.agents[0].type = data.agent_0.type_0;
// set epsilon to be much lower for more optimal behavior
agent0.epsilon = 0.20;
//same for second agent
var agent1 = w.agents[1].brain;
agent1.fromJSON(data.agent_1.brain_1); // cross your fingers...
w.agents[1].type = data.agent_1.type_1;
agent1.epsilon = 0.20;
$("#eps_slider").slider('value', agent0.epsilon);
$("#eps").html(agent0.epsilon.toFixed(2));
// kill learning rate to not learn
agent0.alpha = 0.000;
agent1.alpha = 0.000;
$("#alpha_slider").slider('value', agent0.alpha);
$("#alpha").html(agent0.alpha.toFixed(2));
});
}
function toggleAgentView() {
agentView = !agentView;
}
var w; // global world object
var current_interval_id;
var skipdraw = false;
function start() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
eval($("#agentspec").val())
w = new World();
var a = new Agent();
env = a;
// hive_mind = new RL.DQNAgent(env, spec);
w.agents = [];
for(var k = 0; k < 2; k++) {
var a = new Agent();
a.brain = new RL.DQNAgent(env, spec); // give agent a TD brain
//a.brain = new RL.RecurrentReinforceAgent(env, {});
w.agents.push(a);
smooth_reward_history.push([]);
}
// epsilon slider
$( "#eps_slider" ).slider({
min: 0,
max: 1,
value: w.agents[0].brain.epsilon,
step: 0.01,
slide: function(event, ui) {
w.agents[0].brain.epsilon = ui.value;
w.agents[1].brain.epsilon = ui.value;
$("#eps").html(ui.value.toFixed(2));
}
});
$("#eps").html(w.agents[0].brain.epsilon.toFixed(2));
$("#eps_slider").slider('value', w.agents[0].brain.epsilon);
// item density slider
$( "#density_slider" ).slider({
min: 0,
max: 500,
value: 300,
step: 1,
slide: function(event, ui) {
w.nitems = ui.value;
$("#density").html(ui.value);
}
});
$("#density").html(w.nitems);
$("#density_slider").slider('value', w.nitems);
// alpha slider
$( "#alpha_slider" ).slider({
min: 0,
max: .05,
value: .005,
step: .0001,
slide: function(event, ui) {
w.agents[0].brain.alpha = ui.value.toFixed(4);
w.agents[1].brain.alpha = ui.value.toFixed(4);
$("#alpha").html(ui.value.toFixed(4));
}
});
$("#alpha").html(w.agents[0].brain.alpha);
$("#alpha_slider").slider('value', w.agents[0].brain.alpha);
initFlot();
loadAgents();
gofast();
// render markdownclass="active"
$(".md").each(function(){
$(this).html(marked($(this).html()));
});
renderJax();
}
var jaxrendered = false;
function renderJax() {
if(jaxrendered) { return; }
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
jaxrendered = true;
})();
}
function updateStats() {
var stats = "<p>";
for(var i=0; i<w.agents.length; i++) {
var a = w.agents[i];
var loves = "apples";
if (a.type === 2) {
loves = "poison";
}
stats += "Player " + (i+1) + ": " + a.apples + " apples, " + a.poison + " poison (loves " + loves + ")<br>";
}
stats += "</p>";
$("#apples_and_poison").html(stats);
}
</script>
<style type="text/css">
canvas { border: 1px solid white; }
</style>
</head>
<body onload="start();">
<a href="https://github.com/greydanus/friendly_qlearning"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
<div id="header">
<h1><b>Friendly qLearning</b>: Exploring social behavior with qLearning agents</h1>
<div style="clear:both;"></div>
</div>
<div class="sechighlight">
<div class="container sec">
<h2>Summary</h2>
<div id="coursedesc">
This is a project I designed in order to study how qlearning networks learn to interact with each other. JavaScript library and much of the world's physics taken from a <a href="https://cs.stanford.edu/people/karpathy/reinforcejs/">project</a> by Andrej Karpathy.
</div>
</div>
</div>
<!-- DEMO STARTS HERE -->
<div class="maintext" style="text-align:center">
<div style="text-align:center;">
<button class="btn btn-danger" onclick="resetAgent()" style="width:150px;height:30px;margin-bottom:5px;">Reinit agent</button>
<button class="btn btn-success" onclick="goveryfast()" style="width:150px;height:30px;margin-bottom:5px;">Go very fast</button>
<button class="btn btn-success" onclick="gofast()" style="width:150px;height:30px;margin-bottom:5px;">Go fast</button>
<button class="btn btn-success" onclick="gonormal()" style="width:150px;height:30px;margin-bottom:5px;">Go normal</button>
<button class="btn btn-success" onclick="goslow()" style="width:150px;height:30px;margin-bottom:5px;">Go slow</button>
<br>
<button class="btn btn-primary" onclick="loadAgents()" style="width:200px;height:30px;margin-bottom:5px;margin-right:20px;">Load Pretrained Agents</button>
<button class="btn btn-primary" onclick="saveAgent()" style="width:200px;height:30px;margin-bottom:5px;margin-right:20px;">Save Agents</button>
<br>
<br>
Exploration epsilon: <span id="eps">0.15</span> <div style="width:70%;margin-left:auto;margin-right:auto" id="eps_slider"></div>
Item density: <span id="density">300</span> <div style="width:70%;margin-left:auto;margin-right:auto" id="density_slider"></div>
Learning rate alpha: <span id="alpha">0.005</span> <div style="width:70%;margin-left:auto;margin-right:auto" id="alpha_slider"></div>
<br>
<canvas id="canvas" width="700" height="500"></canvas>
</div>
<div id="apples_and_poison"></div>
<div id="brain_info_div"></div>
<br>
<br>
<div id="expi"></div>
<div id="tde"></div>
<textarea id="agentspec" style="width:70%;height:250px">
// agent parameter spec to play with (this gets eval()'d on Agent reset)
var spec = {}
spec.update = 'qlearn'; // qlearn | sarsa
spec.gamma = 0.9; // discount factor, [0, 1)
spec.epsilon = 0.2; // initial epsilon for epsilon-greedy policy, [0, 1)
spec.alpha = 0.005; // value function learning rate
spec.experience_add_every = 5; // number of time steps before we add another experience to replay memory
spec.experience_size = 10000; // size of experience
spec.learning_steps_per_iteration = 5;
spec.tderror_clamp = 1.0; // for robustness
spec.num_hidden_units = 100 // number of neurons in hidden layer
</textarea>
<textarea id="mysterybox" style="width:70%;">agent json data</textarea>
<div id="flotreward" style="width:100%; height:400px;"></div>
</div>
<div class="maintext">
<h3>Social qLearning</h3>
<p>
The items in this world begin as 'flipme' items. The agents come in two types: apple-loving and poison-loving. Once an agent touches one of these items, the item becomes the opposite of what the agent likes. My hope is that two different agents will learn an optimal strategy of 'hanging out' together so that they can flip items for each other's mutual benefit. Yay cooperation!
</p>
<p>
<b>Note</b>. To test whether or not cooperation is happening, click 'Load Pretrained Agent' (or train your own), reduce the epsilon and alpha parameters to 0, and reduce the number of items to 0 or only a small number (such as 10 or 20). You will see the agents interact with one another, but their strategy will perhaps surprise you.
</p>
</div>
<div class="sechighlight">
<div id="footer">
Ongoing project
</div>
</div>
</body></html>