ai/courses

AI Fundamentals/Lesson 1 of 8

How Machine Learning Works: Loss and Gradient Descent

Models, parameters, loss and gradient descent: what “training” actually does.

Lesson
1 of 8
Time
25 min
Updated

TL;DR

The short answer

Machine learning means finding the settings of a model that make its predictions match a set of examples. You start with a formula full of adjustable numbers (parameters), score how wrong its predictions are with a single number (the loss), and let an algorithm called gradient descent nudge every parameter in the direction that lowers the loss, over and over, until it stops improving.

That's the whole trick. A spam filter, a face-unlock model and ChatGPT were all trained with this same loop. They differ in the formula, the examples and the scale, not in the idea.

Programs that nobody wrote

A normal program is a recipe. A programmer thinks through the problem and writes down every step: if the email contains "WIN A FREE CRUISE", mark it as spam. That works until spammers write "W1N A FR3E CRUISE", and then someone has to write another rule, forever.

Machine learning turns the job around. Instead of rules, you hand the computer examples with answers: a hundred thousand emails, each labeled "spam" or "not spam" by a person. The computer's job is to find a rule that reproduces those answers. If it finds a good one, it will also work on emails it has never seen, including ones with creative spelling.

Fig. 1Traditional programming: you write the rules, the computer produces answers. Machine learning: you provide examples with answers, the computer produces the rules.

The rule the computer finds is called a model, and finding it is called training. Every machine learning system has the same four ingredients, so it's worth learning their names once:

  • Data: the examples. For a spam filter, emails with labels. For ChatGPT, a large share of all the text on the public internet.
  • A model: a formula with adjustable numbers in it, called parameters or weights. Before training they're random and the model is useless.
  • A loss function: a way to score how wrong the model is on the examples, as a single number. Lower is better.
  • An optimizer: a procedure that adjusts the parameters to lower the loss. Almost always some version of gradient descent.

The rest of this lesson builds each ingredient by hand, on a problem small enough to fit in your head.

Kind of learningWhat the examples look likeEveryday example
SupervisedInputs with the right answer attachedSpam filter, price prediction, photo tagging
UnsupervisedInputs only; find structure in themGrouping customers by behavior
ReinforcementActions and a reward score, no right answersGame-playing AI, robot control
Self-supervisedRaw data where the answer is hidden in the data itselfLanguage models: the next word is the answer
TableThe four kinds of machine learning you will hear about. Self-supervised learning is the one behind ChatGPT; it is covered in lesson 6.

A model is a formula with knobs

Let's teach a computer to predict taxi fares. We have eight past trips: the distance in kilometers and what each one cost. We suspect the price works like most taxi meters, a fixed starting fee plus a price per kilometer. So our model is:

fare = base fee + price per km × distance

This formula has two knobs, the base fee and the price per km. Those are its parameters. Training means finding knob positions that make the formula agree with our eight real trips. Once we have them, we can predict a 7 km trip we've never taken.

A real neural network is the same thing with more knobs. The model behind GPT-3 had 175 billion of them. But two knobs are enough to see everything that matters.

Loss: one number for how wrong you are

To improve the model we need to measure it. For each trip, the model makes a prediction and we compare it with the real fare. The difference is the error for that trip: maybe we predicted $9.50 and it cost $10.40, so we're $0.90 off.

Eight trips give eight errors. We want one number, so we combine them. The most common way is the mean squared error: square every error, then take the average. Squaring does two useful things. It makes all errors positive, so a miss of +$2 and a miss of −$2 don't cancel out. And it punishes big misses much more than small ones: being $4 off counts sixteen times as much as being $1 off, not four times.

That single number is the loss. Training has exactly one goal: make it as small as possible. Try to do it yourself first.

DemoDrag the two knobs until the line runs through the dots. The red segments are the errors; the loss is their squared average. Then let gradient descent do it and try all three step sizes.

You probably got close in under a minute. You looked at the picture, saw that the line was too low or too steep, and moved the right knob. Notice what you were doing: for each knob, you were asking "if I move this a little, does the loss go up or down?" and then moving it the way that helps. Gradient descent does exactly that, without the picture.

Gradient descent: walking downhill in fog

Imagine every possible pair of knob settings as a point on a huge landscape, where the height at each point is the loss. Bad settings are high mountains, good settings are low valleys. Training means finding the bottom of the deepest valley.

The catch is that you can't see the landscape. Computing the loss for every possible setting would take forever, and real models have billions of knobs, so the landscape has billions of dimensions. What you can do cheaply is measure the slope right where you're standing. That slope is called the gradient: for each knob, it says which direction makes the loss go up, and how steeply.

So you do the obvious thing. Take a small step in the opposite direction, downhill. Measure the slope again. Step again. That's gradient descent, and it's how essentially every neural network in the world is trained.

Fig. 2Gradient descent on one knob: each step follows the slope downhill, and the steps shrink as the ground flattens near the minimum. A step that is too big overshoots to the other side.

