-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
neural-network.ts
1331 lines (1203 loc) · 39.6 KB
/
neural-network.ts
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
import { Thaw } from 'thaw.js';
import { ITrainingStatus } from './feed-forward';
import { INumberHash, lookup } from './lookup';
import {
INeuralNetworkBinaryTestResult,
INeuralNetworkState,
INeuralNetworkTestResult,
} from './neural-network-types';
import { arrayToFloat32Array } from './utilities/cast';
import { LookupTable } from './utilities/lookup-table';
import { max } from './utilities/max';
import { mse } from './utilities/mse';
import { randos } from './utilities/randos';
import { zeros } from './utilities/zeros';
type NeuralNetworkFormatter =
| ((v: INumberHash) => Float32Array)
| ((v: number[]) => Float32Array);
export function getTypedArrayFn(
value: INeuralNetworkData,
table: INumberHash | null
): null | NeuralNetworkFormatter {
if ((value as Float32Array).buffer instanceof ArrayBuffer) {
return null;
}
if (Array.isArray(value)) {
return arrayToFloat32Array;
}
if (!table) throw new Error('table is not Object');
const { length } = Object.keys(table);
return (v: INumberHash): Float32Array => {
const array = new Float32Array(length);
for (const p in table) {
if (!table.hasOwnProperty(p)) continue;
if (typeof v[p] !== 'number') continue;
array[table[p]] = v[p] || 0;
}
return array;
};
}
export type NeuralNetworkActivation =
| 'sigmoid'
| 'relu'
| 'leaky-relu'
| 'tanh';
export interface IJSONLayer {
biases: number[];
weights: number[][];
}
export interface INeuralNetworkJSON {
type: string;
sizes: number[];
layers: IJSONLayer[];
inputLookup: INumberHash | null;
inputLookupLength: number;
outputLookup: INumberHash | null;
outputLookupLength: number;
options: INeuralNetworkOptions;
trainOpts: INeuralNetworkTrainOptionsJSON;
}
export interface INeuralNetworkOptions {
inputSize: number;
outputSize: number;
binaryThresh: number;
hiddenLayers?: number[];
}
export function defaults(): INeuralNetworkOptions {
return {
inputSize: 0,
outputSize: 0,
binaryThresh: 0.5,
};
}
export interface INeuralNetworkTrainOptionsJSON {
activation: NeuralNetworkActivation | string;
iterations: number;
errorThresh: number;
log: boolean;
logPeriod: number;
leakyReluAlpha: number;
learningRate: number;
momentum: number;
callbackPeriod: number;
timeout: number | 'Infinity';
praxis?: 'adam';
beta1: number;
beta2: number;
epsilon: number;
}
export interface INeuralNetworkPreppedTrainingData<T> {
status: ITrainingStatus;
preparedData: Array<INeuralNetworkDatumFormatted<T>>;
endTime: number;
}
export interface INeuralNetworkTrainOptions {
activation: NeuralNetworkActivation | string;
iterations: number;
errorThresh: number;
log: boolean | ((status: INeuralNetworkState) => void);
logPeriod: number;
leakyReluAlpha: number;
learningRate: number;
momentum: number;
callback?: (status: { iterations: number; error: number }) => void;
callbackPeriod: number;
timeout: number;
praxis?: 'adam';
beta1: number;
beta2: number;
epsilon: number;
}
export function trainDefaults(): INeuralNetworkTrainOptions {
return {
activation: 'sigmoid',
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
leakyReluAlpha: 0.01,
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
callbackPeriod: 10, // the number of iterations through the training data between callback calls
timeout: Infinity, // the max number of milliseconds to train for
beta1: 0.9,
beta2: 0.999,
epsilon: 1e-8,
};
}
export type INeuralNetworkData = number[] | Float32Array | Partial<INumberHash>;
// TODO: should be replaced by ITrainingDatum
export interface INeuralNetworkDatum<InputType, OutputType> {
input: InputType;
output: OutputType;
}
export interface INeuralNetworkDatumFormatted<T> {
input: T;
output: T;
}
export class NeuralNetwork<
InputType extends INeuralNetworkData,
OutputType extends INeuralNetworkData
> {
options: INeuralNetworkOptions = defaults();
trainOpts: INeuralNetworkTrainOptions = trainDefaults();
sizes: number[] = [];
outputLayer = -1;
biases: Float32Array[] = [];
weights: Float32Array[][] = []; // weights for bias nodes
outputs: Float32Array[] = [];
// state for training
deltas: Float32Array[] = [];
changes: Float32Array[][] = []; // for momentum
errors: Float32Array[] = [];
errorCheckInterval = 1;
inputLookup: INumberHash | null = null;
inputLookupLength = 0;
outputLookup: INumberHash | null = null;
outputLookupLength = 0;
_formatInput: NeuralNetworkFormatter | null = null;
_formatOutput: NeuralNetworkFormatter | null = null;
runInput: (input: Float32Array) => Float32Array = (input: Float32Array) => {
this.setActivation();
return this.runInput(input);
};
calculateDeltas: (output: Float32Array) => void = (
output: Float32Array
): void => {
this.setActivation();
return this.calculateDeltas(output);
};
// adam
biasChangesLow: Float32Array[] = [];
biasChangesHigh: Float32Array[] = [];
changesLow: Float32Array[][] = [];
changesHigh: Float32Array[][] = [];
iterations = 0;
constructor(
options: Partial<INeuralNetworkOptions & INeuralNetworkTrainOptions> = {}
) {
this.options = { ...this.options, ...options };
this.updateTrainingOptions(options);
const { inputSize, hiddenLayers, outputSize } = this.options;
if (inputSize && outputSize) {
this.sizes = [inputSize].concat(hiddenLayers ?? []).concat([outputSize]);
}
}
/**
*
* Expects this.sizes to have been set
*/
initialize(): void {
if (!this.sizes.length) {
throw new Error('Sizes must be set before initializing');
}
this.outputLayer = this.sizes.length - 1;
this.biases = new Array(this.outputLayer); // weights for bias nodes
this.weights = new Array(this.outputLayer);
this.outputs = new Array(this.outputLayer);
// state for training
this.deltas = new Array(this.outputLayer);
this.changes = new Array(this.outputLayer); // for momentum
this.errors = new Array(this.outputLayer);
for (let layerIndex = 0; layerIndex <= this.outputLayer; layerIndex++) {
const size = this.sizes[layerIndex];
this.deltas[layerIndex] = zeros(size);
this.errors[layerIndex] = zeros(size);
this.outputs[layerIndex] = zeros(size);
if (layerIndex > 0) {
this.biases[layerIndex] = randos(size);
this.weights[layerIndex] = new Array(size);
this.changes[layerIndex] = new Array(size);
for (let nodeIndex = 0; nodeIndex < size; nodeIndex++) {
const prevSize = this.sizes[layerIndex - 1];
this.weights[layerIndex][nodeIndex] = randos(prevSize);
this.changes[layerIndex][nodeIndex] = zeros(prevSize);
}
}
}
this.setActivation();
if (this.trainOpts.praxis === 'adam') {
this._setupAdam();
}
}
setActivation(activation?: NeuralNetworkActivation): void {
const value = activation ?? this.trainOpts.activation;
switch (value) {
case 'sigmoid':
this.runInput = this._runInputSigmoid;
this.calculateDeltas = this._calculateDeltasSigmoid;
break;
case 'relu':
this.runInput = this._runInputRelu;
this.calculateDeltas = this._calculateDeltasRelu;
break;
case 'leaky-relu':
this.runInput = this._runInputLeakyRelu;
this.calculateDeltas = this._calculateDeltasLeakyRelu;
break;
case 'tanh':
this.runInput = this._runInputTanh;
this.calculateDeltas = this._calculateDeltasTanh;
break;
default:
throw new Error(
`Unknown activation ${value}. Available activations are: 'sigmoid', 'relu', 'leaky-relu', 'tanh'`
);
}
}
get isRunnable(): boolean {
return this.sizes.length > 0;
}
run(input: Partial<InputType>): OutputType {
if (!this.isRunnable) {
throw new Error('network not runnable');
}
let formattedInput: Float32Array;
if (this.inputLookup) {
formattedInput = lookup.toArray(
this.inputLookup,
(input as unknown) as INumberHash,
this.inputLookupLength
);
} else {
formattedInput = (input as unknown) as Float32Array;
}
this.validateInput(formattedInput);
const output = this.runInput(formattedInput).slice(0);
if (this.outputLookup) {
return (lookup.toObject(
this.outputLookup,
output
) as unknown) as OutputType;
}
return (output as unknown) as OutputType;
}
_runInputSigmoid(input: Float32Array): Float32Array {
this.outputs[0] = input; // set output state of input layer
let output = null;
for (let layer = 1; layer <= this.outputLayer; layer++) {
const activeLayer = this.sizes[layer];
const activeWeights = this.weights[layer];
const activeBiases = this.biases[layer];
const activeOutputs = this.outputs[layer];
for (let node = 0; node < activeLayer; node++) {
const weights = activeWeights[node];
let sum = activeBiases[node];
for (let k = 0; k < weights.length; k++) {
sum += weights[k] * input[k];
}
// sigmoid
activeOutputs[node] = 1 / (1 + Math.exp(-sum));
}
output = input = activeOutputs;
}
if (!output) {
throw new Error('output was empty');
}
return output;
}
_runInputRelu(input: Float32Array): Float32Array {
this.outputs[0] = input; // set output state of input layer
let output = null;
for (let layer = 1; layer <= this.outputLayer; layer++) {
const activeSize = this.sizes[layer];
const activeWeights = this.weights[layer];
const activeBiases = this.biases[layer];
const activeOutputs = this.outputs[layer];
for (let node = 0; node < activeSize; node++) {
const weights = activeWeights[node];
let sum = activeBiases[node];
for (let k = 0; k < weights.length; k++) {
sum += weights[k] * input[k];
}
// relu
activeOutputs[node] = sum < 0 ? 0 : sum;
}
output = input = activeOutputs;
}
if (!output) {
throw new Error('output was empty');
}
return output;
}
_runInputLeakyRelu(input: Float32Array): Float32Array {
this.outputs[0] = input; // set output state of input layer
const { leakyReluAlpha } = this.trainOpts;
let output = null;
for (let layer = 1; layer <= this.outputLayer; layer++) {
const activeSize = this.sizes[layer];
const activeWeights = this.weights[layer];
const activeBiases = this.biases[layer];
const activeOutputs = this.outputs[layer];
for (let node = 0; node < activeSize; node++) {
const weights = activeWeights[node];
let sum = activeBiases[node];
for (let k = 0; k < weights.length; k++) {
sum += weights[k] * input[k];
}
// leaky relu
activeOutputs[node] = Math.max(sum, leakyReluAlpha * sum);
}
output = input = activeOutputs;
}
if (!output) {
throw new Error('output was empty');
}
return output;
}
_runInputTanh(input: Float32Array): Float32Array {
this.outputs[0] = input; // set output state of input layer
let output = null;
for (let layer = 1; layer <= this.outputLayer; layer++) {
const activeSize = this.sizes[layer];
const activeWeights = this.weights[layer];
const activeBiases = this.biases[layer];
const activeOutputs = this.outputs[layer];
for (let node = 0; node < activeSize; node++) {
const weights = activeWeights[node];
let sum = activeBiases[node];
for (let k = 0; k < weights.length; k++) {
sum += weights[k] * input[k];
}
// tanh
activeOutputs[node] = Math.tanh(sum);
}
output = input = activeOutputs;
}
if (!output) {
throw new Error('output was empty');
}
return output;
}
/**
*
* Verifies network sizes are initialized
* If they are not it will initialize them based off the data set.
*/
verifyIsInitialized(
preparedData: Array<INeuralNetworkDatumFormatted<Float32Array>>
): void {
if (this.sizes.length && this.outputLayer > 0) return;
this.sizes = [];
this.sizes.push(preparedData[0].input.length);
if (!this.options.hiddenLayers) {
this.sizes.push(
Math.max(3, Math.floor(preparedData[0].input.length / 2))
);
} else {
this.options.hiddenLayers.forEach((size) => {
this.sizes.push(size);
});
}
this.sizes.push(preparedData[0].output.length);
this.initialize();
}
updateTrainingOptions(trainOpts: Partial<INeuralNetworkTrainOptions>): void {
const merged = { ...this.trainOpts, ...trainOpts };
this.validateTrainingOptions(merged);
this.trainOpts = merged;
this.setLogMethod(this.trainOpts.log);
}
validateTrainingOptions(options: INeuralNetworkTrainOptions): void {
const validations: { [fnName: string]: () => boolean } = {
activation: () => {
return ['sigmoid', 'relu', 'leaky-relu', 'tanh'].includes(
options.activation
);
},
iterations: () => {
const val = options.iterations;
return typeof val === 'number' && val > 0;
},
errorThresh: () => {
const val = options.errorThresh;
return typeof val === 'number' && val > 0 && val < 1;
},
log: () => {
const val = options.log;
return typeof val === 'function' || typeof val === 'boolean';
},
logPeriod: () => {
const val = options.logPeriod;
return typeof val === 'number' && val > 0;
},
leakyReluAlpha: () => {
const val = options.leakyReluAlpha;
return typeof val === 'number' && val > 0 && val < 1;
},
learningRate: () => {
const val = options.learningRate;
return typeof val === 'number' && val > 0 && val < 1;
},
momentum: () => {
const val = options.momentum;
return typeof val === 'number' && val > 0 && val < 1;
},
callback: () => {
const val = options.callback;
return typeof val === 'function' || val === undefined;
},
callbackPeriod: () => {
const val = options.callbackPeriod;
return typeof val === 'number' && val > 0;
},
timeout: () => {
const val = options.timeout;
return typeof val === 'number' && val > 0;
},
praxis: () => {
const val = options.praxis;
return !val || val === 'adam';
},
beta1: () => {
const val = options.beta1;
return val > 0 && val < 1;
},
beta2: () => {
const val = options.beta2;
return val > 0 && val < 1;
},
epsilon: () => {
const val = options.epsilon;
return val > 0 && val < 1;
},
};
for (const p in validations) {
const v = (options as unknown) as { [v: string]: string };
if (!validations[p]()) {
throw new Error(
`[${p}, ${v[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(): INeuralNetworkTrainOptionsJSON {
const {
activation,
iterations,
errorThresh,
log,
logPeriod,
leakyReluAlpha,
learningRate,
momentum,
callbackPeriod,
timeout,
praxis,
beta1,
beta2,
epsilon,
} = this.trainOpts;
return {
activation,
iterations,
errorThresh,
log:
typeof log === 'function'
? true
: typeof log === 'boolean'
? log
: false,
logPeriod,
leakyReluAlpha,
learningRate,
momentum,
callbackPeriod,
timeout: timeout === Infinity ? 'Infinity' : timeout,
praxis,
beta1,
beta2,
epsilon,
};
}
setLogMethod(log: boolean | ((state: INeuralNetworkState) => void)): void {
if (typeof log === 'function') {
this.trainOpts.log = log;
} else if (log) {
this.trainOpts.log = this.logTrainingStatus;
} else {
this.trainOpts.log = false;
}
}
logTrainingStatus(status: INeuralNetworkState): void {
console.log(
`iterations: ${status.iterations}, training error: ${status.error}`
);
}
calculateTrainingError(
data: Array<INeuralNetworkDatumFormatted<Float32Array>>
): number {
let sum = 0;
for (let i = 0; i < data.length; ++i) {
sum += this.trainPattern(data[i], true) as number;
}
return sum / data.length;
}
trainPatterns(data: Array<INeuralNetworkDatumFormatted<Float32Array>>): void {
for (let i = 0; i < data.length; ++i) {
this.trainPattern(data[i]);
}
}
trainingTick(
data: Array<INeuralNetworkDatumFormatted<Float32Array>>,
status: INeuralNetworkState,
endTime: number
): boolean {
const {
callback,
callbackPeriod,
errorThresh,
iterations,
log,
logPeriod,
} = this.trainOpts;
if (
status.iterations >= iterations ||
status.error <= errorThresh ||
Date.now() >= endTime
) {
return false;
}
status.iterations++;
if (log && status.iterations % logPeriod === 0) {
status.error = this.calculateTrainingError(data);
(log as (state: INeuralNetworkState) => void)(status);
} else if (status.iterations % this.errorCheckInterval === 0) {
status.error = this.calculateTrainingError(data);
} else {
this.trainPatterns(data);
}
if (callback && status.iterations % callbackPeriod === 0) {
callback({
iterations: status.iterations,
error: status.error,
});
}
return true;
}
prepTraining(
data: Array<INeuralNetworkDatum<InputType, OutputType>>,
options: Partial<INeuralNetworkTrainOptions> = {}
): INeuralNetworkPreppedTrainingData<Float32Array> {
this.updateTrainingOptions(options);
const preparedData = this.formatData(data);
const endTime = Date.now() + this.trainOpts.timeout;
const status = {
error: 1,
iterations: 0,
};
this.verifyIsInitialized(preparedData);
this.validateData(preparedData);
return {
preparedData,
status,
endTime,
};
}
train(
data: Array<INeuralNetworkDatum<Partial<InputType>, Partial<OutputType>>>,
options: Partial<INeuralNetworkTrainOptions> = {}
): INeuralNetworkState {
const { preparedData, status, endTime } = this.prepTraining(
data as Array<INeuralNetworkDatum<InputType, OutputType>>,
options
);
while (true) {
if (!this.trainingTick(preparedData, status, endTime)) {
break;
}
}
return status;
}
async trainAsync(
data: Array<INeuralNetworkDatum<InputType, OutputType>>,
options: Partial<INeuralNetworkTrainOptions> = {}
): Promise<ITrainingStatus> {
const { preparedData, status, endTime } = this.prepTraining(data, options);
return await new Promise((resolve, reject) => {
try {
const thawedTrain: Thaw = new Thaw(
new Array(this.trainOpts.iterations),
{
delay: true,
each: () =>
this.trainingTick(preparedData, status, endTime) ||
thawedTrain.stop(),
done: () => resolve(status),
}
);
thawedTrain.tick();
} catch (trainError) {
reject(trainError);
}
});
}
trainPattern(
value: INeuralNetworkDatumFormatted<Float32Array>,
logErrorRate?: boolean
): number | null {
// forward propagate
this.runInput(value.input);
// back propagate
this.calculateDeltas(value.output);
this.adjustWeights();
if (logErrorRate) {
return mse(this.errors[this.outputLayer]);
}
return null;
}
_calculateDeltasSigmoid(target: Float32Array): void {
for (let layer = this.outputLayer; layer >= 0; layer--) {
const activeSize = this.sizes[layer];
const activeOutput = this.outputs[layer];
const activeError = this.errors[layer];
const activeDeltas = this.deltas[layer];
const nextLayer = this.weights[layer + 1];
for (let node = 0; node < activeSize; node++) {
const output = activeOutput[node];
let error = 0;
if (layer === this.outputLayer) {
error = target[node] - output;
} else {
const deltas = this.deltas[layer + 1];
for (let k = 0; k < deltas.length; k++) {
error += deltas[k] * nextLayer[k][node];
}
}
activeError[node] = error;
activeDeltas[node] = error * output * (1 - output);
}
}
}
_calculateDeltasRelu(target: Float32Array): void {
for (let layer = this.outputLayer; layer >= 0; layer--) {
const currentSize = this.sizes[layer];
const currentOutputs = this.outputs[layer];
const nextWeights = this.weights[layer + 1];
const nextDeltas = this.deltas[layer + 1];
const currentErrors = this.errors[layer];
const currentDeltas = this.deltas[layer];
for (let node = 0; node < currentSize; node++) {
const output = currentOutputs[node];
let error = 0;
if (layer === this.outputLayer) {
error = target[node] - output;
} else {
for (let k = 0; k < nextDeltas.length; k++) {
error += nextDeltas[k] * nextWeights[k][node];
}
}
currentErrors[node] = error;
currentDeltas[node] = output > 0 ? error : 0;
}
}
}
_calculateDeltasLeakyRelu(target: Float32Array): void {
const alpha = this.trainOpts.leakyReluAlpha;
for (let layer = this.outputLayer; layer >= 0; layer--) {
const currentSize = this.sizes[layer];
const currentOutputs = this.outputs[layer];
const nextDeltas = this.deltas[layer + 1];
const nextWeights = this.weights[layer + 1];
const currentErrors = this.errors[layer];
const currentDeltas = this.deltas[layer];
for (let node = 0; node < currentSize; node++) {
const output = currentOutputs[node];
let error = 0;
if (layer === this.outputLayer) {
error = target[node] - output;
} else {
for (let k = 0; k < nextDeltas.length; k++) {
error += nextDeltas[k] * nextWeights[k][node];
}
}
currentErrors[node] = error;
currentDeltas[node] = output > 0 ? error : alpha * error;
}
}
}
_calculateDeltasTanh(target: Float32Array): void {
for (let layer = this.outputLayer; layer >= 0; layer--) {
const currentSize = this.sizes[layer];
const currentOutputs = this.outputs[layer];
const nextDeltas = this.deltas[layer + 1];
const nextWeights = this.weights[layer + 1];
const currentErrors = this.errors[layer];
const currentDeltas = this.deltas[layer];
for (let node = 0; node < currentSize; node++) {
const output = currentOutputs[node];
let error = 0;
if (layer === this.outputLayer) {
error = target[node] - output;
} else {
for (let k = 0; k < nextDeltas.length; k++) {
error += nextDeltas[k] * nextWeights[k][node];
}
}
currentErrors[node] = error;
currentDeltas[node] = (1 - output * output) * error;
}
}
}
/**
*
* Changes weights of networks
*/
adjustWeights(): void {
const { learningRate, momentum } = this.trainOpts;
for (let layer = 1; layer <= this.outputLayer; layer++) {
const incoming = this.outputs[layer - 1];
const activeSize = this.sizes[layer];
const activeDelta = this.deltas[layer];
const activeChanges = this.changes[layer];
const activeWeights = this.weights[layer];
const activeBiases = this.biases[layer];
for (let node = 0; node < activeSize; node++) {
const delta = activeDelta[node];
for (let k = 0; k < incoming.length; k++) {
let change = activeChanges[node][k];
change = learningRate * delta * incoming[k] + momentum * change;
activeChanges[node][k] = change;
activeWeights[node][k] += change;
}
activeBiases[node] += learningRate * delta;
}
}
}
_setupAdam(): void {
this.biasChangesLow = [];
this.biasChangesHigh = [];
this.changesLow = [];
this.changesHigh = [];
this.iterations = 0;
for (let layer = 0; layer <= this.outputLayer; layer++) {
const 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++) {
const prevSize = this.sizes[layer - 1];
this.changesLow[layer][node] = zeros(prevSize);
this.changesHigh[layer][node] = zeros(prevSize);
}
}
}
this.adjustWeights = this._adjustWeightsAdam;
}
_adjustWeightsAdam(): void {
this.iterations++;
const { iterations } = this;
const { beta1, beta2, epsilon, learningRate } = this.trainOpts;
for (let layer = 1; layer <= this.outputLayer; layer++) {
const incoming = this.outputs[layer - 1];
const currentSize = this.sizes[layer];
const currentDeltas = this.deltas[layer];
const currentChangesLow = this.changesLow[layer];
const currentChangesHigh = this.changesHigh[layer];
const currentWeights = this.weights[layer];
const currentBiases = this.biases[layer];
const currentBiasChangesLow = this.biasChangesLow[layer];
const currentBiasChangesHigh = this.biasChangesHigh[layer];
for (let node = 0; node < currentSize; node++) {
const delta = currentDeltas[node];
for (let k = 0; k < incoming.length; k++) {
const gradient = delta * incoming[k];
const changeLow =
currentChangesLow[node][k] * beta1 + (1 - beta1) * gradient;
const changeHigh =
currentChangesHigh[node][k] * beta2 +
(1 - beta2) * gradient * gradient;
const momentumCorrection =
changeLow / (1 - Math.pow(beta1, iterations));
const gradientCorrection =
changeHigh / (1 - Math.pow(beta2, iterations));
currentChangesLow[node][k] = changeLow;
currentChangesHigh[node][k] = changeHigh;
currentWeights[node][k] +=
(learningRate * momentumCorrection) /
(Math.sqrt(gradientCorrection) + epsilon);
}
const biasGradient = currentDeltas[node];
const biasChangeLow =
currentBiasChangesLow[node] * beta1 + (1 - beta1) * biasGradient;
const biasChangeHigh =
currentBiasChangesHigh[node] * beta2 +
(1 - beta2) * biasGradient * biasGradient;
const biasMomentumCorrection =
currentBiasChangesLow[node] / (1 - Math.pow(beta1, iterations));
const biasGradientCorrection =
currentBiasChangesHigh[node] / (1 - Math.pow(beta2, iterations));
currentBiasChangesLow[node] = biasChangeLow;
currentBiasChangesHigh[node] = biasChangeHigh;
currentBiases[node] +=
(learningRate * biasMomentumCorrection) /
(Math.sqrt(biasGradientCorrection) + epsilon);
}
}
}
validateData(data: Array<INeuralNetworkDatumFormatted<Float32Array>>): void {
const inputSize = this.sizes[0];
const outputSize = this.sizes[this.sizes.length - 1];
const { length } = data;
for (let i = 0; i < length; i++) {
const { input, output } = data[i];
if (input.length !== inputSize) {
throw new Error(
`input at index ${i} length ${input.length} must be ${inputSize}`
);
}
if (data[i].output.length !== outputSize) {
throw new Error(
`output at index ${i} length ${output.length} must be ${outputSize}`
);
}
}
}
validateInput(formattedInput: Float32Array): void {
const inputSize = this.sizes[0];
if (formattedInput.length !== inputSize) {
throw new Error(
`input length ${formattedInput.length} must match options.inputSize of ${inputSize}`
);
}
}
formatData(
data: Array<INeuralNetworkDatum<InputType, OutputType>>
): Array<INeuralNetworkDatumFormatted<Float32Array>> {
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 (!this._formatInput) {
this._formatInput = getTypedArrayFn(data[0].input, this.inputLookup);
}