-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
458 lines (393 loc) · 14.1 KB
/
index.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
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div>
<div id="graphs">
<canvas id="truth" width="200px" height="200px"></canvas>
<br/>
<canvas id="network" width="200px" height="200px"></canvas>
<br/>
<canvas id="network21" width="200px" height="200px"></canvas>
<canvas id="network22" width="200px" height="200px"></canvas>
<canvas id="network23" width="200px" height="200px"></canvas>
<canvas id="network24" width="200px" height="200px"></canvas>
<br/>
<canvas id="network3" width="200px" height="200px"></canvas>
<br/>
<canvas id="output" width="200px" height="200px"></canvas>
</div>
<div id="network-vis"></div>
</div>
<div>
Iteration: <label id="iteration">0</label>
Classified wrong: <label id="error">NaN</label>%
</div>
<form>
<label for="batchSize">Batch size:</label>
<input id="batchSize" type="number" value="10" step="5" min="1"/>
<label for="learnRate">Learn rate:</label>
<input id="learnRate" type="number" value="0.03" step="0.02" min="0.00001"/>
<label for="momentum">Momentum:</label>
<input id="momentum" type="number" value="0.3" step="0.1"/>
<input id="playpause" type="button" value="Play/Pause" />
</form>
<script type='text/javascript' src='visualization.js'></script>
<script>
function indexOfMax(arr) {
if (arr.length === 0) {
return -1;
}
var max = arr[0];
var maxIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] > max) {
maxIndex = i;
max = arr[i];
}
}
return maxIndex;
}
function shuffle(a) {
for (let i = a.length; i; i--) {
let j = Math.floor(Math.random() * i);
[a[i - 1], a[j]] = [a[j], a[i - 1]];
}
}
function Sigmoid() {
this.lastValue = NaN;
}
Sigmoid.prototype.value = function(x) {
this.lastValue = 1 / (1 + Math.exp(-x));
return this.lastValue;
}
Sigmoid.prototype.derivative = function(x) {
let value = (typeof x !== 'undefined') ? this.value(x) : this.lastValue;
return value * (1 - value);
}
function Tanh() {
this.lastValue = NaN;
}
Tanh.prototype.value = function(x) {
var ez = Math.exp(x);
var emz = Math.exp(-x);
this.lastValue = (ez - emz)/(ez + emz);
return this.lastValue;
}
Tanh.prototype.derivative = function(x) {
let value = (typeof x !== 'undefined') ? this.value(x) : this.lastValue;
return 1 - (value*value);
}
function Neuron(inputSize, func) {
this.func = func || new Tanh();
this.weights = [];
for (var i = 0; i < inputSize; ++i) {
this.weights.push(2*Math.random()-1.0);
if (this.weights[i] == 0)
--i;
// this.weights.push(Math.random());
// this.weights.push(1);
}
}
Neuron.prototype.weightedInputSum = function(input) {
if (input.length != this.weights.length) {
throw TypeError;
}
var sum = 0;
for (var i = 0; i < this.weights.length; ++i) {
sum += this.weights[i] * input[i];
}
return sum;
}
Neuron.prototype.value = function(input) {
return this.func.value(this.weightedInputSum(input));
}
Neuron.prototype.errorGradient = function(error, input) {
return error * this.func.derivative(input && this.weightedInputSum(input));
}
// Neuron.prototype.adjustWeights = function(learnRate, error, input, useCached) {
// let errGradient = this.errorGradient(error, (useCached ? undefined : input));
// for (var i = 0; i < this.weights.length; ++i) {
// this.weights[i] += -1 * learnRate * errGradient * input[i];
// }
// }
Neuron.prototype.adjustWeights = function(learnRate, errorGradient, momentum) {
for (var i = 0; i < this.weights.length; ++i) {
this.weights[i] += -1 * learnRate * errorGradient[i] + momentum[i];
}
}
function Layer(size, neuronClass) {
this.neurons = [];
for (var i = 0; i < size; ++i) {
this.neurons.push(new neuronClass());
}
}
Layer.prototype.value = function(input) {
var output = [];
for (var i = 0; i < this.neurons.length; ++i) {
output.push(this.neurons[i].value(input));
}
return output;
}
Layer.prototype.errorGradients = function(errors, input) {
return this.neurons.map(function(neuron, i) {
return neuron.errorGradient(errors[i], input);
});
}
// Layer.prototype.inputError = function(errors, input, useCached) {
// useCached = useCached === true;
// var inputErrors = [];
// for (var j = 0; j < input.length; ++j) {
// inputErrors.push(0);
// }
// for (var i = 0; i < this.neurons.length; ++i) {
// var errorGradient = this.neurons[i].errorGradient(errors[i], (useCached ? undefined : input));
// for (var j = 0; j < input.length; ++j) {
// inputErrors[j] += errorGradient * this.neurons[i].weights[j];
// }
// }
// return inputErrors;
// }
Layer.prototype.inputError = function(errorGradients) {
if (this.neurons.length !== errorGradients.length) {
throw TypeError;
}
var inputErrors = [];
var inputLength = this.neurons[0].weights.length;
for (var j = 0; j < inputLength; ++j) {
inputErrors.push(0);
}
for (var i = 0; i < this.neurons.length; ++i) {
for (var j = 0; j < inputLength; ++j) {
inputErrors[j] += errorGradients[i] * this.neurons[i].weights[j];
}
}
return inputErrors;
}
// Layer.prototype.correctErrors = function(learningRate, errors, input, useCached) {
// useCached = useCached === true;
// for (var i = 0; i < this.neurons.length; ++i) {
// this.neurons[i].adjustWeights(learningRate, errors[i], input, useCached);
// }
// }
// Layer.prototype.correctErrors = function(learningRate, errors, input, useCached) {
// useCached = useCached === true;
// for (var i = 0; i < this.neurons.length; ++i) {
// let grad = this.neurons[i].errorGradient(errors[i], (useCached ? undefined : input));
// this.neurons[i].adjustWeights(learningRate, input.map(function(x) { return x * grad; }));
// }
// }
Layer.prototype.correctErrors = function(learningRate, errorGradients, momentum) {
for (var i = 0; i < this.neurons.length; ++i) {
this.neurons[i].adjustWeights(learningRate, errorGradients[i], momentum[i]);
}
};
(function() {
var rateInput = document.getElementById('learnRate');
var rate = rateInput.value;
rateInput.addEventListener('change', function(x) {
rate = rateInput.value;
console.log("new rate " + rate);
});
var momentumInput = document.getElementById('momentum');
var momentumRate = momentumInput.value;
momentumInput.addEventListener('change', function(x) {
momentumRate = momentumInput.value;
console.log("new momentumRate " + momentumRate);
});
var errorLabel = $('#error');
var iterationLabel = $('#iteration');
var trainData = 200;
let numberOfClasses = 2;
const layers = [
new Layer(3, Neuron.bind(null, 3)),
new Layer(3, Neuron.bind(null, 4)),
new Layer(numberOfClasses, Neuron.bind(null, 4)),
];
const net = {
value: function(input) {
let value = input;
for (let i = 0; i < layers.length; ++i) {
value = layers[i].value(value.concat([1]));
}
return value;
}
};
const visualizationContainer = $('#network-vis');
const layerVisualizations = layers.map(function(l) {
const lv = new LayerVisualizer(l);
visualizationContainer.append(lv.dom);
return lv;
});
var original = [];
var classes = [];
function pointInRing(radius, width) {
// var radius = 0.8;
var spanWidth = width;
var span = Math.random() / (1/spanWidth) - spanWidth/2;
var angle = Math.random()*Math.PI*2;
x = (0.5 + Math.cos(angle)*(radius + span));
y = (0.5 + Math.sin(angle)*(radius + span));
return [x, y];
}
function circleInRing() {
for (var i = 0; i < trainData; ++i) {
var pClass = Math.floor(Math.random() * numberOfClasses);
var x = 0, y = 0;
if (!pClass) {
var point = pointInRing(0.125, 0.25);
x = point[0];
y = point[1];
} else {
var point = pointInRing(0.425, 0.15);
x = point[0];
y = point[1];
}
original.push([x, y]);
classes.push(pClass);
}
}
function separable() {
for (var i = 0; i < trainData; ++i) {
var pClass = Math.floor(Math.random() * numberOfClasses);
var x = 0, y = 0;
if (!pClass) {
var point = pointInRing(0.15, 0.3);
x = point[0] - 0.25;
y = point[1] - 0.25;
} else {
var point = pointInRing(0.15, 0.3);
x = point[0] + 0.25;
y = point[1] + 0.25;
}
original.push([x, y]);
classes.push(pClass);
}
}
circleInRing();
var currentIteration = 0;
var stop = true;
var itOrder = original.map(function(x, i) { return i; });
function emptyErrors() {
return layers.map((l)=>l.neurons.map((n)=>n.weights.map((w)=>0)));
}
function go(learn) {
learn = learn !== false;
const j = currentIteration++;
let avgError = 0;
const batchSize = parseInt($('#batchSize')[0].value);
let good = [];
let output = layers.map(function () {
return [];
});
let gErrors = emptyErrors();
let momentum = emptyErrors();
shuffle(itOrder);
let count = 0;
function step(index) {
++count;
const input = original[index];
const tClass = classes[index];
let lastOutput = input;
const netInputs = layers.map(function (l) {
const input = lastOutput.concat([1]);
lastOutput = l.value(input);
return input;
}).concat([lastOutput.concat([1])]);
const chosenClass = indexOfMax(lastOutput);
const outputErrors = lastOutput.map(function (x, i) {
if (i === tClass)
return x - 1;
return x + 1;
});
let errorGrads = [];
let errors = [];
errors[layers.length - 1] = outputErrors;
errorGrads[layers.length - 1] = layers[layers.length - 1].errorGradients(errors[layers.length - 1], netInputs[layers.length - 1]);
for (let i = layers.length - 2; i >= 0; --i) {
errors[i] = layers[i+1].inputError(errorGrads[i + 1]);
errorGrads[i] = layers[i].errorGradients(errors[i], netInputs[i]);
}
gErrors = errorGrads.map(function (errGrad, layerIndex) {
return errGrad.map(function (x, i) {
return netInputs[layerIndex].map(function (inp, j) {
return gErrors[layerIndex][i][j] + inp * x;
});
});
});
if ((count % batchSize) === 0 || count === trainData.length) {
for (let ln = 0; ln < layers.length; ++ln) {
for (let nn = 0; nn < gErrors[ln].length; ++nn) {
for (let wn = 0; wn < gErrors[ln][nn].length; ++wn) {
gErrors[ln][nn][wn] /= batchSize;
}
}
}
if (learn) {
const oldWeights = layers.map((l)=>l.neurons.map((n)=>n.weights.map((w)=>w)));
layers.forEach(function (l, i) {
l.correctErrors(rate, gErrors[i], momentum[i]);
});
momentum = layers.map((l, li)=>l.neurons.map((n, ni)=>n.weights.map((w, wi)=>momentumRate * (w-oldWeights[li][ni][wi]))));
}
layerVisualizations.forEach(function (lv, i) {
lv.update(gErrors[i]);
});
gErrors = emptyErrors();
}
avgError += (chosenClass !== tClass);
good[index] = (chosenClass === tClass);
for (let i = 1; i < netInputs.length; ++i) {
output[i-1][index] = netInputs[i];
}
errorLabel.text(toFixed((avgError / count) * 100, 2));
// iterationLabel.text(j);
// paintPlot(document.getElementById('truth'), original, classes);
// paintPlot(document.getElementById('network'), output, classes);
// paintPlot(document.getElementById('network21'), output2, classes, true, 0, 1);
// paintPlot(document.getElementById('network22'), output2, classes, true, 1, 2);
// paintPlot(document.getElementById('network23'), output2, classes, true, 2, 3);
// paintPlot(document.getElementById('network24'), output2, classes, true, 3, 0);
// paintPlot(document.getElementById('network3'), output3, classes);
//
//
// visualizeNetwork(document.getElementById('output'), net);
// paintPlot(document.getElementById('output'), original, good, false, 0, 1, true);
}
for (let i = 0; i < itOrder.length; ++i) {
step(i);
window.setTimeout(step.bind(this, i), 0);
}
window.setTimeout(function() {
// avgError /= itOrder.length;
// errorLabel.text(avgError * 100);
iterationLabel.text(j);
// console.log("Iteration " + j + " error " + avgError);
paintPlot(document.getElementById('truth'), original, classes);
paintPlot(document.getElementById('network'), output[0], classes);
paintPlot(document.getElementById('network21'), output[1], classes, true, 0, 1);
paintPlot(document.getElementById('network22'), output[1], classes, true, 1, 2);
paintPlot(document.getElementById('network23'), output[1], classes, true, 2, 3);
paintPlot(document.getElementById('network24'), output[1], classes, true, 3, 0);
paintPlot(document.getElementById('network3'), output[output.length - 1], classes);
visualizeNetwork(document.getElementById('output'), net);
paintPlot(document.getElementById('output'), original, good, false, 0, 1, true);
if (!stop)
window.setTimeout(go.bind(this, true), 0);
}, 0);
}
// go once without learning
go(false);
document.getElementById('playpause').onclick = function() {
stop = !stop;
if (!stop) {
go(true)
}
}
})();
</script>
</body>
</html>