-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathNeuralNetworkWithBias.java
654 lines (560 loc) · 20.5 KB
/
NeuralNetworkWithBias.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
/*
* MIT License
*
* Copyright (c) 2019 Sebastian Gössl
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package neuralnetwork;
import java.util.Arrays;
import matrix.Matrix;
import java.util.Random;
import java.util.function.DoubleUnaryOperator;
import java.util.function.UnaryOperator;
/**
* Neural network implementation.
* Supports operations for forward propagation and backpropagation.
* (Matricies and layers are zero indexed!)
*
* Input & output sets are stored in matricies in which every row represents
* anndataset and every column gets feed into an node (e.g. element[1][2] is a
* parameter of a dataset with index [1] and gets feed into the node with
* index [2])
*
* The network is build up from an array of layers. Every layer consists of
* the weights leading to it from the previous layer, its biases, its nodes
* (neurons) and its activation function (and derivative forbackpropagation =
* optimization = training) that gets applied to the values in every node.
* The first layer (index: 0) is the first hidden layer.
* The last layer (index: layers.lenght-1) is the output layer.
*
* The weights are aranged in matricies. The conection of an single weight
* represent the indices of the nodes it connects where the row indicate the
* previous node and the column the node it leads into. (e.g. weight[2][1] of
* layer[3] connects the node[2] of layer[2] with node[1] of layer[3])
*
* The biases of every layer are row vectors where every column is the bias
* for one node.
*
* @author Sebastian Gössl
* @version 1.3 13.9.2019
*/
public class NeuralNetworkWithBias implements UnaryOperator<Matrix> {
/**
* Layers of the network.
*/
private final Layer[] layers;
/**
* Constructs a copy of the given NeuralNetwork.
*
* @param other network to copy
*/
public NeuralNetworkWithBias(NeuralNetworkWithBias other) {
this(other.getNumberOfInputs(), other.getLayerSizes(),
other.getActivationFunctions(),
other.getActivationFunctionPrimes());
setWeights(other.getWeights());
setBiases(other.getBiases());
}
/**
* Constructs a new NeuralNetwork.
*
* @param numberOfInputs number of input nodes
* @param layerSizes number of nodes in the hidden layers
* @param activationFunctions activation functions in the hidden layers
* @param activationFunctionPrimes derivatives of the activation functions
* in the hidden layers
*/
public NeuralNetworkWithBias(int numberOfInputs, int[] layerSizes,
DoubleUnaryOperator[] activationFunctions,
DoubleUnaryOperator[] activationFunctionPrimes) {
layers = new Layer[layerSizes.length];
layers[0] = new Layer(numberOfInputs, layerSizes[0],
activationFunctions[0], activationFunctionPrimes[0]);
for(int i=1; i<layers.length; i++) {
layers[i] = new Layer(layerSizes[i-1], layerSizes[i],
activationFunctions[i], activationFunctionPrimes[i]);
}
seedWeightsXavier();
}
/**
* Returns the number of input nodes.
*
* @return number of input nodes
*/
public int getNumberOfInputs() {
return layers[0].getNumberOfInputs();
}
/**
* Returns the number of output nodes.
*
* @return number of output nodes
*/
public int getNumberOfOutputs() {
return layers[layers.length-1].getNumberOfOutputs();
}
/**
* Returns the number of layers.
*
* @return number of layers
*/
public int getNumberOfLayers() {
return layers.length;
}
/**
* Returns the number of nodes in the specified layer.
*
* @param layer index of the layer
* @return number of nodes in the specified layer
*/
public int getLayerSize(int layer) {
return layers[layer].getNumberOfOutputs();
}
/**
* Returns all layer sizes as an array.
*
* @return all layer sizes as an array
*/
public int[] getLayerSizes() {
final int[] layerSizes = new int[getNumberOfLayers()];
Arrays.setAll(layerSizes, (i) -> getLayerSize(i));
return layerSizes;
}
/**
* Returns the weights of the specified layer.
*
* @param layer index of the layer
* @return weights of the specified layer
*/
public Matrix getWeights(int layer) {
return layers[layer].getWeights();
}
/**
* Returns all weights as an array.
*
* @return all weights as an array
*/
public Matrix[] getWeights() {
final Matrix[] weights = new Matrix[getNumberOfLayers()];
Arrays.setAll(weights, (i) -> getWeights(i));
return weights;
}
/**
* Replaces the weights of the specified layer with the given weights.
*
* @param layer index of the layer
* @param weights weights to replace the current weights with
*/
public void setWeights(int layer, Matrix weights) {
layers[layer].setWeights(weights);
}
/**
* Replaces all weights with the given weights.
*
* @param weights weights to replace the current weights with
*/
public void setWeights(Matrix[] weights) {
for(int i=0; i<getNumberOfLayers(); i++) {
setWeights(i, weights[i]);
}
}
/**
* Returns the biases of the specified layer.
*
* @param layer index of the layer
* @return biases of the specified layer
*/
public Matrix getBiases(int layer) {
return layers[layer].getBiases();
}
/**
* Returns all biases as an array.
*
* @return all biases as an array
*/
public Matrix[] getBiases() {
final Matrix[] biases = new Matrix[getNumberOfLayers()];
Arrays.setAll(biases, (i) -> getBiases(i));
return biases;
}
/**
* Replaces the biases of the specified layer with the given biases.
*
* @param layer index of the layer
* @param biases biases to replace the current biases with
*/
public void setBiases(int layer, Matrix biases) {
layers[layer].setBiases(biases);
}
/**
* Replaces all weights with the given weights.
*
* @param biases biases to replace the current biases with
*/
public void setBiases(Matrix[] biases) {
for(int i=0; i<getNumberOfLayers(); i++) {
setBiases(i, biases[i]);
}
}
/**
* Returns the activation function of the specified layer.
*
* @param layer index of the layer
* @return activation function of the specified layer
*/
public DoubleUnaryOperator getActivationFunction(int layer) {
return layers[layer].getActivationFunction();
}
/**
* Returns all activation functions as an array.
*
* @return all activation functions as an array
*/
public DoubleUnaryOperator[] getActivationFunctions() {
final DoubleUnaryOperator[] activationFunctions =
new DoubleUnaryOperator[getNumberOfLayers()];
Arrays.setAll(activationFunctions, (i) -> getActivationFunction(i));
return activationFunctions;
}
/**
* Returns the derivative of the activation function of the specified
* layer.
*
* @param layer index of the layer
* @return derivative of the activation function of the specified layer
*/
public DoubleUnaryOperator getActivationFunctionPrime(int layer) {
return layers[layer].getActivationFunctionPrime();
}
/**
* Returns all activation function derivatives as an array.
*
* @return all activation function derivatives as an array
*/
public DoubleUnaryOperator[] getActivationFunctionPrimes() {
final DoubleUnaryOperator[] activationFunctionPrimes =
new DoubleUnaryOperator[getNumberOfLayers()];
Arrays.setAll(activationFunctionPrimes,
(i) -> getActivationFunctionPrime(i));
return activationFunctionPrimes;
}
/**
* Randomizes all weights based on the Xavier initialization algorithm.
*/
public void seedWeightsXavier() {
seedWeightsXavier(new Random());
}
/**
* Randomizes all weights based on the Xavier initialization algorithm with
* a specified seed for the pseudorandom number generator.
*
* @param seed the initial seed
*/
public void seedWeightsXavier(long seed) {
seedWeightsXavier(new Random(seed));
}
/**
* Randomizes all weights based on the Xavier initialization algorithm with
* the given random number generator.
*
* @param rand random number generator
*/
public void seedWeightsXavier(Random rand) {
for(Layer layer : layers) {
final double average =
(layer.getNumberOfInputs() + layer.getNumberOfOutputs())
/ 2;
layer.getWeights().set(
() -> rand.nextGaussian() / Math.sqrt(average));
layer.getBiases().set(() -> rand.nextGaussian());
}
}
/**
* Limits all weights to a minimum of <code>-Double.MAX_VALUE / 2</code>
* and a maximum of <code>Double.MAX_VALUE / 2</code> while also
* eliminating NaNs.
*/
public void keepWeightsAndBiasesInBounds() {
keepWeightsAndBiasesInBounds(
-Double.MAX_VALUE / 2, Double.MAX_VALUE / 2);
}
/**
* Limits all weights to the given minimum and maximum while also
* eliminating NaNs by replacing the with the average of the given limits.
*
* @param minimum minimum value for the weights
* @param maximum maximum value for the weights
*/
public void keepWeightsAndBiasesInBounds(double minimum, double maximum) {
final DoubleUnaryOperator op = (x) -> {
if(Double.isNaN(x)) {
return (minimum + maximum) / 2;
}
return Math.min(Math.max(x, minimum), maximum);
};
for(Layer layer : layers) {
layer.weights.apply(op);
layer.biases.apply(op);
}
}
/**
* Forward propagates the given input through the neural network and
* returns the result.
*
* @param t input to propagate through the network
* @return output of the network
*/
@Override
public Matrix apply(Matrix t) {
Matrix a = t;
for(Layer layer : layers) {
a = layer.apply(a);
}
return a;
}
/**
* Forward propagates the given input through the neural network and
* returns the mean squared error by comparing its output to the given
* output.
*
* @param input input for the network
* @param output output to compare the networks output with
* @return mean squared error of the networks output and the given output
*/
public double cost(Matrix input, Matrix output) {
final Matrix difference = output.subtract(apply(input));
final Matrix squaredError = difference.multiplyElementwise(difference);
double cost = 0;
for(double error : squaredError) {
cost += error;
}
cost /= 2;
return cost;
}
/**
* Returns the derivative of the cost with respect to every weight & bias
* in alternating order (weights[0], biases[0], weights[1], biases[1],...).
*
* @param input input for the network
* @param output wanted output of the network
* @return derivative of the cost with respect to every weight
*/
public Matrix[] costPrime(Matrix input, Matrix output) {
final Matrix yHat = apply(input);
final Matrix[] dJ = new Matrix[2*layers.length];
Matrix delta = yHat
.subtract(output)
.multiplyElementwise(layers[layers.length-1].z
.applyNew(layers[layers.length-1]
.activationFunctionPrime));
for(int i=layers.length-1; i>0; i--) {
dJ[2*i] = layers[i].backpropagateToWeights(delta, layers[i-1]);
dJ[2*i + 1] = layers[i].backpropagateToBiases(delta);
delta = layers[i-1].backpropagate(delta, layers[i]);
}
dJ[0] = input.transpose().multiply(delta);
dJ[1] = layers[0].backpropagateToBiases(delta);
return dJ;
}
/**
* Helper class which represents a single layer of the neural network.
* It consists of its nodes (neurons), biases and the weights (synapses)
* leading to it from the previous layer.
*/
private class Layer implements UnaryOperator<Matrix> {
/**
* Activation function and its derivative.
*/
private final DoubleUnaryOperator activationFunction,
activationFunctionPrime;
/**
* Weights leading into this layer and biases.
*/
private Matrix weights, biases;
/**
* Activation values needed for backpropagation.
* z = weighted, added and biased inputs from the previous layer
* a = z with applied activation function
*/
private Matrix z, a;
/**
* Constructs a copy of the given layer
*
* @param other layer to copy
*/
public Layer(Layer other) {
this(other.getNumberOfInputs(), other.getNumberOfOutputs(),
other.getActivationFunction(),
other.getActivationFunctionPrime());
setWeights(other.getWeights());
setBiases(other.getBiases());
}
/**
* Constructs a new layer on a neural network.
*
* @param inputs number of nodes of the previous layer
* @param outputs number of nodes (outputs) of this layer
* @param activationFunction activation function that gets applied in
* this layers nodes
* @param activationFunctionPrime derivative of the activation function
*/
public Layer(int inputs, int outputs,
DoubleUnaryOperator activationFunction,
DoubleUnaryOperator activationFunctionPrime) {
this.activationFunction = activationFunction;
this.activationFunctionPrime = activationFunctionPrime;
weights = new Matrix(inputs, outputs);
biases = new Matrix(1, outputs);
}
/**
* Returns the number of inputs (number of nodes of the previous
* layer).
*
* @return number of inputs
*/
public int getNumberOfInputs() {
return weights.getHeight();
}
/**
* Returns the number of nodes (outputs).
*
* @return number of nodes (outputs)
*/
public int getNumberOfOutputs() {
return weights.getWidth();
}
/**
* Returns the weights.
*
* @return weights
*/
public Matrix getWeights() {
return weights;
}
/**
* Returns the biases.
*
* @return biases
*/
public Matrix getBiases() {
return biases;
}
/**
* Returns the activation function.
*
* @return activation function
*/
public DoubleUnaryOperator getActivationFunction() {
return activationFunction;
}
/**
* Returns the derivative of the activation function.
*
* @return derivative of the activation function
*/
public DoubleUnaryOperator getActivationFunctionPrime() {
return activationFunctionPrime;
}
/**
* Sets the weights to the given weights.
*
* @param weights new weights
*/
public void setWeights(Matrix weights) {
if(this.weights.getHeight() != weights.getHeight()
|| this.weights.getWidth() != weights.getWidth()) {
throw new IllegalArgumentException("Wrong weights dimensions");
}
this.weights = weights;
}
/**
* Sets the biases to the given biases.
*
* @param biases new biases
*/
public void setBiases(Matrix biases) {
if(this.biases.getHeight() != biases.getHeight()
|| this.biases.getWidth() != biases.getWidth()) {
throw new IllegalArgumentException("Wrong biases dimensions");
}
this.biases = biases;
}
/**
* Forward propagates the given input through the layer and returns the
* result.
*
* @param t input to forward propagate through the layer
* @return output of the layer
*/
@Override
public Matrix apply(Matrix t) {
z = t.multiply(weights).applyNewDifSize(biases,
(x, y) -> x + y);
a = z.applyNew(activationFunction);
return a;
}
/**
* Backpropagates the given matrix which represents a derivative with
* respect to every node of this layer to a the derivative with respect
* to every node of the previous layer.
*
* @param deltaNext derivative with respect to every node of this layer
* @param next next layer
* @return derivative with respect to every node of the previous layer
*/
public Matrix backpropagate(Matrix deltaNext, Layer next) {
return deltaNext
.multiply(next.weights.transpose())
.multiplyElementwise(z.applyNew(activationFunctionPrime));
}
/**
* Backpropagates the given matrix which represents a derivative with
* respect to every node of this layer to a the derivative with respect
* to every weight of this layer.
*
* @param delta derivative with respect to every node of this layer
* @param previous previous layer
* @return derivative with respect to every weight of this layer
*/
public Matrix backpropagateToWeights(Matrix delta, Layer prev) {
return prev.a.transpose().multiply(delta);
}
/**
* Backpropagates the given matrix which represents a derivative with
* respect to every node of this layer to a the derivative with respect
* to every bias of this layer.
*
* @param delta derivative with respect to every node of this layer
* @param previous previous layer
* @return derivative with respect to every bias of this layer
*/
public Matrix backpropagateToBiases(Matrix delta) {
final Matrix matrix = new Matrix(
biases.getHeight(), biases.getWidth(),
(y, x) -> {
double sum = 0;
for(int i=0; i<delta.getHeight(); i++) {
sum += delta.get(i, x);
}
return sum;
});
return matrix;
}
}
}