AI voor Iedereen

Search

Search chapters and demos

🧠 Neural Networks

🔌 One neuron

✍️ A network that reads your handwriting

Click one of the digits below the drawing board, or click "Reset" and draw a digit yourself. The neural network behind this demo usually recognizes it right away.

Loading demo

How can a computer program do that? Nobody programmed rules such as "a 7 is a horizontal stroke with a slanted leg". The network taught itself this from tens of thousands of examples of handwritten digits, and it does so with building blocks that are surprisingly simple.

Such a building block is called a neuron: a small calculating unit that takes in a few numbers, lets each number count more or less heavily, and turns them into a single result. A neural network is nothing more than a great many of those units, passing on to each other what they calculate. In the demo above, the circles in the middle and the ten boxes on the right are such neurons.

Neural networks are inside almost all the AI you come across every day: the spam filter of your mailbox, the face recognition that unlocks your phone, the automatic subtitles on YouTube, translation systems such as DeepL and language models such as ChatGPT. If you use such tools, you want to know what happens inside that "black box": why they are so good at recognizing patterns, and why they are sometimes wrong with great confidence.

In this chapter we build this up from small to large: first one neuron, then how such a neuron learns, and then what happens when you let hundreds of them work together.

🍽️ Back to the Alma

Let us take up the example from the chapter on the dimensions of AI once more. You are sitting in the Alma, KU Leuven's student restaurant, and you want to guess whether an unknown person at your table is a student or a researcher, based only on what is on their tray. For eight other people at the table you already know:

Name🥖 Bread roll🍲 Soup🍎 Fruit🥣 YogurtStudent or researcher?
Ankeyesnonoyesstudent
Bartyesnoyesnostudent
Caroyesyesnonostudent
Dirknoyesyesnoresearcher
Evynoyesnoyesresearcher
Flooryesyesyesnoresearcher
Gertnonoyesyesstudent
Hannenoyesyesyesresearcher

A neuron tackles that question as a points tally. Every part of the meal is worth a number of points: positive if it points to a student, negative if it points to a researcher, and around zero if it does not matter. For a new person you add up the points of everything on the tray. If the total is positive, you say "student"; if it is negative, you say "researcher".

Suppose, for example, that 🍲 soup is worth −3 points and 🍎 fruit 0 points. Dirk takes soup and fruit, so he ends up at −3 + 0 = −3: a researcher, and that is correct. The parts of the meal are called the inputs of the neuron: an input is 1 if that part is on the tray, and 0 if it is not.

🎚️ Weights and bias

In a neuron, the points that each part is worth are called the weights. You can think of them as the volume knobs on a mixing console: each weight determines how strongly one input counts in the final result. Turn the weight of 🥖 bread roll all the way up, and a bread roll on the tray weighs heavily toward "student". Set the weight of 🍲 soup to a negative value, and soup pulls the outcome toward "researcher" instead. If a weight is zero, the neuron ignores that part completely.

A weighted sum is a sum in which each number is first multiplied by a weight that says how heavily it counts. Your overall grade for the year is one: a course of 6 credits counts twice as heavily as a course of 3 credits. In the Alma, every input is 1 (on the tray) or 0 (not on it), so the weighted sum is simply the sum of the weights of what is on the tray.

In addition, every neuron has a bias: a fixed number of starting points that is always added, whatever is on the tray. A positive bias makes the neuron generous (it says "student" more readily), a negative bias makes it strict.

Try it yourself. In the demo below, the inputs are on the left: a filled circle with a check mark is on the tray (1), an empty circle with a cross is not (0). Each arrow has a slider for its weight. At the top is the bias, as a circle with a 1 in it: it is always on, so the bias always counts. On the right you see what the neuron decides.

The tray belongs to Anke, a student: a bread roll and yogurt. All the weights are at zero, so the neuron has no opinion at all yet and says 50%, just short of "student". Move the weights until the neuron gets Anke right. In the dark blue frame you see how the total becomes a probability: the orange dot slides along the curve with the total. Which sliders make a difference, and which do not?

Loading demo
Solution

🌊 From points to a probability

The points total of a neuron (the weighted sum) can be any number: −3, 0.6 or 12. The sign says which way it leans, but not how sure the neuron is: is a total of 0.6 as convinced as a total of 12? That is why the neuron sends that total through one last step, the activation function, which turns it into a usable output.

