๐ŸŽจ THEME ENGINE
PROMETHEUS OS ยท 23 THEMES
Trial version: Dark + Light themes only.
Full theme access with PROMETHEUS OS license.
Dark theme active
Experience all 23 themes in PROMETHEUS OS

How Machines Learn

Beginner 14 minยท 4 exercises

Learn how a machine learning model turns examples into skill: data and features, neural networks and parameters, loss and gradient descent, overfitting, and the three main styles of learning.

By the end of this lesson you will be able to
  • Define data, features, labels, parameters, training and inference, and explain how they relate.
  • Compute the mean squared error and its gradient for a one-parameter model by hand.
  • Apply gradient descent updates by hand and in Python, and explain how the learning rate affects convergence.
  • Use training, validation and test sets to diagnose overfitting and avoid data leakage.
  • Compare supervised, unsupervised, reinforcement and self-supervised learning with an example of each.

Before this: What AI Is (and Isn't)

Why this matters

Every modern AI system, from a spam filter to a chatbot, was made the same basic way: by showing a program many examples and letting it adjust itself until its answers improve. Once you understand that loop, a lot of AI behaviour, good and bad, stops being mysterious.

Data and features

Machine learning starts with data: a collection of examples. For a house-price predictor, each example is one house sold in the past.

A feature is a measurable property of an example that the model can use, such as floor area, number of bedrooms, or postcode. The thing we want to predict, here the sale price, is called the label or target.

In older machine learning, people chose features by hand. In deep learning, the model largely discovers useful features on its own from raw data such as pixels or text.

Training vs inference

There are two distinct phases in a model's life:

  • Training is the learning phase. The model sees examples, makes guesses, measures how wrong they are, and adjusts itself. For large models this takes enormous amounts of computing power and can run for weeks.
  • Inference is the using phase. The trained model is frozen and simply produces answers for new inputs. When you type into a chat assistant, you are running inference. The model is not learning from your conversation in that moment.

Neural networks and parameters

A neural network is a mathematical function built from layers of simple units, loosely inspired by brain cells. Each unit receives numbers from the previous layer, multiplies each by a weight (how much that input matters), adds them up, and passes the result through a simple rule to the next layer.

The weights, together with a few related numbers, are called the model's parameters. They are the settings that training adjusts. A small network might have thousands of parameters; large language models have billions. Everything a model "knows" is stored in these numbers, not as a list of facts but as a pattern spread across all of them.

Loss: measuring how wrong you are

To improve, the model needs a score for its mistakes. That score is the loss: a single number that is large when predictions are bad and small when they are good.

A worked example, deliberately simplified to a model with one parameter. Suppose we predict price as w times floor area, and we have three past sales:

HouseArea (sq ft)Actual price
A1,000$200,000
B1,500$300,000
C2,000$400,000

Start with a guess of w = 150 dollars per square foot. Predictions are $150,000, $225,000 and $300,000, so the errors are $50,000, $75,000 and $100,000 too low, an average error of $75,000. Every prediction is too low, so w should go up. Try w = 180: errors shrink to $20,000, $30,000 and $40,000, average $30,000. Try w = 200: every prediction is exact and the loss is zero.

Real models do exactly this, but with billions of parameters at once, so they need an automatic way to know which direction to move each one.

Gradient descent: walking downhill in fog

Picture yourself on a hillside in thick fog, trying to reach the valley floor. You can't see the valley, but you can feel which way the ground slopes under your feet. So you take a small step downhill, feel again, and take another step. Eventually you reach low ground.

That is gradient descent. The height of the land is the loss. Your position is the current set of parameters. The gradient is the slope: it tells the model, for every parameter, which direction would reduce the loss and how steeply. The learning rate is your step size: too big and you overshoot the valley; too small and you take forever.

A method called backpropagation calculates the gradient efficiently for every parameter in a network by working backwards from the error at the output. Training is simply this loop repeated millions of times: predict, measure loss, compute gradient, nudge parameters.

One honest caveat: the real landscape has billions of dimensions and many dips, and the model usually ends up in a good low spot rather than the single lowest one. In practice that is usually good enough.

Overfitting: memorising instead of learning

A model can get very good at its training data without learning anything general. Imagine a student who memorises last year's exam answers: perfect on that paper, lost on a new one. That is overfitting.

To catch it, practitioners hold back some data the model never trains on, often called a test set, and check performance there. If the model scores well on training data but poorly on the test set, it has overfitted. Remedies include more varied data, smaller or simpler models, and stopping training earlier.

Why data quality matters

A model can only learn patterns that are present in its data. If the examples are wrong, out of date, or unrepresentative, the model learns those flaws faithfully. A skin-condition classifier trained mostly on light skin tends to perform worse on darker skin. A chatbot trained on text full of a common misconception will repeat it. "Garbage in, garbage out" is a long-standing rule in computing, and it applies with full force here.

Three styles of learning

StyleHow it learnsExample
Supervised learningFrom examples paired with the correct answer (labels)Emails marked spam or not spam
Unsupervised learningFinds structure in data with no labelsGrouping customers into similar segments
Reinforcement learningTries actions and learns from rewards or penaltiesA program learning a game by being rewarded for winning

Large language models mix these. Their main training predicts the next piece of text, a form often called self-supervised learning because the labels come from the data itself. Later stages use human-labelled examples and reinforcement learning, which the next lesson explains.

Going deeper

This section redoes the house-price example with the actual formulas that training uses. To keep the numbers readable, measure floor area xx in thousands of square feet and price yy in thousands of dollars, so the three houses become x=(1,1.5,2)x = (1, 1.5, 2) and y=(200,300,400)y = (200, 300, 400). The model is y^=wx\hat{y} = w x, where y^\hat{y} ("y-hat") is the prediction and ww is the single parameter.

The loss as a formula

The earlier walkthrough used the average size of the errors. Most regression models instead use the mean squared error (MSE):

L(w)=1nโˆ‘i=1n(wxiโˆ’yi)2L(w) = \frac{1}{n} \sum_{i=1}^{n} \left( w x_i - y_i \right)^2

where n=3n = 3 is the number of examples and wxiโˆ’yiw x_i - y_i is the error (the residual) on example ii. Squaring does two useful things: it makes every error count as positive, and it punishes large errors much more than small ones. It also gives a smooth curve, which makes the slope easy to compute.

At w=150w = 150 the residuals are โˆ’50-50, โˆ’75-75 and โˆ’100-100, so

L(150)=2500+5625+100003=6041.67L(150) = \frac{2500 + 5625 + 10000}{3} = 6041.67

Deriving the gradient

The slope of the loss with respect to ww comes from ordinary calculus (the chain rule):

dLdw=2nโˆ‘i=1nxi(wxiโˆ’yi)\frac{dL}{dw} = \frac{2}{n} \sum_{i=1}^{n} x_i \left( w x_i - y_i \right)

At w=150w = 150: 1ร—(โˆ’50)+1.5ร—(โˆ’75)+2ร—(โˆ’100)=โˆ’50โˆ’112.5โˆ’200=โˆ’362.51 \times (-50) + 1.5 \times (-75) + 2 \times (-100) = -50 - 112.5 - 200 = -362.5, and 23ร—(โˆ’362.5)=โˆ’241.67\tfrac{2}{3} \times (-362.5) = -241.67. The slope is negative, which means increasing ww lowers the loss, exactly what the intuition said.

Gradient descent moves against the slope by a step of size ฮท\eta (the learning rate):

wโ†wโˆ’ฮทโ€‰dLdww \leftarrow w - \eta \, \frac{dL}{dw}

With ฮท=0.1\eta = 0.1: w=150โˆ’0.1ร—(โˆ’241.67)=174.17w = 150 - 0.1 \times (-241.67) = 174.17. Repeating:

StepLoss before the stepww after the step
16041.67174.17
21612.79186.65
3430.53193.10
4114.93196.44
530.68198.16

The parameter closes in on 200 and the loss heads to zero.

How big a step is safe?

For this model we can see exactly what the learning rate does. Expanding the gradient with โˆ‘xi2=7.25\sum x_i^2 = 7.25 and โˆ‘xiyi=1450\sum x_i y_i = 1450 gives

dLdw=23(7.25โ€‰wโˆ’1450)โ‰ˆ4.833โ€‰(wโˆ’200)\frac{dL}{dw} = \frac{2}{3}\left(7.25\,w - 1450\right) \approx 4.833\,(w - 200)

So the distance from the best value, e=wโˆ’200e = w - 200, changes each step by a fixed factor: eโ†(1โˆ’4.833โ€‰ฮท)โ€‰ee \leftarrow (1 - 4.833\,\eta)\, e. Training converges only if that factor lies between โˆ’1-1 and 11, which means 0<ฮท<2/4.833โ‰ˆ0.410 < \eta < 2 / 4.833 \approx 0.41. With ฮท=0.1\eta = 0.1 the factor is 0.520.52, so the error roughly halves each step (as in the table). With ฮท=0.5\eta = 0.5 the factor is โˆ’1.42-1.42: the parameter overshoots, lands further away on the other side, and the loss explodes. Large networks have no tidy formula like this, but the same thing happens: a learning rate that is too large makes the loss jump around or blow up, and one that is too small makes progress painfully slow.

Many parameters at once

A real network has a vector of parameters ฮธ\theta (theta), and the gradient โˆ‡L(ฮธ)\nabla L(\theta) is the vector of slopes, one per parameter. The update has the same shape: ฮธโ†ฮธโˆ’ฮทโ€‰โˆ‡L(ฮธ)\theta \leftarrow \theta - \eta \, \nabla L(\theta). Computing the loss over the whole dataset at every step would be far too slow, so training uses stochastic gradient descent: estimate the gradient from a small random mini-batch of examples, take a step, draw another batch. The estimate is noisy but cheap. Backpropagation computes every entry of the gradient at a cost of a small constant multiple of one forward pass through the network, which is what makes models with billions of parameters trainable at all.

The same loop in Python

import numpy as np
x = np.array([1.0, 1.5, 2.0])      # floor area, thousands of sq ft
y = np.array([200., 300., 400.])   # price, thousands of dollars
w, lr = 150.0, 0.1
for step in range(1, 11):
    pred = w * x
    loss = np.mean((pred - y) ** 2)          # mean squared error
    grad = np.mean(2 * x * (pred - y))       # dL/dw
    w = w - lr * grad
    print(f"step {step:2d}  loss {loss:9.2f}  new w {w:8.3f}")

Each pass computes predictions, the MSE loss, the gradient and the update. The printed numbers match the table above, and after 10 steps ww is 199.93. Try changing lr to 0.5 to watch it diverge.

Measuring generalisation properly

Practitioners usually split data three ways. The training set is used to fit parameters. The validation set is used to make choices such as the learning rate, the model size or when to stop. The test set is touched once, at the end, to estimate performance on new data. If you make choices by looking at the test set, it quietly becomes part of training and your final score will be too optimistic. The difference between test loss and training loss is the generalisation gap; a large gap is the numerical signature of overfitting.

Common pitfalls

  • Data leakage. Information from outside the training data slips in: duplicate records shared between training and test sets, a feature that is only known after the outcome, or scaling the data using statistics from the full dataset. Scores look excellent and collapse in real use.
  • Tuning on the test set. Every decision made by looking at test results makes them less trustworthy. Use a validation set for choices.
  • Never looking at the loss curve. A learning rate that is too high shows up as a jumpy or exploding loss; too low shows up as a nearly flat line.
  • Unscaled features. If one feature is in millions and another in single digits, gradient descent zigzags and converges slowly. Standardising features is routine.
  • Trusting accuracy on unbalanced data. If 99% of transactions are legitimate, a model that always says "legitimate" is 99% accurate and useless.
  • Assuming bigger is always better. More parameters can fit noise; size must be matched to data and checked on validation data.

In practice

  • When an AI tool behaves oddly, ask what data it was likely trained on; gaps and biases there usually explain the behaviour.
  • Remember that chatting with a model is inference: it is not learning from you in real time unless the product explicitly stores and reuses your data.
  • Be wary of any system evaluated only on the data it was trained on. Ask how it performs on new, unseen examples.

Key takeaways

  • Machine learning adjusts a model's parameters so its predictions on example data become less wrong.
  • Training is the expensive learning phase; inference is using the frozen model to answer new inputs.
  • Loss measures error, and gradient descent repeatedly nudges every parameter in the direction that lowers it.
  • Overfitting means memorising the training data rather than learning patterns that generalise, so models must be tested on unseen data.
  • A model can only be as good as its data: errors and biases in the data become errors and biases in the model.

Terms in this lesson

Feature
A measurable property of an example, such as floor area, that a model uses to make predictions.
Label
The correct answer attached to a training example, such as the actual sale price.
Training
The phase in which a model learns by adjusting its parameters to reduce errors on example data.
Inference
Using a trained, fixed model to produce outputs for new inputs.
Neural network
A function made of layers of simple units connected by adjustable weights.
Parameter
A number inside a model, such as a connection weight, that is adjusted during training.
Loss
A single number measuring how wrong a model's predictions are.
Gradient descent
A method that reduces loss by repeatedly moving each parameter a small step in the direction that lowers the error.
Backpropagation
An efficient way to calculate how much each parameter contributed to the error, by working backwards through the network.
Overfitting
When a model learns its training data too specifically and performs poorly on new data.
Mean squared error (MSE)
A loss equal to the average of the squared differences between predictions and correct values.
Learning rate
The step size used in gradient descent, controlling how far parameters move on each update.
Data leakage
When information that would not be available at prediction time, or that comes from the test data, influences training and inflates evaluation scores.

Check your understanding

  1. 1.

    In the 'walking downhill in fog' analogy for gradient descent, what does the slope under your feet represent?

  2. 2.

    A model scores 99% on its training examples but 60% on new examples it has never seen. What is the most likely problem?

  3. 3.

    When you chat with a deployed AI assistant, what is happening to the model's parameters?

  4. 4.

    Data: x = (1, 2), y = (3, 6). Model: y-hat = w x with mean squared error loss. What is dL/dw at w = 1?

  5. 5.

    Training loss keeps falling, but validation loss reached its lowest point at epoch 8 and has risen since. What is the best response?

Exercises

Work each problem before opening the solution.

  1. Exercise 1Core

    Using the house data in thousands (x=(1,1.5,2)x = (1, 1.5, 2), y=(200,300,400)y = (200, 300, 400)) and y^=wx\hat{y} = wx: (a) compute the MSE at w=180w = 180; (b) compute dL/dwdL/dw at w=180w = 180; (c) take one gradient-descent step with ฮท=0.1\eta = 0.1.

    Show solution

    (a) Predictions are 180, 270, 360, so residuals are โˆ’20,โˆ’30,โˆ’40-20, -30, -40. Squares: 400, 900, 1600. MSE =2900/3=966.67= 2900 / 3 = 966.67.

    (b) โˆ‘xiri=1(โˆ’20)+1.5(โˆ’30)+2(โˆ’40)=โˆ’20โˆ’45โˆ’80=โˆ’145\sum x_i r_i = 1(-20) + 1.5(-30) + 2(-40) = -20 - 45 - 80 = -145. Multiply by 2/32/3: dL/dw=โˆ’96.67dL/dw = -96.67. (Check with the shortcut 4.833ร—(180โˆ’200)=โˆ’96.674.833 \times (180 - 200) = -96.67.)

    (c) w=180โˆ’0.1ร—(โˆ’96.67)=189.67w = 180 - 0.1 \times (-96.67) = 189.67.

  2. Exercise 2Core

    Start at w=150w = 150 with learning rate ฮท=0.5\eta = 0.5. Compute ww after one and two steps and explain what is happening.

    Show solution

    Using dL/dw=23(7.25wโˆ’1450)dL/dw = \tfrac{2}{3}(7.25w - 1450):

    • Step 1: gradient =23(1087.5โˆ’1450)=โˆ’241.67= \tfrac{2}{3}(1087.5 - 1450) = -241.67, so w=150+120.83=270.83w = 150 + 120.83 = 270.83.
    • Step 2: gradient =23(1963.54โˆ’1450)=342.36= \tfrac{2}{3}(1963.54 - 1450) = 342.36, so w=270.83โˆ’171.18=99.65w = 270.83 - 171.18 = 99.65.

    The distance from 200 goes โˆ’50โ†’+70.8โ†’โˆ’100.3-50 \to +70.8 \to -100.3: each step multiplies it by 1โˆ’4.833ร—0.5=โˆ’1.421 - 4.833 \times 0.5 = -1.42. The parameter overshoots further each time, so training diverges. Any ฮท\eta above about 0.41 does this for this data.

  3. Exercise 3Core

    Coding. Real prices include a fixed part. Change the data to y=(250,350,450)y = (250, 350, 450) (that is, 200 per thousand sq ft plus 50) and the model to y^=wx+b\hat{y} = wx + b. Extend the gradient-descent code to learn both ww and bb from w=150,b=0w = 150, b = 0 with learning rate 0.1. What values does it reach?

    Show solution

    The gradient for bb is 2nโˆ‘(y^iโˆ’yi)\tfrac{2}{n}\sum(\hat{y}_i - y_i), the same as for ww but without the xix_i factor.

    import numpy as np
    x = np.array([1.0, 1.5, 2.0])       # thousands of sq ft
    y = np.array([250., 350., 450.])    # thousands of dollars
    w, b, lr = 150.0, 0.0, 0.1
    for step in range(5000):
        err = (w * x + b) - y
        grad_w = np.mean(2 * err * x)
        grad_b = np.mean(2 * err)
        w -= lr * grad_w
        b -= lr * grad_b
    print(round(w, 2), round(b, 2), round(np.mean(err ** 2), 6))
    

    It prints 200.0 50.0 0.0: the model recovers the slope 200 and intercept 50, and the loss reaches zero. It needs many more steps than the one-parameter version because ww and bb pull against each other (both can explain a higher price), which makes the loss surface a long narrow valley. Centring xx around its mean would speed it up.

  4. Exercise 4Challenge

    (a) For the model y^=wx\hat{y} = wx with MSE loss, show that the best ww is wโˆ—=โˆ‘xiyi/โˆ‘xi2w^* = \sum x_i y_i / \sum x_i^2, and check it on the house data. (b) A team predicting which customers will cancel a subscription reports 97% test accuracy. One feature is account_closed_date (empty for active customers). Explain what is wrong and how to fix their evaluation.

    Show solution

    (a) At the minimum the slope is zero: 2nโˆ‘xi(wxiโˆ’yi)=0\tfrac{2}{n}\sum x_i(w x_i - y_i) = 0, so wโˆ‘xi2=โˆ‘xiyiw\sum x_i^2 = \sum x_i y_i and wโˆ—=โˆ‘xiyi/โˆ‘xi2w^* = \sum x_i y_i / \sum x_i^2. For the houses: 1450/7.25=2001450 / 7.25 = 200, matching gradient descent. (Small models like this have a closed-form answer; deep networks do not, which is why we iterate.)

    (b) This is data leakage. A closing date only exists once a customer has already left, so the feature effectively contains the answer; at prediction time, for a customer who has not yet cancelled, it is always empty. Fix: remove any feature not available at the moment the prediction would be made, rebuild features using only information from before a cut-off date, split training and test sets by time (train on earlier months, test on later), and re-run the evaluation. Expect a much lower but honest score.

Further reading

Go further

Fact-checked and last reviewed 2026-11-05

Stay in the loop
Prometheus OSโ„ข ยท Native AI OS ยท Built for the future ยฉ 2025 - 2026