Understanding neural networks | Part 2: Writing code
Part 1: Introduction and my wild thoughts was only English and no code. This is the code.
Everything below is a complete file. Copy it, run it, compare against the output printed underneath. You do not need Part 1 to follow it.
A neuron is a weighted sum plus a constant
Each input gets multiplied by its own weight. The results are added up. Then one more number is added that was not multiplied by anything. That last number is the bias.
package main
import "fmt"
func main() {
inputs := []float64{1, 2, 3}
weights := []float64{0.2, 0.8, -0.5}
bias := 2.0
output := (inputs[0] * weights[0]) + (inputs[1] * weights[1]) + (inputs[2] * weights[2])
output += bias
fmt.Println(output)
}
2.3
I wrote that in two statements rather than one, without thinking about it. Looking at it afterwards, the split is doing work. The weighted sum is one line. The bias is added on the next line, multiplied by nothing. Anyone reading it can see the bias is not paired with an input. One chained expression would have buried it in the middle.
One thing nearly bit me and did not. That .0 in bias := 2.0 is load-bearing. Write bias := 2 and Go infers an integer, and output += bias refuses to compile. Go will not add an int to a float64. Not implicitly, not when the conversion is obvious, not ever.
The bias is what a neuron says when the inputs say nothing
Set every input to zero and run it again.
inputs := []float64{0, 0, 0}
2
Every weight got multiplied by zero and vanished. The bias did not, because nothing multiplies it.
Take the bias out and the output is zero, and it is zero whatever the weights are, because zero times anything is zero. Without a bias, a neuron is nailed to the origin.
Example: That matters because real quantities do not politely cross zero. A thermostat should switch below 18 degrees, not below 0. A loan should approve above 50,000, not above 0. The weight decides how much an input matters. It cannot say from where. The bias is the from where.
I predicted my first bug, checked, and did not find it
Before writing any of this I expected 2.3 to come out as 2.3000000000000003. That is what floating point usually does to a sum of products, and I was braced for it.
It came out clean. So did the four input version, 4.8.
I am recording the wrong prediction rather than pretending the ugly number was never expected. It turns up later, in a place I was not watching.
12 multiplications, none of which the compiler can check
A layer is a group of neurons that all see the same input. Each has its own weights and its own bias, and produces its own output. Four inputs, three neurons, twelve multiplications.
I wrote it out by hand on purpose.
package main
import "fmt"
func main() {
inputs := []float64{1, 2, 3, 2.5}
weights1 := []float64{0.2, 0.8, -0.5, 1}
weights2 := []float64{0.5, -0.91, 0.26, -0.5}
weights3 := []float64{-0.26, -0.27, 0.17, 0.87}
bias1, bias2, bias3 := 2.0, 3.0, 0.5
output1 := (inputs[0] * weights1[0]) + (inputs[1] * weights1[1]) + (inputs[2] * weights1[2]) + (inputs[3] * weights1[3])
output1 += bias1
output2 := (inputs[0] * weights2[0]) + (inputs[1] * weights2[1]) + (inputs[2] * weights2[2]) + (inputs[3] * weights2[3])
output2 += bias2
output3 := (inputs[0] * weights3[0]) + (inputs[1] * weights3[1]) + (inputs[2] * weights3[2]) + (inputs[3] * weights3[3])
output3 += bias3
fmt.Println(output1, output2, output3)
}
4.8 1.21 2.385
Correct. Now suppose in the second block I had typed weights1[2] instead of weights2[2]. One character.
It compiles. It runs. It prints three numbers, and the wrong one sits between two right ones looking entirely plausible. Both names exist. Both indexes are in range. Nothing in the language fires, because nothing about it is invalid. It is only wrong.
The only thing that caught it that day was me being careful twelve times in a row.
The compiler proves the indexes are in range. It does not prove they are the ones you meant.
There is a second problem in that file and it is not in the numbers. output1, output2, output3 are three loose variables. The input was a slice. The output cannot be passed to anything expecting a slice, so it cannot be fed into another layer. The program is correct and does not compose.
An error needs someone who can act on it
Before looping, the repeated multiply-and-add wanted to be a function. Which raised a decision: what should it do when the two slices are different lengths?
I picked the error return, (float64, error). My reason was that error handling catches problems before they cause damage.
The reason was wrong. An error is returned at the exact moment the thing goes wrong, which is when a panic fires. Neither is earlier. What differs is that an error hands the caller a choice.
There is no choice here. A length mismatch does not mean bad data arrived from outside. It means I wired two layers together incorrectly, in code I wrote. Every caller would do the same thing: stop. Threading that through every call site is a lot of plumbing for a decision nobody gets to make.
Return an error when the caller has a decision to make. Panic when the only correct response is to stop.
This is not "Go errors are overhead". Later on I will be downloading files and reading images off disk, and those fail for reasons outside the program. The error return is correct there. I had reached for the right tool and pointed it at the wrong situation.
One place to be wrong instead of twelve
package main
import "fmt"
func main() {
inputs := []float64{1, 2, 3, 2.5}
allWeights := [][]float64{
{0.2, 0.8, -0.5, 1},
{0.5, -0.91, 0.26, -0.5},
{-0.26, -0.27, 0.17, 0.87},
}
biases := []float64{2.0, 3.0, 0.5}
output := []float64{}
for index, weights := range allWeights {
result := dot(inputs, weights)
result += biases[index]
output = append(output, result)
}
fmt.Println(output)
}
func dot(a, b []float64) float64 {
if len(a) != len(b) {
panic(fmt.Sprintf("dot: length mismatch: %d vs %d", len(a), len(b)))
}
sum := 0.0
for index, value := range a {
sum += value * b[index]
}
return sum
}
[4.8 1.21 2.385]
Same numbers. 12 typed indexes down to one, and the output is a slice rather than three loose floats.
That inner loop, multiply each pair and add up the results, is the dot product. I wrote it because the arithmetic demanded it and learned the name afterwards, which is the right order.
Too many crashes, too few is silent
I broke the guard on purpose, in both directions, because one felt incomplete.
siddhantangore@Siddhants-MacBook-Pro nnfs-go % go run main.go
panic: dot: length mismatch: 4 vs 3
goroutine 1 [running]:
main.dot(...)
/Users/siddhantangore/Code/GitHub/go-tools/nnfs/nnfs-go/main.go:28 +0xc0
main.main()
/Users/siddhantangore/Code/GitHub/go-tools/nnfs/nnfs-go/main.go:18 +0x140
exit status 2
Before the guard, only one of those two directions was loud.
Too many weights and the loop indexes past the end of the inputs, and Go panics on its own. Immediate, with a line number.
Too few weights and the loop runs fewer times, silently ignores the last input, and returns a plausible float. Nothing crashes. Nothing warns.
The failure that crashes is the safe one. The failure that returns an answer is the expensive one, and it is the direction things go wrong in when layer sizes are managed by hand.
The trace has two line numbers and they answer different questions. Line 28 is where it died. Line 18 is who asked. Read down for where, up for why.
9 right numbers in the wrong arrangement
Real training data is thousands of samples at once, not one. So three samples, same weights, same biases, one row of output per sample.
That needs a third loop. I was asked, before writing it, to decide which way round the loops should nest and why. I did not answer. I wrote it.
package main
import "fmt"
func main() {
inputs := [][]float64{
{1, 2, 3, 2.5},
{2, 5, -1, 2},
{-1.5, 2.7, 3.3, -0.8},
}
allWeights := [][]float64{
{0.2, 0.8, -0.5, 1},
{0.5, -0.91, 0.26, -0.5},
{-0.26, -0.27, 0.17, 0.87},
}
biases := []float64{2.0, 3.0, 0.5}
output := [][]float64{}
for index, weights := range allWeights {
layerOutput := []float64{}
for _, inputList := range inputs {
result := dot(inputList, weights)
result += biases[index]
layerOutput = append(layerOutput, result)
}
output = append(output, layerOutput)
}
fmt.Println(output)
}
func dot(a, b []float64) float64 {
if len(a) != len(b) {
panic(fmt.Sprintf("dot: length mismatch: %d vs %d", len(a), len(b)))
}
sum := 0.0
for index, value := range a {
sum += value * b[index]
}
return sum
}
[
[4.8 8.9 1.4100000000000004]
[1.21 -1.8100000000000005 1.0509999999999997]
[2.385 0.19999999999999996 0.025999999999999912]
]
The answer I was checking against:
[[ 4.8 1.21 2.385]
[ 8.9 -1.81 0.2 ]
[ 1.41 1.051 0.026]]
All 9 numbers are correct. My rows are the reference's columns.
I had put neurons on the outside and samples on the inside, so each row I built collected one neuron's answer across all three samples. Row 0 was neuron 1 replying to sample 1, sample 2, sample 3.
Why that matters is not aesthetics. The input was three samples of four numbers. For the output to be feedable into a second layer it has to be the same kind of thing: three samples of three numbers. Mine was three neurons of three sample-results. Feed that forward and the next layer treats one neuron's history as though it were a sample. It computes. It prints numbers.
Now count what could have caught it.
Three samples, three neurons. Square. A transpose of a square matrix is the same size as the original, so no length check can see it and the guard never fires. Every value is in range. Nothing is missing. Four neurons instead of three would have given a 4x3 where the answer is 3x4, and there would still be no error, only 12 correct numbers in the wrong arrangement.
The only thing that revealed it was comparing values against a known answer.
A transpose is the one shape error that survives every check you have, because nothing is missing and nothing is out of range.
The fix is two lines swapped
for _, sample := range inputs {
sampleOutput := []float64{}
for neuronIndex, weightsOfNeuron := range allWeights {
neuronOutput := dot(sample, weightsOfNeuron)
neuronOutput += biases[neuronIndex]
sampleOutput = append(sampleOutput, neuronOutput)
}
output = append(output, sampleOutput)
}
[
[4.8 1.21 2.385]
[8.9 -1.8100000000000005 0.19999999999999996]
[1.4100000000000004 1.0509999999999997 0.025999999999999912]
]
The loop bodies were never wrong. I chose the wrong thing to put on the outside and the shape followed automatically.
The outer loop appends exactly one row per pass, so whatever it ranges over is what a row means. The inner loop fills that row, so what it ranges over is what a column means. Pick the outer loop by asking what one row should be, not by asking what to iterate.
The outer loop decides what a row means. Everything else follows.
The answer I was checking against was already rounded
The ugly floats arrived here, in the place I was not watching. 1.4100000000000004 where the reference prints 1.41.
My first thought was that Go and Python were disagreeing, which would be a problem, because those printed numbers are the only thing I have to check against.
They are not disagreeing. I ran the same arithmetic through NumPy and asked for the raw values rather than the array printout:
what it prints: the actual float64 values:
[[ 4.8 1.21 2.385] 4.8, 1.21, 2.385
[ 8.9 -1.81 0.2 ] 8.9, -1.8100000000000005, 0.19999999999999996
[ 1.41 1.051 0.026]] 1.4100000000000004, 1.0509999999999997, 0.025999999999999912
Every ugly digit in my Go output is sitting inside NumPy too, identical to the last bit. NumPy's array printer rounds to eight significant figures before showing anything.
That is a sensible default for reading a matrix. It also means the clean column of numbers I had been checking against is a rendering, not the data.
A printed answer key has already been through a filter. Matching it exactly was never the test.
A layer that is a thing rather than a loop
At this point main was doing three jobs: holding the data, being a layer, and printing. There was no layer in the program, only a loop shaped like one. Adding a second layer means calling the first thing twice, which needs the first thing to exist.
package main
import "fmt"
type Layer struct {
weights [][]float64
biases []float64
}
func (layer Layer) Forward(inputs [][]float64) [][]float64 {
layerOutput := [][]float64{}
for _, sample := range inputs {
sampleOutput := []float64{}
for neuronIndex, weightsOfNeuron := range layer.weights {
neuronOutput := dot(sample, weightsOfNeuron)
neuronOutput += layer.biases[neuronIndex]
sampleOutput = append(sampleOutput, neuronOutput)
}
layerOutput = append(layerOutput, sampleOutput)
}
return layerOutput
}
func main() {
inputs := [][]float64{
{1, 2, 3, 2.5},
{2, 5, -1, 2},
{-1.5, 2.7, 3.3, -0.8},
}
layer1 := Layer{
weights: [][]float64{
{0.2, 0.8, -0.5, 1},
{0.5, -0.91, 0.26, -0.5},
{-0.26, -0.27, 0.17, 0.87},
},
biases: []float64{2.0, 3.0, 0.5},
}
fmt.Println(layer1.Forward(inputs))
}
func dot(a, b []float64) float64 {
if len(a) != len(b) {
panic(fmt.Sprintf("dot: length mismatch: %d vs %d", len(a), len(b)))
}
sum := 0.0
for index, value := range a {
sum += value * b[index]
}
return sum
}
[
[4.8 1.21 2.385]
[8.9 -1.8100000000000005 0.19999999999999996]
[1.4100000000000004 1.0509999999999997 0.025999999999999912]
]
Identical output. Only the arrangement moved.
The letter I dropped twice (optional, lol just writing so we follow readable code)
Somewhere in the tidying I introduced this:
layerOuput := [][]float64{}
Missing a t. Twice, consistently, so it compiled and ran and produced the correct answer. A name only has to be spelled the same way each time, not spelled right.
I also spent three rounds asking whether the variable names were right, and each round improved less than the one before. It felt productive. There is always a better word available, so the activity never terminates on its own, and nothing in it can fail. That is the same shape as the fourteen pages of English I spent on Part 1. Both felt like work. Neither could be checked.
My second layer was decorative
There is only one rule governing how two layers connect. The first layer has three neurons, so every weight set in the second layer must have exactly three weights.
layer2 := Layer{
weights: [][]float64{
{0.1, -0.14, 0.5},
{-0.5, 0.12, -0.33},
{-0.44, 0.73, -0.13},
},
biases: []float64{-1, 2, -0.5},
}
output1 := layer1.Forward(inputs)
output2 := layer2.Forward(output1)
[
[0.5030999999999999 -1.0418499999999997 -2.0387500000000003]
[0.24340000000000028 -2.7332 -5.7633]
[-0.99314 1.41254 -0.35655000000000037]
]
2 layers, in Go, standard library only. Then I used maths to make this a to single layer, four inputs and three neurons:
collapsed := Layer{
weights: [][]float64{
{-0.18, 0.0724, -0.0014, 0.605},
{0.0458, -0.4201, 0.2251, -0.8471},
{0.3108, -0.9812, 0.3877, -0.9181},
},
biases: []float64{-0.97, 1.195, 0.745},
}
I printed both:
[[0.5030999999999999 -1.0418499999999997 -2.0387500000000003] [0.24340000000000028 -2.7332 -5.7633] [-0.99314 1.41254 -0.35655000000000037]]
[[0.5031000000000001 -1.04185 -2.03875] [0.24340000000000006 -2.733199999999999 -5.763299999999999] [-0.9931399999999999 1.41254 -0.35655000000000003]]
15 decimal places of agreement on all 9 numbers.
Those collapsed weights came from two matrix multiplications. Multiply the second layer's weights by the first layer's weights and you get one set of weights. Multiply the second layer's weights by the first layer's biases, add the second layer's biases, and you get one set of biases. It is the algebra you get from expanding w₂(w₁x + b₁) + b₂, done with numbers instead of symbols.
So my second layer contributes nothing. Not "not much". There exists a single layer that produces its exact output, and finding it took one pass of arithmetic. Stack 10 more and all 10 collapse the same way. The program has depth and no depth.
If you can compute the equivalent single layer, the depth was never real.
The disagreement in the last digits is worth a sentence. Neither version is more correct. The two-layer version rounds after every multiply-and-add and then feeds the rounded result into more multiplies. The collapsed version does fewer operations, so fewer roundings. Floating point addition is not associative, so (a + b) + c and a + (b + c) can differ.
Which settles something I had been worrying about. I was never going to match a reference answer digit for digit past a few operations, whatever I did. Not because of a random seed. Because of the order the additions happen in.
What is next
An activation function between the layers. ReLU, which is y = x with everything below zero flattened to zero.