Neuron Definition

A neuron (also called a perceptron) is the building block of a neural network. It multiplies each input by a weight, adds everything up together with the bias, and sends that total through an activation function that turns it into a single output number.

In our Alma neuron that is the sigmoid function you already saw with logistic regression: the S-shaped curve along which the orange dot slid in the demo above. It squashes every total into a number between 0 and 1, which you can read as a probability. A high total gives a probability close to 100%, a strongly negative total a probability close to 0%, and a total of exactly zero gives 50%: the neuron is in doubt. If the probability is above 50%, the neuron predicts "student". In the next demos the total is called zz and the sigmoid σ\sigma (the Greek letter sigma): that is also how they appear in the formulas further on.

Now that the neuron gives a probability, let us set it loose on the whole table. In the demo below, the eight people from the table are listed beside or below the diagram, each with the current prediction and whether it is correct. Click a person to load their tray, and move the weights until the score reads 8 of 8. The last row, "New", is the unknown person at your table (bread roll, soup and yogurt): what does your neuron predict for that person?

Loading demo

Can you get all eight right? First look in the table for the part that makes the clearest difference between the students and the researchers.

Solution
Neuron or perceptron? Did you know?

The name "neuron" comes from the nerve cells (external link) in our brain, which also receive signals from other cells, add them up and pass them on or not. The resemblance is superficial: real neurons are much more complex and learn in a very different way. In 1958 Frank Rosenblatt (external link) named the artificial neuron the perceptron. His version only gave a hard 0 or 1 as output, without probabilities in between.

🧾 The neuron as a formula

You can also write down what the neuron does in a single line. Take the weights from the solution above (bias +1+1, bread roll +1.5+1.5, soup −2-2, fruit −1-1, yogurt +0.5+0.5) and the unknown person at your table, with a bread roll, soup and yogurt on their tray. Multiply each weight by its input (1 if the part is on the tray, 0 otherwise) and add everything up:

z=1+1.5⋅1−2⋅1−1⋅0+0.5⋅1=1z = 1 + 1.5 \cdot 1 - 2 \cdot 1 - 1 \cdot 0 + 0.5 \cdot 1 = 1

For a total of 1 the sigmoid gives about 0.73: a 73% probability of student. You can read that off the S-curve in the demo, or calculate it with the formula of the sigmoid.

In general we call the inputs x1,x2,…,xnx_1, x_2, \ldots, x_n, the weights w1,w2,…,wnw_1, w_2, \ldots, w_n and the bias w0w_0. The neuron then calculates:

output=f(w0+w1x1+w2x2+…+wnxn)\text{output} = f(w_0 + w_1 x_1 + w_2 x_2 + \ldots + w_n x_n)

where ff is the activation function. You can see the bias as the weight of an extra input that is always 1; that is also how it is drawn in the demos and in the figure below.

Diagram of a perceptron: input values x1 and x2 are multiplied by weights w1 and w2, added up together with a bias w0 (Σ), sent through an activation function f, and produce an output.
The two steps of a neuron: first the weighted sum (Σ), then the activation function (f).

With the sigmoid as its activation function, a neuron is exactly the same model as logistic regression. Leave out the activation function, so that the total goes out unchanged (the identity function f(z)=zf(z) = z), and you get linear regression. So both models from the chapter on regression are a single neuron, with or without a sigmoid.

🏋️ How does a neuron learn?

🔁 Guess, compare, adjust

For eight people and four parts of a meal, you can still set the weights by hand, by eye. The network that reads handwriting already has more than twelve thousand weights: the network has to learn those by itself from examples. That learning, the training of the network, is surprisingly simple. The neuron goes through the examples from the table one by one, and does three things for each example:

  1. 🔮 Guess: with its current weights, it calculates a probability for this person.
  2. 🔍 Compare: it looks at the right answer in the table. Was the guess too high, too low, or about right?
  3. 🔧 Adjust: it turns the weights a little in the direction that would have brought the guess closer to the right answer.

