-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.html
888 lines (773 loc) · 24.1 KB
/
web.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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="robots" content="index, follow">
<link href="https://fonts.googleapis.com/css?family=Fira+Sans+Extra+Condensed:400,700|Noto+Serif:400,400i,700" rel="stylesheet">
<title>NeuralNet</title>
<script src="https://use.fontawesome.com/releases/v5.0.10/js/all.js" defer></script>
</head>
<body>
<div class="content">
<div style="max-width:800px; margin:0 auto; ">
<h2>ASAi</h2>
<h3>Anaesthesia Scoring with Artificial Intelligence</h3>
<hr />
<label for=displayselector>Display type:</label>
<select id=displayselector onchange="changedisplay(this)">
<option value=design>Design mode</option>
<option value=training>Training mode</option>
<option value=calculate>Calculate mode</option>
</select>
<hr>
<div style="float:right; max-width:350px; margin-bottom:40px; ">
<h4 style="text-align:center; margin-bottom:12px; ">The Neural Network</h4>
<div style="text-align:center;">
INPUT(S)
</div>
<canvas id="myCanvas" width="600" height="500" style="width:100%;"><span class="red">Needs a modern browser!</span></canvas>
<div style="text-align:center;">
OUTPUT(S)
</div>
<canvas id="opCanvas" width="600" height="100" style="width:100%;"></canvas>
<style>
.gpoint{background:#fdd; border-top:3px solid Red; vertical-align:bottom; width:1px; }
input:invalid {
border: 2px solid red;
}
textarea {width: 100%;}
body {font-family: Arial, Helvetica, sans-serif;}
</style>
<style id=trainingmode disabled>
.trainingsettings {display:none;}
.training {display:block;}
</style>
<style id=calculatemode disabled>
.trainingsettings {display:none;}
.training {display:none;}
</style>
<style id=designmode>
.trainingsettings {display:block;}
.training {display:block;}
</style>
<div class=trainingsettings>
<button type=button id="trained" onclick="trainMe()" >Train Me</button>
Epochs: <span id="epochs">0</span>
Output error: <span id="meanerror"></span>
<div id="trainedResults"></div>
</div>
</div>
<h4 style="margin-bottom:12px; ">ASAi-Risk Scoring</h4>
<div class=trainingsettings>
<h5>ANN Settings</h5>
<table>
<tr class="parameters"><td><label for=topology>Topology</label></td><td><input id=topology required pattern="[0-9][,0-9]*[0-9]" title="Comma-separated list of numbers" ></td></tr>
<tr class="parameters"><td><label for=learningrate>Learning rate</label></td><td><input id=learningrate required type=number max=1 min=0 step="0.0001" ></td></tr>
<tr class="parameters"><td><label for=momentum>Momentum</label></td><td><input id=momentum required type=number max=1 min=0 step="0.05" ></td></tr>
<tr class="parameters"><td><label for=sharpness>Sharpness</label></td><td><input id=sharpness required type=number max=1 min=0 step="0.05" ></td></tr>
<tr class="parameters"><td><label for=stoperror>Target Error</label></td><td><input id=stoperror required type=number min=0 step="0.0001" ></td></tr>
<tr><td colspan=2 title="key names in processing functions should correspond to these names)"><hr>
<label for=inputnames>Names of inputs (separated by spaces)</label><br/>
<textarea id=inputnames >
</textarea>
<hr>
<label for=outputnames>Names of outputs (separated by spaces))</label><br/>
<textarea id=outputnames >
</textarea>
</td></tr>
<tr><td colspan=2><hr>
<label for=preprocessfunc>Preprocessing function (data row passed as object <i>row</i>, should return array of <span id=inputs></span> inputs followed (optionally) by <span id=outputs></span> outputs </label><br/>
<pre> function (row) {</pre>
<textarea data-var=processfunc id=preprocessfunc >
</textarea>
<pre>}</pre>
</td></tr>
<tr><td colspan=2><hr></td></tr>
<tr><td colspan=2><label for=postprocessfunc>Postprocessing function (output passed as <i>output</i>, an array of length <span id=outputs2></span>)</label>
</td></tr>
<tr><td colspan=2>
<pre> function (output) {</pre>
<textarea id=postprocessfunc >
</textarea>
<pre>}</pre>
</td></tr>
<tr><td colspan=2><hr></td></tr>
<tr><td colspan=2>
<label for=rawtrainingdata>Training Data - comma separated list of items to be fed to preprocessing function above</label><br/>
<textarea id=rawtrainingdata>
</textarea>
</td></tr>
</table>
</div>
<h4>Calculate a Score</h4>
<table id=tbl_inputnames></table>
<hr>
<button type=button onclick="calculate()">Calculate Score</button>
<table id=tbl_outputnames></table>
<button type=button class=training onclick="addtotraining()">Add to training set</button>
</div>
</div>
<footer class="footer" style="width:100%; max-width:800px; margin:0 auto; ">
<hr />
<p>
</p>
</footer>
<script type="javascript/worker" id=webworker>
//type not text/javascript so not run automatically - main script wraps this in a blob and starts it as a worker
var topology = [];
var inputs
var outputs;
var trainingdata;
var rawtrainingdata;
var learningrate;
var momentum;
var sharpness;
var stoperror;
var i;
var layer;
var nx = 0;
var n1 = 0;
var n2 = 0;
var numlayers = topology.length;
var maxneuronsperlayer = findMax(topology);
var neurons = [];
var errors = [];
var toterror=0;
var expectedoutputs = [];
var meanoutputerror = 0;
var synapses=[];
var changes=[];
var prevchanges=[];
var startoflayer = [];
initialiseNet();
onmessage = function (evt){
var obj=evt.data;
//console.log(obj);
switch(obj.command) {
case "setup":
topology = obj.topology || topology;
inputs= topology[0];
outputs=topology[topology.length-1];
trainingdata=obj.trainingdata || trainingdata;
learningrate = obj.learningrate || learningrate;
momentum = obj.momentum || momentum;
sharpness = obj.sharpness || sharpness;
stoperror = obj.stoperror || stoperror;
numlayers=topology.length;
maxneuronsperlayer= findMax(topology);
initialiseNet();
break;
case "train":
trainMe()
break;
case "fire":
var results=[];
for (var n=startoflayer[numlayers-1] +1; n <= startoflayer[numlayers-1] + topology[numlayers-1]; n++){
results.push(neurons[n]);
};
postMessage({status:'results',results:results});
default:
//code block
}
}
// === KEY FUNCTIONS ===
function deriv(value){
return (0.1+value*(1-value)); //0.1 is Fahlman's modification to speed up training
}
function calculateoutputerrors(){ //error for each individual output layer
var thiserror=0;
for (var nx=0; nx < outputs; nx++){
var n = startoflayer[numlayers-1] +1 +nx;
errors[n] = expectedoutputs[nx] - neurons[n]; //each output error
errors[n] = errors[n] * deriv(neurons[n]); //?why do this. I got it from somewhere...
// toterror += Math.abs(errors[n]);
thiserror += Math.pow(errors[n],2);
}
toterror += 0.5 * thiserror;
}
function backpropagateerrors(){
for(layer=numlayers-2; layer>=0; layer--){ //move up the network from outputs to inputs
var nextlayer = layer+1;
for (n1=startoflayer[layer]; n1 <= startoflayer[layer] + topology[layer]; n1++){ //loop all layer
errors[n1] = 0;
for (n2=startoflayer[nextlayer] +1; n2 <= startoflayer[nextlayer] + topology[nextlayer]; n2++){
i = synapseindex(n1,n2);
errors[n1] += errors[n2] * synapses[i];
}
errors[n1] = errors[n1] * deriv(neurons[n1]);
}
}
}
function updatesynapseweights(){
for (layer=0;layer<numlayers-1;layer++){
var nextlayer = layer+1;
for (n1=startoflayer[layer]; n1 <= startoflayer[layer] + topology[layer]; n1++){ //loop all layer
// changes[n1]=0;
for (var n2 = startoflayer[nextlayer]; n2 <= startoflayer[nextlayer] + topology[nextlayer]; n2++) {
if (n2!=startoflayer[nextlayer]){ //not going to a bias neuron...
i = synapseindex(n1,n2);
changes[i] = neurons[n1] * errors[n2]; //prev += but synapses became huge...
changes[i] = (momentum * prevchanges[i]) + (1-momentum) * changes[i];
prevchanges[i] = changes[i]; //store for momentum calcs for next cycle
synapses[i] += learningrate * changes[i];
}
}
}
}
}
function debug(txt){
document.getElementById("debug").innerHTML = txt;
}
// === SETUP ===
function initialiseNet(){
var nx=0;
numlayers=topology.length;
maxneuronsperlayer= findMax(topology);
for (layer = 0; layer < numlayers; layer++) {
for (n1 = 0; n1 <= topology[layer]; n1++) {
if (n1 == 0){
neurons[nx] = 1; //bias neurons = 1
errors[nx] = 0;
startoflayer[layer]=nx;
} else {
neurons[nx] = 0; //others = 0
errors[nx] = 0;
}
nx ++;
}
}
randomiseSynapses();
}
function randomiseSynapses(){
//=== randomise synapses
var n1 = 0;
for (layer = 0; layer < numlayers-1; layer++) { //all except output layer
var nextlayer = layer+1;
for (var n = 0; n <= topology[layer]; n++) {
for (var n2 = startoflayer[nextlayer]; n2 <= startoflayer[nextlayer] + topology[nextlayer]; n2++) {
i = synapseindex(n1,n2);
var randval=0.2 + 0.5 * Math.random();
if (Math.random() < 0.5){randval = 0 - randval;}
synapses[i]=randval;
changes[i]=0;
prevchanges[i]=0;
}
n1++;
}
}
}
function shuffleTrainingarray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
function runOneEpoch(){
shuffleTrainingarray(trainingdata);
toterror=0;
for (var i=0;i<trainingdata.length;i++){
var arr=trainingdata[i];
for(var index=0; index<inputs; index++){
neurons[index+1]=parseFloat(arr[index]);
}
for (index=0;index<outputs;index++){
expectedoutputs[index]=parseFloat(arr[inputs+index]);
}
fire();
calculateoutputerrors();
backpropagateerrors();
updatesynapseweights();
}
// toterror = toterror / topology[numlayers-1];
return(toterror);
}
function reset(){
initialiseNet();
}
function trainMe(){
randomiseSynapses();
var training = 1; //bool
toterror=0;
meanoutputerror = 0;
var epochx = 0;
var errorOutput
var epochCounter
while (training==1){
meanoutputerror = runOneEpoch();
epochx++;
if (epochx % 10 == 0){ //update every 10 epochs
self.postMessage({status:'trainupdate',
meanoutputerror:meanoutputerror,
epochx:epochx,
training:1});
}
if (meanoutputerror < stoperror || epochx >=50000) {
training=0;
self.postMessage({status:'trainupdate',
meanoutputerror:meanoutputerror,
epochx:epochx,
training:0});
self.postMessage({status:'networkupdate',
neurons:neurons,
synapses:synapses,
errors:errors});
}
}
}
</script>
<script id=common>
function findMax(arr){
var m = -Infinity, i = 0, n = arr.length;
for (; i != n; ++i) {
if (arr[i] > m) {
m = arr[i];
}
}
return m;
}
function squash(value){
return (1/(1+Math.exp(-sharpness*value)));
}
function synapseindex(v1,v2){
return(v1*(maxneuronsperlayer+1)+v2);
}
function fire(){ //inputs set? ... fires the network
for (var layer=0;layer<numlayers-1;layer++){
var nextlayer = layer+1;
for (var n2 = startoflayer[nextlayer]+1; n2 <= startoflayer[nextlayer] + topology[nextlayer]; n2++) {
neurons[n2] = 0;
for (var n1 = startoflayer[layer]; n1 <= startoflayer[layer] + topology[layer]; n1++) {
if (n2!=startoflayer[nextlayer]){ //synapse not going to a bias neuron...
var si = synapseindex(n1,n2);
neurons[n2] += neurons[n1] * synapses[si];
}
}
neurons[n2] = squash(neurons[n2]);
}
}
}
</script>
<script id=netparameters>
var topology = [2,2,1];
var rawtrainingdata=[
{x:0,y:0,result:0},
{x:0,y:1,result:1},
{x:1,y:0,result:1},
{x:1,y:1,result:0}];
var learningrate = 0.8;
var momentum = 0.9;
var sharpness = 1;
var stoperror = 0.0001;
var preprocessfunc = "return [Number(row.x),Number(row.y),Number(row.result)];";
var postprocessfunc ="return {result:output[0]};";
var inputnames="x y";
var outputnames="result";
</script>
<script id=browserscript>
//wrap workerscript in a blob then launch it
var workerscript=document.getElementById('webworker').innerHTML;
var webworker= new Worker(URL.createObjectURL(new Blob([document.getElementById('common').innerHTML,document.getElementById('webworker').innerHTML],{type:'text/javascript'})));
var traindisplay
webworker.onmessage = function(e){
switch (e.data.status){
case 'trainupdate':
traindisplay(e.data.meanoutputerror,e.data.training);
break;
case 'networkupdate':
neurons=e.data.neurons;
synapses=e.data.synapses;
errors=e.data.errors;
drawNet();
}
}
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var op = document.getElementById("opCanvas");
var ctxOutput = op.getContext("2d");
var i;
var layer;
var nx = 0;
var n1 = 0;
var n2 = 0;
var xpos = 0;
var ypos = 0;
var inputs=topology[0];
var outputs=topology[topology.length-1];
var trainingdata=[];
var numlayers = topology.length;
var maxneuronsperlayer = findMax(topology);
var neurons = [];
var errors = [];
var toterror=0;
var expectedoutputs = [];
var meanoutputerror = 0;
var synapses=[];
var changes=[];
var prevchanges=[];
var startoflayer = [];
var xgap = 600 / (maxneuronsperlayer + 1);
var ygap = (600 / numlayers) - 10;
var topmargin = 30;
initialiseNet();
drawNet();
// === KEY FUNCTIONS ===
function synapseColour(value){ //greys light to dark
value=squash(value); //to 0-1?
var shades=['d','c','a','8','6','4'];
var i = Math.floor( value * (shades.length-1) );
return ('#' + shades[i] + shades[i] + shades[i]);
}
function neuronColour(value){ //maps 0-1 to a shade of yellow (non-linear!)
var shades=['0','6','8','a','c','d','e','f'];
var i = Math.floor( value * (shades.length-1) );
return ('#' + shades[i] + shades[i] + '0');
}
function debug(txt){
document.getElementById("debug").innerHTML = txt;
}
// === SETUP ===
function initialiseNet(){
numlayers=topology.length;
maxneuronsperlayer= findMax(topology);
inputs=topology[0];
outputs=topology[topology.length-1];
nx=0
for (layer = 0; layer < numlayers; layer++) {
for (n1 = 0; n1 <= topology[layer]; n1++) {
if (n1 == 0){
neurons[nx] = 1; //bias neurons = 1
errors[nx] = 0;
startoflayer[layer]=nx;
} else {
neurons[nx] = 0; //others = 0
errors[nx] = 0;
}
nx ++;
}
}
randomiseSynapses();
document.getElementById('inputs').innerHTML=inputs;
document.getElementById('outputs').innerHTML=outputs;
document.getElementById('outputs2').innerHTML=outputs;
webworker.postMessage(
{command:'setup',
topology:topology,
learningrate:learningrate,
momentum:momentum,
sharpness:sharpness,
stoperror:stoperror})
}
function randomiseSynapses(){
//=== randomise synapses
var n1 = 0;
for (layer = 0; layer < numlayers-1; layer++) { //all except output layer
var nextlayer = layer+1;
for (var n = 0; n <= topology[layer]; n++) {
for (var n2 = startoflayer[nextlayer]; n2 <= startoflayer[nextlayer] + topology[nextlayer]; n2++) {
i = synapseindex(n1,n2);
// var randval=0.2 + 0.5 * Math.random();
// if (Math.random() < 0.5){randval = 0 - randval;}
synapses[i]=0.5;
changes[i]=0;
prevchanges[i]=0;
//console.log('randomised '+i+' to '+randval);
}
n1++;
}
}
}
function showNetTest(){
var results='';
for (var i=0;i<trainingdata.length;i++){
var arr=trainingdata[i].slice(0,inputs);
fixAndString=function(x){return x.toFixed(0).toString();}
results += arr.map(fixAndString).join();
results += ' = ';
results += runOneSet(arr).map(fixAndString).join();
results += '<br />';
}
trainedResults.innerHTML = "<hr />Testing trained net...<br />"+results;
}
function runOneSet(arr){
var l1
var l2
l1=neurons.length
neurons.splice.apply(neurons,[1,inputs].concat(arr));
fire();
console.log(''+l1+' + '+neurons.length);
retval = neurons.slice(startoflayer[numlayers-1]+1,startoflayer[numlayers-1] + topology[numlayers-1]+1);
console.log(retval);
return retval;
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function reset(){
initialiseNet();
drawNet();
}
function trainMe(){
trainingdata=rawtrainingdata.map(Function('row',preprocessfunc))
console.log(preprocessfunc);
console.log(trainingdata);
webworker.postMessage({command:'setup',trainingdata:trainingdata});
webworker.postMessage({command:'train'});
var training = 1; //bool
toterror=0;
meanoutputerror = 0;
var epochx = 0;
var errorOutput = document.getElementById("meanerror");
var epochCounter = document.getElementById("epochs");
ctxOutput.clearRect(0,0,800,100);
var outputX=0;
var thisY=0;
var prevY=0;
if (epochx==0){ //start training loop
traindisplay = function(meanoutputerror,training) {
if (training==1){
epochx++;
if (epochCounter != null){epochCounter.innerHTML = numberWithCommas(epochx); }
var borderWidth = (1350 * meanoutputerror).toFixed(0);
if (borderWidth > 90){
borderWidth=90;
}
if (errorOutput != null){ errorOutput.innerHTML = (13 * meanoutputerror).toFixed(2); }
thisY=100-borderWidth;
ctxOutput.clearRect(outputX+1,0,60,100);
ctxOutput.strokeStyle = 'Pink';
ctxOutput.beginPath();
ctxOutput.moveTo(outputX,100);
ctxOutput.lineTo(outputX,thisY);
ctxOutput.stroke();
ctxOutput.strokeStyle = 'Red';
ctxOutput.beginPath();
ctxOutput.moveTo(outputX,thisY);
ctxOutput.lineTo(outputX-1,prevY);
ctxOutput.stroke();
outputX++;
prevY=thisY;
if (outputX==800){outputX=0;}
topMargin = 100 - borderWidth;
} else {
if (trained != null && meanoutputerror < stoperror){
trained.innerHTML = 'Trained!';
trained.style.backgroundColor = "lime";
} else {
trained.innerHTML = 'Failed to train';
trained.style.backgroundColor = "pink";
}
if (epochCounter != null){epochCounter.innerHTML = numberWithCommas(epochx);}
if (errorOutput != null){errorOutput.innerHTML = meanoutputerror.toFixed(2);}
showNetTest();
}
drawNet();
}
}
}
function drawNet(){//topology,neurons,synapses){
var numlayers = topology.length;
var maxneuronsperlayer = findMax(topology);
var startoflayer = [];
n1=0;
for (var i=0;i<topology.length;i++){
startoflayer.push(n1);
n1+=topology[i]+1
}
//console.log(JSON.stringify(startoflayer));
var xgap = 600 / (maxneuronsperlayer + 1);
var ygap = (600 / numlayers) - 10;
var topmargin = 30;
ctx.clearRect(0,0,800,600);
// === draw synapses
n1 = 0;
for (layer=0;layer<numlayers-1;layer++){
var nextlayer = layer+1;
ypos = topmargin + layer * ygap;
var leftmargin = 10 + (maxneuronsperlayer - topology[layer]) * xgap / 2;
var leftmarginnextlayer = 10 + (maxneuronsperlayer - topology[nextlayer]) * xgap / 2;
for (var n = 0; n <= topology[layer]; n++) {
var xpos = leftmargin + n * xgap;
for (var n2 = startoflayer[nextlayer]; n2 <= startoflayer[nextlayer] + topology[nextlayer]; n2++) {
var nextlayerxpos = leftmarginnextlayer + (n2-startoflayer[nextlayer]) * xgap;
if (n2!=startoflayer[nextlayer]){ //not going to a bias neuron...
i = synapseindex(n1,n2);
//console.log(i+':'+synapses[i]);
// ctx.strokeStyle = doShade(synapses[i]);
ctx.strokeStyle = synapseColour(synapses[i]);
ctx.beginPath();
ctx.moveTo(xpos,ypos);
ctx.lineTo(nextlayerxpos,ypos + ygap);
ctx.stroke();
ctx.fillStyle = 'LightGreen';
ctx.font = "12px Arial";
ctx.fillText( synapses[i].toFixed(3), xpos - 8 + (nextlayerxpos-xpos)/4, ypos + (3+n2-startoflayer[nextlayer]) * 12);
}
}
n1 ++;
}
}
// === draw neurons
nx = 0;
ctx.strokeStyle="black";
for (layer=0;layer<numlayers;layer++){
ypos = topmargin + layer * ygap;
var leftmargin = 10 + (maxneuronsperlayer - topology[layer]) * xgap / 2;
for (n1 = 0; n1 <= topology[layer]; n1++) {
if (n1==0 && layer==numlayers-1){
//bias neuron on OUTPUT layer - ignore, it doesn't exist
} else {
xpos = leftmargin + n1 * xgap;
ctx.strokeStyle='LightGrey';
if (n1==0){ //bias on any layer except output
ctx.fillStyle = 'lime';
} else {
ctx.fillStyle = neuronColour(neurons[nx]);
// ctx.fillStyle = 'lime';
}
ctx.beginPath();
ctx.arc(xpos,ypos,6,0,2*Math.PI);
ctx.fill();
ctx.stroke();
ctx.font = "12px Arial";
ctx.fillStyle = '#888';
ctx.fillText( neurons[nx].toFixed(3), xpos + 10, ypos + 2);
ctx.fillStyle = 'red';
ctx.fillText( errors[nx].toFixed(3), xpos + 10, ypos + 12);
}
nx++;
}
}
}
function changesettings(element){
var value;
element = element.srcElement || element;
console.log(element);
if (element.validity && element.validity.valid){
switch (element.id){
case 'topology':
case 'rawtrainingdata':
value=JSON.parse('['+element.value+']');
break;
case 'preprocessfunc':
case 'postprocessfunc':
value=element.value;
break;
case 'inputnames':
case 'outputnames':
var targetdiv=document.getElementById('tbl_'+element.id);
filterfunc=function(e){return e};
mapfunc=function(e){
var newinput=document.createElement('input');
var newlabel=document.createElement('label');
var newtr=document.createElement('tr');
var newtd=[document.createElement('td'),document.createElement('td')]
newinput.id='values_'+e;
newlabel.for=newinput.id;
newlabel.appendChild(document.createTextNode(e));
newtd[0].appendChild(newlabel);
newtd[1].appendChild(newinput);
newtr.appendChild(newtd[0]);
newtr.appendChild(newtd[1]);
targetdiv.appendChild(newtr);
}
if (targetdiv.hasChildNodes()){while(targetdiv.removeChild(targetdiv.childNodes[0])){}};
element.value.split(' ').filter(filterfunc).map(mapfunc);
value=element.value;
break;
default:
value=Number(element.value);
}
window[element.id]=value;
initialiseNet();
drawNet();
} else {
switch (element.id){
case 'topology':
case 'rawtrainingdata':
value=window[element.id].join();
break;
default:
value=window[element.id];
}
element.value=value;
}
}
function calculate(){
var inputnamesarray=inputnames.split(' ').filter(function(s){return s});
var outputnamesarray=outputnames.split(' ').filter(function(s){return s});
var inputobject={};
for (var i=0;i<inputnamesarray.length;i++){
inputobject[inputnamesarray[i]]=document.getElementById('values_'+inputnamesarray[i]).value;
}
var rowinputs=Function('row',preprocessfunc)(inputobject).slice(0,inputs);
var outputobject=Function('output',postprocessfunc)(runOneSet(rowinputs));
for (var i=0;i<outputnamesarray.length;i++){
document.getElementById('values_'+outputnamesarray[i]).value=outputobject[outputnamesarray[i]];
}
console.log(outputobject);
}
function addtotraining(){
var inputnamesarray=inputnames.split(' ').filter(function(s){return s});
var outputnamesarray=outputnames.split(' ').filter(function(s){return s});
var dataobject={};
for (var i=0;i<inputnamesarray.length;i++){
dataobject[inputnamesarray[i]]=document.getElementById('values_'+inputnamesarray[i]).value;
}
for (var i=0;i<outputnamesarray.length;i++){
dataobject[outputnamesarray[i]]=document.getElementById('values_'+outputnamesarray[i]).value;
}
rawtrainingdata.push(dataobject);
document.getElementById('rawtrainingdata').value=rawtrainingdata.map(JSON.stringify).join()
}
function changedisplay(element){
var css={design:document.getElementById('designmode'),training:document.getElementById('trainingmode'),calculate:document.getElementById('calculatemode')}
css.design.disabled=true;
css.training.disabled=true;
css.calculate.disabled=true;
css[element.value].disabled=false;
}
document.getElementById("preprocessfunc").value = preprocessfunc;
document.getElementById("postprocessfunc").value = postprocessfunc;
document.getElementById("inputnames").value = inputnames;
document.getElementById("outputnames").value = outputnames;
document.getElementById("rawtrainingdata").value = rawtrainingdata.map(JSON.stringify).join(',\n');
document.querySelectorAll('tr.parameters input').forEach(function(e){
changesettings(e);
e.addEventListener('change',changesettings);
});
document.querySelectorAll('textarea').forEach(function(e){
changesettings(e);
e.addEventListener('blur',changesettings);
});
</script>
<script>
function doAjax(ajaxfile,msg) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
doSomethingWithResponse(this.responseText);
}
};
xmlhttp.open("GET", ajaxfile + "?msg=" + msg, true);
xmlhttp.send();
}
</script>
</body>
</html>