https://github.com/mattlack15/NeuralNetLib
Purpose
This is a small Java library I wrote in 2021 for building fully-connected (dense) neural networks and training them on the CPU. It has no dependencies. The matrix math, back propagation and the Adam optimizer are all written from scratch. It isn't meant for large networks, you should use a real deep learning library for that.
Features
- Dense layers of any size
- ReLU (default), sigmoid and linear activation functions
- Training with back propagation and mini-batches
- Adaptive moment estimation (Adam) for weight updates
- Weights initialized from a Gaussian scaled by 1/√(inputs)
Usage
Here is a small network with two inputs, a hidden layer of 8, and one sigmoid output:
Network network = new Network();
network.addLayer(new DenseLayer(2, 8));
network.addLayer(new DenseLayer(8, 1).setActivationFunctionSigmoid());
network.setLearningRate(0.01);
// Train on a set of examples with a batch size of 4
double loss = network.train(examples, labels, 4);
double[] output = network.propagate(new double[]{1, 0});
How it works
Matrix
Everything is built on a small Matrix class that stores its data in a flat double[]. Most operations modify the matrix in place and return this, so they can be chained without allocating a new array at every step. When I need to keep the original, I call copy() first.
Forward propagation
Each layer multiplies its input by its weights, adds its biases, and applies its activation function. It also remembers its input and its value before activation, because back propagation needs both:
public Matrix propagate(Matrix input) {
this.prevInput.copyExternal(input);
input = input.vDot(this.weights).add(biases);
this.nonActivatedState.copyExternal(input);
return input.apply(activationFunction);
}
Back propagation
Training goes through each example, computes the error (label - output), and walks backwards through the layers. Each layer multiplies the error by the derivative of its activation function, adds its share of the gradient to an accumulator, and passes the error back through its weights to the layer before it:
public Matrix backPropagate(Matrix input) {
input.multiply(this.nonActivatedState.copy().apply(activationFunctionDer));
this.accBiasUpdates.add(input);
this.accUpdates.add(input.vInterMultiply(this.prevInput));
accumulationNum++;
return input.vDot(this.weights.copy().transpose());
}
vInterMultiply is the outer product of the error and the layer's previous input, which is exactly the gradient for each weight.
Adam
After every batch, each layer updates its weights using Adam. Instead of moving each weight directly along its gradient, Adam keeps a running average of the gradient (m) and of the squared gradient (v) for every weight, corrects them for being initialized at zero, and steps by m / (√v + ε). Weights with consistent gradients move quickly, and noisy ones move carefully. I use the usual β₁ = 0.9 and β₂ = 0.999.
//Update using Adam method
m.multiply(beta_1).add(accUpdates.copy().multiply(1D - beta_1));
Matrix g2 = accUpdates;
g2.apply((t) -> Math.pow(t, 2));
v.multiply(beta_2).add(g2.multiply(1D - beta_2));
Matrix m_hat = m.divide(1D - Math.pow(beta_1, updateIteration));
Matrix v_hat = v.divide(1D - Math.pow(beta_2, updateIteration));
v_hat.apply(Math::sqrt).add(nonZero);
m_hat.divide(v_hat).multiply(learningRate / accumulationNum);
this.weights.add(m_hat);
Where I used it
I later used this library for the actor and critic networks in my implementation of Proximal Policy Optimization. See https://mattlack.com/project/1748838882885