…
…
AI Fundamentals · Lesson 16 / 31 · Neural network intuition
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In the last lesson you wrote all the weights and thresholds of the three-neuron network yourself. Elena asks: "A real model has millions of weights. Who chooses them?" In this lesson you will watch a one-weight model find the right weight on its own, then look at the training logs of three friends and say whose model is really learning.
In the linear model and in the neuron you saw the same calculation: inputs are multiplied by weights and added. You always chose the weights yourself; you changed one and checked by eye whether the result got better. For a model, learning means doing this work itself: it changes the weights a little at a time so that its predictions move closer to the truth. There is no other secret behind it.
Let's watch this in the smallest possible model. Elena has the weekly study hours and homework scores of five students (a fictional sample of five students). This time the model does not say pass or fail; it predicts a score. It has a single weight: prediction = w × hours. As w grows, all predictions grow; as w shrinks, they all shrink. The question is: what should w be?
Before going in any direction, the model needs to know where it stands. To do that, it first measures how wrong it is. For each student we take the difference between the prediction and the real score. If we simply add up the differences, positives can cancel negatives: a model that predicts 10 points too high for one student and 10 points too low for another looks like it made "zero error." So we square each difference and take the average. We call this single number the error measure; smaller is better.
Example 1 (case): The error with w = 3
| hours | real score | prediction (3 × hours) | difference (prediction − real) | squared difference |
|---|---|---|---|---|
| 2 | 12 | 6 | −6 | 36 |
| 4 | 18 | 12 | −6 | 36 |
| 6 | 32 | 18 | −14 | 196 |
| 8 | 38 | 24 | −14 | 196 |
| 10 | 52 | 30 | −22 | 484 |
The squares add up to 948, and dividing by five gives an error of 189.6. If you do the same calculation with other weights, you get an error of 52.8 for w = 4 and 4.0 for w = 5. Squaring has another effect: a miss of 22 points (484) counts as more than thirteen times heavier than a miss of 6 points (36). The model cares about big misses much more than small ones. In classification the error measure can also be the number of wrong predictions; the idea is the same: a single number, and smaller is better.
All the differences in the table are negative. This says the model falls below the truth for every student. In this case, which way do you think w should move?
With w = 3, the model says 30 points for the student who studies 10 hours, and the real score is 52. The other four predictions are also below the truth. Which way should w move to reduce the error?
With a single weight you could also find the best w by trying values: look at 3, 4, 5, 6 in turn and pick the one with the smallest error. But remember the weight count from lesson 15: a big network has millions of weights. Even if you tried only ten values for each weight, you would not have a lifetime long enough to try all the combinations. So the model does not look at all the options; it only looks at which direction from where it stands will reduce the error.
Once the direction is known, the model takes a small step, measures the error again, and takes another step. The loop has four steps: predict, measure the error, move the weight a little in the direction that reduces the error, repeat. One pass over all the data is called a round (also called an epoch). Looking at all five students and moving the weight once is one round.
How does the model find the direction? For each student it multiplies the difference by that student's hours and takes the average of these products. This number is the slope under your feet. If the slope is negative, the predictions are too low and w increases; if it is positive, w decreases. The model always moves w against the slope: new w = w − step × slope. If the slope is large, the valley is far away and the step is automatically large; as you get closer to the valley, the slope gets smaller and the steps get shorter. The name of this method is gradient descent; knowing the name is enough. If you are curious about the slope formula, see the Tip box at the end of the lesson.
Example 2 (case): A single step from w = 3
| step by step | value |
|---|---|
| differences | −6, −6, −14, −14, −22 |
| difference × hours | −12, −24, −84, −112, −220 |
| sum | −452 |
| slope (sum / 5) | −90.4 |
| step size | 0.01 |
| new w = 3 − 0.01 × (−90.4) | 3.904 (about 3.9) |
| error: before → after | 189.6 → 62.1 |
The slope came out negative, and since a negative minus a negative is a positive, w increased. In a single step the error fell to a third. Below, w starts from zero this time and the loop runs for three rounds. Watch which sign the slope_total box ends with in each round, and then why w increases.
Run the code line by line: see which line runs next, the variable boxes and the output.
hours = [2, 4, 6, 8, 10] scores = [12, 18, 32, 38, 52] w = 0.0 step = 0.01 for round_number in range(1, 4): squared_total = 0 slope_total = 0 for x, y in zip(hours, scores): diff = w * x - y squared_total += diff ** 2 slope_total += diff * x error = squared_total / 5 w = w - step * slope_total / 5 print("round", round_number, "error:", round(error, 1), "new w:", round(w, 2))
In three rounds the error fell from 1128 to 114.4, and w rose from 0 to 4.17. slope_total ended negative in every round; the predictions were still below the truth, so w increased every round. Nobody told the model "the right weight is around 5"; it got close by measuring its error again and again. Now put the steps of the loop in order yourself.
Put what the model does in one round into the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
One setting remains in the loop: how far should w move in each round? The step value in the formula is called the step size (also called the learning rate). The model does not learn it; the person who sets up the training chooses it. This setting matters more than you might think; first let's see it with an everyday example.
Example 3 (outside the case): The temperature of shower water
You want the shower water to reach 38°C, and the water is coming out at 20°C. On each try you feel the difference and turn the tap by "difference × rate." The first three tries of three people who choose the rate in three different ways:
| rate | 1st try | 2nd try | 3rd try | what happens |
|---|---|---|---|---|
| 0.1 | 21.8 | 23.4 | 24.9 | goes the right way but very slowly |
| 0.5 | 29 | 33.5 | 35.75 | gets close quickly, slows down as it gets close |
| 2.2 | 59.6 | 12.1 | 69.1 | one try scalds, the next freezes, and each time it is thrown farther away |
The person with a rate of 2.2 feels the difference and finds the right direction too, yet cannot set the water at all, because each time they go far beyond the target. They want to be fast and never arrive. The model's step behaves the same way. In Elena's model, with a step of 0.01, the error fell to 3.9 in 10 rounds. Would making the step bigger make you faster?
With a step size of 0.01, the error fell from 1128 to 3.9 in 10 rounds. Elena says "let it learn faster" and makes the step 0.05. What do you think happens after 20 rounds?
Change the step size: where does the error go in 20 rounds, and where does w end up?
Pick a value; predict the output first, then look.
1hours = [2, 4, 6, 8, 10]2scores = [12, 18, 32, 38, 52]3step = 0.014w = 0.05for round_number in range(1, 21):6 squared_total = 07 slope_total = 08 for x, y in zip(hours, scores):9 diff = w * x - y10 squared_total += diff ** 211 slope_total += diff * x12 error = squared_total / 513 w = w - step * slope_total / 514 if round_number in (1, 2, 3, 5, 10, 20):15 print("round", round_number, "error:", round(error, 1), "new w:", round(w, 2))
round 1 error: 1128.0 new w: 2.22 round 2 error: 356.4 new w: 3.47 round 3 error: 114.4 new w: 4.17 round 5 error: 14.7 new w: 4.78 round 10 error: 3.9 new w: 5.04 round 20 error: 3.9 new w: 5.05
Faded lines didn't run with this value. With 0.01 the error drops to 3.9 in 10 rounds and w settles at 5.05. With 0.001 the direction is right but the steps are tiny: after 20 rounds w has only reached 3, and the error is still above 200. With 0.05 every step jumps to the other slope of the valley, higher than before: w alternates between positive and negative, and the error grows every round.
The three settings give three different results. If the step is too small, the model goes in the right direction but cannot finish the trip: after 20 rounds w has only reached 3, and the error is still 207.2. If the step is suitable, the error falls quickly in the first rounds, then more slowly, and stops somewhere. If the step is too large, the model is thrown around: at every step it overshoots the bottom of the valley, w alternates between positive and negative, and the error passes a million in 20 rounds.
In a real training you cannot follow w one by one; there are millions of weights. Instead, at the end of each round you print the error and plot it. This line is called the error curve. The shape of the curve is a diagnosis: without opening the model, it tells you whether the training is going well. Below, Elena's model was started from w = 0 with three different step sizes, and the first seven rounds of each training are plotted. It does not say which step belongs to which curve; work it out from the shapes.
error · Fictional sample data of five students
| — | Error |
|---|---|
| 0 | 1128 |
| 1 | 356.4 |
| 2 | 114.4 |
| 3 | 38.5 |
| 4 | 14.7 |
| 5 | 7.3 |
| 6 | 4.9 |
| 7 | 4.2 |
error · Fictional sample data of five students
| — | Error |
|---|---|
| 0 | 1128 |
| 1 | 1622.6 |
| 2 | 2334.9 |
| 3 | 3360.5 |
| 4 | 4837.4 |
| 5 | 6964.2 |
| 6 | 10026.7 |
| 7 | 14436.8 |
error · Fictional sample data of five students
| — | Error |
|---|---|
| 0 | 1128 |
| 1 | 1031.3 |
| 2 | 942.8 |
| 3 | 862 |
| 4 | 788.2 |
| 5 | 720.7 |
| 6 | 659 |
| 7 | 602.6 |
The vertical axes of the three charts are different: because curve B goes above 14,000, if all three were on one chart, the other two would look flat. So look at the numbers too: all three start at 1128, but in the seventh round one is at 4.2, one is at 602.6, and one is at 14,436.8.
Match each curve with its diagnosis.
For each row, pick its match from the list, then check.
The hidden step sizes were these: curve A was plotted with a step of 0.01, curve B with 0.05, and curve C with 0.001; the numbers are the same as the first rounds of the degistir block above.
A diagnosis is useless if it does not make you do something. If the curve falls slowly but steadily, increase the step or increase the number of rounds; both bring the model to the valley, one in fewer rounds. If the curve grows every round, decrease the step; waiting does not help, since every round makes things worse. If the curve dropped and flattened, the training has done its job. A suitable step depends on the data: with these five students 0.01 worked well, and with other data it might be too small or too large. So people who set up trainings try a few values and put the error curves side by side. Instead of looking at one training and saying "the model is not learning," they first look at the shape of the curve: is the problem in the model, in a mistake in the data, or only in the step setting? Often the answer is the simplest one, and changing a single number is enough.
With a suitable step, the training flattened and stayed there. Now think about the reason.
With a step of 0.01, the error stopped at 3.9 and did not go lower even in 20 rounds. Why did it not reach zero?
Even with the best setting, the error did not reach 0; it stayed at 3.9. The five points do not lie on a single line; no w can fit all of them at once. The goal of learning is not to make the error zero but to lower it as far as it can go. Besides, this error is measured on the training data. As you saw in lesson 11, it is not the training error but the test set you set aside that tells you how good the model is on new students. If the training error is very low and the test error is high, the model may have memorized.
This is what happens in a neural network too. The only difference is the number: instead of one w, there are millions of weights arranged in layers, and in every round all of them are moved a little at once. Sharing the blame for the error with each weight, from the output back to the input, is called backpropagation; libraries do the calculation. When a model is said to have "learned," what happened is that a great many numbers were adjusted to reduce the error. The person who sets up the training also looks at the error curve: is it falling, has it flattened, is it being thrown around?
For those who know Python: the whole loop from the lesson. The error first drops quickly, then more slowly, and stops at 3.9.
hours = [2, 4, 6, 8, 10] scores = [12, 18, 32, 38, 52] w = 0.0 step = 0.01 for round_number in range(1, 21): # 1. Measure the slope slope = sum((w * x - y) * x for x, y in zip(hours, scores)) / 5 # 2. Move the weight against the slope w = w - step * slope # 3. Measure the error again error = sum((w * x - y) ** 2 for x, y in zip(hours, scores)) / 5 if round_number in (1, 5, 10, 20): print("round", round_number, "w:", round(w, 2), "error:", round(error, 1)) print("Prediction for 12 hours:", round(w * 12))
Outputround 1 w: 2.22 error: 356.4
round 5 w: 4.78 error: 7.3
round 10 w: 5.04 error: 3.9
round 20 w: 5.05 error: 3.9
Prediction for 12 hours: 61Because this code measures the error after moving the weight, its lines are one round ahead of the degistir block: the error at the end of round 1 is 356.4.
Moving the weight in the same direction as the slope instead of against it. A single sign changes in the formula:
Outputcorrect: new w = w − step × slope
wrong: new w = w + step × slopeThe calculation raises no error and the numbers keep flowing, but the model climbs uphill in every round.
Example 7 (case): When the sign is written backward (from w = 3, step 0.01)
| round | w | error |
|---|---|---|
| start | 3 | 189.6 |
| 1 | 2.1 | 389.0 |
| 2 | 0.79 | 802.5 |
| 3 | −1.08 | 1659.9 |
While the predictions are already below the truth, w gets smaller; the predictions fall even lower, and the error doubles every round. At first glance this curve looks like the "step too large" curve, because the error grows in both. What tells them apart is the path of w: with a step that is too large, w alternates between positive and negative (11.12 → −2.22 → 13.79), while with a direction mistake it runs away in one direction (3 → 2.1 → 0.79 → −1.08). With a direction mistake, making the step smaller only slows the escape. Rule: print the error every round during training; if the error is not falling, look at the direction first, then at the step size.
Next lesson: we move on to language models; we will start with a model that is trained with the same loop and predicts the next word.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
The table in Example 3, with the same rule: on each try the temperature changes by "difference × rate."
target = 38 for rate in (0.1, 0.5, 2.2): water = 20 tries = [] for attempt in range(3): water = water + (target - water) * rate tries.append(round(water, 2)) print("rate", rate, ":", tries)
Outputrate 0.1 : [21.8, 23.42, 24.88]
rate 0.5 : [29.0, 33.5, 35.75]
rate 2.2 : [59.6, 12.08, 69.1]The data of the three charts was produced with this code: for each step size it starts from w = 0, measures the error, moves the weight, and adds the first eight errors (the start and 7 rounds) to a list.
hours = [2, 4, 6, 8, 10] scores = [12, 18, 32, 38, 52] for step in (0.01, 0.05, 0.001): w = 0.0 errors = [] for round_number in range(8): error = sum((w * x - y) ** 2 for x, y in zip(hours, scores)) / 5 errors.append(round(error, 1)) slope = sum((w * x - y) * x for x, y in zip(hours, scores)) / 5 w = w - step * slope print(step, errors)
Output0.01 [1128.0, 356.4, 114.4, 38.5, 14.7, 7.3, 4.9, 4.2]
0.05 [1128.0, 1622.6, 2334.9, 3360.5, 4837.4, 6964.2, 10026.7, 14436.8]
0.001 [1128.0, 1031.3, 942.8, 862.0, 788.2, 720.7, 659.0, 602.6]