Take Anke, a student with a bread roll and yogurt on her tray. If the neuron says 50%, that is too low. So the weights of exactly those two parts go up a little, together with the bias, so that a tray like Anke's gets a higher probability next time. What Anke did not take (soup and fruit) is left alone: those parts played no role in this guess. Then take Dirk, a researcher with soup and fruit. If he gets 80%, the guess was far too high, and the weights of soup and fruit go down considerably, together with the bias. The bigger the error, the bigger the correction. If the guess was already almost right, hardly anything changes: only the confidence can be raised a tiny bit more.

One such correction makes the neuron better for the person it just saw, but it can push another person just across the boundary. That is why the neuron repeats this for all the people, round after round, until the weights are right for everyone at once.

Watch it step by step in the demo. All the weights start at zero, so every guess is 50%. Click ▶ or the arrow to process one person at a time: below the diagram you read which guess the neuron made, how far off it was and which weights shift as a result. Drag the slider to the end to see where the neuron ends up after sixteen rounds.

Loading demo

Notice that the neuron arrives by itself at the same result as we did in the previous exercise: a strongly negative weight for soup, a positive weight for bread roll and a small weight for yogurt. Nobody told the neuron that soup points to a researcher. It extracted that pattern from the table by itself, just by correcting its own mistakes. That is the core of how neural networks learn.

🐢 The learning rate

The size of such a nudge is set by the learning rate. In the demo you choose it with 🐢, 🚶 and 🐇. With a small learning rate the neuron takes careful little steps: safe, but after sixteen rounds it still gives Caro just under 50%. With a large learning rate it makes big jumps: it gets close quickly, but overshoots far with every mistake and jumps back and forth for the first rounds. On a small, clean table like this one it still gets there in the end; on harder problems that jumping can go on. A good learning rate usually lies in between.

Three graphs that show the effect of the learning rate: too large (jumps over the optimum), too small (extremely slow convergence), and good (converges to the minimum)
The same error curve and the same starting point, only a different learning rate. Too large: jumps back and forth over the valley, and the error even grows. Too small: crawls painfully slowly. Good: reaches the lowest point smoothly.

This way of learning is exactly the gradient descent from the chapter on regression. Every combination of weights gives a certain total error on the table, and together those form a landscape with hills and valleys. Every adjustment is a small step downhill, blindfolded: the neuron does not see the valley, but feels which way the ground slopes down.

🔧 The update rule as a formula

As a formula, every weight is adjusted for every example as follows:

winew←wi+α⋅(t−o)⋅xiw^{\text{new}}_i \leftarrow w_i + \alpha \cdot (t - o) \cdot x_i

Where:

  • wiw_i = the current weight for input ii, and wineww^{\text{new}}_i = that weight after the adjustment
  • α\alpha = the learning rate
  • tt = the right answer (the target value): 1 for a student, 0 for a researcher
  • oo = the neuron's guess (its output), the probability it calculated
  • xix_i = the input that belongs to weight wiw_i (always 1 for the bias)

The difference (t−o)(t - o) is the error: positive if the guess was too low, negative if it was too high, and zero if it was perfect. Because it is multiplied by xix_i, only the weights of inputs that were "on" change; in the Alma those are the parts that were on the tray.

Fill in Anke with learning rate α=1\alpha = 1: she is a student (t=1t = 1), the neuron guessed o=0.5o = 0.5, and bread roll and yogurt are 1. Each of those two weights and the bias then rises by 1⋅(1−0.5)⋅1=0.51 \cdot (1 - 0.5) \cdot 1 = 0.5; the weights of soup and fruit do not change, because there xi=0x_i = 0. That is exactly the first step the demo above shows.

This rule comes from the gradient of the binary cross-entropy for a neuron with the sigmoid as its activation function: the same loss function as in logistic regression.

📏 What one neuron can and cannot do

📍 A neuron draws a straight line

In the Alma, the inputs were yes-or-no questions. Usually they are measured numbers: the length and the weight of a piece of fruit, the number of hours someone studied, the brightness of a pixel. In the chapter on regression you already saw students as dots in a plane this way, with their score on a mock exam and their number of hours of study as the two features, and a straight line between those who passed and those who failed. A neuron with the sigmoid is that model, so it draws such a straight line too.

