-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
neural-network.js
1082 lines (971 loc) · 30.7 KB
/
neural-network.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
const Thaw = require('thaw.js').default;
const lookup = require('./lookup');
const TrainStream = require('./train-stream');
const max = require('./utilities/max');
const mse = require('./utilities/mse');
const randos = require('./utilities/randos');
const range = require('./utilities/range');
const toArray = require('./utilities/to-array');
const zeros = require('./utilities/zeros');
const LookupTable = require('./utilities/lookup-table');
const { arrayToFloat32Array } = require('./utilities/cast');
/**
* @param {object} options
* @constructor
*/
class NeuralNetwork {
static get trainDefaults() {
return {
iterations: 20000, // the maximum times to iterate the training data
errorThresh: 0.005, // the acceptable error percentage from training data
log: false, // true to use console.log, when a function is supplied it is used
logPeriod: 10, // iterations between logging out
learningRate: 0.3, // multiply's against the input and the delta then adds to momentum
momentum: 0.1, // multiply's against the specified "change" then adds to learning rate for change
callback: null, // a periodic call back that can be triggered while training
callbackPeriod: 10, // the number of iterations through the training data between callback calls
timeout: Infinity, // the max number of milliseconds to train for
praxis: null,
beta1: 0.9,
beta2: 0.999,
epsilon: 1e-8,
};
}
static get defaults() {
return {
leakyReluAlpha: 0.01,
binaryThresh: 0.5,
hiddenLayers: null, // array of ints for the sizes of the hidden layers in the network
activation: 'sigmoid' // Supported activation types ['sigmoid', 'relu', 'leaky-relu', 'tanh']
};
}
constructor(options = {}) {
Object.assign(this, this.constructor.defaults, options);
this.trainOpts = {};
this.updateTrainingOptions(Object.assign({}, this.constructor.trainDefaults, options));
this.sizes = null;
this.outputLayer = null;
this.biases = null; // weights for bias nodes
this.weights = null;
this.outputs = null;
// state for training
this.deltas = null;
this.changes = null; // for momentum
this.errors = null;
this.errorCheckInterval = 1;
if (!this.constructor.prototype.hasOwnProperty('runInput')) {
this.runInput = null;
}
if (!this.constructor.prototype.hasOwnProperty('calculateDeltas')) {
this.calculateDeltas = null;
}
this.inputLookup = null;
this.inputLookupLength = null;
this.outputLookup = null;
this.outputLookupLength = null;
}
/**
*
* Expects this.sizes to have been set
*/
initialize() {
if (!this.sizes) throw new Error ('Sizes must be set before initializing');
this.outputLayer = this.sizes.length - 1;
this.biases = []; // weights for bias nodes
this.weights = [];
this.outputs = [];
// state for training
this.deltas = [];
this.changes = []; // for momentum
this.errors = [];
for (let layer = 0; layer <= this.outputLayer; layer++) {
let size = this.sizes[layer];
this.deltas[layer] = zeros(size);
this.errors[layer] = zeros(size);
this.outputs[layer] = zeros(size);
if (layer > 0) {
this.biases[layer] = randos(size);
this.weights[layer] = new Array(size);
this.changes[layer] = new Array(size);
for (let node = 0; node < size; node++) {
let prevSize = this.sizes[layer - 1];
this.weights[layer][node] = randos(prevSize);
this.changes[layer][node] = zeros(prevSize);
}
}
}
this.setActivation();
if (this.trainOpts.praxis === 'adam') {
this._setupAdam();
}
}
/**
*
* @param activation supported inputs: 'sigmoid', 'relu', 'leaky-relu', 'tanh'
*/
setActivation(activation) {
this.activation = activation ? activation : this.activation;
switch (this.activation) {
case 'sigmoid':
this.runInput = this.runInput || this._runInputSigmoid;
this.calculateDeltas = this.calculateDeltas || this._calculateDeltasSigmoid;
break;
case 'relu':
this.runInput = this.runInput || this._runInputRelu;
this.calculateDeltas = this.calculateDeltas || this._calculateDeltasRelu;
break;
case 'leaky-relu':
this.runInput = this.runInput || this._runInputLeakyRelu;
this.calculateDeltas = this.calculateDeltas || this._calculateDeltasLeakyRelu;
break;
case 'tanh':
this.runInput = this.runInput || this._runInputTanh;
this.calculateDeltas = this.calculateDeltas || this._calculateDeltasTanh;
break;
default:
throw new Error('unknown activation ' + this.activation + ', The activation should be one of [\'sigmoid\', \'relu\', \'leaky-relu\', \'tanh\']');
}
}
/**
*
* @returns boolean
*/
get isRunnable(){
if(!this.runInput){
console.error('Activation function has not been initialized, did you run train()?');
return false;
}
const checkFns = [
'sizes',
'outputLayer',
'biases',
'weights',
'outputs',
'deltas',
'changes',
'errors',
].filter(c => this[c] === null);
if(checkFns.length > 0){
console.error(`Some settings have not been initialized correctly, did you run train()? Found issues with: ${checkFns.join(', ')}`);
return false;
}
return true;
}
/**
*
* @param input
* @returns {*}
*/
run(input) {
if (!this.isRunnable) return null;
if (this.inputLookup) {
input = lookup.toArray(this.inputLookup, input, this.inputLookupLength);
}
let output = this.runInput(input).slice(0);
if (this.outputLookup) {
output = lookup.toObject(this.outputLookup, output);
}
return output;
}
/**
* trains via sigmoid
* @param input
* @returns {*}
*/
_runInputSigmoid(input) {
this.outputs[0] = input; // set output state of input layer
let output = null;
for (let layer = 1; layer <= this.outputLayer; layer++) {
for (let node = 0; node < this.sizes[layer]; node++) {
let weights = this.weights[layer][node];
let sum = this.biases[layer][node];
for (let k = 0; k < weights.length; k++) {
sum += weights[k] * input[k];
}
//sigmoid
this.outputs[layer][node] = 1 / (1 + Math.exp(-sum));
}
output = input = this.outputs[layer];
}
return output;
}
_runInputRelu(input) {
this.outputs[0] = input; // set output state of input layer
let output = null;
for (let layer = 1; layer <= this.outputLayer; layer++) {
for (let node = 0; node < this.sizes[layer]; node++) {
let weights = this.weights[layer][node];
let sum = this.biases[layer][node];
for (let k = 0; k < weights.length; k++) {
sum += weights[k] * input[k];
}
//relu
this.outputs[layer][node] = (sum < 0 ? 0 : sum);
}
output = input = this.outputs[layer];
}
return output;
}
_runInputLeakyRelu(input) {
this.outputs[0] = input; // set output state of input layer
let alpha = this.leakyReluAlpha;
let output = null;
for (let layer = 1; layer <= this.outputLayer; layer++) {
for (let node = 0; node < this.sizes[layer]; node++) {
let weights = this.weights[layer][node];
let sum = this.biases[layer][node];
for (let k = 0; k < weights.length; k++) {
sum += weights[k] * input[k];
}
//leaky relu
this.outputs[layer][node] = (sum < 0 ? 0 : alpha * sum);
}
output = input = this.outputs[layer];
}
return output;
}
_runInputTanh(input) {
this.outputs[0] = input; // set output state of input layer
let output = null;
for (let layer = 1; layer <= this.outputLayer; layer++) {
for (let node = 0; node < this.sizes[layer]; node++) {
let weights = this.weights[layer][node];
let sum = this.biases[layer][node];
for (let k = 0; k < weights.length; k++) {
sum += weights[k] * input[k];
}
//tanh
this.outputs[layer][node] = Math.tanh(sum);
}
output = input = this.outputs[layer];
}
return output;
}
/**
*
* @param data
* Verifies network sizes are initialized
* If they are not it will initialize them based off the data set.
*/
verifyIsInitialized(data) {
if (this.sizes) return;
this.sizes = [];
this.sizes.push(data[0].input.length);
if (!this.hiddenLayers) {
this.sizes.push(Math.max(3, Math.floor(data[0].input.length / 2)));
} else {
this.hiddenLayers.forEach(size => {
this.sizes.push(size);
});
}
this.sizes.push(data[0].output.length);
this.initialize();
}
/**
*
* @param options
* Supports all `trainDefaults` properties
* also supports:
* learningRate: (number),
* momentum: (number),
* activation: 'sigmoid', 'relu', 'leaky-relu', 'tanh'
*/
updateTrainingOptions(options) {
const trainDefaults = this.constructor.trainDefaults;
for (const p in trainDefaults) {
if (!trainDefaults.hasOwnProperty(p)) continue;
this.trainOpts[p] = options.hasOwnProperty(p)
? options[p]
: trainDefaults[p];
}
this.validateTrainingOptions(this.trainOpts);
this.setLogMethod(options.log || this.trainOpts.log);
this.activation = options.activation || this.activation;
}
/**
*
* @param options
*/
validateTrainingOptions(options) {
const validations = {
iterations: (val) => { return typeof val === 'number' && val > 0; },
errorThresh: (val) => { return typeof val === 'number' && val > 0 && val < 1; },
log: (val) => { return typeof val === 'function' || typeof val === 'boolean'; },
logPeriod: (val) => { return typeof val === 'number' && val > 0; },
learningRate: (val) => { return typeof val === 'number' && val > 0 && val < 1; },
momentum: (val) => { return typeof val === 'number' && val > 0 && val < 1; },
callback: (val) => { return typeof val === 'function' || val === null },
callbackPeriod: (val) => { return typeof val === 'number' && val > 0; },
timeout: (val) => { return typeof val === 'number' && val > 0 }
};
for (const p in validations) {
if (!validations.hasOwnProperty(p)) continue;
if (!options.hasOwnProperty(p)) continue;
if (!validations[p](options[p])) {
throw new Error(`[${p}, ${options[p]}] is out of normal training range, your network will probably not train.`);
}
}
}
/**
*
* Gets JSON of trainOpts object
* NOTE: Activation is stored directly on JSON object and not in the training options
*/
getTrainOptsJSON() {
return Object.keys(this.constructor.trainDefaults)
.reduce((opts, opt) => {
if (opt === 'timeout' && this.trainOpts[opt] === Infinity) return opts;
if (opt === 'callback') return opts;
if (this.trainOpts[opt]) opts[opt] = this.trainOpts[opt];
if (opt === 'log') opts.log = typeof opts.log === 'function';
return opts;
}, {});
}
/**
*
* @param log
* if a method is passed in method is used
* if false passed in nothing is logged
* @returns error
*/
setLogMethod(log) {
if (typeof log === 'function'){
this.trainOpts.log = log;
} else if (log) {
this.trainOpts.log = console.log;
} else {
this.trainOpts.log = false;
}
}
/**
*
* @param data
* @returns {Number} error
*/
calculateTrainingError(data) {
let sum = 0;
for (let i = 0; i < data.length; ++i) {
sum += this.trainPattern(data[i], true);
}
return sum / data.length;
}
/**
* @param data
*/
trainPatterns(data) {
for (let i = 0; i < data.length; ++i) {
this.trainPattern(data[i]);
}
}
/**
*
* @param {object} data
* @param {object} status { iterations: number, error: number }
* @param endTime
*/
trainingTick(data, status, endTime) {
if (status.iterations >= this.trainOpts.iterations || status.error <= this.trainOpts.errorThresh || Date.now() >= endTime) {
return false;
}
status.iterations++;
if (this.trainOpts.log && (status.iterations % this.trainOpts.logPeriod === 0)) {
status.error = this.calculateTrainingError(data);
this.trainOpts.log(`iterations: ${status.iterations}, training error: ${status.error}`);
} else {
if (status.iterations % this.errorCheckInterval === 0) {
status.error = this.calculateTrainingError(data);
} else {
this.trainPatterns(data);
}
}
if (this.trainOpts.callback && (status.iterations % this.trainOpts.callbackPeriod === 0)) {
this.trainOpts.callback({
iterations: status.iterations,
error: status.error
});
}
return true;
}
/**
*
* @param data
* @param options
* @protected
* @return {object} { data, status, endTime }
*/
prepTraining(data, options) {
this.updateTrainingOptions(options);
data = this.formatData(data);
const endTime = Date.now() + this.trainOpts.timeout;
const status = {
error: 1,
iterations: 0,
};
this.verifyIsInitialized(data);
return {
data,
status,
endTime,
};
}
/**
*
* @param data
* @param options
* @returns {object} {error: number, iterations: number}
*/
train(data, options = {}) {
let status, endTime;
({ data, status, endTime } = this.prepTraining(data, options));
while (this.trainingTick(data, status, endTime));
return status;
}
/**
*
* @param data
* @param options
* @returns {Promise}
* @resolves {{error: number, iterations: number}}
* @rejects {{trainError: string, status: {error: number, iterations: number}}
*/
trainAsync(data, options = {}) {
let status, endTime;
({ data, status, endTime } = this.prepTraining(data, options));
return new Promise((resolve, reject) => {
try {
const thawedTrain = new Thaw(new Array(this.trainOpts.iterations), {
delay: true,
each: () => this.trainingTick(data, status, endTime) || thawedTrain.stop(),
done: () => resolve(status)
});
thawedTrain.tick();
} catch (trainError) {
reject({trainError, status});
}
});
}
/**
*
* @param {object} value
* @param {boolean} [logErrorRate]
*/
trainPattern(value, logErrorRate) {
// forward propagate
this.runInput(value.input);
// back propagate
this.calculateDeltas(value.output);
this.adjustWeights();
if (logErrorRate) {
return mse(this.errors[this.outputLayer]);
} else {
return null;
}
}
/**
*
* @param target
*/
_calculateDeltasSigmoid(target) {
for (let layer = this.outputLayer; layer >= 0; layer--) {
for (let node = 0; node < this.sizes[layer]; node++) {
let output = this.outputs[layer][node];
let error = 0;
if (layer === this.outputLayer) {
error = target[node] - output;
}
else {
let deltas = this.deltas[layer + 1];
for (let k = 0; k < deltas.length; k++) {
error += deltas[k] * this.weights[layer + 1][k][node];
}
}
this.errors[layer][node] = error;
this.deltas[layer][node] = error * output * (1 - output);
}
}
}
/**
*
* @param target
*/
_calculateDeltasRelu(target) {
for (let layer = this.outputLayer; layer >= 0; layer--) {
for (let node = 0; node < this.sizes[layer]; node++) {
let output = this.outputs[layer][node];
let error = 0;
if (layer === this.outputLayer) {
error = target[node] - output;
}
else {
let deltas = this.deltas[layer + 1];
for (let k = 0; k < deltas.length; k++) {
error += deltas[k] * this.weights[layer + 1][k][node];
}
}
this.errors[layer][node] = error;
this.deltas[layer][node] = output > 0 ? error : 0;
}
}
}
/**
*
* @param target
*/
_calculateDeltasLeakyRelu(target) {
let alpha = this.leakyReluAlpha;
for (let layer = this.outputLayer; layer >= 0; layer--) {
for (let node = 0; node < this.sizes[layer]; node++) {
let output = this.outputs[layer][node];
let error = 0;
if (layer === this.outputLayer) {
error = target[node] - output;
}
else {
let deltas = this.deltas[layer + 1];
for (let k = 0; k < deltas.length; k++) {
error += deltas[k] * this.weights[layer + 1][k][node];
}
}
this.errors[layer][node] = error;
this.deltas[layer][node] = output > 0 ? error : alpha * error;
}
}
}
/**
*
* @param target
*/
_calculateDeltasTanh(target) {
for (let layer = this.outputLayer; layer >= 0; layer--) {
for (let node = 0; node < this.sizes[layer]; node++) {
let output = this.outputs[layer][node];
let error = 0;
if (layer === this.outputLayer) {
error = target[node] - output;
}
else {
let deltas = this.deltas[layer + 1];
for (let k = 0; k < deltas.length; k++) {
error += deltas[k] * this.weights[layer + 1][k][node];
}
}
this.errors[layer][node] = error;
this.deltas[layer][node] = (1 - output * output) * error;
}
}
}
/**
*
* Changes weights of networks
*/
adjustWeights() {
for (let layer = 1; layer <= this.outputLayer; layer++) {
let incoming = this.outputs[layer - 1];
for (let node = 0; node < this.sizes[layer]; node++) {
let delta = this.deltas[layer][node];
for (let k = 0; k < incoming.length; k++) {
let change = this.changes[layer][node][k];
change = (this.trainOpts.learningRate * delta * incoming[k])
+ (this.trainOpts.momentum * change);
this.changes[layer][node][k] = change;
this.weights[layer][node][k] += change;
}
this.biases[layer][node] += this.trainOpts.learningRate * delta;
}
}
}
_setupAdam() {
this.biasChangesLow = [];
this.biasChangesHigh = [];
this.changesLow = [];
this.changesHigh = [];
this.iterations = 0;
for (let layer = 0; layer <= this.outputLayer; layer++) {
let size = this.sizes[layer];
if (layer > 0) {
this.biasChangesLow[layer] = zeros(size);
this.biasChangesHigh[layer] = zeros(size);
this.changesLow[layer] = new Array(size);
this.changesHigh[layer] = new Array(size);
for (let node = 0; node < size; node++) {
let prevSize = this.sizes[layer - 1];
this.changesLow[layer][node] = zeros(prevSize);
this.changesHigh[layer][node] = zeros(prevSize);
}
}
}
this.adjustWeights = this._adjustWeightsAdam;
}
_adjustWeightsAdam() {
const trainOpts = this.trainOpts;
this.iterations++;
for (let layer = 1; layer <= this.outputLayer; layer++) {
const incoming = this.outputs[layer - 1];
for (let node = 0; node < this.sizes[layer]; node++) {
const delta = this.deltas[layer][node];
for (let k = 0; k < incoming.length; k++) {
const gradient = delta * incoming[k];
const changeLow = this.changesLow[layer][node][k] * trainOpts.beta1 + (1 - trainOpts.beta1) * gradient;
const changeHigh = this.changesHigh[layer][node][k] * trainOpts.beta2 + (1 - trainOpts.beta2) * gradient * gradient;
const momentumCorrection = changeLow / (1 - Math.pow(trainOpts.beta1, this.iterations));
const gradientCorrection = changeHigh / (1 - Math.pow(trainOpts.beta2, this.iterations));
this.changesLow[layer][node][k] = changeLow;
this.changesHigh[layer][node][k] = changeHigh;
this.weights[layer][node][k] += this.trainOpts.learningRate * momentumCorrection / (Math.sqrt(gradientCorrection) + trainOpts.epsilon);
}
const biasGradient = this.deltas[layer][node];
const biasChangeLow = this.biasChangesLow[layer][node] * trainOpts.beta1 + (1 - trainOpts.beta1) * biasGradient;
const biasChangeHigh = this.biasChangesHigh[layer][node] * trainOpts.beta2 + (1 - trainOpts.beta2) * biasGradient * biasGradient;
const biasMomentumCorrection = this.biasChangesLow[layer][node] / (1 - Math.pow(trainOpts.beta1, this.iterations));
const biasGradientCorrection = this.biasChangesHigh[layer][node] / (1 - Math.pow(trainOpts.beta2, this.iterations));
this.biasChangesLow[layer][node] = biasChangeLow;
this.biasChangesHigh[layer][node] = biasChangeHigh;
this.biases[layer][node] += trainOpts.learningRate * biasMomentumCorrection / (Math.sqrt(biasGradientCorrection) + trainOpts.epsilon);
}
}
}
/**
*
* @param data
* @returns {*}
*/
formatData(data) {
if (!Array.isArray(data)) { // turn stream datum into array
data = [data];
}
if (!Array.isArray(data[0].input)) {
if (this.inputLookup) {
this.inputLookupLength = Object.keys(this.inputLookup).length;
} else {
const inputLookup = new LookupTable(data, 'input');
this.inputLookup = inputLookup.table;
this.inputLookupLength = inputLookup.length;
}
}
if (!Array.isArray(data[0].output)) {
if (this.outputLookup) {
this.outputLookupLength = Object.keys(this.outputLookup).length;
} else {
const lookup = new LookupTable(data, 'output');
this.outputLookup = lookup.table;
this.outputLookupLength = lookup.length;
}
}
if (typeof this._formatInput === 'undefined') {
this._formatInput = getTypedArrayFn(data[0].input, this.inputLookup);
this._formatOutput = getTypedArrayFn(data[0].output, this.outputLookup);
}
// turn sparse hash input into arrays with 0s as filler
if (this._formatInput && this._formatOutput) {
const result = [];
for (let i = 0; i < data.length; i++) {
result.push({
input: this._formatInput(data[i].input),
output: this._formatOutput(data[i].output),
});
}
return result;
} else if (this._formatInput) {
const result = [];
for (let i = 0; i < data.length; i++) {
result.push({
input: this._formatInput(data[i].input),
output: data[i].output
});
}
return result;
} else if (this._formatOutput) {
const result = [];
for (let i = 0; i < data.length; i++) {
result.push({
input: data[i].input,
output: this._formatOutput(data[i].output)
});
}
return result;
}
return data;
}
addFormat(data) {
this.inputLookup = lookup.addKeys(data.input, this.inputLookup);
if (this.inputLookup) {
this.inputLookupLength = Object.keys(this.inputLookup).length;
}
this.outputLookup = lookup.addKeys(data.output, this.outputLookup);
if (this.outputLookup) {
this.outputLookupLength = Object.keys(this.outputLookup).length;
}
}
/**
*
* @param data
* @returns {
* {
* error: number,
* misclasses: Array,
* }
* }
*/
test(data) {
data = this.formatData(data);
// for binary classification problems with one output node
const isBinary = data[0].output.length === 1;
// for classification problems
const misclasses = [];
// run each pattern through the trained network and collect
// error and misclassification statistics
let errorSum = 0;
if (isBinary) {
let falsePos = 0;
let falseNeg = 0;
let truePos = 0;
let trueNeg = 0;
for (let i = 0; i < data.length; i++) {
const output = this.runInput(data[i].input);
const target = data[i].output;
const actual = output[0] > this.binaryThresh ? 1 : 0;
const expected = target[0];
if (actual !== expected) {
const misclass = data[i];
misclasses.push({
input: misclass.input,
output: misclass.output,
actual,
expected
});
}
if (actual === 0 && expected === 0) {
trueNeg++;
} else if (actual === 1 && expected === 1) {
truePos++;
} else if (actual === 0 && expected === 1) {
falseNeg++;
} else if (actual === 1 && expected === 0) {
falsePos++;
}
errorSum += mse(output.map((value, i) => {
return target[i] - value;
}));
}
return {
error: errorSum / data.length,
misclasses: misclasses,
total: data.length,
trueNeg: trueNeg,
truePos: truePos,
falseNeg: falseNeg,
falsePos: falsePos,
precision: truePos > 0 ? truePos / (truePos + falsePos) : 0,
recall: truePos > 0 ? truePos / (truePos + falseNeg) : 0,
accuracy: (trueNeg + truePos) / data.length
};
}
for (let i = 0; i < data.length; i++) {
const output = this.runInput(data[i].input);
const target = data[i].output;
const actual = output.indexOf(max(output));
const expected = target.indexOf(max(target));
if (actual !== expected) {
const misclass = data[i];
misclasses.push({
input: misclass.input,
output: misclass.output,
actual,
expected
});
}
errorSum += mse(output.map((value, i) => {
return target[i] - value;
}));
}
return {
error: errorSum / data.length,
misclasses: misclasses,
total: data.length
};
}
/**
*
* @returns
* {
* layers: [
* {
* x: {},
* y: {}
* },
* {
* '0': {
* bias: -0.98771313,
* weights: {
* x: 0.8374838,
* y: 1.245858
* },
* '1': {
* bias: 3.48192004,
* weights: {
* x: 1.7825821,
* y: -2.67899
* }
* }
* },
* {
* f: {
* bias: 0.27205739,
* weights: {
* '0': 1.3161821,
* '1': 2.00436
* }
* }
* }
* ]
* }
*/
toJSON() {
const layers = [];
for (let layer = 0; layer <= this.outputLayer; layer++) {
layers[layer] = {};
let nodes;
// turn any internal arrays back into hashes for readable json
if (layer === 0 && this.inputLookup) {
nodes = Object.keys(this.inputLookup);
} else if (this.outputLookup && layer === this.outputLayer) {
nodes = Object.keys(this.outputLookup);
} else {
nodes = range(0, this.sizes[layer]);
}
for (let j = 0; j < nodes.length; j++) {
const node = nodes[j];
layers[layer][node] = {};
if (layer > 0) {
layers[layer][node].bias = this.biases[layer][j];
layers[layer][node].weights = {};
for (let k in layers[layer - 1]) {
let index = k;
if (layer === 1 && this.inputLookup) {
index = this.inputLookup[k];
}
layers[layer][node].weights[k] = this.weights[layer][j][index];
}
}
}
}
return {
sizes: this.sizes.slice(0),
layers,
outputLookup: this.outputLookup !== null,
inputLookup: this.inputLookup !== null,
activation: this.activation,
trainOpts: this.getTrainOptsJSON()
};
}
/**
*
* @param json
* @returns {NeuralNetwork}
*/
fromJSON(json) {
Object.assign(this, this.constructor.defaults, json);
this.sizes = json.sizes;
this.initialize();
for (let i = 0; i <= this.outputLayer; i++) {
let layer = json.layers[i];
if (i === 0 && (!layer[0] || json.inputLookup)) {
this.inputLookup = lookup.toHash(layer);
this.inputLookupLength = Object.keys(this.inputLookup).length;
}
else if (i === this.outputLayer && (!layer[0] || json.outputLookup)) {
this.outputLookup = lookup.toHash(layer);
}
if (i > 0) {
const nodes = Object.keys(layer);
this.sizes[i] = nodes.length;
for (let j in nodes) {
if (nodes.hasOwnProperty(j)) {
const node = nodes[j];
this.biases[i][j] = layer[node].bias;
this.weights[i][j] = toArray(layer[node].weights);
}
}
}
}
if (json.hasOwnProperty('trainOpts')) {
this.updateTrainingOptions(json.trainOpts);
}
return this;
}
/**
*