The size of each step is controlled by a setting called the learning rate, and the demo above lets you feel why it matters:

  • Too small, and training crawls. You'll get there, eventually, after a very long walk.
  • Just right, and the loss drops fast and settles at the bottom.
  • Too big, and each step overshoots the valley and lands higher up on the other side. The next step overshoots even more, and the loss explodes. This is a real failure that real engineers fight: a training run that "diverges" can waste days of expensive computer time.

Picking the learning rate is one of the most important decisions in training any model, which is why so many tricks exist to adjust it automatically during training.

Fig. 3The loop at the heart of all machine learning. For a large language model it runs millions of times, on thousands of chips in parallel, for weeks or months.

From two knobs to a trillion

Everything you just did scales up with surprisingly few changes.

The model gets bigger. Instead of a straight line, a neural network is a deep stack of simple formulas, with millions or billions of knobs. It can bend to fit almost any pattern, which is both its power and, as we'll see in a moment, a danger.

The data gets bigger, so we take it in bites. Computing the loss on all the data before every step would be far too slow when the data is a few trillion words. So each step uses a small random batch of examples, maybe a few thousand, to estimate the slope. The estimate is noisy, but it's cheap, and taking many cheap, slightly wobbly steps works better than taking a few perfect ones. This is stochastic gradient descent, the version that's actually used.

The loop runs for a long time. A large language model takes hundreds of thousands of steps, each one processing millions of words, spread over thousands of chips. But each step is still: guess, measure the loss, compute the slope, nudge every knob a little.

taxi.py
import numpy as np

km   = np.array([1, 2, 3, 5, 6, 8, 10, 12])
fare = np.array([4.6, 6.1, 7.2, 10.4, 11.3, 14.9, 17.8, 21.2])

base, per_km = 0.0, 0.0      # two knobs, start anywhere
lr = 0.015                   # learning rate: the size of each step

for step in range(5000):
    guess = base + per_km * km
    error = guess - fare
    loss = (error ** 2).mean()            # mean squared error
    # The gradient: which way each knob should turn to reduce the loss
    base   -= lr * 2 * error.mean()
    per_km -= lr * 2 * (error * km).mean()

print(f"base ${base:.2f}, ${per_km:.2f} per km, loss {loss:.3f}")
print(f"A 7 km trip: ${base + per_km * 7:.2f}")
CodeThe whole lesson in a few lines of Python with numpy. It prints base $2.87, $1.50 per km, and predicts $13.38 for a 7 km trip. Optional: you can skip every code block in this course.

The trap: learning by heart

There's a way to get zero loss on our taxi data without learning anything: memorize the eight trips. A model with enough knobs can draw a wiggly curve that passes exactly through every dot, and it will predict nonsense for the 7 km trip that falls between them.

This is called overfitting, and it's the machine learning version of a student who memorizes last year's exam answers. Perfect score on the practice test, lost on the real one.

The defense is simple and universal: hold some examples back. Train on most of the data, and measure the loss on a test set the model never saw during training. If the training loss keeps falling but the test loss starts rising, the model has stopped learning the pattern and started memorizing the examples. Every serious result in AI, from the ImageNet contest to the benchmarks companies quote for new chatbots, is a score on held-out data.

Exercise · about 5 minutes

Be the gradient descent

Pick something from your own life with a number that depends on another number: grocery bill vs number of items, commute time vs departure time, coffee cups vs hours of sleep. Write down five real data points.

  1. Guess a rule of the form result = start + rate × input.
  2. For each data point, write the error: your prediction minus the real value.
  3. Change one of your two numbers a little in the direction that should shrink the errors, and compute them again. Did the average error go down?
  4. Repeat two more times.

You just ran three steps of gradient descent by hand. Bonus: paste your five data points into ChatGPT, Claude or Gemini and ask it to fit a straight line. Compare its numbers with yours.

Quiz

  1. 1.What is the main difference between traditional programming and machine learning?

  2. 2.In the taxi model fare = base + price per km × distance, what are the parameters?

  3. 3.What does the loss measure?

  4. 4.You train with a very large learning rate and the loss grows with every step. What is happening?

  5. 5.A model scores perfectly on its training data but badly on new data. What is this called, and how do you catch it?

0 of 5 answered

Key takeaways

  • Machine learning finds rules from examples with answers instead of having a programmer write them.

  • A model is a formula with adjustable numbers called parameters or weights. Training sets them.

  • The loss turns all the model’s errors into one number. Training means making it small.

  • Gradient descent repeatedly nudges every parameter in the direction that lowers the loss. The learning rate sets the step size.

  • A model that memorizes its training data overfits. Always judge a model on data it never saw.

Go deeper

AI Fundamentals: How Modern AI Actually Works

  1. 01How machines learn25 min
  2. 02Neural networks30 min
  3. 03Tokens20 min
  4. 04Embeddings25 min
  5. 05Attention and transformers30 min
  6. 06How LLMs are trained30 min
  7. 07How LLMs generate text25 min
  8. 08RAG, tools and agents30 min