The demo below shows this with two features and no story attached: x1x_1 on the horizontal axis, x2x_2 on the vertical axis, and the color of a dot is its label. A neuron with two inputs has three weights: w1w_1, w2w_2 and the bias w0w_0. Move them and look at the graph with the dots: the neuron predicts "blue" for everything on one side of a straight line and "orange" for everything on the other side (the background color), and the line turns and shifts along with the weights. Close to the line the color is pale (the neuron is in doubt, the probability is around 50%), far from the line it is strong.

Loading demo

That is the whole trick of a single neuron: it draws a straight line through the picture and says on which side a point lies. With three features that becomes a flat plane, with more features something we can no longer picture, but that is just as "straight". Training here simply means: turning and shifting the line until it separates the two colors as well as possible. So everything extra that a neural network can do, as you will see shortly, does not come from the neuron itself, but from connecting hundreds of them together.

✏️ Why it is always a straight line

The sigmoid gives exactly 50% when the weighted sum is zero. So the boundary between "blue" and "orange" is the set of points for which

w0+w1x1+w2x2=0w_0 + w_1 x_1 + w_2 x_2 = 0

and that is the equation of a straight line in the x1x2x_1 x_2 plane. Rewrite it as x2=−w1w2x1−w0w2x_2 = -\frac{w_1}{w_2} x_1 - \frac{w_0}{w_2} and you see that w1w_1 and w2w_2 together determine the slope and w0w_0 shifts the line. With nn inputs this becomes a plane (or hyperplane) in nn dimensions: always straight, never curved.

🚧 When a straight line is not enough

Now let the neuron train by itself. With the dataset "Two Gaussian clusters" the line neatly turns between the two colors after a few dozen steps. Then switch, at the top left, to "Concentric circles" or "XOR pattern" and train again.

Loading demo

However long you train, it does not work. With the circles, one class forms a ring around the other, and in the XOR pattern the points of the same color lie in opposite corners: no straight line can pull them apart. That is the fundamental limitation of a single neuron: it can only separate classes that are linearly separable, in other words separable with a straight line. Most interesting problems are not. A handwritten 3 and an 8 cannot be separated cleanly by a single straight boundary between pixel values.

Minsky, Papert and the perceptron Did you know?

This limitation was already known in 1969: in their book Perceptrons (external link), Marvin Minsky and Seymour Papert showed that a single perceptron cannot learn even the simple XOR pattern from the demo. That stalled research on neural networks for years. Several neurons in layers can handle XOR, but how to train such a network only became clear later, with backpropagation.

🪜 From neuron to network

🧱 Multilayer perceptron

The solution is to use not one neuron but a whole group, in layers. Every neuron in the first layer gets the same inputs (the features) and draws its own straight line. The outputs of those neurons become the inputs of the next layer, which weighs and combines them again, until a last neuron makes the final decision.

Schematic diagram of a multilayer perceptron: an input layer with x1, x2 and bias, two hidden layers with 4 and 3 neurons plus bias respectively, and an output layer with 1 neuron. Every neuron is connected to all the neurons in the next layer.
A multilayer perceptron with two hidden layers. Every arrow is a weight, every yellow node is a neuron (weighted sum plus activation function), and the dotted nodes are the biases.
Multilayer perceptron Definition

A multilayer perceptron (MLP) is a neural network in which the neurons are arranged in layers: an input layer with the features, one or more hidden layers and an output layer with the prediction. Every neuron is connected to all the neurons of the next layer, and the information flows in one direction, from input to output.

The layers between input and output are called "hidden" because from the outside you only see the features that go in and the prediction that comes out. This is also where the term deep learning comes from: a "deep" network is simply a network with many hidden layers. The "deep" refers to the architecture, not to a deeper way of thinking.

🔺 Three lines make a triangle

Why does this solve the circle problem? Give the hidden layer three neurons. Each of them draws one straight line, and together three lines can mark out a triangle around the inner class. The output neuron then only has to learn: inside the triangle is orange, outside it is blue.

Click "Start training" and watch how the network learns to separate the circles. Then move your mouse over one of the three neurons in the hidden layer (or tap it). The graph then shows what that one neuron calculates: a straight boundary, with blue on one side and orange on the other. The epoch counter at the top counts how many times the network has already seen all the training points, like the rounds of the Alma neuron.

Loading demo

