Lesson 1 of 88 min
Functions and loss
A model is a function with numbers it can change, and its loss is one number for how wrong those numbers make it.
After this lesson you can read a model as a function and a loss as a score of how wrong it is.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
A miss in kilograms
The loss of 0.155 is in kilograms squared, which is hard to picture. Take its square root and you are back in kilograms: 0.39. That is about how far a typical guess of the tilted line is from a penguin's real mass. It is called the root mean squared error, and people often report it beside the loss.
import numpy as np
import pandas as pd
url = "https://raw.githubusercontent.com/allisonhorst/palmerpenguins/main/inst/extdata/penguins.csv"
penguins = pd.read_csv(url).dropna(subset=["flipper_length_mm", "body_mass_g"])
flipper = penguins["flipper_length_mm"].to_numpy()
mass = penguins["body_mass_g"].to_numpy() / 1000
x = flipper / 10 - 20
miss = 0.5 * x + 4.16 - mass
mse = (miss ** 2).mean()
print(mse.round(3), np.sqrt(mse).round(2))0.155 0.39
The same number from scikit-learn
scikit-learn has the mean squared error ready-made, and its square root too. Give it the real masses first and the guesses second. For this loss the order doesn't change the number, but for most of scikit-learn's scores it does, so keep the habit.
from sklearn.metrics import mean_squared_error, root_mean_squared_error
guess = 0.5 * x + 4.16
print(round(mean_squared_error(mass, guess), 3))
print(round(root_mean_squared_error(mass, guess), 2))0.155 0.39
The average size of the misses
Squaring is one way to stop the misses cancelling. Another is to drop their sign and average their sizes: the mean absolute error. It ranks the three lines from the video in the same order, but a miss twice as long counts twice as much, not four times.
for w, b in [(0.5, 4.16), (0, 4.2), (-0.5, 4.25)]:
miss = w * x + b - mass
print(w, b, np.abs(miss).mean().round(3), (miss ** 2).mean().round(3))0.5 4.16 0.313 0.155 0 4.2 0.676 0.641 -0.5 4.25 1.253 2.114
Why the line starts at 20 cm
In the video, b is the guess for a flipper of 20 cm. Measured from 0 cm instead, the line and its loss stay the same, but b becomes −5.84 kg: the mass of a penguin with no flipper. Measuring from a size real penguins have keeps both weights easy to read.
cm = flipper / 10
guess_from_0 = 0.5 * cm - 5.84
guess_from_20 = 0.5 * (cm - 20) + 4.16
print(np.allclose(guess_from_0, guess_from_20))
print(((guess_from_0 - mass) ** 2).mean().round(3))True 0.155
Run on Python 3.13, NumPy 2.5.5, pandas 3.1.1 and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson. Answer as often as you like.
1 of 2
A line misses one penguin by +1 kg and another by −1 kg. Its average miss is 0. What does that tell you about the line?
2 of 2
A line gives a penguin with a 20 cm flipper 4 kg, and adds half a kilo for each centimeter more. A penguin's flipper is 22 cm, and it weighs 5.5 kg. What is the line's miss for it?
The ideas in this lesson
- Model and weights
- A function with numbers it can change, its weights: in goes an input, out comes a guess.
- Mean squared error
- Square each miss, then average: misses can't cancel, and a big miss counts much more.
- Loss
- One number for how wrong a model is with its weights; learning means making it small.
It leans on
- Vectorization
Transcript
What the video says, part by part. Press a time to watch from there.
Calculus and Optimization for AI
How does an AI model learn from its mistakes? It takes small steps down a hill, again and again. Hi, I'm Mohi Fayden. Calculus is the math of change. It tells the model which way is down. Optimization is how it takes the steps. This course shows it all in pictures, with no proofs. By the end, you'll see how a model learns. And you'll be able to read its code. To start, you need school math and a little Python. Every lesson has its own page on faydenai.com, with a quiz. There's a lab every few lessons, and a project at the end.
The question
Here's a question. A model learns from its mistakes. So first, it needs to know how wrong it is. And it needs that as one number. Where does that number come from?
A line that guesses
Here are the penguins from Python for AI. Each dot is one penguin. Its flipper length goes across, and its mass, how heavy it is, goes up. Penguins with longer flippers are heavier. Now draw a straight line through them. The line can guess. Take a flipper of twenty-two centimeters. Go up to the line, then across. The line guesses five point one six kilos. In goes a flipper length, and out comes a guess. A function that makes guesses like this... is called a model.
Two numbers
So what makes it this line, and not another one?
Two numbers. The first is called b. It's the mass the line gives for a flipper of twenty centimeters: four point one six kilos. The second is called w. It's how much each extra centimeter adds: half a kilo.
So a flipper of twenty-two centimeters is two centimeters past twenty. Four point one six, plus two times a half... is five point one six.
Its weights
Change w, and the line tilts. Change b, and the line slides up or down.
The numbers a model can change, like these two, are called its weights.
So what does a w of zero do?
A flat line.
Every penguin gets the same guess.
Put it at the average mass, four point two kilos... and that's the flat line.
One number for how wrong
Which line is better? The tilted one, or the flat one?
Your eye sees it right away. The tilted one. But a computer can't look at a picture. It needs one number for how wrong a line is.
A miss
Start with one penguin, the first one in the table. Its flipper is about eighteen centimeters, and it weighs three and three quarter kilos. The tilted line guesses about three point two. That's about half a kilo too light.
The guess minus the real mass is called the miss. So here, the miss is below zero: about minus a half.
When a dot is above the line, the line guessed too light, so its miss is below zero.
When a dot is below the line, its miss is above zero.
Every penguin has a miss. That's three hundred and forty-two of them.
The average
So how do you turn all these misses into one score?
The first idea is to average them. The best line should get the average closest to zero. Here are three lines. The tilted one, the flat one... and one that tilts the wrong way. Which line gets the best average?
All three... get zero.
The misses above each line cancel the misses below it.
All three lines cross at the middle of the dots: the average penguin, with the average flipper and the average mass.
Any line through that spot averages zero. If you picked the tilted line, your eye was right. The average just can't tell the lines apart.
Square each miss
So square every miss before you average them. A square is never below zero... so nothing cancels.
Now average the squares. The tilted line gets zero point one five five. The flat line gets zero point six four. And the line that tilts the wrong way gets about two point one. Now the numbers agree with your eye.
A big miss counts more
So why is the wrong way so much worse? A miss twice as long gives a square four times as big. So a few big misses count for a lot. Square, then average. This is called mean squared error. Mean is the average... and the error is the miss.
The loss
One number for how wrong a model is... is called its loss.
Mean squared error is one kind of loss.
Lower is better, and zero would be a line through every dot.
With the penguins fixed, the loss depends only on the weights.
Put in w and b, and out comes one number.
So the loss is a function too.
That's a loss function.
Learning means finding the weights where the loss is lowest.
The loss for every w
Can we see that? Start from the flat line, with b at four point two, and turn w from zero up to one. The line tilts, and the loss changes. At zero, the loss is zero point six four. At a half, it's down to zero point one six.
And at one, it's back up to zero point six six.
Draw the loss for every w, and you get a curve, with one bottom. Where's the bottom?
Near zero point five. So learning means getting down to that bottom. That's the downhill I meant at the start.
In code
Now in real code.
Here are the penguins as NumPy arrays. The table keeps flippers in millimeters, so the first line turns them into centimeters past twenty. The next line of code makes all three hundred and forty-two guesses at once. The one after it makes the misses. What will the average miss print?
Zero. And the average of the squared misses... zero point one five five.
Now change the code to the line that tilts the wrong way.
Zero again... and about two point one. In PyTorch, this whole recipe is one ready-made loss, called MSE loss.
MSE stands for mean squared error.
Give it the guesses and the real masses as tensors.
Those are PyTorch's arrays.
It prints the same number.
MSE loss is the loss of any model that guesses a number.
A model and its loss
So a model is a function, with weights it can change. A chatbot is one too. It learns from one number: how wrong its guesses for the next word were.
One number for how wrong
So a loss is one number for how wrong a model is. Now try it on this lesson's page, and take the quiz. Beat the flat line with an average miss that isn't zero.
You use this lesson in Lab 1: Find the Gentoos' middle, by walking downhill, after Gradient descent and the learning rate.
Facts last checked on .
