-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsnet.js
429 lines (358 loc) · 15 KB
/
jsnet.js
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
// neural network
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var output = [];
var input = [];
var totalInput;
var digit;
var canvas = document.getElementById('canv');
var ctx = canvas.getContext('2d');
var canvasRes = document.getElementById('results');
var ctxRes = canvasRes.getContext('2d');
function DigitRecog() {
this.net = new Network([Math.pow(28, 2), 16, 16, 10]);
this.pics, this.labels, this.totalPics, this.testInterval;
this.successArr = [];
this.costArr = [];
this.avgNablaW = Array(this.net.numLayers-1).fill(0);
this.avgNablaB = Array(this.net.numLayers-1).fill(0);
this.currTest = -1;
this.totalSuccess = 0;
this.avgCost = 0;
// tests a certain picture to see how the network classifies it. can also display results
this.test = function(pic, label, display, index) {
var result = this.net.processInput(pic);
var desired = math.zeros(1, 10); desired['_data'][0][label] = 1;
var verdict = maxIndex(result['_data'][0]);
var cost = getCost(result, desired);
if (display) {
if (document.getElementById('disp-output-text').checked) {
document.getElementById('output-text').innerHTML =
'Output: <br><br>' +
'Verdict: This is ' + verdict + '<br>Expected: This is ' + label + '<br>' +
(verdict === label ? '<span style="color: lime;"><b>Correct!</b></span>' : '<span style="color: red;"><b>Incorrect...</b></span>') +
'<br>Cost: ' + cost.toString().substr(0, 10);
}
if (document.getElementById('dispmode-one').checked) {
drawNum(pic, label);
} else if (document.getElementById('dispmode-all').checked) {
drawNumSmall(pic, label, verdict, index);
}
}
return [verdict, cost, desired];
}
this.testPlusBackprop = function(index) {
// perform test
var [verdict, cost, desired] = this.test(this.pics[index], this.labels[index], !document.getElementById('dispmode-none').checked, index);
this.totalSuccess += (verdict === this.labels[index] ? 1 : 0);
this.avgCost += cost/this.totalPics;
// add backpropagation gradient to an average
if (document.getElementById('learn').checked) {
var [nablaW, nablaB] = this.net.backprop(desired);
for (var i = 0; i < this.net.numLayers-1; i++) {
this.avgNablaW[i] = math.add(this.avgNablaW[i], nablaW[i]);
this.avgNablaB[i] = math.add(this.avgNablaB[i], nablaB[i]);
}
}
}
this.postTests = function() {
// learn if needed
if (document.getElementById('learn').checked) {
for (var i = 0; i < this.net.numLayers-1; i++) {
this.net.weights[i] = math.add(this.net.weights[i], math.multiply(this.avgNablaW[i], -document.getElementById('learn-speed').value/this.totalPics));
this.net.biases[i] = math.add(this.net.biases[i], math.multiply(this.avgNablaB[i], -document.getElementById('learn-speed').value/this.totalPics));
}
}
// logging success
console.log('success: ' + this.totalSuccess);
this.successArr.push(this.totalSuccess/this.totalPics);
console.log('avg. cost: ' + this.avgCost);
this.costArr.push(this.avgCost);
// draw graph if needed
if (document.getElementById('show-graph').checked) {
drawGraph(this.successArr, this.costArr);
}
// output total success if needed
if (document.getElementById('disp-output-text').checked) {
document.getElementById('output-text').innerHTML = 'Output: <br><br>Total Success: ' + this.totalSuccess;
}
this.avgNablaW = Array(this.net.numLayers-1).fill(0);
this.avgNablaB = Array(this.net.numLayers-1).fill(0);
this.totalSuccess = 0;
this.avgCost = 0;
this.getSet(parseInt(document.getElementById("index-size").value));
}
this.getSet = function(num) {
[this.pics, this.labels] = getSet(num);
this.totalPics = this.pics.length;
}
// this function is called by the setInterval, and as such its 'this' keyword would register as Window
this.testAllInterval = function() {
digit.testAll();
}
// tests all pictures quickly
this.testAll = function() {
if (this.testState === 0) {
// setting test state
this.testState = 1;
// doing tests
for (var i = 0; i < this.totalPics; i++) {
this.testPlusBackprop(i);
}
this.postTests();
// deciding whether or not to continue
if (document.getElementById('continue').checked === false) {
clearInterval(this.testInterval);
this.testInterval = undefined;
}
// resetting test state
this.testState = 0;
}
}
// this function is called by the setInterval, and as such its 'this' keyword would register as Window
this.testAllSlowInterval = function() {
digit.testAllSlow();
}
// a slower but more visual version of testAll
this.testAllSlow = function() {
if (this.currTest < this.totalPics) {
this.testPlusBackprop(this.currTest);
} else if (this.currTest === this.totalPics) {
this.postTests();
// check whether to continue
if (document.getElementById('continue').checked === false) {
clearInterval(this.testInterval);
this.testInterval = undefined;
}
this.currTest = -1;
}
this.currTest++;
}
this.startDoTest = function() {
if (this.testInterval === undefined) {
if (document.getElementById('speed-slow').checked) {
this.testInterval = setInterval(this.testAllSlowInterval, 0.5);
this.currTest = 0;
} else if (document.getElementById('speed-fast').checked) {
this.testInterval = setInterval(this.testAllInterval, 1);
if (this.testState !== 1) {this.testState = 0;}
}
// resetting variables
this.avgNablaW = Array(this.net.numLayers-1).fill(0);
this.avgNablaB = Array(this.net.numLayers-1).fill(0);
this.totalSuccess = 0;
this.avgCost = 0;
this.getSet(parseInt(document.getElementById("index-size").value));
}
}
}
// initializes the neural network
function init() {
if (digit !== undefined) {
if (digit.testInterval !== undefined) {
clearInterval(digit.testInterval);
}
}
digit = new DigitRecog();
}
// selects a set from input and output arrays
function getSet(num) {
var pics = []; var labels = [];
for (var i = 0; i < num; i++) {
var pos = Math.floor(Math.random() * totalInput);
pics.push(math.multiply(input.slice(pos * Math.pow(28, 2), (pos+1) * Math.pow(28, 2)), 1/256));
labels.push(output[pos]);
}
return [pics, labels];
}
// draws a number given pixel data and the label
function drawNum(pic, label) {
ctx.clearRect(0, 0, 280, 280);
for (var i = 0; i < pic.length; i++) {
var currColor = Math.floor(pic[i]*256).toString(16).padStart(2, '0');
ctx.fillStyle = '#' + currColor + currColor + currColor;
ctx.fillRect(10 * (i % 28), 10 * (Math.floor(i / 28)), 10, 10);
}
document.getElementById('label').textContent = 'Label: ' + label;
}
// draws a smaller number, used for the 'draw all' display option
function drawNumSmall(pic, label, verdict, index) {
for (var i = 0; i < pic.length; i++) {
var colStr = Math.floor(pic[i]*256).toString(16).padStart(2, '0');
ctx.fillStyle = (verdict === label ? "#00" + colStr + "00" : "#" + colStr + "0000");
ctx.fillRect(28 * ((index % 100) % 10) + (i % 28), 28 * Math.floor((index % 100) / 10) + Math.floor(i / 28), 1, 1);
}
document.getElementById('label').textContent = 'Label: ' + label;
}
// draws a graph showing progression of cost/success
function drawGraph(successArr, costArr) {
var successes = successArr.slice(Math.max(0, successArr.length-100), successArr.length);
var costs = costArr.slice(Math.max(0, costArr.length-100), costArr.length);
var width = canvasRes.width;
var height = canvasRes.height;
ctxRes.clearRect(0, 0, width, height);
// axes
for (var i = 0; i < 5; i++) {
ctxRes.beginPath();
ctxRes.strokeStyle = '#000000';
ctxRes.moveTo(0, i*(height/5));
ctxRes.lineTo(width, i*(height/5));
ctxRes.stroke();
ctxRes.fillStyle = '#0000FF';
ctxRes.textAlign = 'right';
ctxRes.fillText(Math.round((1-(i/5))*100).toString() + '%', width, i*(height/5));
ctxRes.fillStyle = '#FF0000';
ctxRes.textAlign = 'left';
ctxRes.fillText((Math.round((1-(i/5))*100)/100).toString(), 0, i*(height/5));
}
// success rate
ctxRes.beginPath();
ctxRes.strokeStyle = '#0000FF';
ctxRes.moveTo(0, height * (1-successes[0]));
for (var i = 1; i < successes.length; i++) {
ctxRes.lineTo((width/100) * i, height * (1-successes[i]));
}
ctxRes.stroke();
// cost
ctxRes.beginPath();
ctxRes.strokeStyle = '#FF0000';
ctxRes.moveTo(0, height * (1-costs[0]));
for (var i = 1; i < costs.length; i++) {
ctxRes.lineTo((width/100) * i, height * (1-costs[i]));
}
ctxRes.stroke();
}
// returns index of max value in array
function maxIndex(arr) {
var max = arr[0]; var ind = 0;
for (var i = 1; i < arr.length; ++i) {
if (arr[i] > max) {
max = arr[i];
ind = i;
}
}
return ind;
}
// picture drawing
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var canvasDraw = document.getElementById('drawing');
var ctxDraw = canvasDraw.getContext('2d');
var drawMouseDown = false;
// handling clicking/dragging on the canvas
canvasDraw.onmousedown = function() {
drawMouseDown = true;
}
canvasDraw.onmousemove = function(event) {
if (drawMouseDown) {
var x = event.layerX - event.srcElement.offsetLeft;
var y = event.layerY - event.srcElement.offsetTop;
canvasDrawAt(ctxDraw, x, y, 10);
}
}
canvasDraw.onmouseup = function() {
drawMouseDown = false;
}
canvasDraw.onmouseout = function() {
drawMouseDown = false;
}
// drawing button interaction
document.getElementById('btn-drawing-test').onclick = function() {
var output = testDrawing();
document.getElementById('drawing-result').textContent = "Result: " + output;
}
document.getElementById('btn-drawing-clear').onclick = function() {
ctxDraw.clearRect(0, 0, canvasDraw.width, canvasDraw.height);
}
// fills in a circle at the given point with a given size
function canvasDrawAt(context, x, y, size) {
context.fillStyle = '#000000';
for (var i = -size; i < size; ++i) {
for (var j = -size; j < size; ++j) {
// finding distance from the center
var dx = Math.abs(i);
var dy = Math.abs(j);
var dist = Math.sqrt((dx*dx) + (dy*dy));
// if the distance is less than the given size, we put a pixel there
if (dist < size) {
context.fillRect(x+i, y+j, 1, 1);
}
}
}
}
// tests the picture in the canvas
function testDrawing() {
// getting the relevant pixel data
var dataDraw = ctxDraw.getImageData(0, 0, 280, 280).data;
// taking the stuff in the drawing array and making it into a valid input
var pixels = [];
for (var row = 0; row < 28; ++row) {
for (var col = 0; col < 28; ++col) {
var sum = 0;
for (var y = 0; y < 10; ++y) {
for (var x = 0; x < 10; ++x) {
var dataPos = (((row * 10) + y) * 280 + (col * 10) + x) * 4 + 3;
sum += dataDraw[dataPos] / 255;
}
}
var avg = sum / 100;
pixels[row * 28 + col] = avg;
}
}
// performing the test, finding the output digit
var result = digit.net.processInput(pixels);
return maxIndex(result['_data'][0]);
}
// getting and receiving text files
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var ready = 0;
// getting input
var request = new XMLHttpRequest();
request.responseType = 'arraybuffer';
request.open('GET', 'train-images.idx3-ubyte', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
var arrayBuffer = this.response;
var byteArr = new Uint8Array(arrayBuffer);
input = [];
for (var i = 0; i < byteArr.length; i++) {input.push(byteArr[i]);}
input.splice(0, 16);
console.log('Request complete. (input)');
ready++;
document.getElementById('loading-input').innerHTML += 'Complete!';
if (ready === 2) {readyUp();}
}
}
request.send();
// getting output
var request = new XMLHttpRequest();
request.responseType = 'arraybuffer';
request.open('GET', 'train-labels.idx1-ubyte', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
var arrayBuffer = this.response;
var byteArr = new Uint8Array(arrayBuffer);
for (var i = 0; i < byteArr.length; i++) {output.push(byteArr[i]);}
output.splice(0, 4);
var temp = output.splice(0, 4);
totalInput = ((temp[3]) + (Math.pow(2, 8) * temp[2]) + (Math.pow(2, 16) * temp[1]) + (Math.pow(2, 24) * temp[0]));
console.log('Request complete. (output)');
ready++;
document.getElementById('loading-output').innerHTML += 'Complete!';
if (ready === 2) {readyUp();}
}
}
request.send();
function readyUp() {
document.getElementById('main').style.display = '';
document.getElementById('loading').style.display = 'none';
init();
}
// changing tabs in UI
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function changeTab(tab) {
document.getElementById('open-test').classList.remove('selected');
document.getElementById('open-settings').classList.remove('selected');
document.getElementById('open-' + tab).classList.add('selected');
document.getElementById('div-test').style.display = 'none';
document.getElementById('div-settings').style.display = 'none';
document.getElementById('div-' + tab).style.display = '';
}