🔍 Every layer rewrites the question

There is a more general idea behind this: every layer converts the data into a new form that makes the task easier. People do that too. Someone who has to judge hundreds of CVs for a job opening does not read them "for relevance" in one go, but first picks the key words out of every CV, groups those into aspects that matter for the job, gives each aspect a score, and finally adds up those scores. Every step rewrites the CV into a form in which the next step becomes simpler, until the final judgment is just a sum.

A neural network works the same way. The first hidden layer draws simple straight lines through the features. The second layer combines those lines into corners and curves, and a third layer joins those into spirals and other complex patterns. That way every layer makes a new intermediate representation of the data, until the output layer only has to draw a simple boundary.

Test it on the spiral below, a pattern on which a single neuron gets hopelessly stuck. Click "Start training" and give the network some time: the spiral is a good deal harder than the circles. Then move your mouse over the neurons: in the first layer you see straight divisions, in deeper layers more and more twisting shapes. With the buttons above the network you can add or remove layers, and with the + and − above each layer the number of neurons in that layer: the fewer layers, the harder it is for the network to follow the spiral.

Loading demo

🔗 Training a whole network

Training a network follows the same recipe as a single neuron: guess, compare, adjust. Only now there are hundreds of weights in different layers, and only the last neuron sees directly how far off the guess was. How does a neuron in the first layer know how much to adjust?

The answer is called backpropagation: the error is passed back through the network, from back to front. Compare it to a factory where a faulty product comes off the assembly line. The last workstation sees the defect and checks which parts from the previous station caused it; that station does the same for the station before it, and so on, all the way to the front. That way every weight gets its share of the blame and is adjusted in proportion to it. What you see moving in the demos is exactly that: at every step all the weights shift a little at the same time, from the last layer to the first.

You sum up how well the network is doing in a single number: the loss, which says how far off the guesses are on average. The lower, the better. At the bottom of the spiral demo above you see the loss go down while you train. The purple line is the loss on the training data, the pink line the loss on separate validation data that the network never got to see. As long as both go down, the network is learning something that also holds outside the training data. You will see further on what happens if you keep training for too long.

Moreover, the error landscape of a network is more irregular than the smooth bowl of linear regression: with hundreds of weights there are several valleys. Gradient descent can get stuck in a valley that is not the lowest one. In practice this is not too bad, but it explains why two training runs of the same network with different starting weights can end up at a different solution.

Error landscape with two valleys. Two gradient descents start from different starting weights: one gets stuck in the shallow local minimum, the other rolls on into the deepest (global) minimum.
The error landscape of a network can contain several valleys. Where gradient descent ends up depends on the starting weights: one training run gets stuck in a local minimum, the other reaches the lowest (global) minimum.

⛓️ Backpropagation and the chain rule

Take the simplest case: one input xx, one weight ww, a bias bb, the sigmoid as activation function and the squared error. One after the other, this happens:

  • ➕ the weighted sum: z=w⋅x+bz = w \cdot x + b
  • 🌊 the prediction: y^=σ(z)\hat{y} = \sigma(z)
  • 🎯 the error: L=(y−y^)2L = (y - \hat{y})^2, with yy the right answer

We want to know how much the error changes when ww changes a tiny bit: the derivative ∂L∂w\frac{\partial L}{\partial w}. Because LL depends on y^\hat{y}, y^\hat{y} on zz and zz on ww, the chain rule splits that into a product of simple derivatives:

∂L∂w=∂L∂y^⋅∂y^∂z⋅∂z∂w=−2(y−y^)⋅σ′(z)⋅x\frac{\partial L}{\partial w} = \frac{\partial L}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial z} \cdot \frac{\partial z}{\partial w} = -2(y - \hat{y}) \cdot \sigma'(z) \cdot x

In a network with more layers, more factors are simply added: every layer passes its derivative on to the layer before it. That passing on from back to front is literally what "backpropagation" means, and it makes it possible to adjust all the weights of a network in a single backward pass. The algorithm was made popular in 1986 by Rumelhart, Hinton and Williams (external link). Modern frameworks such as PyTorch calculate all those derivatives automatically with automatic differentiation (autodiff), so you only have to describe the network and the loss function.

〰️ Activation functions in the hidden layers

