-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathneuralnetwork.html
315 lines (284 loc) · 10.7 KB
/
neuralnetwork.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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Helen Flynn</title>
<meta name="verify-v1" content="8Fcv4zU4kEpmqFt1JgX8TNobfjaWLWwA7/MpesGh5B4=" />
<link rel="stylesheet" media="screen" type="text/css" href="style.css"
/>
<link rel="stylesheet" media="screen" type="text/css" href="js/jquery-ui/jquery-ui.css"
/>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<!--[if IE]><meta http-equiv="imagetoolbar" content="no" /><meta http-equiv="X-UA-Compatible" content="IE=8" /><![endif]-->
<script src="js/jquery-1.12.1.js"></script>
<script src="js/jquery-ui/jquery-ui.js"></script>
<script src="js/neuralnetwork.js"></script>
<script type="text/javascript">
//document.addEventListener("DOMContentLoaded", init, false);
var canvas;
var canvasWidth;
var canvasHeight;
var ctx;
var canvasData;
var scaleFactor = 120;
var transX;
var transY;
var points = [];
var nn;
var lrRate;
var numHiddenLayers;
var numUnitsPerLayer;
var activateFn;
var init = false;
var now, then;
var fps = 25;
var fpsInterval = 1000 / fps;
$(function() {
canvas = document.getElementById("canvas");
canvasWidth = canvas.width;
canvasHeight = canvas.height;
ctx = canvas.getContext("2d");
transX = canvasWidth * 0.5;
transY = canvasHeight * 0.5;
ctx.translate(transX, transY);
canvasData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
canvas.addEventListener("mousedown", onMouseDown, false);
then = Date.now();
startTime = then;
// generate a noisy sine function
numExamples = 10;
for (var i = 1; i <= numExamples; i++) {
var val = 2 * i * Math.PI / numExamples;
points.push({
x: val,
x2: val*val,
x3: val*val*val,
x4: val*val*val*val,
y: Math.sin(val) + 0.2 * Math.random()
});
}
// normalize the points to have mean 0 and unit variance
points = normalize(points);
numHiddenLayers = 2;
numUnitsPerLayer = 15;
lrRate = 1;
lrMult = 0.0005;
activateFn = 'tanh';
nn = new NeuralNetwork(Math.pow(2, lrRate)*lrMult, numHiddenLayers, numUnitsPerLayer, activateFn);
init = true;
$('#textNumHiddenLayers').text(numHiddenLayers);
$('#textNumUnits').text(numUnitsPerLayer);
$('#textLearningRate').text(Math.pow(2, lrRate)*lrMult);
$(function() {
$("#sliderHiddenLayers").slider({
step: 1,
min: 0,
max: 4,
value: numHiddenLayers,
change: function(event, ui) {
numHiddenLayers = $(this).slider('values', 0);
$('#textNumHiddenLayers').text(numHiddenLayers);
if (init) {
nn = new NeuralNetwork(Math.pow(2, lrRate)*lrMult, numHiddenLayers,
numUnitsPerLayer, activateFn);
drawPoints();
}
},
slide: function(event, ui) {
numHiddenLayers = $(this).slider('values', 0);
$('#textNumHiddenLayers').text(numHiddenLayers);
}
});
$("#sliderUnitsPerLayer").slider({
step: 1,
min: 1,
max: 20,
value: numUnitsPerLayer,
change: function(event, ui) {
numUnitsPerLayer = $(this).slider('values', 0);
$('#textNumUnits').text(numUnitsPerLayer);
if (init) {
nn = new NeuralNetwork(Math.pow(2, lrRate)*lrMult, numHiddenLayers,
numUnitsPerLayer, activateFn);
drawPoints();
}
},
slide: function(event, ui) {
numUnitsPerLayer = $(this).slider('values', 0);
$('#textNumUnits').text(numUnitsPerLayer);
}
});
$("#sliderLearningRate").slider({
step: 1,
min: 0,
max: 10,
value: lrRate,
change: function(event, ui) {
lrRate = $(this).slider('values', 0);
$('#textLearningRate').text(Math.pow(2, lrRate)*lrMult);
if (init) {
nn.setLrRate(Math.pow(2, lrRate)*lrMult);
drawPoints();
}
},
slide: function(event, ui) {
lrRate = $(this).slider('values', 0);
$('#textLearningRate').text(Math.pow(2, lrRate)*lrMult);
}
});
});
$('input:radio[name="labActivateFn"]').change(function() {
var radioValue = $("input[name='labActivateFn']:checked").val();
activateFn = radioValue;
nn.activateFn = radioValue;
if (init) {
nn = new NeuralNetwork(Math.pow(2, lrRate)*lrMult, numHiddenLayers,
numUnitsPerLayer, activateFn);
drawPoints();
}
});
drawPoints();
});
function drawPoints() {
var N = points.length;
for (var i = 0; i < N; i++) {
color = 'grey';
drawCircle(points[i].x * scaleFactor, points[i].y * scaleFactor, 3,
color);
}
var xmin = -canvasWidth / 2;
var xmax = canvasWidth / 2;
var ymin = -canvasHeight / 2;
var ymax = canvasHeight / 2;
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.moveTo(xmin, 0);
ctx.lineTo(xmax, 0);
ctx.moveTo(0, ymin);
ctx.lineTo(0, ymax);
ctx.strokeStyle = '#C0C0C0';
ctx.stroke();
}
function mainLoop(timer) {
if (init) {
nn.trainOneEpoch(points);
}
requestAnimationFrame(mainLoop);
now = Date.now();
elapsed = now - then;
if (elapsed > fpsInterval) {
then = now - (elapsed % fpsInterval);
if (init) {
drawNNPrediction();
}
}
}
requestAnimationFrame(mainLoop);
function drawNNPrediction() {
clearCanvas();
drawPoints();
for (var i = -2; i <= 2; i += 0.0011) {
var y = nn.predict(i);
color = 'blue';
drawCircle(i * scaleFactor, y * scaleFactor, 1.0, color);
}
updateStats();
}
function clearCanvas() {
// Store the current transformation matrix
ctx.save();
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// Restore the transform
ctx.restore();
}
function drawCircle(centerX, centerY, radius, color) {
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = color;
ctx.fill();
}
function addPoint(a, b, c) {
points.push({
x: a,
y: b,
label: c
});
}
function updateStats() {
ctx.fillStyle = 'black';
ctx.font = "12px Arial";
ctx.fillText("Average loss: " + nn.avgError.toFixed(4), -240, -230);
ctx.fillText("Num epochs: " + nn.currEpoch, -240, -210);
}
function onMouseDown(event) {
var x = event.x;
var y = event.y;
x -= canvas.offsetLeft;
x -= transX;
y -= canvas.offsetTop;
y -= transY;
addPoint(x / scaleFactor, y / scaleFactor, -1);
drawCircle(x, y, 4, 'black');
drawPoints();
updateStats();
}
</script>
</head>
<body>
<div id="main">
<div>
<h1>Neural network demo in pure JS</h1>
<h3>This is a demo of a neural network applied to the problem of learning a polynomial function given a set of noisy points sampled from that function. Use the slider bars below to see the effect of various parameters on the function approximation.</h3>
</div>
<div style="width: 1000px">
<div style="float: left; width: 250px; height: 500px">
Left-click the mouse inside the image to add a new point.
</div>
<div style="float: left; width: 500px; margin: 0 auto; padding: 5px;"><canvas id="canvas" width="500" height="500" style="border:1px solid #000000;"></canvas></div>
<div style="float: left; width: 240px">
<div class="slider">Learning rate: <span id="textLearningRate"></span></div>
<div id="sliderLearningRate"></div>
<div class="slider">Num hidden layers: <span id="textNumHiddenLayers"></span></div>
<div id="sliderHiddenLayers"></div>
<div class="slider">Num units per hidden layer: <span id="textNumUnits"></span></div>
<div id="sliderUnitsPerLayer"></div>
<div class="slider">Activation function: <span id="textActivationFn"></span></div>
<div>
<label><input type="radio" name="labActivateFn" value="linear">Linear</label>
<label><input type="radio" name="labActivateFn" value="tanh" checked="checked">Tanh</label>
<label><input type="radio" name="labActivateFn" value="sigmoid">Sigmoid</label>
</div>
</div>
<br style="clear: left;" />
<div style="text-align: center; width: 1000px; margin: 10px auto; font-size: 14px;">
Fork this code on <a href="https://github.com/flynnhe">Github</a>.
</div>
<div>
This network is learning to map an input x to an output y by minimising the squared difference between the two. The optimisation is being done using stochastic gradient descent (using one training example to update the weights). Stochastic gradient descent tends to take a zig zag route to the minimum and this explains the oscillations during training. These can be reduced by lowering the learning rate, but too low of a learning rate means it will take longer to converge. The more complex the network, the more likely it is to overfit the training points and be unable to generalise to new ones. Also, be aware that the larger the network, the longer it takes to train - so be patient!
</div>
</div>
</div>
<a href="https://github.com/flynnhe"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/52760788cde945287fbb584134c4cbc2bc36f904/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f77686974655f6666666666662e706e67"
alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png"></a>
<!-- 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', '//www.google-analytics.com/analytics.js',
'ga');
ga('create', 'UA-24759090-1', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
</body>
</html>