-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsynaptic.js
2736 lines (2349 loc) · 84.4 KB
/
synaptic.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
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// import
var Layer = require('./layer')
, Network = require('./network')
, Trainer = require('./trainer')
/*******************************************************************************************
ARCHITECT
*******************************************************************************************/
// Colection of useful built-in architectures
var Architect = {
// Multilayer Perceptron
Perceptron: function Perceptron() {
var args = Array.prototype.slice.call(arguments); // convert arguments to Array
if (args.length < 3)
throw new Error("not enough layers (minimum 3) !!");
var inputs = args.shift(); // first argument
var outputs = args.pop(); // last argument
var layers = args; // all the arguments in the middle
var input = new Layer(inputs);
var hidden = [];
var output = new Layer(outputs);
var previous = input;
// generate hidden layers
for (level in layers) {
var size = layers[level];
var layer = new Layer(size);
hidden.push(layer);
previous.project(layer);
previous = layer;
}
previous.project(output);
// set layers of the neural network
this.set({
input: input,
hidden: hidden,
output: output
});
// trainer for the network
this.trainer = new Trainer(this);
},
// Multilayer Long Short-Term Memory
LSTM: function LSTM() {
var args = Array.prototype.slice.call(arguments); // convert arguments to array
if (args.length < 3)
throw new Error("not enough layers (minimum 3) !!");
var last = args.pop();
var option = {
peepholes: Layer.connectionType.ALL_TO_ALL,
hiddenToHidden: false,
outputToHidden: false,
outputToGates: false,
inputToOutput: true,
};
if (typeof last != 'number') {
var outputs = args.pop();
if (last.hasOwnProperty('peepholes'))
option.peepholes = last.peepholes;
if (last.hasOwnProperty('hiddenToHidden'))
option.hiddenToHidden = last.hiddenToHidden;
if (last.hasOwnProperty('outputToHidden'))
option.outputToHidden = last.outputToHidden;
if (last.hasOwnProperty('outputToGates'))
option.outputToGates = last.outputToGates;
if (last.hasOwnProperty('inputToOutput'))
option.inputToOutput = last.inputToOutput;
} else
var outputs = last;
var inputs = args.shift();
var layers = args;
var inputLayer = new Layer(inputs);
var hiddenLayers = [];
var outputLayer = new Layer(outputs);
var previous = null;
// generate layers
for (var layer in layers) {
// generate memory blocks (memory cell and respective gates)
var size = layers[layer];
var inputGate = new Layer(size).set({
bias: 1
});
var forgetGate = new Layer(size).set({
bias: 1
});
var memoryCell = new Layer(size);
var outputGate = new Layer(size).set({
bias: 1
});
hiddenLayers.push(inputGate);
hiddenLayers.push(forgetGate);
hiddenLayers.push(memoryCell);
hiddenLayers.push(outputGate);
// connections from input layer
var input = inputLayer.project(memoryCell);
inputLayer.project(inputGate);
inputLayer.project(forgetGate);
inputLayer.project(outputGate);
// connections from previous memory-block layer to this one
if (previous != null) {
var cell = previous.project(memoryCell);
previous.project(inputGate);
previous.project(forgetGate);
previous.project(outputGate);
}
// connections from memory cell
var output = memoryCell.project(outputLayer);
// self-connection
var self = memoryCell.project(memoryCell);
// hidden to hidden recurrent connection
if (option.hiddenToHidden)
memoryCell.project(memoryCell, Layer.connectionType.ALL_TO_ELSE);
// out to hidden recurrent connection
if (option.outputToHidden)
outputLayer.project(memoryCell);
// out to gates recurrent connection
if (option.outputToGates) {
outputLayer.project(inputGate);
outputLayer.project(outputGate);
outputLayer.project(forgetGate);
}
// peepholes
memoryCell.project(inputGate, option.peepholes);
memoryCell.project(forgetGate, option.peepholes);
memoryCell.project(outputGate, option.peepholes);
// gates
inputGate.gate(input, Layer.gateType.INPUT);
forgetGate.gate(self, Layer.gateType.ONE_TO_ONE);
outputGate.gate(output, Layer.gateType.OUTPUT);
if (previous != null)
inputGate.gate(cell, Layer.gateType.INPUT);
previous = memoryCell;
}
// input to output direct connection
if (option.inputToOutput)
inputLayer.project(outputLayer);
// set the layers of the neural network
this.set({
input: inputLayer,
hidden: hiddenLayers,
output: outputLayer
});
// trainer
this.trainer = new Trainer(this);
},
// Liquid State Machine
Liquid: function Liquid(inputs, hidden, outputs, connections, gates) {
// create layers
var inputLayer = new Layer(inputs);
var hiddenLayer = new Layer(hidden);
var outputLayer = new Layer(outputs);
// make connections and gates randomly among the neurons
var neurons = hiddenLayer.neurons();
var connectionList = [];
for (var i = 0; i < connections; i++) {
// connect two random neurons
var from = Math.random() * neurons.length | 0;
var to = Math.random() * neurons.length | 0;
var connection = neurons[from].project(neurons[to]);
connectionList.push(connection);
}
for (var j = 0; j < gates; j++) {
// pick a random gater neuron
var gater = Math.random() * neurons.length | 0;
// pick a random connection to gate
var connection = Math.random() * connectionList.length | 0;
// let the gater gate the connection
neurons[gater].gate(connectionList[connection]);
}
// connect the layers
inputLayer.project(hiddenLayer);
hiddenLayer.project(outputLayer);
// set the layers of the network
this.set({
input: inputLayer,
hidden: [hiddenLayer],
output: outputLayer
});
// trainer
this.trainer = new Trainer(this);
},
Hopfield: function Hopfield(size)
{
var inputLayer = new Layer(size);
var outputLayer = new Layer(size);
inputLayer.project(outputLayer, Layer.connectionType.ALL_TO_ALL);
this.set({
input: inputLayer,
hidden: [],
output: outputLayer
});
var trainer = new Trainer(this);
var proto = Architect.Hopfield.prototype;
proto.learn = proto.learn || function(patterns)
{
var set = [];
for (var p in patterns)
set.push({
input: patterns[p],
output: patterns[p]
});
return trainer.train(set, {
iterations: 500000,
error: .00005,
rate: 1
});
}
proto.feed = proto.feed || function(pattern)
{
var output = this.activate(pattern);
var pattern = [];
for (var i in output)
pattern[i] = output[i] > .5 ? 1 : 0;
return pattern;
}
}
}
// Extend prototype chain (so every architectures is an instance of Network)
for (var architecture in Architect) {
Architect[architecture].prototype = new Network();
Architect[architecture].prototype.constructor = Architect[architecture];
}
// export
if (module) module.exports = Architect;
},{"./layer":2,"./network":3,"./trainer":6}],2:[function(require,module,exports){
// export
if (module) module.exports = Layer;
// import
var Neuron = require('./neuron')
, Network = require('./network')
/*******************************************************************************************
LAYER
*******************************************************************************************/
function Layer(size, label) {
this.size = size | 0;
this.list = [];
this.label = label || null;
this.connectedTo = [];
while (size--) {
var neuron = new Neuron();
this.list.push(neuron);
}
}
Layer.prototype = {
// activates all the neurons in the layer
activate: function(input) {
var activations = [];
if (typeof input != 'undefined') {
if (input.length != this.size)
throw new Error("INPUT size and LAYER size must be the same to activate!");
for (var id in this.list) {
var neuron = this.list[id];
var activation = neuron.activate(input[id]);
activations.push(activation);
}
} else {
for (var id in this.list) {
var neuron = this.list[id];
var activation = neuron.activate();
activations.push(activation);
}
}
return activations;
},
// propagates the error on all the neurons of the layer
propagate: function(rate, target) {
if (typeof target != 'undefined') {
if (target.length != this.size)
throw new Error("TARGET size and LAYER size must be the same to propagate!");
for (var id = this.list.length - 1; id >= 0; id--) {
var neuron = this.list[id];
neuron.propagate(rate, target[id]);
}
} else {
for (var id = this.list.length - 1; id >= 0; id--) {
var neuron = this.list[id];
neuron.propagate(rate);
}
}
},
// projects a connection from this layer to another one
project: function(layer, type, weights) {
if (layer instanceof Network)
layer = layer.layers.input;
if (layer instanceof Layer) {
if (!this.connected(layer))
return new Layer.connection(this, layer, type, weights);
} else
throw new Error("Invalid argument, you can only project connections to LAYERS and NETWORKS!");
},
// gates a connection betwenn two layers
gate: function(connection, type) {
if (type == Layer.gateType.INPUT) {
if (connection.to.size != this.size)
throw new Error("GATER layer and CONNECTION.TO layer must be the same size in order to gate!");
for (var id in connection.to.list) {
var neuron = connection.to.list[id];
var gater = this.list[id];
for (var input in neuron.connections.inputs) {
var gated = neuron.connections.inputs[input];
if (gated.ID in connection.connections)
gater.gate(gated);
}
}
} else if (type == Layer.gateType.OUTPUT) {
if (connection.from.size != this.size)
throw new Error("GATER layer and CONNECTION.FROM layer must be the same size in order to gate!");
for (var id in connection.from.list) {
var neuron = connection.from.list[id];
var gater = this.list[id];
for (var projected in neuron.connections.projected) {
var gated = neuron.connections.projected[projected];
if (gated.ID in connection.connections)
gater.gate(gated);
}
}
} else if (type == Layer.gateType.ONE_TO_ONE) {
if (connection.size != this.size)
throw new Error("The number of GATER UNITS must be the same as the number of CONNECTIONS to gate!");
for (var id in connection.list) {
var gater = this.list[id];
var gated = connection.list[id];
gater.gate(gated);
}
}
connection.gatedfrom.push({layer: this, type: type});
},
// true or false whether the whole layer is self-connected or not
selfconnected: function() {
for (var id in this.list) {
var neuron = this.list[id];
if (!neuron.selfconnected())
return false;
}
return true;
},
// true of false whether the layer is connected to another layer (parameter) or not
connected: function(layer) {
// Check if ALL to ALL connection
var connections = 0;
for (var here in this.list) {
for (var there in layer.list) {
var from = this.list[here];
var to = layer.list[there];
var connected = from.connected(to);
if (connected.type == 'projected')
connections++;
}
}
if (connections == this.size * layer.size)
return Layer.connectionType.ALL_TO_ALL;
// Check if ONE to ONE connection
connections = 0;
for (var neuron in this.list) {
var from = this.list[neuron];
var to = layer.list[neuron];
var connected = from.connected(to);
if (connected.type == 'projected')
connections++;
}
if (connections == this.size)
return Layer.connectionType.ONE_TO_ONE;
},
// clears all the neuorns in the layer
clear: function() {
for (var id in this.list) {
var neuron = this.list[id];
neuron.clear();
}
},
// resets all the neurons in the layer
reset: function() {
for (var id in this.list) {
var neuron = this.list[id];
neuron.reset();
}
},
// returns all the neurons in the layer (array)
neurons: function() {
return this.list;
},
// adds a neuron to the layer
add: function(neuron) {
this.neurons[neuron.ID] = neuron || new Neuron();
this.list.push(neuron);
this.size++;
},
set: function(options) {
options = options || {};
for (var i in this.list) {
var neuron = this.list[i];
if (options.label)
neuron.label = options.label + '_' + neuron.ID;
if (options.squash)
neuron.squash = options.squash;
if (options.bias)
neuron.bias = options.bias;
}
return this;
}
}
// represents a connection from one layer to another, and keeps track of its weight and gain
Layer.connection = function LayerConnection(fromLayer, toLayer, type, weights) {
this.ID = Layer.connection.uid();
this.from = fromLayer;
this.to = toLayer;
this.selfconnection = toLayer == fromLayer;
this.type = type;
this.connections = {};
this.list = [];
this.size = 0;
this.gatedfrom = [];
if (typeof this.type == 'undefined')
{
if (fromLayer == toLayer)
this.type = Layer.connectionType.ONE_TO_ONE;
else
this.type = Layer.connectionType.ALL_TO_ALL;
}
if (this.type == Layer.connectionType.ALL_TO_ALL ||
this.type == Layer.connectionType.ALL_TO_ELSE) {
for (var here in this.from.list) {
for (var there in this.to.list) {
var from = this.from.list[here];
var to = this.to.list[there];
if(this.type == Layer.connectionType.ALL_TO_ELSE && from == to)
continue;
var connection = from.project(to, weights);
this.connections[connection.ID] = connection;
this.size = this.list.push(connection);
}
}
} else if (this.type == Layer.connectionType.ONE_TO_ONE) {
for (var neuron in this.from.list) {
var from = this.from.list[neuron];
var to = this.to.list[neuron];
var connection = from.project(to, weights);
this.connections[connection.ID] = connection;
this.size = this.list.push(connection);
}
}
fromLayer.connectedTo.push(this);
}
// types of connections
Layer.connectionType = {};
Layer.connectionType.ALL_TO_ALL = "ALL TO ALL";
Layer.connectionType.ONE_TO_ONE = "ONE TO ONE";
Layer.connectionType.ALL_TO_ELSE = "ALL TO ELSE";
// types of gates
Layer.gateType = {};
Layer.gateType.INPUT = "INPUT";
Layer.gateType.OUTPUT = "OUTPUT";
Layer.gateType.ONE_TO_ONE = "ONE TO ONE";
(function() {
var connections = 0;
Layer.connection.uid = function() {
return connections++;
}
})();
},{"./network":3,"./neuron":4}],3:[function(require,module,exports){
// export
if (module) module.exports = Network;
// import
var Neuron = require('./neuron')
, Layer = require('./layer')
/*******************************************************************************************
NETWORK
*******************************************************************************************/
function Network(layers) {
if (typeof layers != 'undefined') {
this.layers = layers || {
input: null,
hidden: {},
output: null
};
this.optimized = null;
}
}
Network.prototype = {
// feed-forward activation of all the layers to produce an ouput
activate: function(input) {
if (this.optimized === false)
{
this.layers.input.activate(input);
for (var layer in this.layers.hidden)
this.layers.hidden[layer].activate();
return this.layers.output.activate();
}
else
{
if (this.optimized == null)
this.optimize();
return this.optimized.activate(input);
}
},
// back-propagate the error thru the network
propagate: function(rate, target) {
if (this.optimized === false)
{
this.layers.output.propagate(rate, target);
var reverse = [];
for (var layer in this.layers.hidden)
reverse.push(this.layers.hidden[layer]);
reverse.reverse();
for (var layer in reverse)
reverse[layer].propagate(rate);
}
else
{
if (this.optimized == null)
this.optimize();
this.optimized.propagate(rate, target);
}
},
// project a connection to another unit (either a network or a layer)
project: function(unit, type, weights) {
if (this.optimized)
this.optimized.reset();
if (unit instanceof Network)
return this.layers.output.project(unit.layers.input, type, weights);
if (unit instanceof Layer)
return this.layers.output.project(unit, type, weights);
throw new Error("Invalid argument, you can only project connections to LAYERS and NETWORKS!");
},
// let this network gate a connection
gate: function(connection, type) {
if (this.optimized)
this.optimized.reset();
this.layers.output.gate(connection, type);
},
// clear all elegibility traces and extended elegibility traces (the network forgets its context, but not what was trained)
clear: function() {
this.restore();
var inputLayer = this.layers.input,
outputLayer = this.layers.output;
inputLayer.clear();
for (var layer in this.layers.hidden) {
var hiddenLayer = this.layers.hidden[layer];
hiddenLayer.clear();
}
outputLayer.clear();
if (this.optimized)
this.optimized.reset();
},
// reset all weights and clear all traces (ends up like a new network)
reset: function() {
this.restore();
var inputLayer = this.layers.input,
outputLayer = this.layers.output;
inputLayer.reset();
for (var layer in this.layers.hidden) {
var hiddenLayer = this.layers.hidden[layer];
hiddenLayer.reset();
}
outputLayer.reset();
if (this.optimized)
this.optimized.reset();
},
// hardcodes the behaviour of the whole network into a single optimized function
optimize: function() {
var that = this;
var optimized = {};
var neurons = this.neurons();
for (var i in neurons) {
var neuron = neurons[i].neuron;
var layer = neurons[i].layer;
while (neuron.neuron)
neuron = neuron.neuron;
optimized = neuron.optimize(optimized, layer);
}
for (var i in optimized.propagation_sentences)
optimized.propagation_sentences[i].reverse();
optimized.propagation_sentences.reverse();
var hardcode = "";
hardcode += "var F = Float64Array ? new Float64Array(" + optimized.memory +
") : []; ";
for (var i in optimized.variables)
hardcode += "F[" + optimized.variables[i].id + "] = " + (optimized.variables[
i].value || 0) + "; ";
hardcode += "var activate = function(input){\n";
for (var i in optimized.inputs)
hardcode += "F[" + optimized.inputs[i] + "] = input[" + i + "]; ";
for (var currentLayer in optimized.activation_sentences) {
if (optimized.activation_sentences[currentLayer].length > 0) {
for (var currentNeuron in optimized.activation_sentences[currentLayer]) {
hardcode += optimized.activation_sentences[currentLayer][currentNeuron].join(" ");
hardcode += optimized.trace_sentences[currentLayer][currentNeuron].join(" ");
}
}
}
hardcode += " var output = []; "
for (var i in optimized.outputs)
hardcode += "output[" + i + "] = F[" + optimized.outputs[i] + "]; ";
hardcode += "return output; }; "
hardcode += "var propagate = function(rate, target){\n";
hardcode += "F[" + optimized.variables.rate.id + "] = rate; ";
for (var i in optimized.targets)
hardcode += "F[" + optimized.targets[i] + "] = target[" + i + "]; ";
for (var currentLayer in optimized.propagation_sentences)
for (var currentNeuron in optimized.propagation_sentences[currentLayer])
hardcode += optimized.propagation_sentences[currentLayer][currentNeuron].join(" ") + " ";
hardcode += " };\n";
hardcode +=
"var ownership = function(memoryBuffer){\nF = memoryBuffer;\nthis.memory = F;\n};\n";
hardcode +=
"return {\nmemory: F,\nactivate: activate,\npropagate: propagate,\nownership: ownership\n};";
hardcode = hardcode.split(";").join(";\n");
var constructor = new Function(hardcode);
var network = constructor();
network.data = {
variables: optimized.variables,
activate: optimized.activation_sentences,
propagate: optimized.propagation_sentences,
trace: optimized.trace_sentences,
inputs: optimized.inputs,
outputs: optimized.outputs,
check_activation: this.activate,
check_propagation: this.propagate
}
network.reset = function() {
if (that.optimized) {
that.optimized = null;
that.activate = network.data.check_activation;
that.propagate = network.data.check_propagation;
}
}
this.optimized = network;
this.activate = network.activate;
this.propagate = network.propagate;
},
// restores all the values from the optimized network the their respective objects in order to manipulate the network
restore: function() {
if (!this.optimized)
return;
var optimized = this.optimized;
var getValue = function() {
var args = Array.prototype.slice.call(arguments);
var unit = args.shift();
var prop = args.pop();
var id = prop + '_';
for (var property in args)
id += args[property] + '_';
id += unit.ID;
var memory = optimized.memory;
var variables = optimized.data.variables;
if (id in variables)
return memory[variables[id].id];
return 0;
}
var list = this.neurons();
// link id's to positions in the array
var ids = {};
for (var i in list) {
var neuron = list[i].neuron;
while (neuron.neuron)
neuron = neuron.neuron;
neuron.state = getValue(neuron, 'state');
neuron.old = getValue(neuron, 'old');
neuron.activation = getValue(neuron, 'activation');
neuron.bias = getValue(neuron, 'bias');
for (var input in neuron.trace.elegibility)
neuron.trace.elegibility[input] = getValue(neuron, 'trace',
'elegibility', input);
for (var gated in neuron.trace.extended)
for (var input in neuron.trace.extended[gated])
neuron.trace.extended[gated][input] = getValue(neuron, 'trace',
'extended', gated, input);
}
// get connections
for (var i in list) {
var neuron = list[i].neuron;
while (neuron.neuron)
neuron = neuron.neuron;
for (var j in neuron.connections.projected) {
var connection = neuron.connections.projected[j];
connection.weight = getValue(connection, 'weight');
connection.gain = getValue(connection, 'gain');
}
}
},
// returns all the neurons in the network
neurons: function() {
var neurons = [];
var inputLayer = this.layers.input.neurons(),
outputLayer = this.layers.output.neurons();
for (var neuron in inputLayer)
neurons.push({
neuron: inputLayer[neuron],
layer: 'input'
});
for (var layer in this.layers.hidden) {
var hiddenLayer = this.layers.hidden[layer].neurons();
for (var neuron in hiddenLayer)
neurons.push({
neuron: hiddenLayer[neuron],
layer: layer
});
}
for (var neuron in outputLayer)
neurons.push({
neuron: outputLayer[neuron],
layer: 'output'
});
return neurons;
},
// returns number of inputs of the network
inputs: function() {
return this.layers.input.size;
},
// returns number of outputs of hte network
outputs: function() {
return this.layers.output.size;
},
// sets the layers of the network
set: function(layers) {
this.layers = layers;
if (this.optimized)
this.optimized.reset();
},
setOptimize: function(bool){
this.restore();
if (this.optimized)
this.optimized.reset();
this.optimized = bool? null : false;
},
// returns a json that represents all the neurons and connections of the network
toJSON: function(ignoreTraces) {
this.restore();
var list = this.neurons();
var neurons = [];
var connections = [];
// link id's to positions in the array
var ids = {};
for (var i in list) {
var neuron = list[i].neuron;
while (neuron.neuron)
neuron = neuron.neuron;
ids[neuron.ID] = i;
var copy = {
trace: {
elegibility: {},
extended: {}
},
state: neuron.state,
old: neuron.old,
activation: neuron.activation,
bias: neuron.bias,
layer: list[i].layer
};
copy.squash = neuron.squash == Neuron.squash.LOGISTIC ? "LOGISTIC" :
neuron.squash == Neuron.squash.TANH ? "TANH" :
neuron.squash == Neuron.squash.IDENTITY ? "IDENTITY" :
neuron.squash == Neuron.squash.HLIM ? "HLIM" :
null;
neurons.push(copy);
}
// get connections
for (var i in list) {
var neuron = list[i].neuron;
while (neuron.neuron)
neuron = neuron.neuron;
for (var j in neuron.connections.projected) {
var connection = neuron.connections.projected[j];
connections.push({
from: ids[connection.from.ID],
to: ids[connection.to.ID],
weight: connection.weight,
gater: connection.gater ? ids[connection.gater.ID] : null,
});
}
if (neuron.selfconnected())
connections.push({
from: ids[neuron.ID],
to: ids[neuron.ID],
weight: neuron.selfconnection.weight,
gater: neuron.selfconnection.gater ? ids[neuron.selfconnection.gater.ID] : null,
});
}
return {
neurons: neurons,
connections: connections
}
},
// export the topology into dot language which can be visualized as graphs using dot
/* example: ... console.log(net.toDotLang());
$ node example.js > example.dot
$ dot example.dot -Tpng > out.png
*/
toDot: function(edgeConnection) {
if (! typeof edgeConnection)
edgeConnection = false;
var code = "digraph nn {\n rankdir = BT\n";
var layers = [this.layers.input].concat(this.layers.hidden, this.layers.output);
for (var layer in layers) {
for (var to in layers[layer].connectedTo) { // projections
var connection = layers[layer].connectedTo[to];
var layerTo = connection.to;
var size = connection.size;
var layerID = layers.indexOf(layers[layer]);
var layerToID = layers.indexOf(layerTo);
/* http://stackoverflow.com/questions/26845540/connect-edges-with-graph-dot
* DOT does not support edge-to-edge connections
* This workaround produces somewhat weird graphs ...
*/
if ( edgeConnection) {
if (connection.gatedfrom.length) {
var fakeNode = "fake" + layerID + "_" + layerToID;
code += " " + fakeNode +
" [label = \"\", shape = point, width = 0.01, height = 0.01]\n";
code += " " + layerID + " -> " + fakeNode + " [label = " + size + ", arrowhead = none]\n";
code += " " + fakeNode + " -> " + layerToID + "\n";
} else
code += " " + layerID + " -> " + layerToID + " [label = " + size + "]\n";
for (var from in connection.gatedfrom) { // gatings
var layerfrom = connection.gatedfrom[from].layer;
var type = connection.gatedfrom[from].type;
var layerfromID = layers.indexOf(layerfrom);
code += " " + layerfromID + " -> " + fakeNode + " [color = blue]\n";
}
} else {
code += " " + layerID + " -> " + layerToID + " [label = " + size + "]\n";
for (var from in connection.gatedfrom) { // gatings
var layerfrom = connection.gatedfrom[from].layer;
var type = connection.gatedfrom[from].type;
var layerfromID = layers.indexOf(layerfrom);
code += " " + layerfromID + " -> " + layerToID + " [color = blue]\n";
}
}
}
}
code += "}\n";
return {
code: code,
link: "https://chart.googleapis.com/chart?chl=" + escape(code.replace("/ /g", "+")) + "&cht=gv"
}
},
// returns a function that works as the activation of the network and can be used without depending on the library
standalone: function() {
if (!this.optimized)