Without an activation function, a network would gain nothing from extra layers: a weighted sum of weighted sums is again a weighted sum, so the whole network together would still draw a single straight line. The activation function has to be able to "bend" the straight line, and for that it has to be non-linear. Which activation function you choose depends on its place in the network:

  • 🌊 Sigmoid: output between 0 and 1. The choice for an output neuron that has to give a probability.
  • 🔄 Tanh (hyperbolic tangent (tanh)): the same S-shape, but between −1 and 1 and centered around zero, which usually makes training in hidden layers more stable. The formula is tanh⁡(z)=ez−e−zez+e−z\tanh(z) = \frac{e^z - e^{-z}}{e^z + e^{-z}}; the demos in this chapter use tanh.
  • ⚡ ReLU: f(z)=max⁡(0,z)f(z) = \max(0, z), everything below zero becomes zero. By far the most popular choice in deep networks: quick to calculate, and the gradient does not "vanish" for large positive values as it does with the sigmoid and tanh.
  • 🔲 Step function: a hard 0 or 1, as in Rosenblatt's original perceptron. Useless for gradient descent, because its derivative is zero everywhere.
  • 📏 Identity function: f(z)=zf(z) = z. The choice for an output neuron that has to predict a number (regression).
Overview of five activation functions: step (red), sigmoid (blue), tanh (orange), ReLU (green) and identity (purple).
The activation functions side by side. Step, sigmoid and tanh are bounded, ReLU and the identity function keep growing without bound.

🎨 Multiple classes

🔢 One output neuron per class

So far the network always chose between two classes, with one output neuron: student or not, blue or orange. Often there are more possibilities: a digit from 0 to 9, or an email that belongs in "inbox", "promotions" or "spam". The solution is simple: give the network one output neuron per class. For digit recognition that makes ten, and every output neuron calculates a score for "its" digit.

Schematic diagram of an MLP with three output neurons y1, y2 and y3, each for one class. The structure is identical to the earlier MLP, including the bias nodes at every layer, but with several output neurons instead of one.
A network with three output neurons (y1y_1, y2y_2, y3y_3), one per class. Compare it with the earlier diagram, which had only one output neuron.

📊 Softmax

Those scores are raw numbers. Suppose a network has to sort an email, and the output neuron for 📥 inbox gives a score of 0.1, the one for 🏷️ promotions 1.0 and the one for 🗑️ spam 2.0. Spam wins, but how sure is the network of that? You would rather have probabilities that add up to 100%. That is what the softmax function does: it turns the scores into probabilities that add up to 100%, with the highest score getting the largest probability. See it as a competition between the output neurons: the higher your score, the bigger your slice of the pie, but even the lowest score still keeps a small slice. The class with the highest probability is the network's prediction.

For the email above that becomes 10% inbox, 24% promotions and 66% spam. Move the scores in the demo and watch how the probabilities move along.

Loading demo

Notice how softmax magnifies differences. Set the score of spam to 4 instead of 2: the probability of spam jumps from 66% to 93%, and only 7% is left for the two other classes together. If you set the three scores equal, each class gets 33%: the network is in complete doubt. So a small difference in score becomes a large difference in probability.

Softmax is not real uncertainty Remark

Softmax produces numbers that you can read as probabilities, but they do not reflect the "real" uncertainty of the network. Because softmax gives extra weight to the highest score, the network looks more confident than it really should be: 93% does not mean that it is right in 93% of such cases.

🥧 The softmax formula

softmax(zi)=ezi∑j=1Kezj=eziez1+ez2+…+ezK\begin{align*} \text{softmax}(z_i) &= \frac{e^{z_i}}{\sum_{j=1}^{K} e^{z_j}} \\ &= \frac{e^{z_i}}{e^{z_1} + e^{z_2} + \ldots + e^{z_K}} \end{align*}

Where:

  • ziz_i = the raw score of output neuron ii
  • KK = the total number of classes

For the email with scores 0.1, 1.0 and 2.0, we get e0.1≈1.11e^{0.1} \approx 1.11, e1.0≈2.72e^{1.0} \approx 2.72 and e2.0≈7.39e^{2.0} \approx 7.39, together 11.2111.21. Spam then gets 7.39/11.21≈0.667.39 / 11.21 \approx 0.66, promotions 2.72/11.21≈0.242.72 / 11.21 \approx 0.24 and inbox 1.11/11.21≈0.101.11 / 11.21 \approx 0.10.

