-
Notifications
You must be signed in to change notification settings - Fork 339
/
gridworld_td.html
752 lines (636 loc) · 33.5 KB
/
gridworld_td.html
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>REINFORCEjs: Gridworld with Dynamic Programming</title>
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- jquery and jqueryui -->
<script src="external/jquery-2.1.3.min.js"></script>
<link href="external/jquery-ui.min.css" rel="stylesheet">
<script src="external/jquery-ui.min.js"></script>
<!-- bootstrap -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<!-- 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>
<!-- mathjax : nvm now loading dynamically
<script type="text/javascript"
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
-->
<!-- rljs -->
<script type="text/javascript" src="lib/rl.js"></script>
<!-- flotjs -->
<script src="external/jquery.flot.min.js"></script>
<!-- GA -->
<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','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-3698471-24', 'auto');
ga('send', 'pageview');
</script>
<style>
#wrap {
width:800px;
margin-left: auto;
margin-right: auto;
}
body {
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
}
#draw {
margin-left: 100px;
}
#exp {
margin-top: 20px;
font-size: 16px;
}
h2 {
text-align: center;
font-size: 30px;
}
svg {
cursor: pointer;
}
</style>
<script type="application/javascript">
// Gridworld
var Gridworld = function(){
this.Rarr = null; // reward array
this.T = null; // cell types, 0 = normal, 1 = cliff
this.reset()
}
Gridworld.prototype = {
reset: function() {
// hardcoding one gridworld for now
this.gh = 10;
this.gw = 10;
this.gs = this.gh * this.gw; // number of states
// specify some rewards
var Rarr = R.zeros(this.gs);
var T = R.zeros(this.gs);
Rarr[55] = 1;
Rarr[54] = -1;
//Rarr[63] = -1;
Rarr[64] = -1;
Rarr[65] = -1;
Rarr[85] = -1;
Rarr[86] = -1;
Rarr[37] = -1;
Rarr[33] = -1;
//Rarr[77] = -1;
Rarr[67] = -1;
Rarr[57] = -1;
// make some cliffs
for(q=0;q<8;q++) { var off = (q+1)*this.gh+2; T[off] = 1; Rarr[off] = 0; }
for(q=0;q<6;q++) { var off = 4*this.gh+q+2; T[off] = 1; Rarr[off] = 0; }
T[5*this.gh+2] = 0; Rarr[5*this.gh+2] = 0; // make a hole
this.Rarr = Rarr;
this.T = T;
},
reward: function(s,a,ns) {
// reward of being in s, taking action a, and ending up in ns
return this.Rarr[s];
},
nextStateDistribution: function(s,a) {
// given (s,a) return distribution over s' (in sparse form)
if(this.T[s] === 1) {
// cliff! oh no!
// var ns = 0; // reset to state zero (start)
} else if(s === 55) {
// agent wins! teleport to start
var ns = this.startState();
while(this.T[ns] === 1) {
var ns = this.randomState();
}
} else {
// ordinary space
var nx, ny;
var x = this.stox(s);
var y = this.stoy(s);
if(a === 0) {nx=x-1; ny=y;}
if(a === 1) {nx=x; ny=y-1;}
if(a === 2) {nx=x; ny=y+1;}
if(a === 3) {nx=x+1; ny=y;}
var ns = nx*this.gh+ny;
if(this.T[ns] === 1) {
// actually never mind, this is a wall. reset the agent
var ns = s;
}
}
// gridworld is deterministic, so return only a single next state
return ns;
},
sampleNextState: function(s,a) {
// gridworld is deterministic, so this is easy
var ns = this.nextStateDistribution(s,a);
var r = this.Rarr[s]; // observe the raw reward of being in s, taking a, and ending up in ns
r -= 0.01; // every step takes a bit of negative reward
var out = {'ns':ns, 'r':r};
if(s === 55 && ns === 0) {
// episode is over
out.reset_episode = true;
}
return out;
},
allowedActions: function(s) {
var x = this.stox(s);
var y = this.stoy(s);
var as = [];
if(x > 0) { as.push(0); }
if(y > 0) { as.push(1); }
if(y < this.gh-1) { as.push(2); }
if(x < this.gw-1) { as.push(3); }
return as;
},
randomState: function() { return Math.floor(Math.random()*this.gs); },
startState: function() { return 0; },
getNumStates: function() { return this.gs; },
getMaxNumActions: function() { return 4; },
// private functions
stox: function(s) { return Math.floor(s/this.gh); },
stoy: function(s) { return s % this.gh; },
xytos: function(x,y) { return x*this.gh + y; },
}
// ------
// UI
// ------
var rs = {};
var trs = {};
var tvs = {};
var pas = {};
var cs = 60; // cell size
var initGrid = function() {
var d3elt = d3.select('#draw');
d3elt.html('');
rs = {};
trs = {};
tvs = {};
pas = {};
var gh= env.gh; // height in cells
var gw = env.gw; // width in cells
var gs = env.gs; // total number of cells
var w = 600;
var h = 600;
svg = d3elt.append('svg').attr('width', w).attr('height', h)
.append('g').attr('transform', 'scale(1)');
// define a marker for drawing arrowheads
svg.append("defs").append("marker")
.attr("id", "arrowhead")
.attr("refX", 3)
.attr("refY", 2)
.attr("markerWidth", 3)
.attr("markerHeight", 4)
.attr("orient", "auto")
.append("path")
.attr("d", "M 0,0 V 4 L3,2 Z");
for(var y=0;y<gh;y++) {
for(var x=0;x<gw;x++) {
var xcoord = x*cs;
var ycoord = y*cs;
var s = env.xytos(x,y);
var g = svg.append('g');
// click callbackfor group
g.on('click', function(ss) {
return function() { cellClicked(ss); } // close over s
}(s));
// set up cell rectangles
var r = g.append('rect')
.attr('x', xcoord)
.attr('y', ycoord)
.attr('height', cs)
.attr('width', cs)
.attr('fill', '#FFF')
.attr('stroke', 'black')
.attr('stroke-width', 2);
rs[s] = r;
// reward text
var tr = g.append('text')
.attr('x', xcoord + 5)
.attr('y', ycoord + 55)
.attr('font-size', 10)
.text('');
trs[s] = tr;
// skip rest for cliffs
if(env.T[s] === 1) { continue; }
// value text
var tv = g.append('text')
.attr('x', xcoord + 5)
.attr('y', ycoord + 20)
.text('');
tvs[s] = tv;
// policy arrows
pas[s] = []
for(var a=0;a<4;a++) {
var pa = g.append('line')
.attr('x1', xcoord)
.attr('y1', ycoord)
.attr('x2', xcoord)
.attr('y2', ycoord)
.attr('stroke', 'black')
.attr('stroke-width', '2')
.attr("marker-end", "url(#arrowhead)");
pas[s].push(pa);
}
}
}
// append agent position circle
svg.append('circle')
.attr('cx', -100)
.attr('cy', -100)
.attr('r', 15)
.attr('fill', '#FF0')
.attr('stroke', '#000')
.attr('id', 'cpos');
}
var drawGrid = function() {
var gh= env.gh; // height in cells
var gw = env.gw; // width in cells
var gs = env.gs; // total number of cells
var sx = env.stox(state);
var sy = env.stoy(state);
d3.select('#cpos')
.attr('cx', sx*cs+cs/2)
.attr('cy', sy*cs+cs/2);
// updates the grid with current state of world/agent
for(var y=0;y<gh;y++) {
for(var x=0;x<gw;x++) {
var xcoord = x*cs;
var ycoord = y*cs;
var r=255,g=255,b=255;
var s = env.xytos(x,y);
// get value of state s under agent policy
if(typeof agent.V !== 'undefined') {
var vv = agent.V[s];
} else if(typeof agent.Q !== 'undefined'){
var poss = env.allowedActions(s);
var vv = -1;
for(var i=0,n=poss.length;i<n;i++) {
var qsa = agent.Q[poss[i]*gs+s];
if(i === 0 || qsa > vv) { vv = qsa; }
}
}
// var poss = env.allowedActions(s);
// var vv = -1;
// for(var i=0,n=poss.length;i<n;i++) {
// var qsa = agent.e[poss[i]*gs+s];
// if(i === 0 || qsa > vv) { vv = qsa; }
// }
var ms = 100;
if(vv > 0) { g = 255; r = 255 - vv*ms; b = 255 - vv*ms; }
if(vv < 0) { g = 255 + vv*ms; r = 255; b = 255 + vv*ms; }
var vcol = 'rgb('+Math.floor(r)+','+Math.floor(g)+','+Math.floor(b)+')';
if(env.T[s] === 1) { vcol = "#AAA"; rcol = "#AAA"; }
// update colors of rectangles based on value
var r = rs[s];
if(s === selected) {
// highlight selected cell
r.attr('fill', '#FF0');
} else {
r.attr('fill', vcol);
}
// write reward texts
var rv = env.Rarr[s];
var tr = trs[s];
if(rv !== 0) {
tr.text('R ' + rv.toFixed(1))
}
// skip rest for cliff
if(env.T[s] === 1) continue;
// write value
var tv = tvs[s];
tv.text(vv.toFixed(2));
// update policy arrows
var paa = pas[s];
for(var a=0;a<4;a++) {
var pa = paa[a];
var prob = agent.P[a*gs+s];
if(prob < 0.01) { pa.attr('visibility', 'hidden'); }
else { pa.attr('visibility', 'visible'); }
var ss = cs/2 * prob * 0.9;
if(a === 0) {nx=-ss; ny=0;}
if(a === 1) {nx=0; ny=-ss;}
if(a === 2) {nx=0; ny=ss;}
if(a === 3) {nx=ss; ny=0;}
pa.attr('x1', xcoord+cs/2)
.attr('y1', ycoord+cs/2)
.attr('x2', xcoord+cs/2+nx)
.attr('y2', ycoord+cs/2+ny);
}
}
}
}
var selected = -1;
var cellClicked = function(s) {
if(s === selected) {
selected = -1; // toggle off
$("#creward").html('(select a cell)');
} else {
selected = s;
$("#creward").html(env.Rarr[s].toFixed(2));
$("#rewardslider").slider('value', env.Rarr[s]);
}
drawGrid(); // redraw
}
var goslow = function() {
steps_per_tick = 1;
}
var gonormal = function(){
steps_per_tick = 10;
}
var gofast = function() {
steps_per_tick = 25;
}
var steps_per_tick = 1;
var sid = -1;
var nsteps_history = [];
var nsteps_counter = 0;
var nflot = 1000;
var tdlearn = function() {
if(sid === -1) {
sid = setInterval(function(){
for(var k=0;k<steps_per_tick;k++) {
var a = agent.act(state); // ask agent for an action
var obs = env.sampleNextState(state, a); // run it through environment dynamics
agent.learn(obs.r); // allow opportunity for the agent to learn
state = obs.ns; // evolve environment to next state
nsteps_counter += 1;
if(typeof obs.reset_episode !== 'undefined') {
agent.resetEpisode();
// record the reward achieved
if(nsteps_history.length >= nflot) {
nsteps_history = nsteps_history.slice(1);
}
nsteps_history.push(nsteps_counter);
nsteps_counter = 0;
}
}
// keep track of reward history
drawGrid(); // draw
}, 20);
} else {
clearInterval(sid);
sid = -1;
}
}
function resetAgent() {
eval($("#agentspec").val())
agent = new RL.TDAgent(env, spec);
$("#slider").slider('value', agent.epsilon);
$("#eps").html(agent.epsilon.toFixed(2));
state = env.startState(); // move state to beginning too
drawGrid();
}
function resetAll() {
env.reset();
agent.reset();
drawGrid();
}
function initGraph() {
var container = $("#flotreward");
var res = getFlotRewards();
series = [{
data: res,
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,
max: 1000
}
});
setInterval(function(){
series[0].data = getFlotRewards();
plot.setData(series);
plot.draw();
}, 100);
}
function getFlotRewards() {
// zip rewards into flot data
var res = [];
for(var i=0,n=nsteps_history.length;i<n;i++) {
res.push([i, nsteps_history[i]]);
}
return res;
}
var state;
var agent, env;
function start() {
env = new Gridworld(); // create environment
state = env.startState();
eval($("#agentspec").val())
agent = new RL.TDAgent(env, spec);
//agent = new RL.ActorCriticAgent(env, {'gamma':0.9, 'epsilon':0.2});
// slider sets agent epsilon
$( "#slider" ).slider({
min: 0,
max: 1,
value: agent.epsilon,
step: 0.01,
slide: function(event, ui) {
agent.epsilon = ui.value;
$("#eps").html(ui.value.toFixed(2));
}
});
$("#rewardslider").slider({
min: -5,
max: 5.1,
value: 0,
step: 0.1,
slide: function(event, ui) {
if(selected >= 0) {
env.Rarr[selected] = ui.value;
$("#creward").html(ui.value.toFixed(2));
drawGrid();
} else {
$("#creward").html('(select a cell)');
}
}
});
$("#eps").html(agent.epsilon.toFixed(2));
$("#slider").slider('value', agent.epsilon);
// render markdown
$(".md").each(function(){
$(this).html(marked($(this).html()));
});
renderJax();
initGrid();
drawGrid();
initGraph();
}
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;
})();
}
</script>
</head>
<body onload="start();">
<a href="https://github.com/karpathy/reinforcejs"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>
<div id="wrap">
<div id="mynav" style="border-bottom:1px solid #999; padding-bottom: 10px; margin-bottom:50px;">
<div>
<img src="loop.svg" style="width:50px;height:50px;float:left;">
<h1 style="font-size:50px;">REINFORCE<span style="color:#058;">js</span></h1>
</div>
<ul class="nav nav-pills">
<li role="presentation"><a href="index.html">About</a></li>
<li role="presentation"><a href="gridworld_dp.html">GridWorld: DP</a></li>
<li role="presentation" class="active"><a href="gridworld_td.html">GridWorld: TD</a></li>
<li role="presentation"><a href="puckworld.html">PuckWorld: DQN</a></li>
<li role="presentation"><a href="waterworld.html">WaterWorld: DQN</a></li>
</ul>
</div>
<h2>Temporal Difference Learning Gridworld Demo</h2>
<br>
<textarea id="agentspec" style="width:100%;height:270px;">
// agent parameter spec to play with (this gets eval()'d on Agent reset)
var spec = {}
spec.update = 'qlearn'; // 'qlearn' or 'sarsa'
spec.gamma = 0.9; // discount factor, [0, 1)
spec.epsilon = 0.2; // initial epsilon for epsilon-greedy policy, [0, 1)
spec.alpha = 0.1; // value function learning rate
spec.lambda = 0; // eligibility trace decay, [0,1). 0 = no eligibility traces
spec.replacing_traces = true; // use replacing or accumulating traces
spec.planN = 50; // number of planning steps per iteration. 0 = no planning
spec.smooth_policy_update = true; // non-standard, updates policy smoothly to follow max_a Q
spec.beta = 0.1; // learning rate for smooth policy update
</textarea>
<button class="btn btn-danger" onclick="resetAgent()" style="width:150px;height:50px;margin-bottom:5px;">Reinit agent</button>
<button class="btn btn-primary" onclick="tdlearn()" style="width:170px;height:50px;margin-bottom:5px;">Toggle TD Learning</button>
<button class="btn btn-success" onclick="gofast()" style="width:150px;height:50px;margin-bottom:5px;">Go fast</button>
<button class="btn btn-success" onclick="gonormal()" style="width:150px;height:50px;margin-bottom:5px;">Go normal</button>
<button class="btn btn-success" onclick="goslow()" style="width:150px;height:50px;margin-bottom:5px;">Go slow</button>
<br>
Exploration epsilon: <span id="eps">0.15</span> <div id="slider"></div>
<br><br>
<div id="draw"></div>
<div id="rewardui">
Cell reward: <span id="creward">(select a cell)</span> <div id="rewardslider"></div>
</div>
<div>
Number of actions before reaching the goal state (low is good):
<div id="flotreward" style="width:800px; height: 400px;"></div>
</div>
<div id="exp" class="md">
### Setup
(*Copy-pasted from Dynamic Programming demo*). This is a toy environment called **Gridworld** that is often used as a toy model in the Reinforcement Learning literature. In this particular case:
- **State space**: GridWorld has 10x10 = 100 distinct states. The start state is the top left cell. The gray cells are walls and cannot be moved to.
- **Actions**: The agent can choose from up to 4 actions to move around. In this example
- **Environment Dynamics**: GridWorld is deterministic, leading to the same new state given each state and action
- **Rewards**: The agent receives +1 reward when it is in the center square (the one that shows R 1.0), and -1 reward in a few states (R -1.0 is shown for these). The state with +1.0 reward is the goal state and resets the agent back to start.
In other words, this is a deterministic, finite Markov Decision Process (MDP) and as always the goal is to find an agent policy (shown here by arrows) that maximizes the future discounted reward. My favorite part is letting the agent find the optimal path, then suddenly change the reward of some cell with the slider and watch it struggle to reroute its policy.
**Interface**. The color of the cells (initially all white) shows the current estimate of the Value (discounted reward) of that state, with the current policy. Note that you can select any cell and change its reward with the *Cell reward* slider.
### Temporal Difference Learning
TD methods (for finite MDPs) are covered very nicely in **Richard Sutton's Free Online Book on Reinforcement Learning**, in this particular case [Chapter 6](http://webdocs.cs.ualberta.ca/~sutton/book/ebook/node60.html), but REINFORCEjs also implements many of the bells and whistles described in Chapters 7 (Eligibility Traces), Chapter 9 (Planning), and Chapter 8 (Function approximation and more generally Deep Q Learning).
Briefly, the core idea is to estimate the action value function \\(Q^\pi(s,a)\\), which is the expected discounted reward obtained by the agent by taking action \\(a\\) in state \\(s\\) and then following some particular policy \\(\pi(a \\mid s)\\):
$$
Q^\pi (s,a) = E\_\pi \\{ r\_t + \\gamma r\_{t+1} + \\gamma^2 r\_{t+2} + \\ldots \\mid s\_t = s, a\_t = a \\}
$$
The expectation above is really over two stochastic sources: 1. the environment and 2. the agent policy which in the general case is also stochastic. Unlike Dynamic Programming, Temporal Difference Learning estimates the value functions from the point of view of an agent who is interacting with the environment, collecting experience about its dynamics and adjusting its policy online. That is, the agent's interaction with the environment (which forms our training set) is a long sequence of \\(s\_t, a\_t, r\_t, s\_{t+1}, a\_{t+1}, r\_{t+1}, s\_{t+2}, \ldots \\), indexed by t (time):
<div style="text-align:center; margin: 20px;">
<img src="img/sarsa.png">
</div>
However, unlike a standard Machine Learning setting the agent picks the actions, and hence influences its own training set. Fun! The core idea is to notice that the Q function satisfies the Bellman equation, which is a recurrence relation that relates the Q function at one action node \\((s\_t, a\_t)\\) to the next one \\((s\_{t+1}, a\_{t+1})\\). In particular, looking at the above diagram the agent:
1. The agent picked some action \\(a\_t\\) in state \\(s\_t\\)
2. The environment responded with some reward \\(r\_t\\) and new state \\(s\_{t+1}\\)
3. The agent then picks some new action \\(a\_{t+1}\\) from its current policy \\(\pi\\).
We can explicitly write out the expect reward of this behavior and express Q recursively based on itself:
$$
Q(s,a) = \sum\_{s'} \mathcal{P}\_{ss'}^a \left[ \mathcal{R}\_{ss'}^a + \\gamma \sum\_{a'} \pi(s',a') Q(s',a') \right]
$$
Where we see the two sources of randomness explicitly summed over (first over the next state, and then over the agent's current policy). Since this equation is expected to hold, our strategy is to initialize \\(Q\\) with some numbers (e.g. all zeros) and then turn this recurrence relation into an update. Of course, we don't have access to the environment dynamics \\(\mathcal{P}\\), but we can base the update on the agent's experience from interacting with the environment, which is at least a sample from this unknown distribution. Notice that we do have access to the policy \\(\pi\\) so we could in principle evaluate the second sum exactly, but in practice it is simpler (especially if your actions were continuous) to sample this part as well, giving rise to the **SARSA** (short for s,a,r,s',a', get it?) algorithm:
$$
Q(s\_t, a\_t) \leftarrow Q(s\_t, a\_t) + \alpha \left[ \underbrace{r\_t + \gamma Q(s\_{t+1}, a\_{t+1})}\_{target} - \underbrace{Q(s\_t, a\_t)}\_{current} \right]
$$
Here the parameter \\( \alpha \\) is the learning rate, and the quantity inside the bracket is called the **TD Error**. In other words the idea is to interact with the environment by starting with some initial \\(Q\\), using some policy \\(\\pi\\), and keeping track of a chain of (s,a,r,...). We then simply treat this as training data, and use online stochastic gradient descent to minimize the loss function, which in this case is the Bellman recurrence relation. Each time we perform the update to the Q function, we can also update our policy to be greedy with respect to our new belief about Q. That is, in each state the policy becomes to take the action that maximizes Q. This approach of starting with some value function and policy and iteratively updating one based on the other is the **policy iteration** scheme described in Sutton's book:
<div style="text-align:center; margin: 20px;">
<img src="img/policyiter.png">
</div>
Now, **SARSA** is called an **on-policy** method because it's evaluating the Q function for a particular policy. It turns out that if you're interested in control rather than estimating Q for some policy, in practice there is an update that works much better. It's called **Q-Learning** and it has the form:
$$
Q(s\_t, a\_t) \leftarrow Q(s\_t, a\_t) + \alpha \left[ r\_t + \gamma \max\_a Q(s\_{t+1}, a) - Q(s\_t, a\_t) \right]
$$
This is an **off-policy** update because the behavior policy does not match the policy whose Q function is being approximated, in this case the optimal action-value function \\(Q^\*\\). Intuitively, the update looks *optimistic*, since it updates the Q function based on its estimate of the value of the best action it can take at state \\(s\_{t+1}\\), not based on the action it happened to sample with its current behavior policy. With this Gridworld demo as well, the Q-Learning update converges much faster than SARSA.
**Exploration**. The last necessary component to get TD Learning to work well is to explicitly ensure some amount of exploration. If the agent always follows its current policy, the danger is that it can get stuck exploiting, somewhat similar to getting stuck in local minima during optimization. One common and perhaps simplest way to ensure some exploration (and make all converge proofs work) is to make the agent's policy **epsilon-greedy**. That is, with probability \\(\epsilon\\) the agent takes a random action, and the remainder of the time it follows its current policy. Some usual settings for this parameter are 0.1, 0.2, or so, and this is usually annealed over the duration of the trianing time to very small numbers (e.g. 0.05 or 0.01, etc).
### TD Bells and Whistles
Looking at the options available to you in the spec for the demo, there are some usual suspects (whether we are using 'qlearn', or 'sarsa'), the discount factor `spec.gamma`, the exploration parameter `spec.epsilon`, and the learning rate `spec.alpha`. What is all the other stuff?
**Eligibility Traces**. The idea behind eligibility traces is to make the TD updates less local and diffuse them backwards through some part of the past experience. In other words, we're keeping a (decaying) trace of where the agent has been previously (the decay strength is controlled by a hyperparameter \\(\lambda\\)), and performing Q value updates not only on one link of the s,a,r,s,a,s,a,r.... chain, but along some recent history of it. This is justified by the fact that when the Q value changes for some state (s,a), then all the other states immediately before it are also influenced due to their recursive dependence. For example, if the agent discovers a reward on some Gridworld square, it would not only update the Q of the immediately previous state, but also several several states it has seen leading up to this state. Use `spec.lambda` to control the decay of the eligibility trace, where 0 means no traces should be used (default).
<div style="text-align:center; margin: 20px;">
<img src="img/lambda.png"><br>
Image taken from Sutton's book, showing the basic idea of eligibility traces.
</div>
Additionally, there is one more option to either use replacing, or accumulating traces which can be controlled with `spec.replacing_traces` (default is true). The difference is only with how the trace is accumulated when the same state is visited multiple times (incremented each time, or reset to a fixed maximum value). Again, a nice diagram from Sutton's book shows the strength of the trace for a single state as it is repeatedly visited, and gets the point across nicely:
<div style="text-align:center; margin: 20px;">
<img src="img/traces.png"><br>
</div>
**Planning**. TD methods are by default called **model-free**, because they do not need to estimate the environment model. That is, we do not need to know the transition probabilities \\(\mathcal{P}\\), or the rewards assigned by the environment to the agent \\(\mathcal{R}\\). We only observe samples of these values and distil their sufficient statistics in the action value function \\(Q\\). However, a model of the environment can still prove extremely useful. The basic idea in planning is that we will explicitly maintain a model of how the environment works (trained again, from observation data). That is, what states and actions lead to what other states, and how the rewards are assigned. In other words, based on our training data trace \\(s\_t, a\_t, r\_t, s\_{t+1}, a\_{t+1}, r\_{t+1}, s\_{t+2}, \ldots \\) , the agent keeps track of the environment model:
$$
Model(s,a) \leftarrow s', r
$$
In this Gridworld demo for example, it's just a simple array lookup for all pairs of \\(s,a\\). The fact that this Gridworld is deterministic helps, because these are all just fixed, unchanging values that are easy to observe once and then remember. This model is very useful because it can help us hallucinate experiences, and perform updates based on these *fake* experiences:
1. Perform some action \\(a\\) in the real world
2. Get the new state \\(s'\\) and reward \\(r\\) from the environment
3. Perform a regular TD update (e.g. Q-Learning update)
4. Update the environment model with \\(Model(s,a) \leftarrow s', r\\)
5. Repeat **N** times: Sample some \\(s,a\\), use the Model to predict \\(s',r\\), perform the Q learning update on this hallucinated experience.
Notice that we're performing many more value function updates per step using our model of the environment. In practice (and in this demo as well), this can help convergence by a large amount. You can control the number of planning steps (fake experience updates) per iteration with `spec.planN` (0 = no planning). Intuitively, the reason this works so well is that when the agent discovers the high reward state, its environment model also *knows* how to get to it, so as the hallucinated experiences end up updating all the states globally backwards through the modeled transitions. In this demo, the arrows will start to "magically" point in the right direction the very first time the high reward state is discovered.
**Priority queue for faster update schedule**. There is one additional whistle that is implemented by REINFORCEjs, which is the use of a **priority queue** to speed things up. We don't just sample random **N** states to perform an update in, but keep track of the states that most need updating, and pop those from the queue with preferential treatment. Intuitively, the TD Error during each update tells us how *surprising* the update is. Say we've updated the Q value of some state \\(s\\) with a large TD error. We can query the model for all states that are predicted to lead to \\(s\\), and place those in the priority queue with priority of the magnitude of the TD error, since we expect their updates to be large as well. This way we don't waste our time sampling states that are somewhere far away and barely need any update. In this Gridworld demo, when the agent discovers the reward state the first time this causes a large positive TD error, which immediately places all the states leading up to the reward state in the priority queue with high priorities. Hence, the Q values diffuse and sync in the fastest possible ways through the entire Q function. This is turned on by default (not a setting).
**Smooth Q function updates**. The last REINFORCEjs settings are `spec.smooth_policy_update` and `spec.beta`. This is non-standard and something I added for nicer visualizations. Normally you update the policy to always take the action that lead to highest Q. With this setting, I am using stochastic policy but smoothly updating the policy to converge slowly to the argmaxy action. This makes for nicer, smoother visualizations of the policy arrows.
### REINFORCEjs API use of TD
Similar to the DP classes, if you'd like to use the REINFORCEjs TD learning you have to define an environment object `env` that has a few methods that the TD agent will need:
- `env.getNumStates()` returns an integer of total number of states
- `env.getMaxNumActions()` returns an integer with max number of actions in any state
- `env.allowedActions(s)` takes an integer `s` and returns a list of available actions, which should be integers from zero to `maxNumActions`
See the GridWorld environment in this demo's source code for an example. The `TDAgent` class assumes a finite MDP (so discrete, finite number of states and actions), and works through a very simple `action = agent.act(state)` and `agent.learn(reward)` interface:
<pre><code class="js">
// create environment
env = new Gridworld();
// create the agent, yay!
var spec = { alpha: 0.01 } // see full options on top of this page
agent = new RL.TDAgent(env, spec);
setInterval(function(){ // start the learning loop
var action = agent.act(s); // s is an integer, action is integer
// execute action in environment and get the reward
agent.learn(reward); // the agent improves its Q,policy,model, etc.
}, 0);
</code></pre>
If you have a problem that doesn't have a discrete number of states but some very large state space and some state features, **DQN** (Deep Q Learning) is for you. Head over to the next section.
</div>
</div>
<br><br><br><br><br>
</body>
</html>