How Machines Learn
An intuitive tour of data, features, models, loss, training, inference, representations, and generalization, with a model you train yourself in a few lines of Python.
In the last lesson you saw that each era of AI history was a move toward letting data do more of the work. Now we open the box. Every machine learning system, from a spam filter to a frontier language model, runs on the same basic loop: make a guess, measure how wrong it was, nudge the model to be a little less wrong, and repeat. Once that loop clicks, the rest of AI becomes much less mysterious. In this lesson we build the intuition, introduce the vocabulary you will use for the rest of the course, and train a real model in a few lines of code.
A running example: predicting house prices
Imagine you want to predict the price of a house. You have a spreadsheet of past sales. Each row is one house; columns include floor area, number of bedrooms, and distance to the city centre, plus the price it sold for. This modest scenario contains every core concept of ML.
Data and features
Data is the collection of examples you learn from. Each example has:
- Features (inputs): the measurable properties the model can see, such as floor area or bedrooms. Collectively they are often written as .
- Label or target (output): the answer we want to predict, here the price, written as .
Choosing and preparing features matters a great deal. If you forget to include location, no algorithm can discover that location matters. Deep learning reduces the need for hand-crafted features, but it still depends entirely on what is in the data.
Note: "Garbage in, garbage out" is the oldest rule in ML. A model can only be as good as the data it learns from, and it will faithfully learn the errors and biases in that data too.
Models and parameters
A model is a function with adjustable knobs, called parameters (or weights). The simplest useful model for our houses is a straight line:
Here (how much each square metre adds) and (a baseline) are the parameters. For example, with (thousand per square metre) and (thousand), a 100 square metre house is predicted at thousand. Different values of and give different lines; training picks the line that fits the data best. A large neural network is the same idea with billions of parameters and a far more flexible shape. Learning means finding good values for the parameters.
Settings that you choose before training, such as how big the model is or how large each update step should be, are called hyperparameters. The model does not learn them; you tune them.
Loss: measuring wrongness
How do we know whether a particular and are good? We compare predictions with true prices using a loss function. A common choice for numeric predictions is mean squared error (MSE). Writing ("y-hat") for the model's prediction on house , for its true price, and for the number of houses:
The sign just means "add up over all houses". Squaring does two things: negative and positive errors no longer cancel out, and big mistakes count much more than small ones. A worked example with three houses (prices in thousands):
| House | Prediction | True price | Error | Squared error |
|---|---|---|---|---|
| 1 | 300 | 320 | -20 | 400 |
| 2 | 250 | 245 | 5 | 25 |
| 3 | 410 | 380 | 30 | 900 |
The MSE is . Notice that house 3's error is only 1.5 times house 1's, but it contributes more than twice as much to the loss. One number now summarizes how wrong the model is. Lower is better.
For classification ("spam or not?") we use different losses, mostly cross-entropy, which punishes a model for being confidently wrong. Language models are trained with cross-entropy on the next token. You will derive it in the math module. The principle is the same: one number that says how wrong the model is, which training drives down.
Training: the learning loop
Training repeats four steps.
The diagram shows the loop at the heart of all machine learning: data flows in, the model predicts, the loss measures the error, the gradient says which way to adjust each parameter, and the updated parameters are used for the next prediction. Step 3 is computed with calculus: the gradient is, for each parameter, the slope of the loss, telling you whether nudging that parameter up would raise or lower the loss and by how much. Module 02 (Math for AI) covers it properly. The step size in step 4 is the learning rate, written (the Greek letter eta):
The arrow means "replace with". If the slope is positive, increasing would raise the loss, so we decrease it; if negative, we increase it. Picture a ball rolling downhill on the loss curve: the slope tells it which way is down, and the learning rate sets how big a step it takes.
Each full pass through the data is an epoch. Here is the whole loop for our line, from scratch with NumPy, including a held-out test set:
import numpy as np
rng = np.random.default_rng(0)
area = rng.uniform(50, 200, size=100) # square metres
price = 2.0 * area + 50 + rng.normal(0, 15, size=100) # thousands, with noise
# Hold out the last 20 houses as a test set
area_tr, area_te = area[:80], area[80:]
price_tr, price_te = price[:80], price[80:]
mu, sigma = area_tr.mean(), area_tr.std() # statistics from TRAINING data only
x_tr = (area_tr - mu) / sigma
x_te = (area_te - mu) / sigma
w, b, lr = 0.0, 0.0, 0.1
for epoch in range(200):
pred = w * x_tr + b
error = pred - price_tr
loss = np.mean(error ** 2)
w -= lr * 2 * np.mean(error * x_tr) # step downhill for w
b -= lr * 2 * np.mean(error) # step downhill for b
if epoch % 50 == 0:
print(f"epoch {epoch:3d} train loss {loss:10.1f}")
test_loss = np.mean((w * x_te + b - price_te) ** 2)
print(f"final train loss {loss:.1f} | test loss {test_loss:.1f}")
print(f"slope per square metre: {w / sigma:.2f}, intercept: {b - w * mu / sigma:.1f}")
Running it prints a training loss that falls from about 100,000 to about 208, a test loss of about 229, and a learned slope of about 1.97 (the true value was 2.0). The losses settle near 225, the variance of the noise we added (): no model can beat that noise floor, because the noise is genuinely random. Nobody told the program the slope; it found it from data.
Two details worth noticing. First, we scaled the feature to have mean 0 and standard deviation 1, which makes training much more stable. Second, the scaling statistics came from the training set only. Using the test set to compute them would leak information, a mistake you will learn to avoid in Module 03 (Python for AI).
Inference: using what was learned
Once training finishes, the parameters are frozen. Using the model to predict on new inputs is called inference. This distinction matters enormously in practice:
| Training | Inference | |
|---|---|---|
| Purpose | Learn parameters | Make predictions |
| Parameters | Changing | Fixed |
| Frequency | Occasionally | Every time a user makes a request |
| Cost driver | Big one-off compute | Ongoing, per request |
For large models, training can cost a fortune once, but inference is paid for millions of times. And with reasoning models that "think" for many tokens before answering, inference compute has become a major cost of its own. That is why Module 12 (AI Cost Optimization) focuses heavily on making inference efficient.
Representations: how models see the world
A straight line works for one feature. But how does a model handle raw images or text? Deep networks stack many simple transformations (layers). Each layer turns its input into a new list of numbers, a vector, and training shapes these vectors so that the final prediction becomes easy. These internal vectors are called representations or, for words and tokens, embeddings.
In a good representation, things that should be treated similarly end up close together. Words with related meanings cluster; photos of cats land near other cats. Hover over the map below to see this idea.
This is the key idea behind deep learning, and it is why one pretrained model can be reused for many tasks: the representations it learned are useful well beyond the task it was trained on. You will meet embeddings again in search, recommendation, and retrieval-augmented generation.
Generalization: the real goal
A model that perfectly memorizes the training houses is useless if it fails on the next house listed. The real goal is generalization: performing well on data it has never seen. Two failure modes appear:
- Underfitting: the model is too simple to capture the pattern. Training and test error are both high. A straight line trying to fit a curved relationship underfits.
- Overfitting: the model is so flexible that it learns noise and quirks of the training set. Training error is very low, but test error is much higher.
The overfitting widget is a good place to see both failure modes at once: fit polynomials of increasing degree (a degree-1 polynomial is a straight line; higher degrees can bend more) to noisy points, and watch training and test error diverge.
Remedies for overfitting include more data, simpler models, and regularization: techniques that discourage overly complex solutions, such as penalizing large weights or randomly dropping parts of the network during training.
Note: Very large modern networks sometimes defy the simple picture: they can fit their training data perfectly and still generalize well, especially with lots of data and the right training recipe. The practical rule does not change: always judge a model on data it has not seen.
Three splits, not two
In practice we split data three ways:
| Split | Used for | Typical share |
|---|---|---|
| Training set | Fitting parameters | 60 to 80% |
| Validation set | Choosing hyperparameters, comparing models, early stopping | 10 to 20% |
| Test set | One final, honest estimate | 10 to 20% |
The pitfall: if you peek at the test set while making decisions, it quietly becomes part of training. Large language models face a version of this called benchmark contamination: if test questions appeared somewhere in the web text used for pretraining, high scores may reflect memory rather than skill.
Hands-on exercise
- Run the training loop above in Colab or Jupyter. Change the learning rate
lrto 0.01 and then to 1.5. What happens to the loss in each case? Write one sentence explaining why (hint: steps too small versus steps that overshoot). - After training, predict the price of a 120 square metre house. Scale the input the same way:
x_new = (120 - mu) / sigma, then computew * x_new + b. You should get roughly 290 (thousand). - Overfit on purpose: fit
np.polyfit(area_tr, price_tr, deg)for degrees 1, 3, and 15, and compute train and test MSE withnp.polyval. Which degree has the best test error? (NumPy may warn that the degree-15 fit is poorly conditioned; that warning is itself a hint.) - Write in your own words why the test set must not be used to choose the degree.
Expected outcome: you have seen loss fall, felt the effect of the learning rate, and watched overfitting appear as a gap between training and test error.
Key takeaways
- ML learns a function from data (features and labels) by adjusting parameters; hyperparameters are set by you.
- A loss function turns "how wrong" into a number; training minimizes it with the predict, loss, gradient, update loop.
- Inference uses a frozen model and is the ongoing cost of serving AI, especially for reasoning models.
- Deep networks learn representations (embeddings) where similar things are close, which makes them reusable.
- The goal is generalization: use training, validation, and test splits, and watch for underfitting and overfitting.
Next, we apply this loop at enormous scale. You will see how a language model is just a next-token predictor trained with this same recipe, and how pretraining, instruction tuning, and reinforcement learning turn it into a helpful assistant.
Further reading
- Google, Machine Learning Crash Course: free, interactive introduction to loss, gradient descent, and generalization at https://developers.google.com/machine-learning/crash-course
- Andrew Ng, Machine Learning Specialization (DeepLearning.AI and Stanford, Coursera): the classic beginner course, updated with Python.
- 3Blue1Brown, Neural Networks video series: outstanding visual intuition for how networks learn.
Save your progress and earn XP
Create a free account to take the quiz, track progress and unlock badges.