The exponential function ezie^{z_i} makes higher scores weigh much more heavily: a small difference in score leads to a large difference in probability. With two classes, softmax comes down to the sigmoid.

✍️ Back to the handwriting

Now you can read the network from the start of this chapter in full. Every digit is an image of 28 × 28 pixels, and every pixel is a number between 0 (no ink) and 1 (full ink). Those 784 numbers are the inputs of the network, exactly like the four parts of the meal in the Alma, only there are a few more of them.

Examples of handwritten digits from the MNIST dataset: rows of the digits 0 through 9, each in a grid of 28×28 pixels.
Examples from the MNIST dataset (external link), a collection of 70,000 handwritten digits. Every image is a grid of 28 × 28 pixels.

The network in the demo consists of three layers:

  • an input layer with 784 neurons: one per pixel
  • a hidden layer with 16 neurons (with tanh as activation function): they learn to recognize patterns in the pixels
  • an output layer with 10 neurons with softmax: one per digit, together a probability per class

Together that makes over 12,700 weights, all learned by guessing, comparing and adjusting on the 60,000 training examples of MNIST. The network was deliberately kept this small, so that you can look at every neuron in the demo.

Loading demo

The circles in the middle are the 16 hidden neurons: their color shows how strongly each neuron responds to your drawing (blue positive, orange negative, pale hardly at all). The lines to the output layer show what is passed on: blue pushes a digit up, orange pushes it down. From the thick lines to the predicted digit you see which neurons argue for it and which against it. Hover over a neuron with your mouse (or tap it) to see its value and bring its lines to the front. While you draw, you see the ten softmax probabilities on the right change live. They always add up to 100%, and the longest bar is the prediction. Note that the network knows the American way of writing digits, with the 1 as a straight stroke and the 7 without a crossbar.

🕵️ Can you fool the network?

Try to challenge the network:

  • Ambiguous digits: draw something that looks like both a 7 and a 1. The probability is then spread over several classes, instead of going to one class.
  • Not a digit: draw a heart, a star or a letter. The network gives a prediction anyway, and the probabilities still add up to 100%.

That last point is an important insight. The network can only choose from the ten digits it was trained on; it has no "this is not a digit" option. For a heart the ten scores still differ, and softmax turns those differences into a seemingly confident statement. In general, a classification network always picks one of the classes it learned, even for input that belongs to none of them.

⚖️ Strengths & limitations

💪 Strengths

When are neural networks really useful, and when are you better off using a simpler model?

🚨 Limitations

  • 📊 More data needed: because of its many weights, a neural network needs many more examples than a simpler model. Where linear regression already works with dozens of data points, a deep network often needs thousands to millions of examples.

  • 💻 Computationally intensive: you train small networks on a laptop, but the models behind ChatGPT or image generators take weeks on large clusters of graphics cards, because every training step adjusts all their weights. That costs energy, time and money.

  • 🔮 Black box: with a decision tree you see exactly why the model decides something, and with a single neuron you can still simply read off the weights (soup points to a researcher). With a network of thousands of neurons, it is usually no longer possible to find out why it makes a particular prediction.

  • 😎 Overconfident: neural networks underestimate their own uncertainty. If a network says "95% sure", that does not mean that it is right in 95% of such cases (external link), and for a heart it picks a digit just as confidently.

  • 📈 Prone to overfitting: more weights means a greater risk that the model learns the training data by heart instead of the real pattern.

🕸️ Overfitting in neural networks

The problem of overfitting, where a model learns the training data by heart instead of the real pattern, is especially acute in neural networks because of their large number of weights. Try it yourself: below is a network with three hidden layers on a dataset with a lot of noise (the two classes overlap). Click "Start training" and keep an eye on the validation accuracy below the graph with the points. After a while it starts to drop, while the training accuracy keeps rising, and the decision boundary becomes more and more irregular: the network is learning the noise by heart.

Then reset the network and remove all the hidden layers (with the minus button at the top of the network diagram). Train again: you now get a single straight line as the decision boundary. It is less flexible, but the validation accuracy is much more stable, and often even better.

