In the Machine Learning (ML) world, the equivalent of a hello world program is building a handwritten digit classifier using a neural network. I decided to take building a digit classifier on as my first project, just dipping my toe into ML and AI, to see if it was something I could compete in. There was no question that I was interested in it. I had dreamed of making artificial intelligence since early high school, long before it became a visible career path. Now, at the ripe old age of 27, I decided to try my hand at the most difficult and competitive field of software engineering, during a time when the job market was one of the worst in years. What could possibly go wrong?

So naturally I needed to figure out if I could swing it, and keep up with people 10 years younger and smarter than me in the field. Towards this end, I decided to do this project in the hardest, but also most learning-intensive, way possible: with little to no references or help, and not following any guide. I would learn about what a neural network was, understand the major concepts required for its functionality, and then build it. This is not the fastest way to build a neural network, or even the most efficient way to learn ML, but it would be a good test to show whether the field was a fit for me: By not using many outside resources, and trying to build and iterate on intuition rather than replicating others’ work, I was simulating my job goal: Building novel neural nets where resources are limited because no one has built anything similar.

A simple neural network with fully connected layers

So what is a neural network (NN)? I expected this question to have a complex answer. It does not. Most basic NNs are simply a number of neurons, which are just a number, and weights. The neurons are organized in layers and connected through weights. Pretty simple, right? I’m not sure what all the fuss is about with ML; this stuff’s easy!

Neural Networks are easy. simple.

How they learn, on the other hand, is very much not easy, not simple. Even though on a high level of abstraction it may seem simple: The learning process is trial and error, and the network goes towards less error. The formal term for this is gradient descent, and its implementation relies largely on a deep understanding of vector calculus: Taking concepts from formal mathematics which are taught in one or two dimensions and applying them between much more complex N-dimensional matrices.

A veryyyyyy simplified example of gradient descent

I won’t make an attempt to fully cover how gradient descent works here, mostly because there are others who have already done this far, far better than I can. A quick web search will return a plethora of resources. For getting started with an intuition for how NNs learn, I used and highly recommend 3Blue1Brown’s excellent video series on the topic, which does not fully explain the complexities in implementing gradient descent, but helps build a fundamental understanding of what it’s meant to do. Beyond that, Andrej Karpathy is an excellent resource for getting everything from high-level understanding down to the code. I also used Michael Nielsen’s online textbook for some points where I got stuck, although I don’t recommend using the code from this textbook, as it was written in Python 2.7, and the function of some modules used has changed dramatically since then.

So our network should be comprised of some minimum number of layers, with an input layer, n number of hidden layers, and an output layer. The neurons in these layers will be connected by weight matrices, where the weights are updated to reduce error in the output layer through a process called gradient descent.

To gain an intuition for how gradient descent works, let’s start with an example which is simple enough to visualize. If we have an output layer of two neurons which can output anywhere from 0 to 1, and a set of training data which gives us knowledge of what the output layer SHOULD be (let’s call these expected values), we should be able to figure out what the difference, or error, is in the output layer. For example:

Or expressed as code:

import numpy as np
output = np.array([1,1])
expected = np.array([0,1])
error = output - expected
print(error) -> [1, 0]

To turn this into something we can minimize, we combine the errors into a single number called the loss (or cost). A common choice is squared error, ½·Σ(output − expected)². The gradient of the loss with respect to our two output neurons tells us how changing each one affects the total error, and for squared error it works out to exactly the error vector above: output − expected. Because this is a simple example with just two neurons, we can plot the error and its gradient in a visually intuitive way; this will quickly become impossible to visualize as each additional neuron adds a dimension to the error vector, but for our very simple example we can plot it to aid our intuitive understanding of error and learning:

The above visuals helpfully show the difference between the error and its gradient, and we can intuitively make the jump that moving down the gradient will reduce our error. Beyond this simple example, it will quickly become impossible to visualize the gradient directly, as even for simple networks the gradient is many thousands of dimensions.

Now that we know the gradient at the location our network currently is, we can adjust the values of our output neurons in the negative direction of the gradient at the current location, thereby reducing error. We can do this either by directly changing neuron activation (changing the bias) or by changing the ways our neurons interact with prior layers (changing the weights). There is a third way we can use the gradient to reduce error, and while it’s the most complex, it’s also by far the most powerful and critical to the secret sauce of ML. So far we’ve only talked about manipulating the neurons in our output layer directly, which would be all we could do if our network was completely flat (a single layer), but neural networks (loosely inspired by the brain) are made of many layers, each feeding forward into the next. True learning comes from changing ALL layers hidden between the input and output layers. That being said, we only have an understanding of what the error gradient is in our output layer, so how would we know which directions to change hidden layers in our network to reduce error?

Enter backpropagation. Backprop is the third way we can use our gradient to reduce error that we referenced earlier, and is by far the most powerful. It’s also where, as we’ll find out in future chapters covering code implementation, the math goes from simple calculus to brain-numbingly complex linear algebra. Yay!

For now, let’s stick with our super simple example. In addition to the two output neurons we have been studying, let’s add a hidden layer feeding into them, also with two neurons:

We’ve calculated the error gradient in the output layer, so we know which direction we want each output neuron to change. We should also know the way those output neurons are influenced by upstream hidden layers, through the weighted connections between neurons in each layer (the weights), so we should logically be able to figure out how we would want individual neurons in prior hidden layers to change to reduce error in the output layer. The term for how we want these upstream neurons to change is the backpropagated error gradient, and we can use it in exactly the same ways as we did in the output layer: to change neuron activations directly (biases), to change the way the prior layers affect them (weights), and to once more backpropagate the error gradient to the next earlier layer. We can repeat this process until we’ve backpropagated the error in our output neurons all the way through our neural network, and then make changes in each layer based on that error.

In our simple example, we can easily plot the error gradient for the whole range of possible output neurons. In real networks, however, we can generally only know the error gradient at the exact point a given training example produces. Because the gradient is not constant, we cannot simply adjust the network to the negative magnitude of the gradient; if the gradient were constant, doing this would reduce error to zero in a single step. In reality, it will most often just cause some random change in the error. To get around this, we will adjust the network weights and biases only by a small percentage of the negative error gradient, just taking a small step in that direction, before repeating this process and taking many small steps down the gradient until we reach a sufficiently low error.

To further increase the accuracy of our gradient descent, we will also average together suggested learning steps from a number of different training examples, only applying the averaged change to our network weights and biases. This process is called batching.

We can also train our network on all our training data multiple times, looping through all training examples for some number of epochs.

All of these processes and steps combine to form the core of our training loop. There are many other things which I’ve left out of this explanation, such as our loss and activation functions, but these will be covered in future chapters. While no single step of the machine learning process is particularly difficult in isolation, they layer atop each other to create a system which is difficult to fully intuit at the beginning of the learning process. Isolating individual steps, testing them in their simplest form, and digging out the actual processes from high-level abstractions are key skills for learning and developing ML.

Armed with this understanding, in the next post we’ll cover using our intuition to start writing the high-level code for a neural network that classifies images of handwritten digits using the MNIST database to train a fully connected network with 1-3 hidden layers.

Posted in

Leave a Reply