-
Notifications
You must be signed in to change notification settings - Fork 0
/
NeuralNetwork.java
1311 lines (1191 loc) · 43.8 KB
/
NeuralNetwork.java
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 java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Collections;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.stream.IntStream;
import java.util.concurrent.atomic.AtomicInteger;
public class NeuralNetwork implements Serializable {
private static final long serialVersionUID = 1L;
//first dimension is layer, second dimension is neuron # in layer
protected double[][] neurons;
protected double[][] neuronsRaw;
protected double[][] biases;
//first dimension is recieving layer, second dimension is recieving neuron #, third dimension is incoming neuron # from previous layer
protected double[][][] weights;
protected int[] neuronsPerLayer;
/* activation choices:
- linear
- sigmoid
- tanh
- relu
- binary
- softmax
*/
protected String[] activations;
public int numLayers;
//gradient clipping threshold
public double clipThreshold = 1;
//whether or not to display accuracy while training (for classification models)
public boolean displayAccuracy = false;
// Regularization type
public static enum RegularizationType {
NONE,
L1,
L2
}
// Callback interface for training updates
public static interface TrainingCallback {
//test accuracy is assigned -1 if not available for the current mini-batch
void onEpochUpdate(int epoch, int batch, double progress, double trainAccuracy, double testAccuracy);
}
public static interface Optimizer {
void initialize(int[] neuronsPerLayer, double[][] biases, double[][][] weights);
void step(double[][] avgBiasGradient, double[][][] avgWeightGradient, double learningRate);
}
public static class OptimizerType {
public static class SGD implements Optimizer {
private double[][] biases;
private double[][][] weights;
private int[] neuronsPerLayer;
@Override
public void initialize(int[] neuronsPerLayer, double[][] biases, double[][][] weights) {
this.biases = biases;
this.weights = weights;
this.neuronsPerLayer = neuronsPerLayer;
}
@Override
public void step(double[][] avgBiasGradient, double[][][] avgWeightGradient, double learningRate) {
for (int i = 1; i < neuronsPerLayer.length; i++) {
for (int j = 0; j < neuronsPerLayer[i]; j++) {
//apply velocity
biases[i][j] = biases[i][j] - learningRate * avgBiasGradient[i][j];
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
//apply velocity
weights[i][j][k] = weights[i][j][k] - learningRate * avgWeightGradient[i][j][k];
}
}
}
}
}
public static class SGDMomentum implements Optimizer {
private double[][] biases;
private double[][][] weights;
private int[] neuronsPerLayer;
private double[][] biasVelocity;
private double[][][] weightVelocity;
private double momentum;
public SGDMomentum(double momentum) {
this.momentum = momentum;
}
@Override
public void initialize(int[] neuronsPerLayer, double[][] biases, double[][][] weights) {
this.biases = biases;
this.weights = weights;
this.neuronsPerLayer = neuronsPerLayer;
biasVelocity = new double[biases.length][biases[0].length];
weightVelocity = new double[weights.length][weights[0].length][weights[0][0].length];
}
@Override
public void step(double[][] avgBiasGradient, double[][][] avgWeightGradient, double learningRate) {
for (int i = 1; i < neuronsPerLayer.length; i++) {
for (int j = 0; j < neuronsPerLayer[i]; j++) {
//do momentum
biasVelocity[i][j] = momentum * biasVelocity[i][j] + (1 - momentum) * avgBiasGradient[i][j];
//apply velocity
biases[i][j] = biases[i][j] - learningRate * biasVelocity[i][j];
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
//do momentum
weightVelocity[i][j][k] = momentum * weightVelocity[i][j][k] + (1 - momentum) * avgWeightGradient[i][j][k];
//apply velocity
weights[i][j][k] = weights[i][j][k] - learningRate * weightVelocity[i][j][k];
}
}
}
}
}
public static class AdaGrad implements Optimizer {
private double[][] biases;
private double[][][] weights;
private int[] neuronsPerLayer;
private double[][] biasCache;
private double[][][] weightCache;
private double epsilon = 1e-8;
@Override
public void initialize(int[] neuronsPerLayer, double[][] biases, double[][][] weights) {
this.biases = biases;
this.weights = weights;
this.neuronsPerLayer = neuronsPerLayer;
biasCache = new double[biases.length][biases[0].length];
weightCache = new double[weights.length][weights[0].length][weights[0][0].length];
}
@Override
public void step(double[][] avgBiasGradient, double[][][] avgWeightGradient, double learningRate) {
for (int i = 1; i < neuronsPerLayer.length; i++) {
for (int j = 0; j < neuronsPerLayer[i]; j++) {
//update cache
biasCache[i][j] += avgBiasGradient[i][j] * avgBiasGradient[i][j];
//apply update
biases[i][j] = biases[i][j] - learningRate * avgBiasGradient[i][j] / (Math.sqrt(biasCache[i][j]) + epsilon);
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
//update cache
weightCache[i][j][k] += avgWeightGradient[i][j][k] * avgWeightGradient[i][j][k];
//apply update
weights[i][j][k] = weights[i][j][k] - learningRate * avgWeightGradient[i][j][k] / (Math.sqrt(weightCache[i][j][k]) + epsilon);
}
}
}
}
}
public static class RMSProp implements Optimizer {
private double[][] biases;
private double[][][] weights;
private int[] neuronsPerLayer;
private double[][] biasCache;
private double[][][] weightCache;
private double decayRate;
private double epsilon = 1e-8;
public RMSProp(double decayRate) {
this.decayRate = decayRate;
}
@Override
public void initialize(int[] neuronsPerLayer, double[][] biases, double[][][] weights) {
this.biases = biases;
this.weights = weights;
this.neuronsPerLayer = neuronsPerLayer;
biasCache = new double[biases.length][biases[0].length];
weightCache = new double[weights.length][weights[0].length][weights[0][0].length];
}
@Override
public void step(double[][] avgBiasGradient, double[][][] avgWeightGradient, double learningRate) {
for (int i = 1; i < neuronsPerLayer.length; i++) {
for (int j = 0; j < neuronsPerLayer[i]; j++) {
//update cache
biasCache[i][j] = decayRate * biasCache[i][j] + (1 - decayRate) * avgBiasGradient[i][j] * avgBiasGradient[i][j];
//apply update
biases[i][j] = biases[i][j] - learningRate * avgBiasGradient[i][j] / (Math.sqrt(biasCache[i][j]) + epsilon);
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
//update cache
weightCache[i][j][k] = decayRate * weightCache[i][j][k] + (1 - decayRate) * avgWeightGradient[i][j][k] * avgWeightGradient[i][j][k];
//apply update
weights[i][j][k] = weights[i][j][k] - learningRate * avgWeightGradient[i][j][k] / (Math.sqrt(weightCache[i][j][k]) + epsilon);
}
}
}
}
}
public static class Adam implements Optimizer {
private double[][] biases;
private double[][][] weights;
private int[] neuronsPerLayer;
private double[][] biasM;
private double[][] biasV;
private double[][][] weightM;
private double[][][] weightV;
private double beta1;
private double beta2;
private double epsilon = 1e-8;
private double beta1t = 1;
private double beta2t = 1;
public Adam(double beta1, double beta2) {
this.beta1 = beta1;
this.beta2 = beta2;
}
@Override
public void initialize(int[] neuronsPerLayer, double[][] biases, double[][][] weights) {
this.biases = biases;
this.weights = weights;
this.neuronsPerLayer = neuronsPerLayer;
biasM = new double[biases.length][biases[0].length];
biasV = new double[biases.length][biases[0].length];
weightM = new double[weights.length][weights[0].length][weights[0][0].length];
weightV = new double[weights.length][weights[0].length][weights[0][0].length];
}
@Override
public void step(double[][] avgBiasGradient, double[][][] avgWeightGradient, double learningRate) {
beta1t *= beta1;
beta2t *= beta2;
double biasCorrectedM;
double biasCorrectedV;
double weightCorrectedM;
double weightCorrectedV;
for (int i = 1; i < neuronsPerLayer.length; i++) {
for (int j = 0; j < neuronsPerLayer[i]; j++) {
//update biased first moment estimate
biasM[i][j] = beta1 * biasM[i][j] + (1 - beta1) * avgBiasGradient[i][j];
//update biased second raw moment estimate
biasV[i][j] = beta2 * biasV[i][j] + (1 - beta2) * avgBiasGradient[i][j] * avgBiasGradient[i][j];
//correct bias first moment
biasCorrectedM = biasM[i][j] / (1 - beta1t);
//correct bias second moment
biasCorrectedV = biasV[i][j] / (1 - beta2t);
//apply update
biases[i][j] = biases[i][j] - learningRate * biasCorrectedM / (Math.sqrt(biasCorrectedV) + epsilon);
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
//update biased first moment estimate
weightM[i][j][k] = beta1 * weightM[i][j][k] + (1 - beta1) * avgWeightGradient[i][j][k];
//update biased second raw moment estimate
weightV[i][j][k] = beta2 * weightV[i][j][k] + (1 - beta2) * avgWeightGradient[i][j][k] * avgWeightGradient[i][j][k];
//correct bias first moment
weightCorrectedM = weightM[i][j][k] / (1 - beta1t);
//correct bias second moment
weightCorrectedV = weightV[i][j][k] / (1 - beta2t);
//apply update
weights[i][j][k] = weights[i][j][k] - learningRate * weightCorrectedM / (Math.sqrt(weightCorrectedV) + epsilon);
}
}
}
}
}
}
// Regularization settings (lambda = regularization strength)
protected double lambda = 0;
protected RegularizationType regularizationType = RegularizationType.NONE;
//used in gradient descent
volatile protected double[][] avgBiasGradient;
volatile protected double[][][] avgWeightGradient;
protected Random r;
//takes in int[] for number of neurons in each layer and string[] for activations of each layer
public NeuralNetwork(int[] topology, String[] active) {
int maxLayerSize = max(topology);
neuronsPerLayer = topology.clone();
numLayers = topology.length;
neurons = new double[numLayers][maxLayerSize];
neuronsRaw = new double[numLayers][maxLayerSize];
biases = new double[numLayers][maxLayerSize];
weights = new double[numLayers][maxLayerSize][maxLayerSize];
activations = active.clone();
r = new Random();
}
public NeuralNetwork(int[] topology, String[] active, RegularizationType regularizationType,
double regularizationStrength) {
this(topology, active);
//set regularization
this.regularizationType = regularizationType;
lambda = regularizationStrength;
}
public NeuralNetwork() {
}
//initialize network with random starting values
public void Init(double biasSpread) {
ClearNeurons();
InitWeights();
InitBiases(biasSpread);
}
//initialize network with random starting values using a specified weight initialization method ('he' or 'xavier')
public void Init(String weightInitMethod, double biasSpread) {
ClearNeurons();
InitWeights(weightInitMethod);
InitBiases(biasSpread);
}
void InitWeights(String initMethod) {
//initMethod is either "he" or "xavier"
if (initMethod.equals("he")) {
Random r = new Random();
for (int i = 1; i < numLayers; i++) {
int n = neuronsPerLayer[i - 1];
//he weight initialization (for relu) (gaussian distribution)
double mean = 0, std = Math.sqrt(2.0 / n);
for (int j = 0; j < neuronsPerLayer[i]; j++) {
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
weights[i][j][k] = r.nextGaussian() * std + mean;
}
}
}
} else if (initMethod.equals("xavier")) {
for (int i = 1; i < numLayers; i++) {
int n = neuronsPerLayer[i - 1];
double min, max;
//xavier weight initialization (for linear, sigmoid, tanh, etc.) (uniform distribution)
max = 1 / Math.sqrt(n);
min = -max;
for (int j = 0; j < neuronsPerLayer[i]; j++) {
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
weights[i][j][k] = randDouble(min, max);
}
}
}
} else {
InitWeights();
}
}
void InitWeights() {
for (int i = 1; i < numLayers; i++) {
int n = neuronsPerLayer[i - 1];
double min, max;
if (activations[i].equals("relu")) {
//he weight initialization (for relu) (gaussian distribution)
Random r = new Random();
double mean = 0, std = Math.sqrt(2.0 / n);
for (int j = 0; j < neuronsPerLayer[i]; j++) {
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
weights[i][j][k] = r.nextGaussian() * std + mean;
}
}
} else {
//xavier weight initialization (for linear, sigmoid, tanh, etc.) (uniform distribution)
max = 1 / Math.sqrt(n);
min = -max;
for (int j = 0; j < neuronsPerLayer[i]; j++) {
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
weights[i][j][k] = randDouble(min, max);
}
}
}
}
}
void InitBiases(double spread) {
for (int i = 1; i < numLayers; i++) {
for (int j = 0; j < neuronsPerLayer[i]; j++) {
biases[i][j] = randDouble(-spread, spread);
}
}
}
public double[][][] GetWeights() {
return weights;
}
public void SetWeight(int layer, int outgoing, int incoming, double value) {
weights[layer][outgoing][incoming] = value;
}
public double[][] GetBiases() {
return biases;
}
public void SetBias(int layer, int neuron, double bias) {
biases[layer][neuron] = bias;
}
public String[] GetActivations() {
return activations;
}
public void SetActivation(int layer, String act) {
activations[layer] = act;
}
public double[][] GetNeurons() {
return neurons;
}
public int[] GetTopology() {
return neuronsPerLayer;
}
public void SetRegularizationType(RegularizationType regularizationType) {
this.regularizationType = regularizationType;
}
public void SetRegularizationLambda(double lambda) {
this.lambda = lambda;
}
public RegularizationType GetRegularizationType() {
return regularizationType;
}
public double GetRegularizationLambda() {
return lambda;
}
double randDouble(double min, double max) {
return min + (max - min) * r.nextDouble();
}
int max(int[] arr) {
int m = -1;
for (int i : arr) {
if (i > m) {
m = i;
}
}
return m;
}
// Total regularization term calculation
double regularizationTerm() {
double regTerm = 0.0;
if (regularizationType == RegularizationType.L1) {
// L1 regularization
for (int i = 1; i < numLayers; i++) {
for (int j = 0; j < neuronsPerLayer[i]; j++) {
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
regTerm += Math.abs(weights[i][j][k]);
}
}
}
} else if (regularizationType == RegularizationType.L2) {
// L2 regularization
for (int i = 1; i < numLayers; i++) {
for (int j = 0; j < neuronsPerLayer[i]; j++) {
for (int k = 0; k < neuronsPerLayer[i - 1]; k++) {
regTerm += weights[i][j][k] * weights[i][j][k];
}
}
}
}
regTerm *= lambda;
return regTerm;
}
double linear_activation(double raw) {
return raw;
}
double sigmoid_activation(double raw) {
return 1d / (1 + Math.exp(-raw));
}
double tanh_activation(double raw) {
return Math.tanh(raw);
}
double relu_activation(double raw) {
return Math.max(0, raw);
}
double binary_activation(double raw) {
return raw > 0 ? 1 : 0;
}
double softmax_activation(double raw, double[] neuronValues) {
double maxVal = max(neuronValues);
// Compute the normalization factor (sum of exponentials)
double total = 0;
for (double value : neuronValues) {
total += Math.exp(value - maxVal);
}
// Compute the softmax activation
return Math.exp(raw - maxVal - Math.log(total));
}
double softmax_der(double[] neuronValues, int index) {
double softmax = softmax_activation(neuronValues[index], neuronValues);
return softmax * (1.0 - softmax);
}
double activate(double raw, int layer) {
switch (activations[layer]) {
case "linear":
return linear_activation(raw);
case "sigmoid":
return sigmoid_activation(raw);
case "tanh":
return tanh_activation(raw);
case "relu":
return relu_activation(raw);
case "binary":
return binary_activation(raw);
case "softmax":
return softmax_activation(raw, Arrays.copyOfRange(neuronsRaw[layer], 0, neuronsPerLayer[layer]));
default:
return linear_activation(raw);
}
}
double activate(double raw, int layer, double[] neuronsRaw) {
switch (activations[layer]) {
case "linear":
return linear_activation(raw);
case "sigmoid":
return sigmoid_activation(raw);
case "tanh":
return tanh_activation(raw);
case "relu":
return relu_activation(raw);
case "binary":
return binary_activation(raw);
case "softmax":
return softmax_activation(raw, neuronsRaw);
default:
return linear_activation(raw);
}
}
double activate_der(double raw, int layer, int index) {
double val;
switch (activations[layer]) {
case "linear":
return 1;
case "sigmoid":
double sigmoidVal = sigmoid_activation(raw);
val = sigmoidVal * (1 - sigmoidVal);
return val;
case "tanh":
val = Math.pow(1d / Math.cosh(raw), 2);
return val;
case "relu":
if (raw <= 0) {
return 0;
} else {
return 1;
}
case "binary":
return 0;
case "softmax":
val = softmax_der(Arrays.copyOfRange(neuronsRaw[layer], 0, neuronsPerLayer[layer]), index);
return val;
default:
return 1;
}
}
double activate_der(double raw, int layer, double[] neuronsRaw, int index) {
double val;
switch (activations[layer]) {
case "linear":
return 1;
case "sigmoid":
double sigmoidVal = sigmoid_activation(raw);
val = sigmoidVal * (1 - sigmoidVal);
return val;
case "tanh":
val = Math.pow(1d / Math.cosh(raw), 2);
return val;
case "relu":
if (raw <= 0) {
return 0;
} else {
return 1;
}
case "binary":
return 0;
case "softmax":
val = softmax_der(neuronsRaw, index);
return val;
default:
return 1;
}
}
void ClearNeurons() {
for (int i = 0; i < numLayers; i++) {
for (int j = 0; j < neurons[i].length; j++) {
neurons[i][j] = 0;
neuronsRaw[i][j] = 0;
}
}
}
void ClearNeurons(double[][] neurons, double[][] neuronsRaw) {
for (int i = 0; i < numLayers; i++) {
for (int j = 0; j < neurons[i].length; j++) {
neurons[i][j] = 0;
neuronsRaw[i][j] = 0;
}
}
}
public double[] Evaluate(double[] input, double[][] neurons, double[][] neuronsRaw) {
ClearNeurons(neurons, neuronsRaw);
// Set input neurons
IntStream.range(0, input.length).parallel().forEach(i -> neurons[0][i] = input[i]);
// Feed forward
for (int layer = 1; layer < numLayers; layer++) {
final int currentLayer = layer; // Capture the current value of layer
IntStream.range(0, neuronsPerLayer[currentLayer]).parallel().forEach(neuron -> {
double raw = biases[currentLayer][neuron];
for (int prevNeuron = 0; prevNeuron < neuronsPerLayer[currentLayer - 1]; prevNeuron++) {
raw += weights[currentLayer][neuron][prevNeuron] * neurons[currentLayer - 1][prevNeuron];
}
neuronsRaw[currentLayer][neuron] = raw;
if (activations[currentLayer].equals("softmax")) {
neurons[currentLayer][neuron] = raw;
} else {
neurons[currentLayer][neuron] = activate(raw, currentLayer);
}
});
if (activations[currentLayer].equals("softmax")) {
IntStream.range(0, neuronsPerLayer[currentLayer]).parallel().forEach(i -> {
neurons[currentLayer][i] = activate(neuronsRaw[currentLayer][i], currentLayer, Arrays.copyOfRange(neuronsRaw[currentLayer], 0, neuronsPerLayer[currentLayer]));
});
}
}
//return output layer
return Arrays.copyOfRange(neurons[numLayers - 1], 0, neuronsPerLayer[numLayers - 1]);
}
public double[] Evaluate(double[] input) {
ClearNeurons();
// Set input neurons
IntStream.range(0, input.length).parallel().forEach(i -> neurons[0][i] = input[i]);
// Feed forward
for (int layer = 1; layer < numLayers; layer++) {
final int currentLayer = layer; // Capture the current value of layer
IntStream.range(0, neuronsPerLayer[currentLayer]).parallel().forEach(neuron -> {
double raw = biases[currentLayer][neuron];
for (int prevNeuron = 0; prevNeuron < neuronsPerLayer[currentLayer - 1]; prevNeuron++) {
raw += weights[currentLayer][neuron][prevNeuron] * neurons[currentLayer - 1][prevNeuron];
}
neuronsRaw[currentLayer][neuron] = raw;
if (activations[currentLayer].equals("softmax")) {
neurons[currentLayer][neuron] = raw;
} else {
neurons[currentLayer][neuron] = activate(raw, currentLayer);
}
});
if (activations[currentLayer].equals("softmax")) {
IntStream.range(0, neuronsPerLayer[currentLayer]).parallel().forEach(i -> {
neurons[currentLayer][i] = activate(neuronsRaw[currentLayer][i], currentLayer);
});
}
}
//return output layer
return Arrays.copyOfRange(neurons[numLayers - 1], 0, neuronsPerLayer[numLayers - 1]);
}
@Override
public String toString() {
StringBuilder print = new StringBuilder().append("Neural Network \n");
print.append("\nTopology (neurons per layer): ").append(printArr(neuronsPerLayer));
print.append("\nActivations (per layer): ").append(printArr(activations));
print.append("\nRegularization: ").append(regularizationType.toString()).append(" lambda: ").append(lambda);
print.append("\nBiases:\n");
for (int i = 0; i < numLayers; i++) {
print.append("Layer ").append((i + 1)).append(": ").append(printArr(Arrays.copyOfRange(biases[i], 0, neuronsPerLayer[i]))).append("\n");
}
print.append("\nWeights:\n");
for (int i = 1; i < numLayers; i++) {
for (int j = 0; j < neuronsPerLayer[i]; j++) {
//each neuron
print.append(" Neuron ").append((j + 1)).append(" of Layer ").append((i + 1)).append(" Weights: \n").append(printArr(Arrays.copyOfRange(weights[i][j], 0, neuronsPerLayer[i - 1]))).append("\n");
}
}
return print.toString();
}
String printArr(int[] arr) {
if (arr == null)
return "[]";
if (arr.length == 0)
return "[]";
StringBuilder print = new StringBuilder().append("[");
for (int i = 0; i < arr.length - 1; i++) {
print.append(arr[i]).append(", ");
}
print.append(arr[arr.length - 1]).append("]");
return print.toString();
}
String printArr(double[] arr) {
if (arr == null)
return "[]";
if (arr.length == 0)
return "[]";
StringBuilder print = new StringBuilder().append("[");
for (int i = 0; i < arr.length - 1; i++) {
print.append(arr[i]).append(", ");
}
print.append(arr[arr.length - 1]).append("]");
return print.toString();
}
String printArr(String[] arr) {
if (arr == null)
return "[]";
if (arr.length == 0)
return "[]";
StringBuilder print = new StringBuilder().append("[");
for (int i = 0; i < arr.length - 1; i++) {
print.append(arr[i]).append(", ");
}
print.append(arr[arr.length - 1]).append("]");
return print.toString();
}
// save the neural network to a file directly as a java object
// not transferable between different programming languages and not human readable
public static void Save(NeuralNetwork network, String path) {
try {
FileOutputStream f = new FileOutputStream(path);
ObjectOutputStream o = new ObjectOutputStream(f);
// Write objects to file
o.writeObject(network);
o.close();
f.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// save the neural network to a file as a plain text file
// transferable between different programming languages and human readable
public static void SaveParameters(NeuralNetwork network, String path) {
BufferedWriter writer = null;
try {
FileWriter fWriter = new FileWriter(path);
writer = new BufferedWriter(fWriter);
StringBuilder print = new StringBuilder();
//write parameters to print
print.append("numlayers ").append(network.numLayers).append("\n");
print.append("topology ");
for (int i = 0; i < network.neuronsPerLayer.length; i++) {
print.append(network.neuronsPerLayer[i]).append(" ");
}
print.append("\nactivations ");
for (int i = 0; i < network.activations.length; i++) {
print.append(network.activations[i]).append(" ");
}
print.append("\nregularization ").append(network.regularizationType.toString()).append(" ")
.append(network.lambda).append("\n");
print.append("biases ");
for (int i = 0; i < network.biases.length; i++) {
for (int j = 0; j < network.neuronsPerLayer[i]; j++) {
print.append(network.biases[i][j]).append(" ");
}
}
//weights start at layer 1 because layer 0 is the input layer
print.append("\nweights ");
for (int i = 1; i < network.weights.length; i++) {
for (int j = 0; j < network.neuronsPerLayer[i]; j++) {
for (int k = 0; k < network.neuronsPerLayer[i - 1]; k++) {
print.append(network.weights[i][j][k]).append(" ");
}
}
}
//write to file
writer.write(print.toString());
writer.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// load a neural network from a file that was saved directly as a java object
// not transferable between different programming languages
public static NeuralNetwork Load(String path) {
try {
FileInputStream fi = new FileInputStream(path);
ObjectInputStream oi = new ObjectInputStream(fi);
// Read objects
NeuralNetwork loadedNetwork = (NeuralNetwork) oi.readObject();
loadedNetwork.r = new Random();
oi.close();
fi.close();
return loadedNetwork;
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// load a neural network from a file that was saved as a plain text file
// transferable between different programming languages
public static NeuralNetwork LoadParameters(String path) {
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
NeuralNetwork network = new NeuralNetwork();
while ((line = reader.readLine()) != null) {
String[] tokens = line.split(" ");
String paramType = tokens[0];
switch (paramType) {
case "numlayers":
network.numLayers = Integer.parseInt(tokens[1]);
network.neuronsPerLayer = new int[network.numLayers];
network.activations = new String[network.numLayers];
break;
case "topology":
int maxLayerSize = 0;
for (int i = 1; i < tokens.length; i++) {
network.neuronsPerLayer[i - 1] = Integer.parseInt(tokens[i]);
maxLayerSize = Math.max(maxLayerSize, network.neuronsPerLayer[i - 1]);
}
network.neurons = new double[network.numLayers][maxLayerSize];
network.neuronsRaw = new double[network.numLayers][maxLayerSize];
network.biases = new double[network.numLayers][maxLayerSize];
network.weights = new double[network.numLayers][maxLayerSize][maxLayerSize];
break;
case "activations":
for (int i = 1; i < tokens.length; i++) {
network.activations[i - 1] = tokens[i];
}
break;
case "regularization":
network.regularizationType = RegularizationType.valueOf(tokens[1]);
network.lambda = Double.parseDouble(tokens[2]);
break;
case "biases":
int layerIndex = 0;
int neuronIndex = 0;
for (int i = 1; i < tokens.length; i++) {
network.biases[layerIndex][neuronIndex] = Double.parseDouble(tokens[i]);
neuronIndex++;
if (neuronIndex == network.neuronsPerLayer[layerIndex]) {
neuronIndex = 0;
layerIndex++;
}
}
break;
case "weights":
layerIndex = 1;
neuronIndex = 0;
int incomingNeuronIndex = 0;
for (int i = 1; i < tokens.length; i++) {
network.weights[layerIndex][neuronIndex][incomingNeuronIndex] = Double
.parseDouble(tokens[i]);
incomingNeuronIndex++;
if (incomingNeuronIndex == network.neuronsPerLayer[layerIndex - 1]) {
incomingNeuronIndex = 0;
neuronIndex++;
if (neuronIndex == network.neuronsPerLayer[layerIndex]) {
neuronIndex = 0;
layerIndex++;
}
}
}
break;
}
}
network.r = new Random();
return network;
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error reading from file");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("File not formatted correctly");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//chance is a number between 0 and 1
public void Mutate(double chance, double variation) {
//mutate weights
for (int i = 0; i < weights.length; i++) {
for (int j = 0; j < weights[0].length; j++) {
for (int k = 0; k < weights[0][0].length; k++) {
if (randDouble(0, 1) <= chance) {
weights[i][j][k] += randDouble(-variation, variation);
}
}
}
}
//mutate biases
for (int i = 0; i < biases.length; i++) {
for (int j = 0; j < biases[0].length; j++) {
if (randDouble(0, 1) <= chance) {
biases[i][j] += randDouble(-variation, variation);
}
}
}
}
public NeuralNetwork clone() {
NeuralNetwork clone = new NeuralNetwork(neuronsPerLayer, activations, regularizationType, lambda);
clone.biases = biases.clone();
clone.weights = weights.clone();
return clone;
}
//error functions
public double Cost(double[] output, double[] expected, String lossFunction) {
double cost = 0;
if (output.length != expected.length) {
return -1;
}
if (lossFunction.equals("sse")) {
for (int i = 0; i < output.length; i++) {
double neuronCost = 0.5 * Math.pow(expected[i] - output[i], 2);
cost += neuronCost;
}
} else if (lossFunction.equals("mse")) {
for (int i = 0; i < output.length; i++) {
double neuronCost = Math.pow(expected[i] - output[i], 2);
cost += neuronCost;
}
cost /= output.length;
} else if (lossFunction.equals("categorical_crossentropy")) {
for (int i = 0; i < output.length; i++) {
cost -= expected[i] * Math.log(output[i] + 1.0e-15d);
}
}
//add regularization term
cost += regularizationTerm();
return cost;
}
//error functions derivative
double cost_der(double predicted, double expected, String lossFunction) {
if (lossFunction.equals("sse")) {
return predicted - expected;
} else if (lossFunction.equals("mse")) {
return (2.0 * (predicted - expected)) / neuronsPerLayer[numLayers - 1];
} else if (lossFunction.equals("categorical_crossentropy")) {
return -expected / (predicted + 1.0e-15);
}
return 1;
}