Module 4 · Beginner · How models learn and why they fail

How machine learning models learn from data

How machine learning models learn: parameters, predictions, loss, optimisation and the training loop, shown step by step in Python with a delivery time example.

By theprogrammers team · · 14 min read

A new food delivery app wants to show customers an estimated delivery time. It has records of 200 past deliveries: how far each one went and how many minutes it took. Nobody writes the rule "minutes = this × distance + that" by hand. Instead, a model learns the rule from those records. But what does "learn" actually mean for a computer?

It means something surprisingly mechanical: start with a guess, measure how wrong the guess is, adjust it to be a little less wrong, and repeat. Every machine learning algorithm in this course, from linear regression to the neural networks behind ChatGPT, is a version of that loop. This lesson shows how machine learning models learn from data, step by step, with a small Python example you can run, and then shows how other algorithms fit the same pattern.

What you need first: machine learning for beginners and gradient descent explained. It also helps to have seen calculus for machine learning, or what is a derivative? for the idea of a slope.

Key terms

  • Model: a function that turns inputs (features) into a prediction, with some numbers left adjustable.
  • Parameters: the adjustable numbers inside the model, such as a slope and an intercept. Training finds them.
  • Hyperparameters: settings you choose before training, such as the learning rate or the depth of a tree. Training doesn't change them.
  • Loss: one number that says how wrong the model's predictions are on the training data. Lower is better.
  • Optimisation: the method that changes the parameters to reduce the loss, such as gradient descent.
  • Generalisation: doing well on new data the model has never seen, not just on the training data.

The three ingredients of learning

Every supervised learning algorithm has three parts:

IngredientQuestion it answersDelivery example
ModelWhat shape can the rule take?minutes = w × distance + b
LossHow do we measure "wrong"?The average of the squared errors
OptimiserHow do we make it less wrong?Gradient descent: nudge w and b downhill

"Learning" is the optimiser lowering the loss by changing the model's parameters. Let's do it.

Step 1: the data

These are 200 simulated deliveries. The true rule used to make them is about 5 minutes of preparation plus 3 minutes per kilometre, plus random delays from traffic and lifts. The model doesn't know that rule; it only sees the data.

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
distance = rng.uniform(0.5, 8, size=200)                          # kilometres
minutes = 5 + 3 * distance + rng.normal(0, 2.5, size=200)        # what really happened
print(f"distance from {distance.min():.1f} to {distance.max():.1f} km")
print("first five distances:", distance[:5].round(1))
print("their minutes:       ", minutes[:5].round(1))
distance from 0.6 to 7.9 km
first five distances: [6.3 3.8 6.9 5.7 1.2]
their minutes:        [25.5 15.4 25.8 21.8  9.5]

Step 2: the model, with a first guess

The model is a straight line: prediction = w × distance + b. Read it as "the prediction is w times the distance, plus b". The two parameters are w, the minutes per kilometre, and b, the fixed minutes for every order.

Before learning, the parameters are just a guess. Start with both at zero:

def predict(distance, w, b):
    return w * distance + b

w, b = 0.0, 0.0
print("predictions for 1, 4 and 8 km:", predict(np.array([1, 4, 8]), w, b))
predictions for 1, 4 and 8 km: [0. 0. 0.]

Every delivery is predicted to take 0 minutes. Terrible, but that's where every model starts: knowing nothing.

Step 3: the loss, one number for "how wrong"