Loading demo

You see the same thing in the loss graph at the bottom: the training loss keeps going down overall, but the validation loss goes back up at a certain point.

Graph with a training loss (purple) that keeps going down and a validation loss (magenta) that rises again after an optimal stopping point, which indicates overfitting.
The training loss (purple) keeps going down, but the validation loss (pink) rises again after the optimal stopping point. Training longer then makes the model worse on new data.

The simplest remedies follow directly from this: stop training just before that turning point (early stopping), use a smaller network, or collect more data.

🪛 When (not) to use them?

A common mistake is to reach for neural networks straight away for every problem. That is like firing a cannon at a mosquito.

Always start simple. Start with a simple model such as linear regression, k-nearest neighbors or a decision tree, and only use a neural network if those simpler models are not enough. A simpler model that performs just as well is always preferable: it is faster, cheaper, easier to interpret and less prone to overfitting.

Neural networks are suitable for:

  • 🖼️ Lots of data: thousands to millions of examples
  • 🌀 Complex patterns: relationships that do not follow a straight line or a simple rule
  • 🎵 Unstructured data: images, text, audio and video, from which you cannot easily extract good features by hand

Simpler models are often better for:

  • 📋 Little data: dozens to hundreds of examples
  • 📏 Simple relationships: linear or nearly linear relations
  • 🔍 Explanation required: when you must be able to justify why the model makes a particular prediction, for example in medical or legal contexts
  • ⚡ Limited computing power: when speed and efficiency matter

♾️ Universal approximation theorem

🏗️ Can a neural network learn anything?

We have seen that neural networks can do a lot, but how much exactly? Can you learn every possible function with a neural network? Almost.

Universal approximation theorem Definition

The universal approximation theorem (external link) states that a feedforward neural network with one hidden layer and enough neurons can approximate any continuous function on a bounded domain to arbitrary accuracy.

In other words: as long as you use enough neurons, even a network with one hidden layer can approximate any (continuous) function as closely as you like.

Intuitively: every neuron in the hidden layer draws a straight boundary through the input space. With a single input that boundary is a point on the axis: two neurons then divide the axis into three pieces, three neurons into four, and so on. With more inputs the number of regions grows even faster. Together all those neurons form a patchwork of regions, each with its own value, and the more neurons, the finer the patchwork.

Two panels: on the left a sine function approximated by 4 straight line segments (a rough approximation), on the right the same sine function approximated by 12 line segments (a finer approximation).
With more neurons in the hidden layer, the network can approximate functions more finely. Left: 4 segments give a rough sketch. Right: 12 segments already follow the curve much more closely.

You can check this yourself in the spiral demo above: with one hidden layer it usually only half works, even with the 16 neurons the demo allows, and with more layers it gets better and better.

⚠️ Existing is not enough

The theorem proves that a network with enough neurons exists that can approximate any function. It does not say that gradient descent will actually find that network. The training process can get stuck on plateaus and saddle points, get trapped in a local minimum, converge too slowly, or simply have too little data. So the theorem gives a theoretical guarantee, not a practical one.

In practice, moreover, deeper networks (more layers with fewer neurons per layer) often turn out to be more efficient than wide networks (one layer with a great many neurons). A deep network can learn the same function with fewer weights in total, because every layer builds on the intermediate representation of the previous one. That is part of the reason why deep learning works so well in practice, even though the theorem says that in theory one layer is enough.

🧪 Hands-on

In this Jupyter notebook you train neural networks yourself in Python, with the PyTorch library. First one neuron and a small network on two half moons, where you see how a hidden layer makes the straight line bend. Then you rebuild the network from the handwriting demo, choose how big it should be and look at which digits it reads wrongly.

Two half-moons and handwritten digits in PyTorch: train a neuron and a network yourself, rebuild the network from the handwriting demo, choose how big it should be, and see which digits it reads wrong.

🕹️ Demos

🗣️ Feedback

Just like machine learning algorithms, we also love learning from your feedback to improve the course.

Let us know how informative and how difficult you found this chapter, and where it could be better.

How informative did you find this chapter?
Was the difficulty of this chapter right for your level of knowledge and skill? This chapter was...
Anonymous with random ID