- 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:
| House | Area (sq ft) | Actual price |
|---|---|---|
| A | 1,000 | $200,000 |
| B | 1,500 | $300,000 |
| C | 2,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
| Style | How it learns | Example |
|---|---|---|
| Supervised learning | From examples paired with the correct answer (labels) | Emails marked spam or not spam |
| Unsupervised learning | Finds structure in data with no labels | Grouping customers into similar segments |
| Reinforcement learning | Tries actions and learns from rewards or penalties | A 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 in thousands of square feet and price in thousands of dollars, so the three houses become and . The model is , where ("y-hat") is the prediction and 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):
where is the number of examples and is the error (the residual) on example . 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 the residuals are , and , so
Deriving the gradient
The slope of the loss with respect to comes from ordinary calculus (the chain rule):
At : , and . The slope is negative, which means increasing lowers the loss, exactly what the intuition said.
Gradient descent moves against the slope by a step of size (the learning rate):
With : . Repeating:
| Step | Loss before the step | after the step |
|---|---|---|
| 1 | 6041.67 | 174.17 |
| 2 | 1612.79 | 186.65 |
| 3 | 430.53 | 193.10 |
| 4 | 114.93 | 196.44 |
| 5 | 30.68 | 198.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 and gives
So the distance from the best value, , changes each step by a fixed factor: . Training converges only if that factor lies between and , which means . With the factor is , so the error roughly halves each step (as in the table). With the factor is : 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), and the gradient is the vector of slopes, one per parameter. The update has the same shape: . 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 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.
In the 'walking downhill in fog' analogy for gradient descent, what does the slope under your feet represent?
- 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.
When you chat with a deployed AI assistant, what is happening to the model's parameters?
- 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.
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.
- Exercise 1Core
Using the house data in thousands (, ) and : (a) compute the MSE at ; (b) compute at ; (c) take one gradient-descent step with .
Show solution
(a) Predictions are 180, 270, 360, so residuals are . Squares: 400, 900, 1600. MSE .
(b) . Multiply by : . (Check with the shortcut .)
(c) .
- Exercise 2Core
Start at with learning rate . Compute after one and two steps and explain what is happening.
Show solution
Using :
- Step 1: gradient , so .
- Step 2: gradient , so .
The distance from 200 goes : each step multiplies it by . The parameter overshoots further each time, so training diverges. Any above about 0.41 does this for this data.
- Exercise 3Core
Coding. Real prices include a fixed part. Change the data to (that is, 200 per thousand sq ft plus 50) and the model to . Extend the gradient-descent code to learn both and from with learning rate 0.1. What values does it reach?
Show solution
The gradient for is , the same as for but without the 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 and pull against each other (both can explain a higher price), which makes the loss surface a long narrow valley. Centring around its mean would speed it up. - Exercise 4Challenge
(a) For the model with MSE loss, show that the best is , 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: , so and . For the houses: , 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
- bookGareth James, Daniela Witten, Trevor Hastie, Robert Tibshirani (and Jonathan Taylor for the Python edition), An Introduction to Statistical Learning
- bookAston Zhang, Zachary C. Lipton, Mu Li, Alexander J. Smola, Dive into Deep Learning (2021โ2023; free online book, arXiv 2106.11342)
- paperDavid E. Rumelhart, Geoffrey E. Hinton, Ronald J. Williams, Learning representations by back-propagating errors, Nature 323 (1986)
Go further
Fact-checked and last reviewed 2026-11-05