For each delivery, the error is prediction − actual. Square each error (so negatives don't cancel positives, and big errors count extra), then take the average. That's the mean squared error (MSE):

MSE = (1/n) × Σ (predictionᵢ − actualᵢ)²

Read it as "one over n, times the sum of each squared error": the average squared error.

def mse(w, b):
    errors = predict(distance, w, b) - minutes
    return np.mean(errors ** 2)

print(f"loss with w = 0, b = 0: {mse(0, 0):.1f}")
print(f"loss with w = 2, b = 5: {mse(2, 5):.1f}")
print(f"loss with w = 3, b = 5: {mse(3, 5):.1f}")
loss with w = 0, b = 0: 364.1
loss with w = 2, b = 5: 30.9
loss with w = 3, b = 5: 6.4

The all-zero guess has a loss of 364.1. w = 2 with b = 5 is much better (30.9), and w = 3 with b = 5 is better still (6.4).

The loss turns "which line is better?" into "which number is smaller?". Fix b at 5 and look at the loss for every value of w:

ws = np.linspace(-1, 7, 200)
losses = [mse(w_value, 5) for w_value in ws]

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(ws, losses, color="#c2410c")
ax.scatter([0, 2, 3], [mse(0, 5), mse(2, 5), mse(3, 5)], color="black", zorder=3)
for w_value in [0, 2, 3]:
    ax.annotate(f"w = {w_value}", (w_value, mse(w_value, 5)), textcoords="offset points", xytext=(8, 8))
ax.set_xlabel("w (minutes per km)")
ax.set_ylabel("Loss (MSE)")
ax.set_title("The loss is a valley: learning means finding the bottom")
plt.show()
A U-shaped curve of the loss against w, with b fixed at 5. The loss is very high at w = -1 and w = 7, and lowest near w = 3. Three marked points show w = 0 high on the left side of the valley, w = 2 lower down, and w = 3 close to the bottom.

The loss is a valley, and the best parameters sit at its bottom. With two parameters it's a bowl over a flat (w, b) plane; with millions of parameters, as in a neural network, it's a landscape you can't draw, but the idea is the same.

Step 4: the optimiser, walking downhill

How does the model find the bottom without trying every value? It uses the gradient: the slope of the loss with respect to each parameter, which says which direction is uphill. For the MSE of a straight line, calculus gives:

SlopeFormulaIn words
∂Loss/∂w(2/n) × Σ errorᵢ × distanceᵢAverage of error times distance, doubled
∂Loss/∂b(2/n) × Σ errorᵢAverage error, doubled

Then take a small step the other way, downhill. The size of the step is the learning rate:

w ← w − learning rate × ∂Loss/∂w and b ← b − learning rate × ∂Loss/∂b

One step by hand, from w = 0 and b = 0, with a learning rate of 0.01:

learning_rate = 0.01
errors = predict(distance, 0, 0) - minutes
grad_w = 2 * np.mean(errors * distance)
grad_b = 2 * np.mean(errors)
print(f"gradient: dLoss/dw = {grad_w:.1f}, dLoss/db = {grad_b:.1f}")

w = 0 - learning_rate * grad_w
b = 0 - learning_rate * grad_b
print(f"after one step: w = {w:.3f}, b = {b:.3f}, loss = {mse(w, b):.1f}")
gradient: dLoss/dw = -177.2, dLoss/db = -35.3
after one step: w = 1.772, b = 0.353, loss = 112.7

The gradients are large and negative: increasing w or b would lower the loss, so the step increases both. One step takes the loss from 364.1 to 112.7. Why does w move so much more than b? Its gradient includes the distances, which are up to 8 km, so it's about five times larger here.

Step 5: the training loop

Repeat that step many times. Each pass is called an epoch here, because each one uses all 200 deliveries:

w, b = 0.0, 0.0
history = []
for epoch in range(2001):
    errors = predict(distance, w, b) - minutes
    w -= learning_rate * 2 * np.mean(errors * distance)
    b -= learning_rate * 2 * np.mean(errors)
    history.append((w, b, mse(w, b)))
    if epoch in [0, 10, 100, 500, 2000]:
        print(f"epoch {epoch:4}: w = {w:.3f}, b = {b:.3f}, loss = {mse(w, b):.2f}")
epoch    0: w = 1.772, b = 0.353, loss = 112.65
epoch   10: w = 3.835, b = 0.882, loss = 8.33
epoch  100: w = 3.656, b = 1.839, loss = 7.27
epoch  500: w = 3.312, b = 3.638, loss = 6.27
epoch 2000: w = 3.220, b = 4.116, loss = 6.22

The loss falls fast at first (112.65 to 8.33 in 10 epochs), then slowly. By epoch 2000 the parameters have settled at w = 3.220 and b = 4.116, with a loss of 6.22. They're close to, but not exactly, the true values of 3 and 5 used to make the data: with only 200 deliveries and random delays of a few minutes, the data itself points to a slightly steeper line. Collect more deliveries and the learnt values move closer to the truth.

Watch the line improve:

fig, ax = plt.subplots(figsize=(8, 5))
ax.scatter(distance, minutes, s=12, color="#9ca3af", label="Past deliveries")
xs = np.array([0, 8.5])
for epoch, colour in [(0, "#fecaca"), (10, "#fca5a5"), (100, "#f87171"), (2000, "#b91c1c")]:
    w_e, b_e, _ = history[epoch]
    ax.plot(xs, predict(xs, w_e, b_e), color=colour, linewidth=2, label=f"after epoch {epoch}")
ax.set_xlabel("Distance (km)")
ax.set_ylabel("Delivery time (minutes)")
ax.set_title("The line moves towards the data as the loss falls")
ax.legend()
plt.show()
A scatter plot of 200 deliveries, delivery time rising with distance from about 5 to 30 minutes. Four lines show the model at different epochs: after epoch 0 the line is far too low and too flat; after epochs 10 and 100 the lines are slightly too steep, starting too low on the left and ending a little high on the right; after epoch 2000, in dark red, the line runs through the middle of the points.

Notice that after epochs 10 and 100 the line is a bit too steep: it starts too low and ends too high. The optimiser fixed the slope quickly but the intercept slowly, so the line then rotates into place. That's learning: no one told the model the rule; it found it by repeatedly reducing the loss.

Step 6: check it learnt, not memorised

A low training loss isn't the goal. The goal is good predictions for new deliveries. Simulate 100 future deliveries from the same process and measure the error there:

new_distance = rng.uniform(0.5, 8, size=100)
new_minutes = 5 + 3 * new_distance + rng.normal(0, 2.5, size=100)

train_rmse = np.sqrt(mse(w, b))
new_rmse = np.sqrt(np.mean((predict(new_distance, w, b) - new_minutes) ** 2))
print(f"typical error on training deliveries: {train_rmse:.2f} minutes")
print(f"typical error on new deliveries:      {new_rmse:.2f} minutes")
typical error on training deliveries: 2.49 minutes
typical error on new deliveries:      2.75 minutes

The typical error is about 2.5 minutes on the training deliveries and 2.75 minutes on new ones: close, so the model learnt the real pattern rather than memorising these particular deliveries. The remaining error is mostly the random delays, which no model could predict from distance alone.

When the error on new data is much worse than on training data, the model has memorised instead of learnt: that's overfitting, the subject of a later lesson in this module. Always keep data aside to check, as in train, validation and test sets.

The same loop in scikit-learn

scikit-learn hides the loop inside fit. SGDRegressor uses gradient descent like ours; LinearRegression solves for the bottom of the bowl directly with linear algebra:

from sklearn.linear_model import LinearRegression

model = LinearRegression().fit(distance.reshape(-1, 1), minutes)
print(f"scikit-learn: w = {model.coef_[0]:.3f}, b = {model.intercept_:.3f}")
print(f"our loop:     w = {w:.3f}, b = {b:.3f}")
scikit-learn: w = 3.220, b = 4.117
our loop:     w = 3.220, b = 4.116

Same answer. fit is "run the optimiser until the loss stops falling", and predict is "use the learnt parameters".

How other algorithms learn

Not every algorithm uses gradient descent, but every one has a model, a way to judge it, and a way to improve it:

AlgorithmWhat it learns (parameters)How it learns
Linear and logistic regressionOne weight per feature, plus a biasGradient descent, or an exact formula for linear regression
Neural networksMillions of weightsGradient descent, with gradients from backpropagation
Decision treesWhich question to ask at each splitGreedy search: try every split, keep the one that reduces impurity most
Random forest, gradient boostingMany treesMany greedy tree searches, combined
Naive BayesClass priors and per-class word probabilitiesCounting
KNNNothing: it stores the dataNo training; it searches the stored data when predicting
K-meansCluster centresRepeat: assign points to the nearest centre, then move each centre

So "learning" can mean descending a loss, searching for good splits, or counting. In every case, the result is a set of numbers or rules taken from the data, not written by a person.

Common mistakes

  • Confusing parameters and hyperparameters. The model learns w and b. You choose the learning rate and the number of epochs.
  • A learning rate that's too big. The steps jump over the valley and the loss grows instead of shrinking. Practice question 3 shows this.
  • Judging the model on the training loss. A model can drive the training loss to almost zero by memorising. Only new data tells you if it learnt.
  • Unscaled features with gradient descent. If one feature is in thousands and another in units, one learning rate can't suit both. Scale first; see feature scaling.

Practice

  1. With w = 3 and b = 5, what does the model predict for a 6 km delivery? Work it out, then check in Python.
Show the answer

3 × 6 + 5 = 23 minutes.

print(predict(6, 3, 5))
23
  1. Which of these are parameters and which are hyperparameters: the slope w, the learning rate, the number of epochs, the intercept b?
Show the answer

Parameters: w and b, because training finds them. Hyperparameters: the learning rate and the number of epochs, because you choose them before training.

  1. Run the training loop with a learning rate of 0.05 instead of 0.01. What happens to the loss?
Show the answer
w_big, b_big = 0.0, 0.0
for epoch in range(6):
    errors = predict(distance, w_big, b_big) - minutes
    w_big -= 0.05 * 2 * np.mean(errors * distance)
    b_big -= 0.05 * 2 * np.mean(errors)
    print(f"epoch {epoch}: loss {mse(w_big, b_big):,.0f}")
epoch 0: loss 604
epoch 1: loss 1,005
epoch 2: loss 1,678
epoch 3: loss 2,803
epoch 4: loss 4,689
epoch 5: loss 7,845

The loss grows every epoch, from 604 to 7,845, instead of shrinking. Each step is so big that it jumps right over the valley and lands higher up on the other side, and the next step jumps back even further. This is called diverging. The fix is a smaller learning rate, or scaling the features.

  1. Train for only 10 epochs with a learning rate of 0.01. Is the model finished learning? How can you tell?
Show the answer

No. After 10 epochs, w was 3.835 and b only 0.882, still far from the final 3.220 and 4.116, and the loss (8.33) was still falling. Plot [h[2] for h in history] against the epoch: while the curve still slopes down, the model hasn't finished. Plot [h[2] for h in history] against the epoch: while the curve still slopes down, the model hasn't finished.

Interview questions

What does it mean for a model to "learn"?

It means adjusting its parameters to minimise a loss function on training data, using an optimisation method such as gradient descent, so that the learnt rule generalises to new data. The model, the loss and the optimiser are the three ingredients of almost every supervised learning algorithm.

What is the difference between a parameter and a hyperparameter?

Parameters are learnt from the data during training, such as regression weights or neural network weights. Hyperparameters are set before training and control how learning happens or how complex the model can be, such as the learning rate, regularisation strength, tree depth or k in KNN. Hyperparameters are chosen with validation data or cross-validation.

Why do we minimise a loss on training data but evaluate on test data?

Minimising training loss is the only thing the optimiser can do, but a flexible model can reach low training loss by memorising noise. The test data, unseen during training, estimates performance on future data, which is what actually matters.

Key takeaways

  • Learning is a loop: predict, measure the loss, adjust the parameters to reduce it, repeat.
  • Every supervised algorithm has a model (the shape of the rule), a loss (how wrong it is) and an optimiser (how to improve).
  • Gradient descent uses the slope of the loss to step downhill; the learning rate sets the step size.
  • From the data alone, the model found 3.22 minutes per km plus 4.12 fixed minutes, close to the true 3 and 5.
  • Success is measured on new data, not on the training data.

Frequently asked questions

Do machine learning models learn like humans?

Only loosely. A model adjusts numbers to reduce a measured error on examples; it has no understanding of what deliveries or distances are. That's why it needs lots of examples and can fail badly on situations unlike its training data.

How long does it take a model to learn?

From milliseconds to months. This two-parameter model learns in a fraction of a second. Large language models have billions of parameters and train for weeks on thousands of specialised chips.

Does a model keep learning after it's deployed?

Usually not. Most models are trained once, then used with fixed parameters. To learn from new data, they're retrained, either on a schedule or when their performance drops. Some systems use online learning, updating the parameters as each new example arrives.

What to learn next

  1. Learn the different ways to measure "wrong" in loss functions explained, the next lesson in this module.
  2. Revisit the optimiser in gradient descent explained.
  3. See the full loop built as a class in linear regression from scratch.