AI contentThis course was created with AI: the lectures, quizzes, labs, narrated videos and the animated instructor are AI-generated. It can contain mistakes, so check important facts against primary sources. The linked YouTube talks are by their original creators.
Written and built with Claude (Anthropic). Code examples and labs were executed and checked automatically; quiz answers and explanations were reviewed for consistency with the lectures. Video narration uses your browser's text-to-speech voice, and the instructor is an illustrated character, not a real person. Certificates record completion of this self-paced, AI-generated course and are not accredited credentials.
From a line through five points to a language model you fine-tuned yourself.
Written lectures with a narrated video for each one, curated talks from the open web, interactive demos you can push around, a quiz and a practice quiz every week, a final exam and certificate per course and a lab with a checkpoint that tells you whether your code is right. Everything runs in this page or in a Python notebook; nothing needs an account.
Lectures are written, in two layersEach lecture is a 6–12 minute read: intuition, the formula to remember, the code. Under it, a Deep dive expands into the full derivation, a worked example you can follow with a calculator, and the mistakes people actually make.
Demos replace the chalkboardNine small simulations run in this page: push the learning rate too high, overfit a polynomial, train a neural network, watch k-means converge, train an agent on a grid.
Quizzes check understandingFive questions per week with explanations for every answer. Scores stay in this browser.
Labs are Jupyter notebooksEach lab is a notebook with TODO cells and a self-check after every step, then a graded practice set of harder exercises and a mini-project. A checkpoint on this page asks for one number your code must produce. The solutions notebooks are fully executed, with outputs and plots.
PrerequisitesPython at the level of loops, functions and lists; high-school algebra. Linear algebra and calculus are introduced where needed.
ToolsPython 3, NumPy, scikit-learn, PyTorch. For Course 4, the Hugging Face stack and a free Colab GPU.
Schedule
One week per row at six to eight hours. Every week has module quizzes, a graded quiz or lab, and a narrated video for each lecture; every course ends with a final exam and a certificate.
Week
Course
Topic
You finish with
1
1
Linear regression and gradient descent
Gradient descent written from scratch, fitting a price line
2
1
Regression with many features
Vectorized regression with z-score scaling and polynomial features
3
1
Classification and regularization
Regularized logistic regression with a plotted decision boundary
4
2
Neural networks
A network written in NumPy, then the same in PyTorch
5
2
Neural network training
A ten-class digit classifier with softmax and Adam
6
2
Advice for applying machine learning
Degree and λ chosen by cross-validation, learning curves, an error analysis
7
2
Decision trees
A tree built from information gain, compared with forests and boosting
8
3
Clustering, anomaly detection, PCA
K-means image compression and a Gaussian anomaly detector
9
3
Recommender systems
Collaborative filtering trained in PyTorch
10
3
Reinforcement learning
Tabular Q-learning that solves a grid world
11
4
From pretrained to adapted
An instruction dataset rendered through the model's chat template
12
4
Parameter-efficient fine-tuning
A complete LoRA run with TRL and a read loss curve
13
4
Alignment, evaluation, deployment
A DPO run, an evaluation against the base model, a GGUF served locally
14
4
Tokenizer and transformer from scratch
BPE, multi-head attention and a tiny GPT trained on CPU, with sampling
15
4
Quantization, inference and serving
int8 / 4-bit quantization, a KV cache verified against full recompute
16
5
Foundations of convolutional networks
A convolutional layer and pooling written in NumPy, checked against PyTorch
17
5
Deep convolutional models
A CNN trained on digits in the page, compared with a dense network
18
5
Detection, segmentation and recognition
IoU, YOLO-style filtering and non-max suppression
19
6
Lifecycle and deployment
A weekly drift monitor that separates data drift from concept drift
20
6
Modeling and data in production
Cleaner labels and a per-camera pipeline fix that lift accuracy
21
6
Scoping and operating ML systems
A scoped project with feasibility, metrics and a model card
The notebooks
Twenty labs in notebooks/, each with a student version (TODO cells, self-checks) and an executed solutions version in notebooks/solutions/. Small datasets ship in notebooks/data/; everything in Courses 1–3, 5 and 6 runs offline on a laptop, and every lab runs in this page. Course 4's real training cells are guarded by a RUN_TRAINING flag for a GPU machine.
Labs marked Runs in browser execute right on this page: open one, press Start Python, then edit and run cells (Shift+Enter). Python is loaded once (about 10 MB; extra packages load only when a cell needs them, and everything is cached afterwards) and your edits are kept in this browser. PyTorch labs run on torchlite, a NumPy re-implementation of the PyTorch API bundled in this page (same code, slower than real PyTorch, CPU only). The Hugging Face training cells in Course 4 stay switched off by RUN_TRAINING = False; for those, download the notebook and the data files below into a folder named data/ and run it on a GPU.
Your progress
Tick each lecture, quiz and lab as you finish it. Ticks and quiz scores stay in this browser only.
Course 1 · Supervised learning0 / 0
Course 2 · Neural networks0 / 0
Course 3 · Unsupervised & RL0 / 0
Course 4 · Fine-tuning0 / 0
Course 5 · CNNs0 / 0
Course 6 · ML in production0 / 0
Watch alongside
The lectures here stand on their own. These free series say the same things in a second voice, which is often when an idea lands.
Supervised Learning: Regression and Classification
Every supervised method in this specialization follows one recipe: choose a model with parameters, define a cost that says how wrong the parameters are, and move them downhill. This course teaches the recipe on the two simplest models and makes you write every piece in NumPy before a library hides it.
45lectures with video
4demos
16quizzes incl. practice + final
3labs
Week 1 · Introduction to machine learning
Introduction to machine learning
Welcome to the Machine Learning Specialization! Meet supervised and unsupervised learning, build your first model, linear regression, and train it with gradient descent.
Video lectures · Week 1
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
Linear Regression, Clearly ExplainedStatQuest with Josh Starmer · YouTube ↗Gradient Descent, Step-by-StepStatQuest with Josh Starmer · YouTube ↗Gradient descent, how neural networks learn3Blue1Brown · YouTube ↗
Module 1
Overview of machine learning
Lecture 1.1 · 3 min read
Welcome to machine learning!
Machine learning is the science of getting computers to learn without being explicitly programmed. You probably use it dozens of times a day without noticing: when a search engine ranks pages, when your photo app recognizes friends, when a streaming service suggests a film, when your phone turns speech into text, and when your email provider quietly moves spam out of the way.
This specialization teaches the ideas behind those systems and, just as importantly, how to make them work in practice. You will write the core algorithms yourself in Python and NumPy, run them in Jupyter notebooks inside this page, and learn the habits that experienced practitioners use to decide what to try next when a model is not good enough.
Course 1 starts with the two most important ideas in the field, linear regression and logistic regression, and the algorithm that trains almost every modern model, gradient descent. Everything later in the specialization, up to fine-tuning large language models, builds on these three.
Lecture 1.2 · 5 min read
Applications of machine learning
Machine learning grew out of artificial intelligence because many tasks people care about are too hard to program by hand. Nobody knows how to write rules for recognizing speech, diagnosing a lung X-ray, or driving a car through a busy junction, but we can collect examples and let a learning algorithm find the rules.
Industry: visual inspection of products in factories, predictive maintenance of machines, optimizing wind turbines, forecasting demand for a supply chain.
Health care: reading medical images, triaging patients, discovering drugs.
Agriculture and environment: estimating crop yields from satellite images, detecting plant disease, monitoring water and forests.
One estimate puts the value machine learning could add to the global economy in the trillions of dollars a year by 2030, much of it outside the software industry. There are many more problems than trained practitioners, which is a good reason to learn the field properly.
Reading · 3 min read
How to use this course
Each week is a list of short modules, just like the outline on the left. A module usually contains a few lectures, one or more optional labs and a practice quiz.
Lectures are written to be read in a few minutes. Each has a narrated video version: press ▶ Watch next to the title. Code in grey boxes runs right here: press Run.
Optional labs are short, guided code walkthroughs that run in the page. They are ungraded but strongly recommended: they show the lecture ideas in working code.
Practice quizzes check each module. Retake them as often as you like.
Practice labs at the end of each week are full Jupyter notebooks with self-checking exercises. Open one, press Start Python, and work cell by cell.
Final exam and certificate: pass the course quizzes, finish the labs and score 80% on the final exam to earn the certificate.
Tick the box next to an item when you finish it. Your progress, quiz grades and notes stay in this browser; the Grades, Notes and Course info links at the top of the outline summarize them.
Module 2
Supervised vs. unsupervised machine learning
Lecture 1.4 · 6 min read
What machine learning is
A conventional program is a set of rules a person wrote. A machine learning program is a set of rules the computer found by looking at examples. The difference matters when the rules are hard to write down: nobody can list the pixel patterns that make a photo contain a cat, but a model can find patterns that separate ten thousand cat photos from ten thousand others.
Arthur Samuel, who coined the term in 1959, taught a computer to play checkers by having it play tens of thousands of games against itself and remember which positions led to wins. He was a mediocre checkers player; the program became better than he was. That is the whole promise: the model's skill is limited by the data and the algorithm, not by what its author already knows.
Three ingredients recur in everything that follows. A model is a function with adjustable numbers in it, the parameters. A cost is a number that says how badly the current parameters fit the examples. A learning algorithm changes the parameters to make the cost smaller. In this course the model is a line, the cost is squared error and the algorithm is gradient descent. In Course 4 the model has seven billion parameters and the cost is cross-entropy over a vocabulary, but the three ingredients are the same.
Deep dive · model, cost and algorithm on five houses
Intuition
The three ingredients are easiest to see side by side with a hand-written rule. Suppose an estate agent says "a house is worth $250 per square foot". That is a model with one parameter that a person chose. A learned model has the same form, but the computer chooses the parameters by making a cost small on examples.
Learned line, ŷ = 202·x + 106: residuals 8, −11, 10, −19, 12. Squares 64, 121, 100, 361, 144 sum to 790, so J = 79.
The learned line is nine times better on these houses because it was chosen to be. That alone proves nothing about new houses. To test the promise of learning, hide one house, learn from the other four, and predict the hidden one.
Held out
Fit on the other four
Prediction
True price
Error
x = 2.0
ŷ = 202·x + 108.5
512.5
500
12.5
Compare a "memorizer" that answers with the price of the nearest training house. Its training error is exactly zero. For the hidden 2.0 house the nearest training houses are 1.5 and 2.5, at equal distance, so it answers 420 or 630 and misses by 80 or 130. Zero training error, ten times worse on the house that matters.
Why generalization is possible at all
The line has two parameters and is fit to many more points than that, so it cannot bend to follow each one. Whatever it captures has to be shared by most houses, and shared structure is what carries over to a new house. The memorizer has as many "parameters" as houses, so nothing forces it to find shared structure. Course 2 makes this trade precise as bias and variance.
Common mistakes
Judging a model by its training cost. Symptom: a model that looks perfect in development fails on real data. Fix: always keep examples the model never saw and report error on them.
Thinking learning removes human choices. The person still picks the model family, the cost and the features. Symptom: blaming "the algorithm" for a bad feature choice. Fix: treat those three choices as part of the design you are responsible for.
Expecting skill beyond the data. Samuel's program improved because self-play produced endless new games. Symptom: a model trained on houses from 800 to 3,000 sq ft confidently prices a 10,000 sq ft mansion. Fix: know the range your examples cover.
Check yourself
If the memorizer instead averages the prices of the two nearest training houses, what does it predict for the hidden 2.0 house, and what is its error?
Answer
The average of 420 and 630 is 525, an error of 25. Better than 80 or 130, still twice the line's error of 12.5.
Lecture 1.5 · 7 min read
Supervised and unsupervised learning
Supervised learning is learning from examples that come with the right answer. The input is called x; the answer, or label, is y. A spam filter learns from emails labeled spam or not. A house-price model learns from houses with known sale prices. The model's job is to map new x to a good guess of y.
Two kinds of supervised problems appear constantly. In regression, y is a number from a continuous range: a price, a temperature, a delivery time. In classification, y is one of a small set of categories: spam or not, which of ten digits, benign or malignant. The distinction decides the model's last step and the cost you use; it is the first question to ask about any new problem.
Unsupervised learning has only x. There is no answer to predict, so the model looks for structure instead: groups of similar customers (clustering), readings that look unlike the rest (anomaly detection), a compact description of high-dimensional data (dimensionality reduction). Course 3 is about those. A third family, reinforcement learning, has no labels but has rewards, and also waits until Course 3.
Predicting tomorrow's electricity demand from the last month: supervised, regression.
Sorting support tickets into billing, bug or feature request: supervised, classification.
Finding segments among a million shoppers with no predefined categories: unsupervised, clustering.
Deep dive · what the label type decides
Intuition
The type of y fixes two things before you write any code: the last step of the model and the cost. A regression model ends in an unbounded number and is scored with squared error. A classification model ends in a probability for each class and is scored with log loss (“Log loss and the same old gradient descent”).
Problem
Type of y
Model output
Typical cost
House price
real number
w·x + b
squared error
Spam or not
2 categories
P(y = 1 | x)
binary log loss
Ticket topic
3 categories
one probability per class
multiclass log loss
Customer segments
no y
cluster id
distance to cluster centre
Derivation: why category codes break regression
Suppose you code ticket topics as numbers, billing = 0, bug = 1, feature request = 2, and fit a regression. Consider several tickets with identical features x. The model must give them one prediction c. Squared error picks the c that minimizes Σ(c − yᵢ)². Differentiate with respect to c and set to zero:
2·Σ(c − yᵢ) = 0 ⇒ c = (1/m)·Σ yᵢUnder squared error the best constant prediction is the mean of the labels.
Now take four such tickets: two billing (0) and two feature requests (2). The mean is 1, so the model predicts "bug", a topic none of the four tickets had. The codes 0, 1, 2 impose an order and a distance that the categories do not have. A classifier instead reports P(billing) = 0.5, P(bug) = 0, P(feature) = 0.5, which is exactly what the data says.
Edge cases
Ordered categories such as star ratings 1 to 5 sit in between. Regression respects the order and is often fine; classification ignores the order but cannot predict 3.7.
The same data, two problems. "Days until a customer cancels" is regression. "Will the customer cancel within 30 days" is classification. The label you define picks the problem.
Labels you do not have. Anomaly detection is unsupervised when nobody has marked anomalies. Once you have a few thousand labeled frauds it becomes a (very imbalanced) classification problem.
Common mistakes
Feeding category codes or IDs as numbers. Symptom: a weight on "zip code" or "store id" that means nothing. Fix: one-hot encode, one 0/1 column per category.
Binning a numeric target to make it a classification. Symptom: predicting "price band 3" loses the information that band 3 is next to band 4. Fix: keep regression unless the decision itself is categorical.
Reporting accuracy on a regression. Symptom: "92% of predictions within $10k" with no notion of how wrong the rest are. Fix: report RMSE or mean absolute error.
Check yourself
A model predicts tomorrow's electricity demand. Your manager only needs to know whether it will exceed the grid's capacity. Which problem should you train?
Answer
Usually still regression on demand, then compare the prediction with capacity. You keep the margin information (how far below capacity), and the capacity can change without retraining. Train a classifier only if exceedances are what you have labels for.
Lecture 1.6 · 6 min read
Supervised learning part 1: regression
Supervised learning is by far the most widely used kind of machine learning. You give the algorithm examples of inputs x together with the right output label y, and it learns a mapping from x to y. Once trained, it predicts y for inputs it has never seen.
Input x
Output y
Application
email
spam? (0/1)
spam filtering
audio
text transcript
speech recognition
English
Spanish
machine translation
ad, user info
click? (0/1)
online advertising
image, radar
positions of other cars
self-driving car
image of a phone
defect? (0/1)
visual inspection
Take predicting house prices from size. Plot price against size for houses that have sold, fit a line or a curve, and read off the predicted price of a new house. Because the output is a number that can take infinitely many values, this kind of supervised learning is called regression.
Lecture 1.7 · 7 min read
Supervised learning part 2: classification
The second major type of supervised learning is classification: predicting a category from a small, finite set. Is a tumor benign (0) or malignant (1)? Is a photo a cat, a dog or neither? The categories are also called classes, and they need not be numbers.
With one input, tumor size, you can draw the examples on a line with two symbols for the two classes. With two inputs, size and the patient's age, they become points in a plane, and the learning algorithm finds a boundary that separates malignant from benign. Real medical systems use many more inputs, such as cell shape and uniformity.
Regression
Classification
Output
a number, infinitely many values
a category, a small set of values
Example
house price
benign or malignant
Course 1 model
linear regression
logistic regression
Lecture 1.8 · 8 min read
Unsupervised learning part 1: clustering
In unsupervised learning the data come without labels. Instead of predicting a known answer, the algorithm looks for structure or patterns on its own. It is called unsupervised because nobody supervises it with right answers.
The most common example is clustering: grouping similar data points together. A news site groups thousands of articles about the same story; geneticists group people by patterns of gene activity; a company groups its customers into market segments to serve each better. In none of these cases does anyone tell the algorithm what the groups are.
import numpy as np
rng = np.random.default_rng(0)
a = rng.normal([2, 2], 0.4, (20, 2)); b = rng.normal([6, 5], 0.5, (20, 2))
X = np.vstack([a, b]) # no labels, just points
c = X[[0, -1]].copy() # two starting centers
for _ in range(5): # a few rounds of k-means (Course 3)
labels = np.argmin(((X[:, None] - c) ** 2).sum(-1), axis=1)
c = np.array([X[labels == k].mean(0) for k in range(2)])
print("cluster sizes:", np.bincount(labels))
print("cluster centers:", c.round(2))
Lecture 1.9 · 4 min read
Unsupervised learning part 2: anomalies and dimensionality
Two more unsupervised tasks appear later in the specialization.
Anomaly detection finds unusual data points. Banks use it to flag fraudulent transactions; factories use it to spot machines behaving unlike all the others.
Dimensionality reduction compresses a dataset with many features into far fewer numbers while losing as little information as possible, for visualization or faster learning.
A quick self-check: spam filtering with labeled emails is supervised; grouping news articles into stories is unsupervised; finding market segments in customer data is unsupervised; diagnosing diabetes from labeled patient records is supervised.
Lecture 1.10 · 4 min read
Jupyter notebooks
Jupyter notebooks are the standard tool for machine learning experiments. A notebook mixes markdown cells, which hold text and equations, with code cells, which run Python and show the output right underneath, including plots.
This course uses notebooks in two ways. The gray code boxes in lectures and optional labs run in the page with a Python kernel shared across the course, so variables defined in one box are available in the next. The practice labs open full notebooks in a viewer: press Start Python, then run cells with Shift+Enter. You can also download every notebook and run it locally in Jupyter or Google Colab.
import sys, numpy as np
print("Python", sys.version.split()[0], "| NumPy", np.__version__)
2 + 3 # the value of the last line is displayed automatically
Optional lab · about 15 min · runs in this page
Python and Jupyter notebooks
Get comfortable with code cells: run them, edit them, and see how variables persist between cells in this course.
Step 1Run a cell
print("Hello, machine learning!")
x = 3
x * 2
Step 2Variables persist
x = x + 10 # uses x from the previous cell
print("x is now", x)
Step 3f-strings and lists
name, score = "gradient descent", 0.97
print(f"{name} reached {score:.1%} accuracy")
squares = [k ** 2 for k in range(6)]
squares
Module 3
Practice quiz: Supervised vs unsupervised learning
Practice quiz · 5 questions
Supervised vs unsupervised learning
Module 4
Regression model
Lecture 1.11 · 8 min read
The linear model
Here is the dataset we will use all week: five houses, their size in thousands of square feet and their sale price in thousands of dollars.
Size x (1000 sq ft)
Price y ($1000)
1.0
300
1.5
420
2.0
500
2.5
630
3.0
700
A model is a function from x to a prediction, written ŷ (y-hat) to distinguish it from the true y. The simplest useful function is a straight line with two parameters: w, the slope, says how much the price rises per thousand square feet; b, the intercept, is the price of a house of size zero, which is not a real house but is a real parameter.
fw,b(x) = w · x + bw and b are the parameters. Training means finding the values of w and b that make the line pass close to the five points.
Notation you will see for the rest of the specialization: the training set has m examples, here m = 5. The i-th example is written (x(i), y(i)), so x(3) = 2.0 and y(3) = 500. Superscripts in parentheses index examples; they are not exponents.
Drag the sliders below. Each vertical segment is a residual, the gap between the line's prediction and the true price. The number at the bottom is the cost, defined in the next lecture; watch it fall as the line gets closer to the points.
Fit the line by handfive houses
cost J(w, b) –best possible 79.0 at w = 202, b = 106
Deep dive · the best line in closed form
Derivation
For one feature the best (w, b) can be found by hand. Set both partial derivatives of J to zero (they are derived in “Gradient descent”). Write x̄ and ȳ for the means of x and y.
∂J/∂b = (1/m)·Σ(w·xᵢ + b − yᵢ) = 0 gives w·x̄ + b − ȳ = 0, so b = ȳ − w·x̄. The best line always passes through the point (x̄, ȳ).
Because Σ(xᵢ − x̄) = 0, you may replace the trailing xᵢ by (xᵢ − x̄) without changing the sum. Solve for w.
w = Σ(xᵢ − x̄)(yᵢ − ȳ) / Σ(xᵢ − x̄)² b = ȳ − w·x̄Ordinary least squares for one feature.
Worked example by hand
x̄ = 2.0 and ȳ = 510.
x
y
x − x̄
y − ȳ
product
(x − x̄)²
1.0
300
−1.0
−210
210
1.00
1.5
420
−0.5
−90
45
0.25
2.0
500
0.0
−10
0
0.00
2.5
630
0.5
120
60
0.25
3.0
700
1.0
190
190
1.00
sum
505
2.50
w = 505 / 2.5 = 202 and b = 510 − 202·2 = 106, the numbers the slider demo reports. The residuals are 8, −11, 10, −19, 12. They sum to zero, which is step 1 restated: with an intercept, least-squares residuals always average to zero.
Reading the parameters
w = 202 is in $1000 per 1000 sq ft, which is $202 per square foot. If you had used raw square feet, the same line would have w = 0.202 and the same b = 106. Changing the units of x rescales w and leaves predictions unchanged. b = 106 is the line's value at x = 0, which is far outside the data (the smallest house is 1.0); it is a parameter, not the price of an empty lot.
Common mistakes
Reading x(2) as x squared. Symptom: code like x**2 where x[1] was meant. Fix: superscripts in parentheses are example indices, and Python counts from 0, so x(2) is x[1].
Swapping x and y. Regressing size on price gives slope 505 / 102800 = 0.004912; inverting it gives 203.56, not 202. Symptom: two "best lines" that disagree. Fix: the variable you want to predict goes on the y side; least squares only minimizes vertical misses.
Interpreting b by extrapolation. Symptom: "a zero-size house costs $106k". Fix: interpret parameters only inside the range of the data.
Mixing units between training and use. Symptom: pricing a 1,200 sq ft house at 202·1200 + 106 = $242,506k. Fix: feed x in the same units it was trained in (1.2, giving $348.4k).
Lecture 1.12 · 6 min read
Linear regression model part 2
The supervised learning recipe has three parts. A training set of inputs (features) and outputs (targets) is fed to a learning algorithm, which produces a function f, the model. Given a new x, f outputs ŷ, the prediction or estimate of y.
x → f → ŷ, fw,b(x) = wx + bw and b are the parameters, also called coefficients or weights. Changing them changes the line.
Why a straight line? It is the simplest function that can capture a trend, it has only two parameters to learn, and it is the building block for everything that follows: curves come from adding features, and neural networks are stacks of linear functions with simple nonlinear steps in between. Linear regression with one input is called univariate linear regression.
Optional lab · about 20 min · runs in this page
Model representation
Implement f(x) = wx + b for the house data and find parameters that fit by hand.
To let a computer choose w and b, we need one number that says how bad a choice is. Take each residual, square it so that misses above and below the line count the same and big misses count more, add them up, and divide by the number of examples so the number does not grow just because the dataset did. The extra factor of ½ is a convention: it cancels the 2 that appears when we differentiate the square, and it does not change which (w, b) is best.
J(w, b) = 1/(2m) · Σi=1..m ( fw,b(x(i)) − y(i) )²Mean squared error, halved. Smaller is better; zero means the line passes through every point.
Work one value by hand so the formula is real. With w = 200 and b = 100 the predictions for the five houses are 300, 400, 500, 600, 700, so the residuals are 0, −20, 0, −30, 0. The squares are 0, 400, 0, 900, 0, which sum to 1300. Divide by 2m = 10: J(200, 100) = 130. That number is the first checkpoint in Lab 1.
J is a function of the parameters, not of the data; the data is fixed. If you plotted J for every w with b held at 100 you would get a parabola, because J is quadratic in w. With both parameters free, J is a bowl in three dimensions. Linear regression's cost has exactly one lowest point, which is why the next lecture's algorithm is guaranteed to find it.
import numpy as np
x = np.array([1.0, 1.5, 2.0, 2.5, 3.0])
y = np.array([300, 420, 500, 630, 700])
def cost(w, b):
yhat = w * x + b
return ((yhat - y) ** 2).sum() / (2 * len(x))
print(cost(200, 100)) # 130.0
Deep dive · why the cost is a bowl
Derivation: J is a quadratic in (w, b)
Expand the square in J = (1/2m)·Σ(w·xᵢ + b − yᵢ)² and write avg(·) for an average over the m examples:
J(w, b) = ½·[ w²·avg(x²) + 2wb·avg(x) + b² − 2w·avg(xy) − 2b·avg(y) + avg(y²) ]Every term is at most second order in the parameters, so J is a quadratic surface.
For the five houses avg(x²) = 4.5, avg(x) = 2, avg(xy) = 1121, avg(y) = 510, avg(y²) = 280660, so
Check at (200, 100): 180000 + 80000 + 10000 − 448400 − 102000 + 280660 = 260, and half of that is 130, matching the hand calculation in the lecture.
Derivation: the bowl has one bottom
The curvature of J is its matrix of second derivatives, the Hessian. From the expanded form, ∂²J/∂w² = avg(x²) = 4.5, ∂²J/∂b² = 1 and ∂²J/∂w∂b = avg(x) = 2. In general, with a column of ones appended to X to carry b, the Hessian is H = XᵀX/m. For any direction v,
vᵀHv = vᵀXᵀXv / m = ‖Xv‖² / m ≥ 0H is positive semidefinite, so J curves upward in every direction: it is convex.
Here det H = 4.5·1 − 2·2 = 0.5 > 0, so H is positive definite and the minimum is unique. Its eigenvalues are 0.0925 and 5.4075. Their ratio is 58.5, so the elliptical contours of J are √58.5 ≈ 7.6 times longer in one direction than the other. The bowl is a stretched valley, a fact “Learning rate and convergence” uses to explain the learning-rate limit.
Why squares and not something else
If each price is the line plus Gaussian noise with spread σ, the probability density of seeing yᵢ is proportional to exp(−(yᵢ − ŷᵢ)² / 2σ²). Taking −log and summing over houses gives Σ(yᵢ − ŷᵢ)² / 2σ² plus a constant. Maximizing the likelihood of the data is exactly minimizing squared error. “Log loss and the same old gradient descent” repeats this argument with a coin instead of a bell curve and gets log loss.
Common mistakes
Reading J as an error in dollars. J = 79 is half a mean of squared thousands of dollars. Fix: report RMSE = √(2J) = √158 ≈ 12.6, which is in $1000.
Dropping the 1/m. Symptom: the cost doubles when the dataset doubles and the learning rate that worked yesterday diverges today. Fix: always average.
Ignoring outliers. One house mispriced by 200 adds 200² / 10 = 4000 to J, fifty times the whole cost of the good fit. Fix: inspect the largest residuals before trusting the fit.
Thinking the ½ changes the answer. Multiplying a function by a positive constant moves no minimum. It only rescales the gradient, and so the effective learning rate.
Lecture 1.14 · 12 min read
Cost function intuition
To see what the cost measures, simplify the model to fw(x) = wx (set b = 0), so the cost depends on one number. Use a tiny training set of three points (1, 1), (2, 2), (3, 3).
w
Predictions
J(w)
1
1, 2, 3
0
0.5
0.5, 1, 1.5
(0.25 + 1 + 2.25) / 6 ≈ 0.58
0
0, 0, 0
(1 + 4 + 9) / 6 ≈ 2.33
−0.5
−0.5, −1, −1.5
(2.25 + 9 + 20.25) / 6 = 5.25
Each value of w is one line on the left-hand plot (x versus y) and one point on the right-hand plot (w versus J). The line that fits best corresponds to the lowest point of J. Learning means finding that w.
import numpy as np
x = np.array([1.0, 2.0, 3.0]); y = np.array([1.0, 2.0, 3.0])
def J(w): return ((w * x - y) ** 2).sum() / (2 * len(x))
for w in [-0.5, 0, 0.5, 1.0, 1.5, 2.0]:
print(f"w = {w:5.1f} J = {J(w):.3f}")
Lecture 1.15 · 8 min read
Visualizing the cost function
With both w and b, the cost J(w, b) is a surface over the (w, b) plane, shaped like a bowl for linear regression with squared error. Two pictures show it. A 3-D surface plot shows the height of the bowl. A contour plot slices the bowl at constant heights and draws the slices from above, like a topographic map: every point on one ellipse has the same cost.
The ellipses are long and thin because w and b affect the predictions on different scales; the center of the smallest ellipse is the minimum, J = 79 at w = 202, b = 106 for the five houses.
Lecture 1.16 · 6 min read
Visualization examples
Pick points on the contour plot and draw the corresponding lines through the data. A point far from the center, such as w = 0, b = 500, is a flat line at 500: it misses the small and large houses badly and sits on a high-cost ellipse. A point closer in, w = 150, b = 200, tilts the right way but still misses. The center, w = 202, b = 106, is the line that passes closest to all five houses.
Searching the grid by hand works for two parameters but not for thousands. Gradient descent, next module, finds the bottom automatically.
Optional lab · about 20 min · runs in this page
Cost function
Write the squared-error cost and explore how it changes with w.
Step 1compute_cost
import numpy as np
x_train = np.array([1.0, 1.5, 2.0, 2.5, 3.0]) # size, 1000 sq ft
y_train = np.array([300.0, 420.0, 500.0, 630.0, 700.0]) # price, $1000
def compute_cost(x, y, w, b):
m = x.shape[0]
return ((w * x + b - y) ** 2).sum() / (2 * m)
print("J(200, 100) =", compute_cost(x_train, y_train, 200, 100))
print("J(202, 106) =", compute_cost(x_train, y_train, 202, 106))
Step 2Cost as a function of w (b fixed at 106)
import matplotlib.pyplot as plt
ws = np.linspace(100, 300, 101)
plt.plot(ws, [compute_cost(x_train, y_train, w, 106) for w in ws])
plt.axvline(202, ls="--", c="gray"); plt.xlabel("w"); plt.ylabel("J"); plt.title("cost with b = 106"); plt.show()
Module 5
Practice quiz: Regression model
Practice quiz · 5 questions
Regression model
Module 6
Train the model with gradient descent
Lecture 1.17 · 11 min read
Gradient descent
Imagine standing on the cost bowl at the point (w, b) in fog. You cannot see the bottom, but you can feel which way is downhill under your feet. Step a little that way, feel again, step again. That is gradient descent, and it is the algorithm behind nearly all of modern machine learning, including every neural network in Courses 2 and 4.
"Which way is downhill" is the derivative. For a function of several parameters, the partial derivative ∂J/∂w is the slope of J in the w direction with b held fixed. The vector of all partial derivatives is the gradient, and it points uphill; we move against it. The learning rate α is the step size.
repeat: w ← w − α · ∂J/∂w b ← b − α · ∂J/∂bCompute both derivatives from the current (w, b), then update both. Updating w first and using the new w to compute ∂J/∂b is a different, worse algorithm.
For our cost the derivatives have a clean form. Differentiate the square, the ½ cancels the 2, and the chain rule brings out x for the w derivative and 1 for the b derivative:
Both are averages of the residual, one weighted by x. If the line predicts too high on average, ∂J/∂b is positive and the update lowers b. If it predicts too high especially on large houses, ∂J/∂w is positive and the update lowers w. The algorithm is doing what you would do by hand, in the direction that reduces the cost fastest.
def gradients(w, b):
err = w * x + b - y # residuals, shape (m,)
dw = (err * x).mean()
db = err.mean()
return dw, db
w, b, alpha = 0.0, 0.0, 0.01
for step in range(10000):
dw, db = gradients(w, b)
w, b = w - alpha * dw, b - alpha * db # simultaneous update
print(round(w, 1), round(b, 1), round(cost(w, b), 1)) # 202.0 106.0 79.0
This version uses every example to compute each gradient, which is called batch gradient descent. With millions of examples you compute the gradient on a small random batch instead; that is stochastic gradient descent, and you will meet it in Course 2.
Deep dive · deriving the two partial derivatives
Derivation
Name the residual of example i: eᵢ = w·xᵢ + b − yᵢ. Then J = (1/2m)·Σ eᵢ². Differentiate one step at a time.
The derivative of a sum is the sum of derivatives, and 1/2m is a constant: ∂J/∂w = (1/2m)·Σ ∂(eᵢ²)/∂w.
Chain rule on the square: ∂(eᵢ²)/∂w = 2eᵢ·∂eᵢ/∂w.
eᵢ is linear in w with coefficient xᵢ, so ∂eᵢ/∂w = xᵢ. It is linear in b with coefficient 1, so ∂eᵢ/∂b = 1.
Combine: ∂J/∂w = (1/2m)·Σ 2eᵢxᵢ = (1/m)·Σ eᵢxᵢ, and ∂J/∂b = (1/m)·Σ eᵢ. The 2 from the square cancels the ½.
Worked example by hand
Start at w = b = 0, α = 0.01. Every prediction is 0, so eᵢ = −yᵢ.
Update: w = 0 − 0.01·(−1121) = 11.21 and b = 0 − 0.01·(−510) = 5.10.
J falls from 140330 to 125572.7. The next step gives (21.81, 9.92) and J = 112368.2.
At the minimum both derivatives must be zero. With w = 202, b = 106 the residuals are 8, −11, 10, −19, 12. Σeᵢ = 0, and Σeᵢxᵢ = 8 − 16.5 + 20 − 47.5 + 36 = 0. Gradient descent stops moving there because there is nothing left to push it.
Code walkthrough: the finite-difference check
eps = 1e-6
num_dw = (cost(w + eps, b) - cost(w - eps, b)) / (2 * eps) # slope of J along w
num_db = (cost(w, b + eps) - cost(w, b - eps)) / (2 * eps)
# at (0, 0) both agree with the formulas: -1121.0 and -510.0
The centred difference has error proportional to eps², so it matches an exact derivative to about 10 digits on a quadratic. Use it every time you write a gradient by hand.
Common mistakes
Sequential update. Updating w first and computing ∂J/∂b with the new w gives b = 4.876 instead of 5.10 on the first step above. Symptom: results that differ slightly from everyone else's. Fix: compute both gradients, then assign both, as in w, b = w - a*dw, b - a*db.
Sign error. Writing eᵢ = yᵢ − ŷᵢ and keeping the minus in the update moves uphill. Symptom: J grows from the first step for every α. Fix: residual is prediction minus target, update subtracts.
Sum instead of mean. Symptom: a gradient m times larger, so α = 0.1 behaves like α = 0.5 on five houses and diverges. Fix: divide by m, or knowingly scale α down.
Forgetting the xᵢ in ∂J/∂w. Symptom: w and b receive the same update and the gradient check fails on w only. Fix: run the check.
Lecture 1.18 · 9 min read
Implementing gradient descent
Gradient descent repeats two updates until the parameters stop changing much:
w ← w − α ∂J/∂w, b ← b − α ∂J/∂bα is the learning rate. The equals sign here means assignment, as in code, not a mathematical truth.
The two updates must be simultaneous: compute both new values from the current (w, b), then assign both. If you update w first and then use the new w to compute b's derivative, you are running a slightly different algorithm. It often still works, but it is not gradient descent, and bugs of this kind are hard to spot.
def step_correct(w, b, dJ_dw, dJ_db, alpha):
tmp_w = w - alpha * dJ_dw(w, b)
tmp_b = b - alpha * dJ_db(w, b)
return tmp_w, tmp_b # assign both at the end
dJ_dw = lambda w, b: 2 * (w + b - 3) # toy cost J = (w + b - 3)^2
dJ_db = lambda w, b: 2 * (w + b - 3)
print("one simultaneous step from (0, 0):", step_correct(0.0, 0.0, dJ_dw, dJ_db, 0.1))
Lecture 1.19 · 7 min read
Gradient descent intuition
Look at one parameter. The derivative ∂J/∂w is the slope of the cost curve at the current w. If the slope is positive, the cost rises to the right, so w − α·(positive) moves w left, downhill. If the slope is negative, the update moves w right, also downhill. Either way the minus sign sends w toward lower cost.
J = lambda w: (w - 3) ** 2
dJ = lambda w: 2 * (w - 3)
for w in (6.0, 0.0):
new = w - 0.1 * dJ(w)
print(f"w = {w}: slope {dJ(w):+.1f} -> new w = {new:.2f}, cost {J(w):.2f} -> {J(new):.2f}")
Lecture 1.20 · 8 min read · demo
Learning rate and convergence
The learning rate is the only setting in gradient descent, and it decides everything. Too small and you creep toward the minimum for thousands of steps. Too large and each step overshoots the bottom, lands higher on the other side, and the cost grows instead of shrinking. The demo below runs gradient descent on a one-parameter bowl. Try α = 0.3, then 0.9, then 1.05.
Gradient descent on a bowlJ(w) = (w − 3)² + 1
w 8.00J(w) 26.00dJ/dw 10.00steps 0
Two things to notice. First, the steps get smaller as you approach the minimum even though α never changed, because the gradient itself shrinks near the bottom. Gradient descent slows down on its own. Second, for this bowl any α below 1.0 converges and any α above 1.0 diverges; the threshold depends on the curvature of the cost, which is why you cannot know a good learning rate in advance for a new problem.
The practical procedure: plot the cost against the iteration number. It should decrease on every step. If it ever increases, the learning rate is too large. Try values roughly three times apart, 0.001, 0.003, 0.01, 0.03, 0.1, and take the largest one that still decreases smoothly. Declare convergence when the cost changes by less than a small ε, say 0.001, between iterations.
Deep dive · the stability bound α < 2/λmax
Derivation in one dimension
For the demo's bowl J(w) = (w − 3)² + 1, dJ/dw = 2(w − 3). One step gives w − 3 ← (w − 3) − α·2(w − 3) = (1 − 2α)(w − 3). The distance to the minimum is multiplied by the same factor (1 − 2α) every step, so it shrinks only if |1 − 2α| < 1, that is 0 < α < 1. The number 2 is the curvature d²J/dw².
α
factor 1 − 2α
w after steps 1, 2, 3 (from 8)
J after steps 1, 2, 3
0.3
0.4
5.0, 3.8, 3.32
5.0, 1.64, 1.1024
0.9
−0.8
−1.0, 6.2, 0.44
17.0, 11.24, 7.5536
1.05
−1.1
−2.5, 9.05, −3.655
31.25, 37.6025, 45.289
A negative factor means the iterate jumps to the other side of the minimum each step. At −0.8 the jumps shrink; at −1.1 they grow.
Derivation for linear regression
Any quadratic cost with Hessian H and minimum θ* has gradient H(θ − θ*). One step gives θ − θ* ← (I − αH)(θ − θ*). Write θ − θ* in the eigenvectors of H. Each component is multiplied by its own factor (1 − αλₖ), where λₖ is the matching eigenvalue. Every component shrinks only if |1 − αλₖ| < 1 for all k:
0 < α < 2 / λmax, H = XᵀX/m (with a ones column)The steepest direction sets the learning-rate limit.
Worked example: the five houses
H = [[4.5, 2], [2, 1]] has eigenvalues 0.0925 and 5.4075 (“The cost function” deep dive), so α must be below 2 / 5.4075 = 0.3699. Run 200 iterations from (0, 0):
α = 0.36: factor in the steep direction 1 − 0.36·5.4075 = −0.947. J = 79.00005, essentially converged.
α = 0.369: factor −0.9954. Still stable, but J = 22089 after 200 steps because the oscillation barely decays.
α = 0.37: factor −1.0008. J = 192300 and climbing.
The flat direction sets the speed. At α = 0.01 its factor is 1 − 0.01·0.0925 = 0.99908, so shrinking that component by a factor of 10⁶ takes ln(10⁻⁶)/ln(0.99908) ≈ 14,900 steps, while the steep component (factor 0.946) is gone in a few hundred. The best fixed step, 2/(λmin + λmax) = 0.364, still leaves a factor of 0.966 per step, set by the ratio λmax/λmin = 58.5. “Feature scaling and checking convergence” shows how scaling shrinks that ratio.
Common mistakes
Lowering α when the cost falls too slowly. Symptom: training gets even slower. Fix: if the curve decreases smoothly, try a larger α; lower it only when the cost rises or oscillates.
Using an absolute tolerance across problems. ε = 0.001 means something different when J is 79 and when J is 10⁸. Fix: test the relative change |ΔJ|/J, or the gradient norm.
Reusing α across datasets. λmax depends on the scale of the features. Symptom: a learning rate that worked on x in thousands of sq ft diverges on raw sq ft. Fix: rescale features or search α again.
Calling a near-limit run converged. At α = 0.369 the cost decreases every step yet is still 280 times the minimum after 200 steps. Fix: look at the value, not only the direction, of the curve.
Lecture 1.21 · 6 min read
Gradient descent for linear regression
Plugging the linear model into the squared-error cost and differentiating gives the two derivatives used in every linear regression implementation:
∂J/∂w = (1/m) Σ (fw,b(x(i)) − y(i)) x(i), ∂J/∂b = (1/m) Σ (fw,b(x(i)) − y(i))The 2 from differentiating the square cancels the 2 in 1/2m, which is why the cost is defined with 1/2m.
The squared-error cost of linear regression is a convex function: a single bowl with no local minima other than the global one. So gradient descent with a suitable learning rate always reaches the best possible line, wherever it starts.
import numpy as np
x_train = np.array([1.0, 1.5, 2.0, 2.5, 3.0]) # size, 1000 sq ft
y_train = np.array([300.0, 420.0, 500.0, 630.0, 700.0]) # price, $1000
def gradients(w, b):
err = w * x_train + b - y_train
return (err * x_train).mean(), err.mean()
print("gradients at (0, 0):", [float(v) for v in gradients(0, 0)])
print("gradients at the minimum (202, 106):", np.round(gradients(202, 106), 10))
Lecture 1.22 · 5 min read
Running gradient descent
Start at w = b = 0 and repeat the updates. On the contour plot the parameters take a path from the outer ellipses toward the center; on the data plot the line swings up and rotates until it fits. Each step uses all m training examples, which is why this version is called batch gradient descent. Later courses use mini-batches, small random subsets, for very large datasets.
import numpy as np
x_train = np.array([1.0, 1.5, 2.0, 2.5, 3.0]) # size, 1000 sq ft
y_train = np.array([300.0, 420.0, 500.0, 630.0, 700.0]) # price, $1000
w, b, alpha = 0.0, 0.0, 0.1
for it in range(1, 3001):
err = w * x_train + b - y_train
w, b = w - alpha * (err * x_train).mean(), b - alpha * err.mean()
if it in (1, 10, 100, 1000, 3000):
J = ((w * x_train + b - y_train) ** 2).mean() / 2
print(f"iteration {it:4d}: w = {w:7.2f}, b = {b:7.2f}, J = {J:9.2f}")
print("price of a 1,200 sq ft house:", round(w * 1.2 + b, 1))
Optional lab · about 25 min · runs in this page
Gradient descent
Implement gradient descent for linear regression, watch the cost fall, and see what a too-large learning rate does.
Step 1Gradients
import numpy as np
x_train = np.array([1.0, 1.5, 2.0, 2.5, 3.0]) # size, 1000 sq ft
y_train = np.array([300.0, 420.0, 500.0, 630.0, 700.0]) # price, $1000
def compute_gradient(x, y, w, b):
err = w * x + b - y
return (err * x).mean(), err.mean()
print("gradient at (0, 0):", [float(v) for v in compute_gradient(x_train, y_train, 0, 0)])
Step 2Gradient descent
def gradient_descent(x, y, w, b, alpha, iters):
J_hist = []
for i in range(iters):
dw, db = compute_gradient(x, y, w, b)
w, b = w - alpha * dw, b - alpha * db
J_hist.append(((w * x + b - y) ** 2).mean() / 2)
return w, b, J_hist
w_final, b_final, J_hist = gradient_descent(x_train, y_train, 0, 0, 0.1, 5000)
print(f"w = {w_final:.2f}, b = {b_final:.2f}, final J = {J_hist[-1]:.2f}")
Open a fresh notebook. You will implement the cost, the gradients and the training loop for the five-house dataset, then use the model to price a house. Write each function yourself before comparing with the lecture.
Step 1Data and a first plot
import numpy as np
import matplotlib.pyplot as plt
x = np.array([1.0, 1.5, 2.0, 2.5, 3.0]) # 1000 sq ft
y = np.array([300, 420, 500, 630, 700]) # $1000
plt.scatter(x, y); plt.xlabel("size (1000 sq ft)"); plt.ylabel("price ($1000)"); plt.show()
Step 2Cost function
Write cost(w, b) returning J as defined in “The cost function”. Test it: cost(0, 0) should equal the mean of y² divided by 2.
Checkpoint 1
What does your cost(200, 100) return?
Step 3Gradients and training loop
Write gradients(w, b) returning (∂J/∂w, ∂J/∂b), then run 10,000 iterations of gradient descent from w = b = 0 with α = 0.01, recording the cost every 100 iterations. Plot the cost history on a log scale and confirm it only decreases.
Checkpoint 2
What value of w do you get after 10,000 iterations (nearest whole number)?
Step 4Predict and break it
Use the trained line to price a 1,200 sq ft house (you should get about 348). Then rerun training with α = 0.9 and look at the cost history. Describe in one sentence what happened and why. Finally, implement a convergence test that stops when the cost changes by less than 0.001 and report how many iterations it took.
Checkpoint 3
Predicted price for a 1,200 sq ft house, in $1000?
Week 2 · Regression with multiple input variables
Regression with multiple input variables
Extend linear regression to many features, make it fast with vectorization, and improve training with feature scaling, feature engineering and polynomial regression.
Video lectures · Week 2
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
Multiple Regression, Clearly ExplainedStatQuest with Josh Starmer · YouTube ↗Vectors · Essence of linear algebra, chapter 13Blue1Brown · YouTube ↗
Module 1
Multiple linear regression
Lecture 2.1 · 7 min read
Multiple linear regression
Suppose each house comes with four numbers: size in square feet, bedrooms, floors and age in years. Write them as a vector x = (x₁, x₂, x₃, x₄). The model now has one weight per feature plus the intercept, and the prediction is a weighted sum.
fw,b(x) = w₁x₁ + w₂x₂ + w₃x₃ + w₄x₄ + b = w · x + bw · x is the dot product. With n features, w and x both have n entries; b is still a single number.
Each weight has an interpretation in the units of its feature: w₁ = 0.1 means each extra square foot adds $100 when other features are held fixed; w₄ = −2 means each year of age removes $2,000. Interpretations like that are the reason linear models stay in use next to far more powerful ones.
The cost and the gradient descent update are unchanged in form. The only difference is that there are now n + 1 partial derivatives to compute each step, one per weight plus the intercept, and the w derivative for feature j uses xj:
Written with loops this is a loop over features inside a loop over examples inside a loop over iterations. The next lecture removes the inner two.
Deep dive · n partial derivatives and what a weight means
Derivation
With n features, eᵢ = w₁xᵢ₁ + … + wₙxᵢₙ + b − yᵢ. The residual is linear in each weight, and the coefficient of wⱼ is xᵢⱼ, so ∂eᵢ/∂wⱼ = xᵢⱼ. Every other step is the one-feature derivation from “Gradient descent”:
∂J/∂wⱼ = (1/2m)·Σᵢ 2eᵢ·xᵢⱼ = (1/m)·Σᵢ eᵢ·xᵢⱼ ∂J/∂b = (1/m)·Σᵢ eᵢOne derivative per weight, each weighted by its own feature column.
Worked example: the gradient at zero
For the five houses with sqft, bedrooms, floors and age, start at w = 0, b = 0. Then eᵢ = −yᵢ, and ∂J/∂wⱼ = −avg(xⱼ·y). For sqft that is −(2104·460 + 1416·232 + 1534·315 + 852·178 + 1200·250)/5 = −2231218/5 = −446243.6. The four weight derivatives are −446243.6, −1009.4, −396.4 and −10167.6, and ∂J/∂b = −287. The sqft component is 442 times the bedrooms component only because square feet are big numbers. “Feature scaling and checking convergence” is about that imbalance.
What "holding the others fixed" really means
A weight is the change in prediction when its feature rises by one unit and every other feature stays the same. When features move together, that is a situation the data rarely shows, and the weight can look absurd. The exact least-squares fit on these five houses is
An extra bedroom "costs" $158k. The reason: sqft and bedrooms have correlation 0.957 here, so the data cannot tell their effects apart, and the fit trades one against the other. There is a second problem. Five houses and five parameters (four weights plus b) means five equations in five unknowns, so the plane passes exactly through every house and J = 0. A perfect fit with nonsense weights is the signature of too many parameters for the data. The same model prices a 1,650 sq ft, 3-bedroom, 1-floor, 40-year-old house at $504k, more than the 2,104 sq ft house that sold for $460k.
Common mistakes
Interpreting weights of correlated features one by one. Symptom: signs that contradict common sense. Fix: interpret groups of correlated features together, or drop one of them.
Fitting n + 1 ≥ m parameters. Symptom: training cost exactly 0. Fix: get more examples or use fewer features or regularization (“Regularization”).
Mixing up i and j. Symptom: summing over features instead of examples, giving a gradient of the wrong length. Fix: i runs over the m rows, j over the n columns; the derivative for wⱼ sums over i.
Updating inside the feature loop. Symptom: later weights see already-updated earlier weights. Fix: compute all n + 1 derivatives first, then update.
Lecture 2.2 · 8 min read
Vectorization
Stack the m training examples as rows of a matrix X with shape (m, n). Then every prediction at once is the matrix–vector product X·w plus b, and every residual at once is that minus y. The gradient for all weights at once is Xᵀ times the residual vector, divided by m. Four lines of NumPy replace three nested loops, and they run on vectorized CPU instructions or a GPU without any change to your code.
def predict(X, w, b): # X: (m, n), w: (n,), b: scalar
return X @ w + b # (m,)
def cost(X, y, w, b):
err = predict(X, w, b) - y
return (err @ err) / (2 * len(y))
def gradients(X, y, w, b):
err = predict(X, w, b) - y # (m,)
dw = X.T @ err / len(y) # (n,) one derivative per weight
db = err.mean()
return dw, db
Check shapes before trusting any of it: X is (m, n), w is (n,), so X @ w is (m,); X.T is (n, m), err is (m,), so X.T @ err is (n,), matching w. Shape errors are the most common bug in this specialization, and reasoning about them out loud is the fastest way to find them.
The training loop does not change. It calls gradients and updates w as a whole vector: w = w - alpha * dw updates all n weights in one line, simultaneously by construction.
Deep dive · the gradient as a matrix product
Derivation
Collect the residuals in a vector e = Xw + b·1 − y of shape (m,), where 1 is a vector of m ones. The cost is J = (1/2m)·eᵀe. Component j of Xᵀe is Σᵢ xᵢⱼeᵢ, which is m times ∂J/∂wⱼ from “Multiple linear regression”. So all n derivatives at once are
∇wJ = Xᵀe / m ∂J/∂b = 1ᵀe / m = mean(e)Row j of Xᵀ is feature column j; its dot product with e is the sum over examples.
Bias column trick. Prepend a column of ones to X to get X̃ of shape (m, n + 1), and put b first in θ = (b, w₁, …, wₙ). Then ŷ = X̃θ, and the whole gradient is X̃ᵀe/m. The ones column turns b into an ordinary weight whose feature is always 1, which is why the b formula is the w formula with xᵢⱼ = 1.
Shapes table
Expression
Shapes
Result
X @ w
(m, n) @ (n,)
(m,)
X @ w + b - y
(m,) + scalar − (m,)
(m,)
X.T @ err
(n, m) @ (m,)
(n,)
err @ err
(m,) @ (m,)
scalar
Worked example
On the five-house, four-feature data at w = 0, b = 0, e = −y, so Xᵀe/m = −Xᵀy/5. The first entry is the dot product of the sqft column with the prices, −2231218/5 = −446243.6, the same number you get from the per-feature sum in “Multiple linear regression”. One matrix product does the four sums.
Code walkthrough: the broadcasting trap
y_col = y.reshape(-1, 1) # shape (5, 1), as pandas .values[:, [k]] produces
err = X @ w + b - y_col # (5,) - (5, 1) broadcasts to (5, 5)
print(err.shape) # (5, 5): 25 "residuals", every prediction minus every target
cost = (err ** 2).sum() / (2 * 5) # runs without error and returns the wrong number
Nothing crashes. The cost is simply wrong, and so is every gradient. Add assert err.shape == y.shape or flatten targets with y.ravel().
Common mistakes
(m, 1) targets against (m,) predictions. Symptom: cost far too large, gradients of shape (n, m). Fix: keep y one-dimensional.
X @ err instead of X.T @ err. Symptom: a shape error when m ≠ n, and a silent wrong answer when m = n, as with five houses and five columns in X̃. Fix: say the shapes out loud.
In-place updates on a shared array.w -= alpha * dw inside a function modifies the caller's array too. Symptom: a second training run starts from the first run's result. Fix: write w = w - alpha * dw or pass w.copy().
* where @ was meant.X * w broadcasts to an (m, n) array of products. Symptom: predictions of shape (m, n). Fix: @ for matrix products, * for elementwise.
Lecture 2.3 · 6 min read
Vectorization part 2
Why is vectorized code so much faster? A Python loop over 16 features does 16 separate multiplications and additions, one after another, each with interpreter overhead. np.dot(w, x) hands the whole job to optimized compiled code that uses parallel hardware: modern CPUs multiply several numbers in one instruction, and GPUs thousands.
The same applies to the gradient descent update. With 16 weights, the loop for j in range(16): w[j] = w[j] - 0.1 * d[j] becomes one line, w = w - 0.1 * d, which updates all weights at once.
import numpy as np, time
rng = np.random.default_rng(0)
w = rng.normal(size=1_000_000); d = rng.normal(size=1_000_000)
t0 = time.perf_counter()
w_loop = w.copy()
for j in range(len(w_loop)):
w_loop[j] = w_loop[j] - 0.1 * d[j]
t1 = time.perf_counter()
w_vec = w - 0.1 * d
t2 = time.perf_counter()
print("same result:", np.allclose(w_loop, w_vec))
print(f"loop {1000*(t1-t0):.0f} ms, vectorized {1000*(t2-t1):.1f} ms")
Optional lab · about 25 min · runs in this page
Python, NumPy and vectorization
The NumPy operations used throughout the specialization: creating arrays, indexing, slicing, element-wise operations and dot products.
Step 1Vectors
import numpy as np
a = np.arange(10); b = np.zeros(4); c = np.random.default_rng(0).random(4)
print(a, a.shape, a.dtype)
print("a[2] =", a[2], " a[-1] =", a[-1], " a[2:7:2] =", a[2:7:2])
print("sum", a.sum(), " mean", a.mean(), " a*2 =", a * 2)
Step 2Dot product, loop versus np.dot
def my_dot(a, b):
total = 0.0
for i in range(a.shape[0]):
total += a[i] * b[i]
return total
x = np.array([1., 2., 3., 4.]); w = np.array([-1., 4., 3., 2.])
print("loop:", my_dot(x, w), " np.dot:", np.dot(x, w), " @:", x @ w)
With n features the model is f(x) = w · x + b, where w and x are vectors. The update rule keeps exactly the same form; there is now one derivative per weight:
wj ← wj − α (1/m) Σ (f(x(i)) − y(i)) xj(i) for j = 1 … n, b ← b − α (1/m) Σ (f(x(i)) − y(i))Vectorized: w ← w − α Xᵀ(Xw + b − y) / m.
An alternative for linear regression only is the normal equation, which solves for w and b directly without iterations. Libraries may use it (or a related least-squares solver) behind the scenes. It does not generalize to other models and becomes slow with very many features, so gradient descent remains the method to know.
import numpy as np
X = np.array([[2104, 5, 1, 45], [1416, 3, 2, 40], [852, 2, 1, 35]], dtype=float)
y = np.array([460.0, 232.0, 178.0])
Xs = (X - X.mean(0)) / X.std(0) # scale features first (next module)
w, b = np.zeros(4), 0.0
for _ in range(2000):
err = Xs @ w + b - y
w, b = w - 0.1 * Xs.T @ err / len(y), b - 0.1 * err.mean()
print("predictions:", (Xs @ w + b).round(1), " targets:", y)
Optional lab · about 25 min · runs in this page
Multiple linear regression
Vectorized cost, gradient and gradient descent for a model with four features.
def compute_cost(X, y, w, b):
return ((X @ w + b - y) ** 2).mean() / 2
def compute_gradient(X, y, w, b):
err = X @ w + b - y
return X.T @ err / len(y), err.mean()
print("cost at w_init:", round(compute_cost(X_train, y_train, w_init, b_init), 4))
dw, db = compute_gradient(X_train, y_train, np.zeros(4), 0.0)
print("gradient at zeros:", dw.round(1), round(db, 1))
Step 3Gradient descent without scaling
w, b = np.zeros(4), 0.0
for i in range(1000):
dw, db = compute_gradient(X_train, y_train, w, b)
w, b = w - 5e-7 * dw, b - 5e-7 * db
print("w:", w.round(3), " b:", round(b, 4))
print("predictions:", (X_train @ w + b).round(1), " targets:", y_train)
Module 2
Practice quiz: Multiple linear regression
Practice quiz · 5 questions
Multiple linear regression
Module 3
Gradient descent in practice
Lecture 2.5 · 9 min read
Feature scaling and checking convergence
Size runs from 800 to 2,500 square feet; bedrooms run from 1 to 5. A change of one unit in w₁ moves predictions by thousands; the same change in w₂ moves them by single digits. The cost bowl is therefore stretched into a long, narrow valley, and gradient descent bounces between the steep walls while making slow progress along the floor. A learning rate small enough to be stable in the steep direction is far too small in the flat one.
The fix is to put every feature on a similar scale before training. The most common choice is z-score normalization: subtract the mean of the feature and divide by its standard deviation, so each feature has mean 0 and standard deviation 1.
xj ← ( xj − μj ) / σjCompute μ and σ on the training set only, and apply the same values to every new example at prediction time.
mu, sigma = X.mean(axis=0), X.std(axis=0)
X_norm = (X - mu) / sigma # broadcasting: one mu and sigma per column
house = np.array([2104, 5, 1, 45])
house_norm = (house - mu) / sigma # same mu, sigma, never recomputed
After scaling, a learning rate near 0.1 typically works and training converges orders of magnitude faster. A tiny dataset with correlated features can still need thousands of iterations, because scaling fixes the units but not the correlation. Two cautions: scaling changes the weights' values (a weight now says how much the prediction moves per standard deviation of the feature, not per unit), and forgetting to scale new examples with the stored μ and σ is a classic production bug that produces confident, wrong predictions.
Deep dive · what z-scoring does to the condition number
Intuition
From “Learning rate and convergence”, gradient descent needs α < 2/λmax to be stable, and its slowest component shrinks by (1 − αλmin) per step. The ratio κ = λmax/λmin of the Hessian H = X̃ᵀX̃/m, the condition number, therefore decides how many steps you need: roughly κ steps for each factor of e. Scaling is a way of making κ small.
Worked example: the five houses, four features
The diagonal of H holds avg(xⱼ²). For sqft that is 2,190,186; for floors (1, 2, 2, 1, 1) it is 2.2. That spread alone guarantees a huge κ.
Eigenvalues of H
κ
Largest stable α
Raw features
0.0060, 0.0596, 0.376, 84.3, 2.19 × 10⁶
3.65 × 10⁸
9.13 × 10⁻⁷
z-scored
0.00557, 0.622, 1.000, 1.057, 2.316
416
0.864
With raw features at the largest safe α, the slowest component moves by a factor of 1 − 9 × 10⁻⁷ · 0.006 ≈ 1 − 5.4 × 10⁻⁹ per step, so one factor of e takes about 185 million steps. That is why the lab's raw run at α = 10⁻⁷ barely moves. After z-scoring, α = 0.1 gives a slow factor of 1 − 0.1·0.00557, one factor of e per 1,794 steps, and the lab's 20,000 steps shrink the slowest component by e−11.1 ≈ 1.4 × 10⁻⁵.
Derivation: why scaling helps and where it stops
Centering decouples b. The off-diagonal entry of H between b and wⱼ is avg(xⱼ). After subtracting μⱼ it is 0, so b has its own eigenvalue of exactly 1 and its own update. That is why b converges to avg(y) = 287 in the lab.
Dividing by σⱼ equalizes the diagonal. After scaling, every avg(xⱼ²) = 1, and the off-diagonal entries become the correlations between features.
What is left is correlation. For two scaled features with correlation r, their 2×2 block of H has eigenvalues 1 + r and 1 − r. sqft and bedrooms have r = 0.957, which alone gives a ratio of 1.957/0.043 ≈ 45. With only five houses for four features the smallest eigenvalue is smaller still, 0.00557. Scaling cannot remove that; more data, fewer features, or regularization can.
Undoing the scaling
Since wⱼ·(xⱼ − μⱼ)/σⱼ = (wⱼ/σⱼ)·xⱼ − wⱼμⱼ/σⱼ, the raw-unit model has wraw,j = wⱼ/σⱼ and braw = b − Σⱼ wⱼμⱼ/σⱼ. For sqft, 252.69 / 412.77 = 0.6122 per square foot, the same as the normal equations give.
Common mistakes
Mixing ddof conventions. NumPy's std uses ddof = 0 (σ = 412.77 here), pandas' .std() uses ddof = 1 (461.49). The z-score of 2104 sq ft is 1.654 with one and 1.480 with the other. Fix: compute μ and σ once and store them.
Fitting the scaler on all data. Symptom: test error slightly optimistic, because test statistics leaked into training. Fix: fit on the training split, transform the rest.
A constant column. σ = 0 produces NaN everywhere. Fix: drop constant features, or divide by max(σ, tiny).
Scaling the new house with its own statistics. A single row has σ = 0 and μ equal to itself. Fix: always reuse the training μ and σ.
Lecture 2.6 · 7 min read
Feature scaling part 2
Three common ways to bring features to similar ranges:
Method
Formula
Result
Divide by the maximum
x / max(x)
0 to 1 for positive features
Mean normalization
(x − μ) / (max − min)
roughly −1 to 1, centered at 0
Z-score normalization
(x − μ) / σ
mean 0, standard deviation 1
Aim for features roughly in the range −1 to 1; anything from about −3 to 3 is fine, and 0 to 3 or −2 to 0.5 also need no rescaling. Rescale when a feature spans −100 to 100, or is tiny like −0.001 to 0.001, or huge like 98.6 to 105 degrees. When in doubt, scale: it rarely hurts.
Plot the cost J against the number of iterations: this is a learning curve. If gradient descent is working, J decreases after every single iteration. When the curve flattens, the algorithm has converged. The number of iterations needed varies enormously between problems, from 30 to 100,000, so look at the curve rather than guessing.
An automatic convergence test declares convergence when J decreases by less than a small ε, say 0.001, in one iteration. Choosing ε is itself tricky, so the plot is usually more informative.
import numpy as np
x_train = np.array([1.0, 1.5, 2.0, 2.5, 3.0]) # size, 1000 sq ft
y_train = np.array([300.0, 420.0, 500.0, 630.0, 700.0]) # price, $1000
w = b = 0.0; history = []
for it in range(100_000):
err = w * x_train + b - y_train
w, b = w - 0.1 * (err * x_train).mean(), b - 0.1 * err.mean()
history.append(((w * x_train + b - y_train) ** 2).mean() / 2)
if it > 0 and history[-2] - history[-1] < 1e-3:
print(f"converged after {it + 1} iterations, J = {history[-1]:.3f}")
break
print("J ever increased?", any(b2 > a2 for a2, b2 in zip(history, history[1:])))
Lecture 2.8 · 6 min read
Choosing the learning rate
If the cost goes up, or bounces up and down, the learning rate is too large, or there is a bug. A useful debugging check: with a very small α, J must decrease on every iteration. If it does not, there is a bug in the code, for example adding the gradient instead of subtracting it.
To choose α, try values on a roughly ×3 scale, such as 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1, run a few hundred iterations of each, and plot the learning curves. Pick the largest value that decreases J quickly and consistently, or one slightly smaller.
import numpy as np
x_train = np.array([1.0, 1.5, 2.0, 2.5, 3.0]) # size, 1000 sq ft
y_train = np.array([300.0, 420.0, 500.0, 630.0, 700.0]) # price, $1000
xs = (x_train - x_train.mean()) / x_train.std()
for alpha in [0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1.0, 1.5]:
w = b = 0.0
for _ in range(100):
err = w * xs + b - y_train
w, b = w - alpha * (err * xs).mean(), b - alpha * err.mean()
J = ((w * xs + b - y_train) ** 2).mean() / 2
print(f"alpha {alpha:<6} J after 100 iterations: {J:12.2f}")
Optional lab · about 25 min · runs in this page
Feature scaling and learning rate
See how z-score normalization lets gradient descent use a much larger learning rate and converge in far fewer iterations.
Step 1Data with very different ranges
import numpy as np
rng = np.random.default_rng(1)
size = rng.uniform(800, 3000, 100); beds = rng.integers(1, 6, 100); age = rng.uniform(0, 50, 100)
X = np.column_stack([size, beds, age]); y = 0.12 * size + 20 * beds - 1.5 * age + rng.normal(0, 10, 100)
print("feature ranges:", X.min(0).round(), "to", X.max(0).round())
def run(X_, alpha, iters):
w, b = np.zeros(3), 0.0
for _ in range(iters):
err = X_ @ w + b - y
w, b = w - alpha * X_.T @ err / len(y), b - alpha * err.mean()
return ((X_ @ w + b - y) ** 2).mean() / 2
print("raw features, alpha 1e-7, 1000 iters: J =", round(run(X, 1e-7, 1000), 1))
print("scaled features, alpha 0.1, 1000 iters: J =", round(run(Xn, 0.1, 1000), 1))
x_new = np.array([1500, 3, 20]); print("normalize new inputs with the training mu and sigma:", ((x_new - mu) / sigma).round(2))
Lecture 2.9 · 7 min read
Feature engineering and polynomial regression
A linear model is linear in its parameters, not necessarily in the raw inputs. If you have a lot's width and depth, the model cannot discover that area matters; but you can hand it a new feature x₃ = width × depth, and the model is still linear in w. Designing features from domain knowledge is feature engineering, and for small and medium datasets it matters more than the choice of algorithm.
The same trick fits curves. Add powers of a feature, x, x², x³, as separate columns, and the linear model becomes a polynomial in x. Square roots, logarithms and interaction terms between features work the same way. Scaling becomes essential here: if x ranges to 1,000, x³ ranges to a billion.
X_poly = np.c_[x, x**2, x**3] # three columns from one feature
mu, sigma = X_poly.mean(0), X_poly.std(0)
X_poly = (X_poly - mu) / sigma # now all three columns are comparable
After training, look at the weights. A weight near zero after scaling hints that the term is not needed, but only if training has converged; powers of one feature are highly correlated, so check with held-out error rather than by reading weights. That inspection is a crude form of the model-selection tools you will learn properly in Course 2; the honest version holds out data and measures error on it, which is where Week 3's overfitting lecture goes.
Deep dive · polynomial features are badly conditioned
Intuition
Adding x², x³ keeps the model linear in w, so everything from Lectures 2.1 to 2.3 applies. The catch is that powers of a positive variable look alike. Over the range of the data, x, x² and x³ all rise together, so the columns are almost parallel, and “Feature scaling and checking convergence” showed that correlated columns make κ large even after scaling.
Worked example: 100 houses
In houses_100.csv, sqft runs from 809 to 3,139, so x³ reaches 3.09 × 10¹⁰. The correlations are 0.988 between x and x², 0.992 between x² and x³ and 0.961 between x and x³. After z-scoring, the eigenvalues of XᵀX/m are 0.000153, 0.0392 and 2.961, so κ ≈ 19,400.
The lab trains for 5,000 steps at α = 0.1. The slowest component shrinks by (1 − 0.1·0.000153)5000 ≈ 0.93, so it is barely touched. The lab's weights come out as (77.0, 62.6, −32.7) with J = 733.2. The exact least-squares weights on the same scaled columns are (−95.7, 434.1, −235.1) with J = 717.2. Reading "the x³ weight is small, so the cubic term is not needed" from an unconverged run would be reading the starting point, not the data.
A cheap fix: center before taking powers. With c = x − x̄, the columns c, c², c³ have correlations −0.175, −0.258 and 0.914, and after z-scoring κ drops to 24.6. The model is the same polynomial; only the basis changed.
Worked example by hand: degree versus fit
On the five houses, training J falls as the degree rises: 79 (line), 61.14 (quadratic), 57.14 (cubic) and 0 (quartic, five coefficients through five points). The quartic is ŷ = −133.3x⁴ + 1053.3x³ − 2986.7x² + 3786.7x − 1420. Its coefficients are thousands, with alternating signs that cancel at the five data points and nowhere else. Huge, cancelling weights are the fingerprint of overfitting that “Regularization” attacks with regularization.
Common mistakes
Choosing the degree by training cost. Training cost can only fall as you add columns. Fix: compare degrees on held-out data (“Overfitting” deep dive does this for the five houses).
Interpreting weights from an unconverged run. Symptom: weights that change a lot when you double the iterations. Fix: compare against np.linalg.lstsq, or train until the gradient norm is tiny.
Powering raw large numbers. Symptom: overflow warnings, or float64 losing digits when x³ is 10¹⁰ next to x. Fix: rescale x (to thousands, or centered) before powering, then z-score.
Extrapolating a polynomial. A cubic goes to ±∞ outside the data. Symptom: absurd prices for a house slightly bigger than any in training. Fix: clip inputs to the training range or prefer low degrees.
Lecture 2.10 · 5 min read
Polynomial regression
Feature engineering lets a linear model fit curves. If prices rise less steeply for very large houses, create new features from size: x, x², x³, or √x, and fit a linear model to them. The model is still linear in its parameters, so the same gradient descent applies.
Feature scaling becomes essential: if size runs from 1 to 1,000, then x² runs to a million and x³ to a billion. Without scaling, one learning rate cannot suit all three weights.
import numpy as np
x = np.arange(0, 20, 1.0); y = 1 + x ** 2
X = np.column_stack([x, x ** 2, x ** 3])
print("feature ranges:", X.max(0))
Xs = (X - X.mean(0)) / X.std(0)
w, b = np.zeros(3), 0.0
for _ in range(10_000):
err = Xs @ w + b - y
w, b = w - 0.1 * Xs.T @ err / len(y), b - 0.1 * err.mean()
print("weights on scaled x, x^2, x^3:", w.round(2), " -> the x^2 feature dominates")
Optional lab · about 25 min · runs in this page
Feature engineering and polynomial regression
Fit curves with linear regression by engineering features, and see why scaling matters for polynomial features.
Step 1A curve a line cannot fit
import numpy as np, matplotlib.pyplot as plt
x = np.arange(0, 20, 1.0); y = np.cos(x / 2)
def fit(X, alpha=0.1, iters=20000):
Xs = (X - X.mean(0)) / X.std(0); w, b = np.zeros(X.shape[1]), 0.0
for _ in range(iters):
err = Xs @ w + b - y
w, b = w - alpha * Xs.T @ err / len(y), b - alpha * err.mean()
return Xs @ w + b
print("target y = cos(x/2) at x = 0, 5, 10:", y[[0, 5, 10]].round(3))
Step 2Add polynomial features
for degree in (1, 5, 13):
X = np.column_stack([x ** k for k in range(1, degree + 1)])
pred = fit(X)
plt.plot(x, pred, label=f"degree {degree}")
print(f"degree {degree:2d}: J = {((pred - y) ** 2).mean() / 2:.4f}")
plt.scatter(x, y, c="k", marker="x"); plt.legend(); plt.show()
Lecture 2.11 · 6 min read
Regression with scikit-learn
Now that you have written the algorithm, use the library. scikit-learn wraps scaling, fitting and prediction in objects with a common interface: fit learns from data, transform or predict applies what was learned.
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import SGDRegressor, LinearRegression
scaler = StandardScaler().fit(X) # learns mu and sigma
X_norm = scaler.transform(X)
sgd = SGDRegressor(max_iter=1000, tol=1e-3).fit(X_norm, y) # gradient descent
print(sgd.coef_, sgd.intercept_)
ols = LinearRegression().fit(X, y) # closed-form solution, no scaling needed
print(ols.predict(np.array([[2104, 5, 1, 45]])))
LinearRegression does not use gradient descent at all. For squared error there is a closed-form answer, the normal equations, that solves for w directly with a least-squares solver instead of iterating. It is exact and needs no learning rate, but it costs roughly n³ operations and does not extend to the other models in this specialization; gradient descent does, which is why you learned it first.
Deep dive · the normal equations
Derivation
Use the bias column trick: X̃ is X with a leading column of ones, θ = (b, w). Then J(θ) = (1/2m)·‖X̃θ − y‖². Expand the squared norm:
J(θ) = (1/2m)·( θᵀX̃ᵀX̃θ − 2θᵀX̃ᵀy + yᵀy )
The gradient of θᵀAθ is 2Aθ for symmetric A, and the gradient of θᵀc is c. So ∇J = (1/m)·(X̃ᵀX̃θ − X̃ᵀy). The cost is convex (“The cost function” deep dive), so the minimum is where the gradient is zero:
X̃ᵀX̃ θ = X̃ᵀyThe normal equations: n + 1 linear equations in n + 1 unknowns.
The name comes from the geometry: X̃ᵀ(y − X̃θ) = 0 says the residual vector is perpendicular (normal) to every column of X̃.
Worked example by hand
Five houses, one feature. X̃ᵀX̃ = [[5, Σx], [Σx, Σx²]] = [[5, 10], [10, 22.5]] and X̃ᵀy = [Σy, Σxy] = [2550, 5605]. The determinant is 5·22.5 − 10·10 = 12.5. By Cramer's rule:
Xt = np.c_[np.ones(len(X)), X] # (m, n+1): ones column carries b
theta = np.linalg.solve(Xt.T @ Xt, Xt.T @ y) # solves the system; never form the inverse
theta_ls, *_ = np.linalg.lstsq(Xt, y, rcond=None) # SVD-based: works even when Xt.T @ Xt is singular
Cost. Forming X̃ᵀX̃ takes about m·n² operations and solving takes about n³/3. For n in the hundreds this is instant; for n = 100,000 the n×n matrix alone needs 80 GB.
Accuracy. The condition number of X̃ᵀX̃ is the square of that of X̃. For the raw four-feature houses it is 3.65 × 10⁸, so about 9 of float64's 16 digits are at risk. lstsq (and scikit-learn's LinearRegression, which calls it) works on X̃ directly and avoids the squaring.
Singularity. If m < n + 1, or one column is a combination of others (sqft and sqft in m², say), X̃ᵀX̃ cannot be inverted and there are infinitely many minimizers. solve fails or returns garbage; lstsq returns the one with the smallest ‖θ‖; adding λI (ridge, “Regularization” deep dive) makes it invertible.
Common mistakes
Forgetting the ones column. Symptom: the fitted line is forced through the origin, with w = 5605/22.5 = 249.1 on the five houses. Fix: add the column, or center x and y first.
Using np.linalg.inv. Symptom: slower and less accurate, and no warning near singularity. Fix: solve or lstsq.
Feeding SGDRegressor unscaled features. It is gradient descent, so “Feature scaling and checking convergence” applies. Symptom: huge or NaN coefficients. Fix: put a StandardScaler in front.
Forgetting SGDRegressor's default penalty. It adds L2 regularization with alpha = 0.0001 unless you set penalty=None. Symptom: coefficients slightly smaller than LinearRegression's. Fix: expect it, or turn it off.
Implement predict, cost and gradients exactly as in “Vectorization”. Train from zeros with α = 1e-7 for 1,000 iterations on the raw features and note how slowly the cost falls.
Step 3Scale, then train again
Compute μ and σ per column (use X.std(axis=0), the population standard deviation), normalize, and train from zeros with α = 0.1 for 1,000 iterations. Compare the two cost histories on one plot.
Checkpoint 1
What is the z-score of the first house's size, 2104 sq ft? (three decimals)
Checkpoint 2
After training on the scaled features, what is b (nearest whole number)? Hint: with centered features, b converges to the mean of y.
Step 4Predict and compare
Price a 1,650 sq ft, 3-bedroom, 1-floor, 40-year-old house. Remember to scale it with the stored μ and σ. Then fit sklearn.linear_model.LinearRegression on the raw X and compare its prediction for the same house with yours; they should agree to within a few hundred dollars.
Week 3 · Classification
Classification
Predict categories with logistic regression, learn its cost function and gradient descent, and handle overfitting with regularization.
Video lectures · Week 3
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
Logistic RegressionStatQuest with Josh Starmer · YouTube ↗Regularization Part 1: Ridge (L2) RegressionStatQuest with Josh Starmer · YouTube ↗
Module 1
Classification with logistic regression
Lecture 3.1 · 6 min read
Why linear regression fails at classification
Take tumors with a measured size and a label: 0 for benign, 1 for malignant. You could fit a line and predict malignant whenever the line is above 0.5. On a clean dataset it almost works. Then add one very large, obviously malignant tumor far to the right. The line tilts to reach it, the 0.5 crossing slides right, and tumors that were correctly classified before are now called benign. One easy example made the classifier worse.
The deeper problem is that a line is the wrong shape. Its output runs from −∞ to +∞, while the thing we want to express is a probability between 0 and 1. We need a function that stays in that range, saturates at both ends so distant examples cannot drag it, and still has a parameterized, differentiable form that gradient descent can train.
Deep dive · one outlier moves the threshold
Worked example by hand
Six tumors of size 1 to 6 with labels 0, 0, 0, 1, 1, 1. Using the closed form from “The linear model”: x̄ = 3.5, ȳ = 0.5, Σ(x − x̄)(y − ȳ) = 4.5 and Σ(x − x̄)² = 17.5, so the line is ŷ = 0.2571·x − 0.4. It crosses 0.5 at x = (0.5 + 0.4)/0.2571 = 3.5, exactly between the classes. Every tumor is classified correctly.
Add a seventh tumor of size 20, label 1. Before refitting, the old line predicts 0.2571·20 − 0.4 = 4.743 for it, a residual of −3.743 whose square, 14.0, is larger than all other squared residuals combined. Least squares pays almost any price to shrink it. The refitted line is ŷ = 0.0461·x + 0.3013, and its 0.5 crossing moves to x = (0.5 − 0.3013)/0.0461 = 4.31. The malignant tumor of size 4 now gets 0.486 and is called benign. An obviously malignant example made the classifier wrong on a borderline one.
Model
Data
Threshold crossing
Line
6 tumors
3.50
Line
+ size 20
4.31
Logistic regression
6 tumors
3.50
Logistic regression
+ size 20
3.50
(The logistic rows use scikit-learn's default regularization, C = 1.) The sigmoid of the size-20 tumor is already about 1, so its residual f − y is nearly 0 and it exerts almost no pull. “Log loss and the same old gradient descent” shows that the logistic gradient is a sum of exactly these residuals.
Derivation: why the line has to tilt
The squared-error gradient for w is (1/m)·Σ eᵢxᵢ. The new point has e = −3.743 and x = 20, contributing −74.9 to the sum, while each of the original six contributes at most a few tenths. Distance from the threshold multiplies the pull, which is the opposite of what a classifier should want: a point far on the correct side is the least informative about where the boundary belongs.
Edge cases
Outputs outside [0, 1]. Even without the outlier, the line predicts −0.143 at size 1 and 1.143 at size 6. Those cannot be probabilities.
Balanced, clean data. On symmetric data like the first six tumors the line happens to put the threshold in the right place. That is luck, not a property of the method.
Common mistakes
Removing "outliers" to rescue a linear classifier. The size-20 tumor is correct data. Fix: change the model, not the data.
Clipping line outputs to [0, 1] and calling them probabilities. Clipping hides the symptom; the threshold is still in the wrong place.
Judging on accuracy alone. Accuracy dropped by just one tumor here; the threshold moved by 0.81 size units. Fix: look at the boundary, not only the score.
Optional lab · about 15 min · runs in this page
Classification
Plot a classification dataset and see why a straight line fit with linear regression makes a poor classifier.
for x_extra in (None, 20.0):
xs = x if x_extra is None else np.append(x, x_extra); ys = y if x_extra is None else np.append(y, 1)
w, b = np.polyfit(xs, ys, 1)
print(f"{'with' if x_extra else 'without'} an extra point at x=20: threshold 0.5 at x = {(0.5 - b) / w:.2f}")
Lecture 3.2 · 9 min read · demo
Logistic regression and the sigmoid
Keep the linear part, z = w · x + b, and pass it through the sigmoid function g, which squashes any real number into (0, 1). The output is read as the model's estimate of the probability that y = 1.
g(z) = 1 / (1 + e−z) fw,b(x) = g(w · x + b) = P(y = 1 | x)g(0) = 0.5, g(z) → 1 as z → +∞, g(z) → 0 as z → −∞. Its derivative is g(z)(1 − g(z)), which makes the gradients in “Log loss and the same old gradient descent” clean.
Move the sliders. The curve is the model's probability of malignancy at each size; the vertical line is where that probability crosses 0.5. Push the big tumor on the right as far as you like: the sigmoid saturates near 1 there, so the crossing barely moves. That saturation is what linear regression lacked.
Logistic regression on one featuretumor size → P(malignant)
boundary at size 3.00log loss –accuracy –
The output is a probability, so the natural threshold for a decision is 0.5, which is where z = 0. But the threshold is a choice, not part of the model. A screening test that must not miss cancers might call anything above 0.2 positive and accept more false alarms. Course 2 gives you precision and recall to reason about that trade.
Deep dive · the sigmoid, its derivative and log-odds
The first factor is g. The second is (1 + e−z − 1)/(1 + e−z) = 1 − g.
g′(z) = g(z)·(1 − g(z))Largest at z = 0, where it equals 0.25; it vanishes in both tails.
Values: g′(0) = 0.25, g′(±2) = 0.105, g′(5) = 0.00665. Also g(−z) = 1 − g(z): the curve is symmetric about (0, 0.5).
Derivation: the linear part is the log-odds
Let p = g(z). Then 1 − p = e−z/(1 + e−z), so p/(1 − p) = 1/e−z = ez, and
ln( p / (1 − p) ) = z = w·x + bLogistic regression is linear regression on the log-odds.
This gives w a precise meaning: raising x by one unit adds w to the log-odds, which multiplies the odds by ew. It does not add a fixed amount to the probability.
Worked example: the demo's defaults
w = 2, b = −6.
Size 3: z = 0, p = 0.5, odds 1.
Size 4: z = 2, p = 0.8808, odds 0.8808/0.1192 = 7.389 = e².
Size 5: z = 4, p = 0.9820. The step from 3 to 4 added 0.38 to p; from 4 to 5 only 0.10. The odds multiplied by 7.389 both times.
Moving the threshold to 0.2 means z ≥ ln(0.2/0.8) = −1.386, so size ≥ (−1.386 + 6)/2 = 2.31. Same model, different decision.
Code walkthrough: a sigmoid that never overflows
def sigmoid_stable(z):
z = np.asarray(z, dtype=float)
out = np.empty_like(z)
pos = z >= 0
out[pos] = 1.0 / (1.0 + np.exp(-z[pos])) # exp of a non-positive number: at most 1
ez = np.exp(z[~pos]) # exp of a negative number: no overflow
out[~pos] = ez / (1.0 + ez) # same value, rearranged
return out
Common mistakes
Reading w as a change in probability. Symptom: "each cm adds 2 to the probability". Fix: w is a change in log-odds; the probability change depends on where you start.
Overflow in np.exp(-z). For z = −1000 it returns inf with a warning, and later code may produce NaN. Fix: the stable version above, or scipy.special.expit.
Applying the sigmoid twice. Symptom: probabilities squeezed into (0.5, 0.73). Fix: one sigmoid, at the very end.
Retraining to change the threshold. The threshold is applied after the model. Fix: keep the probabilities and choose the cut-off separately.
Optional lab · about 15 min · runs in this page
Sigmoid function and logistic regression
Implement the sigmoid and see how logistic regression turns a linear score into a probability.
Step 1Sigmoid
import numpy as np, matplotlib.pyplot as plt
def sigmoid(z): return 1 / (1 + np.exp(-z))
z = np.arange(-10, 11)
for zi in z[::4]:
print(f"z = {zi:3d} sigmoid(z) = {sigmoid(zi):.4f}")
plt.plot(z, sigmoid(z)); plt.axvline(0, ls="--", c="gray"); plt.title("sigmoid"); plt.show()
Step 2Logistic regression on the tumor data
x = np.array([0., 1, 2, 3, 4, 5]); y = np.array([0, 0, 0, 1, 1, 1])
w, b = 2.0, -5.0
print("P(y=1):", sigmoid(w * x + b).round(3))
print("predictions at 0.5:", (sigmoid(w * x + b) >= 0.5).astype(int), " labels:", y)
Lecture 3.3 · 7 min read
Decision boundaries
With two features, the model predicts 1 wherever w₁x₁ + w₂x₂ + b ≥ 0. That inequality describes a half-plane, and the line w₁x₁ + w₂x₂ + b = 0 that separates the two halves is the decision boundary. With w = (1, 1) and b = −3, the boundary is x₁ + x₂ = 3: a diagonal line, with predictions of 1 above it and 0 below.
Logistic regression's boundary is always a straight line, or a flat hyperplane in more dimensions, in whatever feature space you give it. That is both its limit and its loophole. If the true boundary is a circle, add features x₁² and x₂²; the boundary in the new four-dimensional space is still flat, but projected back onto the original two features it is a circle: x₁² + x₂² = 1 when w = (0, 0, 1, 1) and b = −1. Polynomial features give logistic regression curved boundaries exactly as they gave linear regression curves.
The lab this week plots a boundary. Do it every time you train a two-feature classifier; a picture of where the model says yes is the fastest way to notice that it has learned something silly.
Deep dive · the geometry of the boundary
Derivation: w points across the boundary
Take two points xA and xB on the boundary. Both satisfy w·x + b = 0, so subtracting gives w·(xA − xB) = 0. Every direction along the boundary is perpendicular to w, so w is the boundary's normal vector, pointing toward the y = 1 side.
For any point x, write it as a point x₀ on the boundary plus t steps of length 1 along w/‖w‖. Then w·x + b = w·x₀ + b + t‖w‖ = t‖w‖, so
signed distance to boundary = (w·x + b) / ‖w‖ = z / ‖w‖z tells you which side and, divided by ‖w‖, how far.
Lines of equal probability are parallel to the boundary, because p depends on x only through z.
Worked example: the lab's six points
After 10,000 steps the lab finds w = (5.281, 5.078), b = −14.222, so ‖w‖ = 7.327. At x₁ = 0 the boundary is at x₂ = 14.222/5.078 = 2.80.
Point
y
z
p
distance
(0.5, 1.5)
0
−3.965
0.0186
−0.541
(1.0, 1.0)
0
−3.863
0.0206
−0.527
(1.5, 0.5)
0
−3.761
0.0227
−0.513
(3.0, 0.5)
1
4.160
0.9846
0.568
(2.0, 2.0)
1
6.496
0.9985
0.887
(1.0, 2.5)
1
3.754
0.9771
0.512
Edge case: separable data has no finite answer
Every point is correctly classified, so the line separates the classes. Multiplying w and b by any c > 1 keeps the same boundary but pushes every p closer to its label, which lowers the log loss. The loss can always be reduced, so the minimum is at infinity. Run 100,000 steps instead of 10,000 and you get w = (8.35, 8.15), b = −22.69: almost the same boundary, much larger weights, and J falls from 0.0171 to 0.0017. Regularization (“Regularization”) gives a finite answer by charging for ‖w‖.
Worked example: the circle
With features (x₁, x₂, x₁², x₂²), w = (0, 0, 1, 1) and b = −1, z = x₁² + x₂² − 1. At (0.5, 0.5) z = −0.5 and p = 0.378 (inside, predicted 0). At (1, 1) z = 1 and p = 0.731. At (0, 1) z = 0, on the boundary, p = 0.5.
Common mistakes
Dividing by w₂ when it is near zero. Symptom: a boundary drawn off the chart or a division warning. Fix: if |w₂| is small, solve for x₁ instead, or use plt.contour of z = 0 over a grid.
Plotting the boundary in scaled coordinates on raw axes. Symptom: a line nowhere near the data. Fix: draw in the same space you trained in, or convert w and b back to raw units (“Feature scaling and checking convergence” deep dive).
Reading ‖w‖ as confidence in the boundary. On separable data ‖w‖ grows with training time. Fix: compare boundaries, or regularize.
Optional lab · about 15 min · runs in this page
Decision boundary
Plot the decision boundary of a two-feature logistic regression model.
Step 1Data and model
import numpy as np, matplotlib.pyplot as plt
X = np.array([[0.5, 1.5], [1, 1], [1.5, 0.5], [3, 0.5], [2, 2], [1, 2.5]]); y = np.array([0, 0, 0, 1, 1, 1])
w, b = np.array([1.0, 1.0]), -3.0
print("w·x + b:", X @ w + b, " -> predictions", (X @ w + b >= 0).astype(int))
Practice quiz: Classification with logistic regression
Practice quiz · 5 questions
Classification with logistic regression
Module 3
Cost function for logistic regression
Lecture 3.4 · 10 min read
Log loss and the same old gradient descent
Squared error is the wrong cost for a sigmoid output. Plugging g(w·x + b) into the squared-error formula produces a non-convex cost surface with flat plateaus where the sigmoid saturates, and gradient descent can stall there. We want a cost that is convex, a single bowl, and that reflects how probabilities should be scored.
Score each example by how much probability the model gave to the true label. If y = 1, the loss is −log f(x): zero when the model said 1 with certainty, growing without bound as it approaches 0. If y = 0, the loss is −log(1 − f(x)). A model that says 0.99 for a benign tumor pays −log(0.01) ≈ 4.6; one that says 0.01 pays almost nothing. The two cases combine into one expression because y is 0 or 1, so one of the two terms always vanishes.
J(w, b) = −1/m · Σi [ y(i) log f(x(i)) + (1 − y(i)) log(1 − f(x(i))) ]Binary cross-entropy, also called log loss. Convex in w and b, so gradient descent finds the global minimum.
Now differentiate. The sigmoid's derivative g(1 − g) cancels against the logs, and what remains is a formula you have already seen:
These are character for character the gradients of linear regression. Only the definition of f changed. The code is the same loop with a sigmoid inserted, and the same advice about learning rates and scaling applies.
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def cost(X, y, w, b):
p = sigmoid(X @ w + b)
return -(y * np.log(p) + (1 - y) * np.log(1 - p)).mean()
def gradients(X, y, w, b):
err = sigmoid(X @ w + b) - y # the only change from linear regression
return X.T @ err / len(y), err.mean()
Deep dive · log loss from likelihood, and its gradient
Derivation: log loss is maximum likelihood
Treat each label as a biased coin: P(y = 1 | x) = f(x) and P(y = 0 | x) = 1 − f(x). Because y is 0 or 1, both cases are one formula: P(y | x) = fy·(1 − f)1−y. The probability of all m labels, assuming independent examples, is the product Πᵢ fᵢyᵢ(1 − fᵢ)1−yᵢ. Maximizing it is the same as minimizing the average negative log, which turns the product into a sum:
−(1/m)·log Πᵢ P(yᵢ | xᵢ) = −(1/m)·Σᵢ [ yᵢ log fᵢ + (1 − yᵢ) log(1 − fᵢ) ]This is J(w, b) from the lecture.
By hand: three examples with labels (1, 0, 1) and predictions (0.9, 0.2, 0.7). The likelihood is 0.9 · 0.8 · 0.7 = 0.504, and the log loss is −ln(0.504)/3 = 0.2284.
Derivation: the gradient
For one example, L = −[y ln f + (1 − y) ln(1 − f)] with f = g(z) and z = w·x + b. Chain rule in three links:
Multiply: the f(1 − f) cancels and ∂L/∂wⱼ = (f − y)·xⱼ. Averaging over examples gives the lecture's formula.
Derivation: convexity
Differentiate (f − y)xⱼ once more with respect to wₖ: only f depends on w, giving f(1 − f)·xⱼxₖ. So the Hessian is H = (1/m)·Σᵢ fᵢ(1 − fᵢ)·xᵢxᵢᵀ. Each term is a nonnegative number times xxᵀ, and vᵀxxᵀv = (v·x)² ≥ 0, so H is positive semidefinite everywhere and J is convex.
Why squared error on a sigmoid fails
Take one example with y = 0 and squared loss L(z) = g(z)². Then L′ = 2g·g′ = 2g²(1 − g), and
L″(z) = 2g²(1 − g)(2 − 3g)Negative whenever g > 2/3, that is z > ln 2 ≈ 0.693.
Negative curvature means the loss is not convex. It also goes flat exactly when the model is confidently wrong. At z = 5 (p = 0.9933 for a true 0), the squared-error gradient with respect to z is 2g²(1 − g) = 0.0132, while the log-loss gradient is f − y = 0.9933, 75 times larger. Log loss pushes hardest on the worst mistakes; squared error on a sigmoid barely notices them.
Common mistakes
log(0). A prediction of exactly 0 or 1 for the wrong class gives an infinite loss and NaN gradients. Fix: clip p to [10⁻¹², 1 − 10⁻¹²], or compute the loss from z directly.
Labels coded −1/+1. The formula assumes 0/1. Symptom: negative losses. Fix: map labels to 0/1.
Expecting a closed form. Setting the gradient to zero gives equations with sigmoids inside; there is no normal-equation shortcut. Fix: iterate.
Reading a small log loss as accuracy. J = 0.693 = ln 2 is chance level for balanced classes; J = 0.017 on six points says nothing about new ones. Fix: also measure accuracy on held-out data.
Optional lab · about 15 min · runs in this page
Logistic loss
Compare squared error and logistic loss for a sigmoid model and see why logistic loss is the right choice.
for f_ in (0.99, 0.6, 0.1, 0.01):
print(f"y = 1, f = {f_}: log loss {-np.log(f_):.3f} squared error {(1 - f_) ** 2:.3f}")
Lecture 3.5 · 5 min read
Simplified cost function for logistic regression
The logistic loss has two cases, −log(f) when y = 1 and −log(1 − f) when y = 0. Because y is always 0 or 1, both cases fit in one expression: one of the two terms is always multiplied by zero.
L(f, y) = −y log(f) − (1 − y) log(1 − f), J(w, b) = (1/m) Σ L(fw,b(x(i)), y(i))This cost comes from the statistical principle of maximum likelihood, and it is convex in w and b.
import numpy as np
def loss(f, y): return -y * np.log(f) - (1 - y) * np.log(1 - f)
for f_, y_ in [(0.9, 1), (0.1, 1), (0.9, 0), (0.1, 0)]:
print(f"f = {f_}, y = {y_}: loss {loss(f_, y_):.3f}")
Optional lab · about 15 min · runs in this page
Cost function for logistic regression
Implement the logistic regression cost and compare two sets of parameters.
Step 1compute_cost_logistic
import numpy as np
X = np.array([[0.5, 1.5], [1, 1], [1.5, 0.5], [3, 0.5], [2, 2], [1, 2.5]]); y = np.array([0, 0, 0, 1, 1, 1])
def sigmoid(z): return 1 / (1 + np.exp(-z))
def compute_cost_logistic(X, y, w, b):
f = sigmoid(X @ w + b)
return float(np.mean(-y * np.log(f) - (1 - y) * np.log(1 - f)))
print("b = -3:", round(compute_cost_logistic(X, y, np.array([1., 1.]), -3), 4))
print("b = -4:", round(compute_cost_logistic(X, y, np.array([1., 1.]), -4), 4))
Module 4
Practice quiz: Cost function for logistic regression
Practice quiz · 5 questions
Cost function for logistic regression
Module 5
Gradient descent for logistic regression
Lecture 3.6 · 6 min read
Gradient descent implementation for logistic regression
Differentiating the logistic cost gives derivatives that look identical to linear regression's:
∂J/∂wj = (1/m) Σ (f(x(i)) − y(i)) xj(i), ∂J/∂b = (1/m) Σ (f(x(i)) − y(i))The difference is hidden inside f: here f(x) = g(w · x + b), the sigmoid of the linear part.
Everything you learned for linear regression carries over: simultaneous updates, monitoring the learning curve, vectorization and feature scaling.
import numpy as np
X = np.array([[0.5, 1.5], [1, 1], [1.5, 0.5], [3, 0.5], [2, 2], [1, 2.5]])
y = np.array([0, 0, 0, 1, 1, 1])
g = lambda z: 1 / (1 + np.exp(-z))
w, b = np.zeros(2), 0.0
for _ in range(10_000):
err = g(X @ w + b) - y
w, b = w - 0.1 * X.T @ err / len(y), b - 0.1 * err.mean()
print("w =", w.round(2), " b =", round(b, 2))
print("probabilities:", g(X @ w + b).round(2))
Optional lab · about 20 min · runs in this page
Gradient descent for logistic regression
Train logistic regression with gradient descent and watch the cost fall.
Step 1Gradient and training loop
import numpy as np
X = np.array([[0.5, 1.5], [1, 1], [1.5, 0.5], [3, 0.5], [2, 2], [1, 2.5]]); y = np.array([0, 0, 0, 1, 1, 1])
g = lambda z: 1 / (1 + np.exp(-z))
def compute_gradient_logistic(X, y, w, b):
err = g(X @ w + b) - y
return X.T @ err / len(y), err.mean()
w, b = np.zeros(2), 0.0
for i in range(10001):
dw, db = compute_gradient_logistic(X, y, w, b)
w, b = w - 0.1 * dw, b - 0.1 * db
if i % 2500 == 0:
f = g(X @ w + b); print(f"iteration {i:5d}: cost {np.mean(-y*np.log(f)-(1-y)*np.log(1-f)):.4f}")
print("w:", w.round(2), "b:", round(b, 2))
Optional lab · about 10 min · runs in this page
Logistic regression with scikit-learn
Train the same model with scikit-learn in three lines.
Step 1Fit, predict, score
import numpy as np
from sklearn.linear_model import LogisticRegression
X = np.array([[0.5, 1.5], [1, 1], [1.5, 0.5], [3, 0.5], [2, 2], [1, 2.5]]); y = np.array([0, 0, 0, 1, 1, 1])
model = LogisticRegression().fit(X, y)
print("predictions:", model.predict(X))
print("accuracy:", model.score(X, y))
print("w:", model.coef_.round(2), " b:", model.intercept_.round(2))
Module 6
Practice quiz: Gradient descent for logistic regression
Practice quiz · 5 questions
Gradient descent for logistic regression
Module 7
The problem of overfitting
Lecture 3.7 · 9 min read · demo
Overfitting
Give a model enough flexibility and it will fit the noise in your training set as faithfully as the signal. A degree-9 polynomial through ten points can pass through every one of them, cost exactly zero, and predict nonsense between them. The model has memorized the examples rather than learned the pattern. That is overfitting, also called high variance, because small changes to the training set would change the fitted curve wildly.
The opposite failure is underfitting, or high bias: a model too simple to capture the pattern, like a straight line through data that clearly curves. The only honest way to tell the two apart is to hold out examples the model never trained on and measure error on them. The demo splits fourteen points into eight for training and six for testing. Raise the polynomial degree and watch the two errors diverge.
Polynomial degree vs test error8 training points, 6 held out
train MSE –test MSE –largest |w| –
Three remedies, in the order to try them. Get more training data; with enough points even a flexible model cannot bend between them. Use fewer features, choosing the ones that matter, which is a form of model selection. Or keep all the features and shrink their weights, which is regularization, next lecture. In the demo, leave the degree at 7, where the curve passes through every training point, and move the λ slider.
Deep dive · held-out error decides the degree
Worked example by hand: leave-one-out on five houses
With five examples, the most honest split is leave-one-out: fit on four houses, predict the fifth, repeat five times, average the squared errors. Do it for polynomial degrees 0 to 3. (Degree 4 cannot be tested this way: four points do not determine five coefficients.)
Degree
Training MSE (all 5)
Held-out errors
Leave-one-out MSE
0 (constant)
20560
262.5, 112.5, 12.5, −150, −237.5
32125
1 (line)
158
20, −15.7, 12.5, −27.1, 30
488
2
122.3
7.5, −11.8, 33.3, −24.5, 42.5
743
3
114.3
200, −50, 33.3, −50, 200
17222
Training MSE (2J) falls every time the degree rises; it must, because a higher degree contains every lower one. Held-out MSE falls from degree 0 to 1 and then rises. Degree 0 underfits (high bias). Degree 3 fit to four points passes through all four exactly, so its held-out errors are pure extrapolation, worst at the ends (200 at x = 1.0 and x = 3.0). The line wins.
Derivation: why m points allow degree m − 1
A degree-d polynomial has d + 1 coefficients. Requiring it to pass through m points with distinct x gives m linear equations whose matrix has rows (1, xᵢ, xᵢ², …, xᵢᵈ). For d = m − 1 the matrix is square and, for distinct xᵢ, invertible. So there is always exactly one degree-(m − 1) polynomial through m points, and its training cost is zero whatever the data. Zero training cost is then a statement about counting, not about learning.
Derivation: bias and variance
Let the true price be y = h(x) + noise with variance σ², and let ŷ(x) be the prediction of a model trained on a random training set. Add and subtract the average prediction E[ŷ]:
E[(ŷ − y)²] = (E[ŷ] − h)² + E[(ŷ − E[ŷ])²] + σ²bias² + variance + noise; the cross terms have zero expectation.
A constant model has large bias and small variance. A degree-3 fit on four points has small bias and huge variance: drop a different house and the curve changes completely, as the 200-sized errors show. The best degree minimizes the sum.
Common mistakes
Picking the degree on the test set. Symptom: a reported test error that is too optimistic, because you chose the model that happened to do best on it. Fix: choose on a validation split and touch the test set once.
A single tiny split. With 14 points split 8/6, the winning degree can change with the random seed. Fix: repeat with several splits or use cross-validation.
Scaling with statistics from all data. Symptom: slightly optimistic held-out error. Fix: fit μ and σ on the training part only, inside each split.
Calling high training error overfitting. High training error is underfitting. Overfitting is the gap between training and held-out error.
Lecture 3.8 · 8 min read
Addressing overfitting
Three options when a model overfits:
Collect more training examples. With more data, a flexible model is forced toward a smoother function. Often the best fix, when data is available.
Use fewer features. Select the most relevant ones (feature selection). The risk is throwing away useful information.
Regularize. Keep all features but shrink the parameters so no feature has an outsized effect. This usually works well and is the subject of the rest of this module.
By convention only the weights wj are regularized, not b; regularizing b makes little difference in practice.
Optional lab · about 15 min · runs in this page
Overfitting
Fit polynomials of increasing degree and watch training error fall while test error rises.
Step 1Underfit, just right, overfit
import numpy as np, matplotlib.pyplot as plt
rng = np.random.default_rng(2)
x = np.sort(rng.uniform(0, 1, 12)); y = np.sin(2 * np.pi * x) + rng.normal(0, 0.15, 12)
x_te = np.linspace(0, 1, 200); y_te = np.sin(2 * np.pi * x_te)
for d in (1, 3, 11):
coef = np.polyfit(x, y, d)
tr = ((np.polyval(coef, x) - y) ** 2).mean() / 2; te = ((np.polyval(coef, x_te) - y_te) ** 2).mean() / 2
plt.plot(x_te, np.clip(np.polyval(coef, x_te), -2, 2), label=f"degree {d}")
print(f"degree {d:2d}: train J {tr:.4f} test J {te:.4g}")
plt.scatter(x, y, c="k"); plt.legend(); plt.show()
Lecture 3.9 · 8 min read
Regularization
Overfitted models tend to have large weights: to swing a polynomial through every point, the coefficients on high powers must become huge and cancel each other. Regularization adds a penalty on the size of the weights to the cost, so the optimizer must trade fit against simplicity. The usual penalty is the sum of squared weights, scaled by a constant λ that you choose.
Jreg(w, b) = J(w, b) + λ/(2m) · Σj=1..n wj²Applies to linear and logistic regression alike. b is conventionally not penalized. λ = 0 recovers the original model; a very large λ drives every weight toward zero and underfits.
The gradient gains one term per weight, λ/m · wj, so each update first shrinks the weight by a factor slightly below 1 and then applies the usual gradient step. That is why this penalty is also called weight decay, the name it carries in every deep learning library, including the weight_decay argument you will set in Course 4.
def cost_reg(X, y, w, b, lam):
return cost(X, y, w, b) + lam / (2 * len(y)) * (w @ w)
def gradients_reg(X, y, w, b, lam):
dw, db = gradients(X, y, w, b)
return dw + lam / len(y) * w, db # b is not regularized
Choosing λ is the same problem as choosing the polynomial degree: try several values and keep the one with the lowest error on held-out data. Course 2 turns that into a procedure with a dedicated validation set. Squared-weight penalties are called L2 or ridge; a penalty on absolute values, L1 or lasso, pushes small weights to exactly zero and doubles as feature selection.
Deep dive · ridge in closed form, and L1 versus L2
Derivation: ridge for one feature
Minimize J = (1/2m)·[Σ(w·xᵢ + b − yᵢ)² + λw²], with b unpenalized.
∂J/∂b = 0 gives b = ȳ − w·x̄, as without the penalty.
w = Sxy / (Sxx + λ)λ is added to the denominator: the weight is pulled toward 0 but never reaches it.
For the five houses Sxy = 505 and Sxx = 2.5 (“The linear model” deep dive).
λ
w
b = 510 − 2w
0
202
106
1
144.29
221.43
2.5
101
308
10
40.4
429.2
As λ grows the line flattens toward the mean price, 510.
Derivation: the matrix form and shrinkage
With centered X and y, the same steps give (XᵀX + λI)w = Xᵀy. Adding λI raises every eigenvalue of XᵀX by λ, so the system is always solvable, even for the five houses with five parameters. In the eigenvector basis of XᵀX, with eigenvalues dₖ, each component of the unregularized solution is multiplied by dₖ/(dₖ + λ). Directions the data pins down well (large dₖ) barely shrink; poorly determined directions (small dₖ), where overfitting lives, shrink the most.
Weight decay
The gradient step is w ← w − α(∂J/∂w + (λ/m)w) = w·(1 − αλ/m) − α·∂J/∂w. With α = 0.1, λ = 1 and m = 5, every step first multiplies w by 0.98.
L1 versus L2
Replace λw² with λ|w|. For w ≠ 0 the derivative of |w| is sign(w), so step 2 becomes w·Sxx − Sxy + (λ/2)·sign(w) = 0, which gives
w = sign(Sxy) · max(|Sxy| − λ/2, 0) / SxxSoft thresholding: L1 subtracts a fixed amount, then stops at exactly 0.
On the five houses with λ = 10 this gives (505 − 5)/2.5 = 200, and w is exactly 0 for every λ ≥ 1010. Ridge divides instead of subtracting, so its w is never exactly zero. That is why L1 (lasso) performs feature selection and L2 (ridge) does not.
Matching library conventions
Multiply our cost by 2m: Σe² + λ‖w‖². scikit-learn's Ridge(alpha=a) minimizes ‖y − Xw‖² + a‖w‖², so a = λ. Its LogisticRegression(C=c) minimizes c·Σ(log loss) + ½‖w‖²; dividing by c shows C = 1/λ.
Common mistakes
Regularizing unscaled features. The penalty treats a weight of 0.6 per sq ft and 158 per bedroom on the same scale. Symptom: λ hits one feature far harder than another. Fix: z-score first.
Penalizing b. Symptom: predictions pulled toward 0 instead of toward the mean. Fix: leave b out of the penalty.
Choosing λ on training cost. Training cost is smallest at λ = 0 by construction. Fix: choose on validation data.
Mixing conventions. λ in λ/(2m)·Σw² is not alpha in SGDRegressor, which multiplies a per-example average. Fix: write both costs out before comparing numbers.
Lecture 3.10 · 8 min read
Regularized linear regression
With the penalty (λ/2m) Σ wj² added to the cost, the derivative for each weight gains one extra term, and the update can be rewritten in an illuminating way:
wj ← wj(1 − αλ/m) − α (1/m) Σ (f(x(i)) − y(i)) xj(i)The first factor is slightly less than 1, so every step first shrinks each weight a little, then applies the usual update. The update for b is unchanged.
import numpy as np
rng = np.random.default_rng(0)
x = np.linspace(0, 1, 12); y = np.sin(2 * np.pi * x) + rng.normal(0, 0.2, 12)
X = np.column_stack([x ** k for k in range(1, 10)]); X = (X - X.mean(0)) / X.std(0)
for lam in [0, 1, 10]:
w, b = np.zeros(9), 0.0
for _ in range(20_000):
err = X @ w + b - y
w = w * (1 - 0.05 * lam / len(y)) - 0.05 * X.T @ err / len(y)
b = b - 0.05 * err.mean()
print(f"lambda {lam:2d}: max |w| = {np.abs(w).max():6.2f}, training J = {((X @ w + b - y) ** 2).mean() / 2:.4f}")
Lecture 3.11 · 5 min read
Regularized logistic regression
Logistic regression with many features, especially polynomial ones, overfits in the same way: the decision boundary becomes a contorted shape that wraps around individual training points. Add the same penalty to the logistic cost and the boundary becomes smoother.
J(w, b) = (1/m) Σ L(f(x(i)), y(i)) + (λ/2m) Σ wj²The gradient gains the term (λ/m) w_j for each weight, exactly as for linear regression.
import numpy as np
from sklearn.datasets import make_moons
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
X, y = make_moons(200, noise=0.3, random_state=0)
X_te, y_te = make_moons(500, noise=0.3, random_state=1)
for C in [1e4, 1.0, 0.01]: # scikit-learn uses C = 1/λ
m = make_pipeline(PolynomialFeatures(8), StandardScaler(), LogisticRegression(C=C, max_iter=20000)).fit(X, y)
print(f"C = {C:<7} (λ = {1/C:g}): train acc {m.score(X, y):.3f}, test acc {m.score(X_te, y_te):.3f}")
Optional lab · about 20 min · runs in this page
Regularization
Add L2 regularization to the cost and gradient of linear and logistic regression.
Step 1Regularized costs
import numpy as np
def cost_linear_reg(X, y, w, b, lam):
m = len(y); return ((X @ w + b - y) ** 2).sum() / (2 * m) + lam / (2 * m) * (w ** 2).sum()
def cost_logistic_reg(X, y, w, b, lam):
m = len(y); f = 1 / (1 + np.exp(-(X @ w + b)))
return np.mean(-y * np.log(f) - (1 - y) * np.log(1 - f)) + lam / (2 * m) * (w ** 2).sum()
rng = np.random.default_rng(1)
X = rng.random((5, 6)); y = np.array([0, 1, 0, 1, 0]); w = rng.random(6) - 0.5; b = 0.5
print("linear, lambda 0.7:", round(cost_linear_reg(X, y, w, b, 0.7), 4))
print("logistic, lambda 0.7:", round(cost_logistic_reg(X, y, w, b, 0.7), 4))
Step 2Regularized gradients
def gradient_linear_reg(X, y, w, b, lam):
m = len(y); err = X @ w + b - y
return X.T @ err / m + lam / m * w, err.mean()
dw, db = gradient_linear_reg(X, y, w, b, 0.7)
print("dj_dw:", dw.round(4)); print("dj_db:", round(db, 4), "(b is not regularized)")
Implement all three as in “Log loss and the same old gradient descent”. Sanity checks: sigmoid(0) is 0.5 and the cost at w = (0, 0), b = 0 should be ln 2, because the model says 0.5 for everything.
Checkpoint 1
Cost at w = (0, 0), b = 0, to four decimals?
Step 3Train and draw the boundary
Run gradient descent from zeros with α = 0.1 for 10,000 iterations. Then draw the line w₁x₁ + w₂x₂ + b = 0 over the scatter plot: solve for x₂ = −(w₁x₁ + b)/w₂ at two values of x₁ and connect them.
Checkpoint 2
What is b after training (two decimals)?
Step 4Project: a real dataset
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_tr, X_te, y_tr, y_te = train_test_split(data.data, data.target, test_size=0.3, random_state=0)
Scale with μ and σ from X_tr. Train your regularized logistic regression with λ ∈ {0, 1, 10, 100} and report training and test accuracy for each. Then fit sklearn.linear_model.LogisticRegression(C=1.0) and compare; in scikit-learn, C is the inverse of λ. Write three sentences: which λ you would deploy, why, and what the gap between training and test accuracy tells you.
Module 11
Acknowledgments
Reading · 2 min read
Acknowledgments
This course stands on the shoulders of open work. The structure follows the classic progression of machine learning teaching, from linear regression through logistic regression and regularization, popularized by Andrew Ng's courses. The code runs on open-source software: Python, NumPy, pandas, matplotlib, scikit-learn and SciPy, executed in the browser by Pyodide, with PyTorch-style code running on torchlite. The handwritten digits come from the UCI dataset bundled with scikit-learn, and the curated videos belong to their creators, linked to their original channels.
Thank you for learning with this course. When you finish, the Grades page shows what remains for the certificate.
Final exam · 12 questions · pass mark 80%
Final exam
Questions from every week of the course. Pass it to complete the last requirement for the certificate on the Certificates page.
Final exam · 12 questions
Supervised Learning: Regression and Classification
Pass mark 80%. Passing this exam is one of the requirements for the course certificate. You can retake it as often as you like.
Course 2 of 6 · 4 weeks
Neural Networks and Applied Machine Learning
A neural network is logistic regression stacked and repeated until it can learn its own features. This course builds one in NumPy, trains it properly in PyTorch, and then spends a week on the skill that separates working models from demos: knowing why a model is wrong and what to do about it.
56lectures with video
1demos
21quizzes incl. practice + final
4labs
Week 1 · Neural networks
Neural networks
From one neuron to a layered network: the intuition, the model, the code in a framework, and the same thing written from scratch in NumPy.
Video lectures · Week 1
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
But what is a neural network?3Blue1Brown · YouTube ↗The Essential Main Ideas of Neural NetworksStatQuest with Josh Starmer · YouTube ↗
Module 1
Neural networks intuition
Lecture 1.1 · 6 min read
Neurons and the brain
Neural networks began in the 1950s as an attempt to write software that mimics the brain. They went in and out of fashion twice: popular in the 1980s for reading handwritten zip codes, out of favor in the late 1990s, and back from about 2005 under a new name, deep learning. Since then they have taken over speech recognition, computer vision, machine translation and, more recently, text generation.
A biological neuron receives electrical impulses through its dendrites, does some computation, and sends an impulse down its axon to other neurons. The artificial version keeps only the outline of that story: it takes a few numbers as input, computes a weighted sum, passes it through a simple function, and outputs one number. That is exactly the logistic regression unit from Course 1.
a = g(w · x + b) = 1 / (1 + e−(w · x + b))One artificial neuron: a weighted sum followed by an activation function. Its output a is called the activation.
Be careful with the brain analogy. Neuroscientists still understand very little about how the brain learns, and modern networks are designed by engineering principles, not by copying biology. The analogy is a source of inspiration, not a specification.
Why now?
The ideas are decades old; what changed is scale. Digitization produced enormous labeled datasets, and graphics processors made the matrix arithmetic cheap. Traditional algorithms such as logistic regression improve with more data and then plateau. Neural networks keep improving as you feed them more data, and bigger networks keep improving for longer. When data and compute are both plentiful, that difference decides the winner.
Lecture 1.2 · 8 min read
Demand prediction
A clothing shop wants to know whether a new T-shirt will be a top seller. With one feature, the price, logistic regression gives the probability of being a top seller. Call that output a for activation: this single unit is a tiny neural network with one neuron.
Now give the shop four features: price, shipping cost, marketing spend and material quality. Whether a shirt sells well plausibly depends on three intermediate factors: whether buyers can afford it (price, shipping), whether they are aware of it (marketing) and how good they perceive it to be (price, material, marketing). Put one neuron per factor, then a final neuron that combines the three.
x (4 features) → a[1] (3 activations) → a[2] (probability of top seller)Input layer, hidden layer, output layer. Superscripts in square brackets number the layers.
In practice you do not tell the network which inputs feed which factor. Every hidden neuron receives every input, and training decides how much weight each input gets. The network therefore learns its own intermediate features. That is the central idea: a neural network is logistic regression that learns its own features. The middle layer is called hidden because the training data contain the inputs and the correct outputs but never the values in between.
Below are hand-picked weights for the three hidden neurons, just to see the arithmetic. Training would find such numbers automatically.
A 1000 × 1000 grayscale photo is a grid of one million brightness values. Unroll the grid into a vector of length one million and you have the input x for a face-recognition network that outputs the identity of the person.
When researchers looked at what trained face networks compute, they found a striking pattern. Neurons in the first hidden layer respond to short lines and edges at different orientations. The next layer combines edges into parts of faces: an eye, the corner of a nose, an ear. The layer after that responds to larger face-shaped patterns. Each layer looks at a larger window of the image and builds more abstract features from the previous layer.
Train the same architecture on pictures of cars and it learns edges, then wheels and windows, then car shapes. Nobody programmed edge detectors; the features emerged from data. This is why one recipe works across so many domains.
Our labs use a small version of the same problem: 8 × 8 images of handwritten digits, unrolled into 64 inputs.
from sklearn.datasets import load_digits
digits = load_digits()
img = digits.images[0]
print("one image:", img.shape, "-> unrolled:", img.reshape(-1).shape)
print("label:", digits.target[0])
print((img > 7).astype(int)) # a crude look at the pixels
Module 2
Practice quiz: Neural networks intuition
Practice quiz · 5 questions
Neural networks intuition
Module 3
Neural network model
Lecture 1.4 · 8 min read
Neurons and layers
Start from the end of Course 1. A logistic regression unit takes a vector x, computes z = w · x + b and outputs a = g(z). Call that one neuron. Now put three neurons side by side, each with its own w and b, each reading the same x. Their three outputs form a new vector a of three numbers. That is a layer.
Feed a into a second layer of one neuron and you have a two-layer network that outputs a single probability, like logistic regression, except that the input to the final neuron is not the raw x but three learned transformations of it. Nothing tells the first layer what those three numbers should mean. Training will decide, and they usually end up being whatever intermediate features make the final decision easiest.
A demand-forecasting example: inputs are price, shipping cost, marketing spend and material quality. A first layer of three neurons might learn to compute affordability (from price and shipping), awareness (from marketing) and perceived quality (from price and material), and the output neuron combines those into a probability that the product sells well. Nobody designed those features; the data did.
Notation: layers are numbered from 1; the input is layer 0 so that a[0] = x. Layer l has a weight matrix W[l] and a bias vector b[l], and outputs an activation vector a[l]. Square brackets index layers; parentheses still index examples.
Deep dive · A layer is a matrix
Derivation
Neuron j of layer l computes zj = wj · a[l−1] + bj, then aj = g(zj). Write each weight vector wj as a row and stack the rows into a matrix W[l]. Row j times a[l−1] is exactly wj · a[l−1], so all neurons of the layer are computed at once:
z[l] = W[l] a[l−1] + b[l], a[l] = g(z[l])Row j of W holds neuron j's weights; column k holds how every neuron reads input k.
A layer with nin inputs and nout neurons therefore has nout · nin weights plus nout biases. The activation g is applied element by element, so a layer is one matrix product, one vector addition and one elementwise function.
Worked example by hand
Input x = (1, 2), three sigmoid neurons:
neuron
w
b
z = w · x + b
a = σ(z)
1
(0.5, −0.25)
0
0.5 − 0.5 + 0 = 0
0.5
2
(1, 0.5)
−1
1 + 1 − 1 = 1
0.7311
3
(−1, 1)
0.5
−1 + 2 + 0.5 = 1.5
0.8176
As a matrix, W = [[0.5, −0.25], [1, 0.5], [−1, 1]] has shape 3×2 and b = (0, −1, 0.5). The layer maps a 2-vector to the 3-vector a = (0.5, 0.7311, 0.8176), and that vector is the input to the next layer.
Intuition: a feature one neuron cannot compute
XOR outputs 1 when exactly one of two bits is on. No single logistic unit can do it (“Why nonlinearity matters” proves this), but two layers can. Set the hidden neurons by hand to h1 = σ(20x1 + 20x2 − 10), which behaves like OR, and h2 = σ(−20x1 − 20x2 + 30), which behaves like NAND. The output neuron σ(20h1 + 20h2 − 30) is an AND of the two.
x
h1 (OR)
h2 (NAND)
output
(0, 0)
0.00005
1.00000
0.00005
(0, 1)
0.99995
0.99995
0.99995
(1, 0)
0.99995
0.99995
0.99995
(1, 1)
1.00000
0.00005
0.00005
For x = (0, 1): the output pre-activation is 20 · 0.99995 + 20 · 0.99995 − 30 = 9.998, and σ(9.998) = 0.99995. The hidden layer invented two intermediate features, OR and NAND, that make the final decision linear. Training does the same thing without being told which features to build; it will rarely find these exact ones.
Common mistakes
Counting the input as a layer. The 64–25–15–1 network has three layers with parameters; layer 0 is just x. Symptom: parameter counts or layer indices off by one. Fix: number weight matrices, not vectors of values.
Mixing the two indices. a[2]3 is neuron 3 of layer 2; x(7) is example 7. Writing code where a loop over examples indexes layers produces shape errors that are hard to read. Fix: keep examples on the first array axis, layers in a Python list.
Forgetting the biases. Counting only nin · nout gives 2,000 for the digit network instead of 2,031.
Reading meaning into a hidden unit. "Affordability" in the lecture is an illustration. Permuting the 25 hidden units, with their rows and columns, gives an identical function, so unit 3 has no fixed identity across training runs.
Check yourself
A layer reads 3 inputs and has 4 neurons. What is the shape of W and how many parameters does it have?
Answer
W is 4×3 (one row per neuron), so 12 weights plus 4 biases: 16 parameters.
Lecture 1.5 · 7 min read
More complex neural networks
Networks with more layers use the same building block repeatedly. By convention we count the hidden layers and the output layer but not the input, so a network with three hidden layers and one output layer is a four-layer network. Layer 0 is the input, so a[0] = x.
aj[l] = g( wj[l] · a[l−1] + bj[l] )Unit j of layer l takes the whole activation vector of the previous layer, applies its own weights and bias, then the activation function g.
Read the notation carefully: the superscript says which layer, the subscript says which unit. Each unit has its own weight vector, whose length equals the number of units in the previous layer, and its own scalar bias. Stacking all units of a layer gives a weight matrix.
Counting parameters is a good habit, because it tells you the size of the model and catches shape mistakes. For the 64–25–15–1 digit network used in the labs:
Layer
Weights
Biases
Total
1 (25 units)
64 × 25 = 1,600
25
1,625
2 (15 units)
25 × 15 = 375
15
390
3 (1 unit)
15 × 1 = 15
1
16
All
2,031
sizes = [64, 25, 15, 1]
total = 0
for n_in, n_out in zip(sizes[:-1], sizes[1:]):
params = n_in * n_out + n_out
total += params
print(f"{n_in:>3} -> {n_out:<3} {params:>6,} parameters")
print("total:", f"{total:,}")
Lecture 1.6 · 8 min read
Forward propagation
Computing a network's output is called forward propagation because information moves from the input layer forward to the output. Each layer applies the same two steps: a linear map, then a nonlinearity.
z[l] = W[l] a[l−1] + b[l] a[l] = g( z[l] )W[l] has one row per neuron in layer l and one column per input to that layer. a[0] = x. The final a[L] is the prediction.
Take a concrete network for 8×8 pixel digits: 64 inputs, a hidden layer of 25 neurons, another of 15, and a single output neuron for "is this a 1". The shapes follow from the formula: W[1] is 25×64, W[2] is 15×25, W[3] is 1×15. Each bias vector has one entry per neuron. The total number of parameters is 25·64 + 25 + 15·25 + 15 + 15·1 + 1 = 2,031, which is a question in Lab 1.
Why the nonlinearity? Without g, two linear layers compose into one: W[2](W[1]x + b[1]) + b[2] is just another linear map. However many layers you stack, a purely linear network is linear regression with extra steps. The sigmoid, or the ReLU you will meet next week, is what lets depth buy anything.
Deep dive · Shapes and a forward pass by hand
Derivation of the shape rule
In z[l] = W[l] a[l−1] + b[l], a matrix of shape (p, q) can multiply a vector only if the vector has q entries, and the result has p entries. With nl neurons in layer l, W[l] must be (nl, nl−1) and b[l] must have nl entries. The parameter count follows: Σl nl(nl−1 + 1). The cost of one forward pass is Σl nl · nl−1 multiply-adds.
layer
W shape
b shape
a shape
parameters
multiply-adds
1
25×64
25
25
1,625
1,600
2
15×25
15
15
390
375
3
1×15
1
1
16
15
total
2,031
1,990
The first layer holds 80% of the parameters because it touches the widest vector. That pattern holds in most networks: the layers next to a wide input or a large vocabulary dominate the count.
Worked example by hand: a 2-2-1 network
This small network comes back in “Backpropagation”, where we backpropagate through it. Sigmoid on both layers, input x = (1, 0.5).
W[1] = [[0.5, −0.4], [0.3, 0.8]], b[1] = (0.1, −0.2), W[2] = [1.2, −0.7], b[2] = 0.05W[1] is 2×2: two neurons, two inputs. W[2] is 1×2.
a[2] = σ(0.332704) = 0.582417, the predicted probability.
If the label is y = 1, the log loss is −ln 0.582417 = 0.540568.
Every intermediate number here is cached during a real forward pass, because backpropagation needs a[1] and a[2] again.
Common mistakes
Transposed weights. Writing W[1] as 64×25 in the lecture convention raises a shape error, which is the good case. If a layer is square, the transposed matrix multiplies without complaint and gives wrong numbers. Fix: assert shapes after building parameters.
Nonlinearity missing on a hidden layer. The network still trains but behaves like logistic regression. Symptom: accuracy stuck at the linear baseline.
Sigmoid on a regression output. Predictions are trapped in (0, 1) and house prices of 300 cannot be reached. Fix: linear output for regression.
Applying the sigmoid twice. Taking σ of an output that is already a probability squeezes everything into (0.5, 0.73). Symptom: every prediction is "positive" at threshold 0.5.
Check yourself
How many parameters does a 784–128–10 network have?
Inference, or forward propagation, means running a trained network on new inputs. Take a coffee-roasting example: two features, the roasting temperature in °C and the duration in minutes, and a label saying whether the roast was good. A small network with one hidden layer of three units and one output unit does the job.
In TensorFlow with Keras you describe each layer and call it on the data. This snippet needs TensorFlow, which does not run inside this page, so it is shown for reference:
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense
x = np.array([[200.0, 17.0]]) # one example: 200 °C, 17 minutes
layer_1 = Dense(units=3, activation="sigmoid")
a1 = layer_1(x)
layer_2 = Dense(units=1, activation="sigmoid")
a2 = layer_2(a1)
print(a2.numpy() > 0.5)
PyTorch expresses the same model with nn.Linear layers and explicit activation modules. This version runs here (on torchlite, the bundled NumPy implementation of the PyTorch API). The weights are random because nothing has been trained yet; the point is the flow of shapes.
import torch, torch.nn as nn
torch.manual_seed(0)
x = torch.tensor([[200.0, 17.0]])
x = (x - torch.tensor([[230.0, 14.0]])) / torch.tensor([[25.0, 3.0]]) # normalize the two features
model = nn.Sequential(nn.Linear(2, 3), nn.Sigmoid(), nn.Linear(3, 1), nn.Sigmoid())
a2 = model(x)
print("output shape:", tuple(a2.shape), " probability:", round(a2.item(), 3))
print("good roast?", a2.item() > 0.5)
Both frameworks follow the same pattern: input matrix in, one layer at a time, activations out. Normalizing the inputs first matters just as much as it did for linear regression in Course 1.
Lecture 1.8 · 8 min read
Data in TensorFlow and PyTorch
NumPy and the deep learning frameworks represent data slightly differently, and most beginner bugs are shape bugs. The rule to remember: frameworks expect a 2-D matrix with one row per example and one column per feature, even when you have a single example.
import numpy as np
a = np.array([200.0, 17.0]) # 1-D vector, shape (2,)
x = np.array([[200.0, 17.0]]) # 1 x 2 matrix: one example, two features
col = np.array([[200.0], [17.0]]) # 2 x 1 column
print(a.shape, x.shape, col.shape)
X = np.array([[200.0, 17.0], [120.0, 5.0], [425.0, 20.0]])
print("batch of three examples:", X.shape)
A 1-D array has no notion of rows versus columns, which is why (2,) and (1, 2) behave differently in matrix products. Course 1 used 1-D arrays freely; from here on, keep your inputs 2-D.
TensorFlow stores data as tf.Tensor and PyTorch as torch.Tensor. Both are NumPy-like arrays that can live on a GPU and track gradients. Converting is one call each way: tf.convert_to_tensor(X) and tensor.numpy() in TensorFlow, torch.from_numpy(X) or torch.tensor(X) and tensor.numpy() in PyTorch. Frameworks default to 32-bit floats, so cast your data with astype(np.float32) to avoid dtype errors.
import torch
X32 = X.astype(np.float32)
T = torch.tensor(X32)
print(type(T).__name__, tuple(T.shape), T.dtype)
back = T.numpy()
print("round trip equal:", np.allclose(back, X32))
Lecture 1.9 · 8 min read
The same network in PyTorch
PyTorch gives you the same dense layer as a Linear module, with the weights, the random initialization and, crucially, the gradients computed for you. The forward pass reads almost like the NumPy version.
import torch, torch.nn as nn
model = nn.Sequential(
nn.Linear(64, 25), nn.ReLU(),
nn.Linear(25, 15), nn.ReLU(),
nn.Linear(15, 1), # raw logit; the sigmoid lives in the loss
)
print(sum(p.numel() for p in model.parameters())) # 2031
loss_fn = nn.BCEWithLogitsLoss() # sigmoid + log loss, numerically stable
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(100):
logits = model(X_train) # X_train: float tensor (m, 64)
loss = loss_fn(logits.squeeze(1), y_train) # y_train: float tensor (m,)
opt.zero_grad()
loss.backward() # gradients for all 2,031 parameters
opt.step()
probs = torch.sigmoid(model(X_test)).squeeze(1)
pred = (probs > 0.5).float()
Two conventions worth internalizing. The final layer outputs a raw score, the logit, and the sigmoid is folded into the loss function; BCEWithLogitsLoss computes log(1 + e−z) in a way that cannot overflow, whereas applying a sigmoid and then a log can produce log(0). And the three lines zero_grad, backward, step are the entire gradient descent update: clear old gradients, compute new ones, move the parameters. Every training loop in Courses 2 and 4 has that shape.
Deep dive · What nn.Linear and autograd actually do
Code walkthrough: inside nn.Linear
nn.Linear(64, 25) stores weight with shape (25, 64), the lecture convention of one row per neuron, and computes x @ weight.T + bias. That is why Lab 1 transposes the weight before using it in NumPy. Both tensors are nn.Parameters, which means autograd tracks them and model.parameters() finds them.
The default initialization draws weights and biases uniformly from (−1/√nin, 1/√nin). For nin = 64 the bound is 0.125, so the largest weight you see is just under 0.125, and the standard deviation is 0.125/√3 = 0.072. A uniform distribution on (−c, c) has variance c²/3, so the weight variance is 1/(3nin), a third of the Xavier value. Shallow networks do not care. For deep ReLU stacks, call nn.init.kaiming_normal_ yourself.
Derivation: the stable binary cross-entropy
With p = σ(z), the loss is −y log σ(z) − (1 − y) log(1 − σ(z)). Use two identities: log σ(z) = −log(1 + e−z) and log(1 − σ(z)) = −z − log(1 + e−z). Substituting:
loss = (1 − y) z + log(1 + e−z) = max(z, 0) − z·y + log(1 + e−|z|)The second form never exponentiates a positive number, so it cannot overflow.
To see the two forms agree for z < 0, write log(1 + e−z) = −z + log(1 + ez); the first form becomes −yz + log(1 + ez), which is the second. Differentiating either form gives ∂loss/∂z = σ(z) − y.
Worked example by hand
Take a confidently wrong logit z = 40 with y = 0. In float32, σ(40) = 1 − 4.2·10−18 rounds to exactly 1.0. Sigmoid followed by nn.BCELoss must compute −log(1 − 1) = −log 0. PyTorch clamps the log at −100 and reports a loss of 100, and the gradient through the saturated sigmoid is 0, so the model cannot learn from this example. BCEWithLogitsLoss computes 40 + log(1 + e−40) = 40.0 with gradient σ(40) − 0 = 1.
Why zero_grad exists
backward() adds into .grad rather than overwriting it. With w = 3 and loss w², the first backward() leaves w.grad = 6; calling it again without zeroing leaves 12. Accumulation is deliberate (it lets you sum gradients over several small batches), but in a normal loop forgetting zero_grad() means every step uses the sum of all past gradients.
Common mistakes
Integer labels for BCE.BCEWithLogitsLoss needs float targets of the same shape as the logits. Symptom: a dtype error, or a size-mismatch error if the logits are (m, 1) and labels (m,). Fix: .float() and .squeeze(1).
Float64 NumPy arrays into a float32 model. Symptom: "mat1 and mat2 must have the same dtype". Fix: torch.tensor(X, dtype=torch.float32).
Evaluating with gradients on. Memory grows because every test forward builds a graph. Fix: with torch.no_grad():.
Sigmoid layer inside the model plus BCEWithLogitsLoss. The sigmoid is applied twice and the loss can never go to 0. Fix: let the model output logits.
Check yourself
What are nn.Linear(64, 25).weight.shape and its parameter count?
Answer
(25, 64), and 64 · 25 + 25 = 1,625 parameters.
Module 6
Practice quiz: Framework implementation
Practice quiz · 5 questions
Framework implementation
Module 7
Neural network implementation in Python
Lecture 1.10 · 6 min read
Forward prop in a single layer
Before relying on a framework, compute one layer by hand. For the coffee network, the first hidden layer has three units, each with a weight vector of length two and a bias.
Writing one line per unit does not scale, so stack the weight vectors as the columns of a matrix W and loop over units. This general dense function works for any layer size:
def dense(a_in, W, b, g=sigmoid):
units = W.shape[1]
a_out = np.zeros(units)
for j in range(units):
z = np.dot(W[:, j], a_in) + b[j]
a_out[j] = g(z)
return a_out
W1 = np.array([[1.0, -3.0, 5.0],
[2.0, 4.0, -6.0]]) # column j = weights of unit j
b1 = np.array([-1.0, 1.0, 2.0])
print("dense():", dense(x, W1, b1).round(4)) # same numbers as above
A full forward pass chains dense calls: a1 = dense(x, W1, b1), a2 = dense(a1, W2, b2), and so on. The optional vectorization lectures at the end of this week replace the loop with a single matrix product.
Lecture 1.11 · 7 min read
Vectorized forward propagation in NumPy
One example at a time, a layer is a matrix–vector product. For a whole batch, stack the examples as rows of a matrix A[l−1] with shape (m, inputs), and store the weights transposed so that the batch product is A @ W + b, with W of shape (inputs, neurons). Every library uses this row-major convention, and it is why the lecture formulas and the code look transposed relative to each other.
def dense(A_prev, W, b, g): # A_prev: (m, n_in), W: (n_in, n_out), b: (n_out,)
return g(A_prev @ W + b) # (m, n_out); b broadcasts across rows
def forward(X, params):
A = X
for W, b in params[:-1]:
A = dense(A, W, b, relu)
W, b = params[-1]
return dense(A, W, b, sigmoid) # probabilities, shape (m, 1)
def relu(z): return np.maximum(0, z)
def sigmoid(z): return 1 / (1 + np.exp(-z))
For the digit network, params is a list of three (W, b) pairs with shapes (64, 25), (25,), (25, 15), (15,), (15, 1), (1,). Initialize the weights with small random numbers rather than zeros; if every neuron in a layer starts identical, they receive identical gradients and stay identical forever, and you have paid for one neuron many times.
Deep dive · Batch shapes and initialization variance
Code walkthrough: shapes for a batch of 32
Row i of the batch matrix holds example i. Transposing the single-example rule gives (W[l]a)T = aT(W[l])T, so the code's W is the lecture's W transposed, with shape (n_in, n_out).
X (32, 64) @ W1 (64, 25) -> (32, 25) + b1 (25,) # b1 broadcast to every row
A1 (32, 25) @ W2 (25, 15) -> (32, 15) + b2 (15,)
A2 (32, 15) @ W3 (15, 1) -> (32, 1) + b3 (1,) # one probability per example
Broadcasting aligns trailing dimensions: (32, 25) + (25,) treats b as (1, 25) and repeats it 32 times. A bias of shape (25, 1) fails, which is helpful. The dangerous case is silent: probabilities of shape (32, 1) minus labels of shape (32,) broadcast to a (32, 32) matrix, and the mean of that matrix is a valid-looking but meaningless loss. Flatten one side with .ravel() before comparing.
Derivation: why the scale of random weights matters
For one neuron, z = Σk=1..n wkak with weights drawn independently, mean 0, variance s². Independence makes the variance of the sum the sum of variances, and for each term Var(wkak) = E[wk²]E[ak²] = s² E[a²]. So
Var(z) = n · s² · E[a²]n is the number of inputs to the neuron (fan-in).
If the previous layer is roughly linear around 0 (tanh near 0), E[a²] ≈ Var(zprev), and keeping Var(z) constant across layers needs s² = 1/n. This is Xavier/LeCun initialization. For ReLU, a = max(0, z) with z symmetric about 0, so half the mass is zeroed and E[a²] = ½ Var(zprev). Keeping the variance constant now needs s² = 2/n. This is He initialization.
Worked example: ten ReLU layers
Feed 1,000 standard normal vectors through ten ReLU layers of width 256 and print the standard deviation of the activations after layers 1, 5 and 10.
weight std
layer 1
layer 5
layer 10
0.01
0.093
1.5e-05
2.6e-10
1
9.3
1.5e+05
2.6e+10
√(1/256) (Xavier)
0.58
0.14
0.023
√(2/256) (He)
0.82
0.81
0.75
With std 0.01, each layer multiplies the scale by about 0.01 · √256 · √½ = 0.113, and ten such factors leave nothing. With std 1 the factor is 11.3 and activations overflow. Xavier with ReLU loses a factor √½ per layer. Only He keeps the signal, and the same argument applies to gradients flowing backwards.
Why not zeros
If all of W[1] is zero, every hidden unit computes the same value and receives the same gradient, so after any number of steps the units are still copies. With ReLU and all-zero weights it is worse: the hidden activations are 0 and the gradient to W[1] is exactly 0, so nothing moves.
Common mistakes
Labels shaped (m,) against outputs shaped (m, 1). Symptom: loss that barely changes or accuracy near 50% on an easy task. Fix: y.reshape(-1, 1) or out.ravel().
Bias stored as (1, n_out) in one place and (n_out,) in another. Works by broadcasting but breaks code that checks shapes. Pick one.
std 1 initialization in a deep net. Symptom: nan loss in the first step. Fix: scale by √(2/n_in).
Looping over examples. A Python loop over 1,000 rows pays interpreter overhead 1,000 times, where one matrix product pays it once and runs in optimized BLAS code. Fix: vectorize the batch.
Module 8
Practice quiz: Neural network implementation in Python
Practice quiz · 5 questions
Neural network implementation in Python
Module 9
Speculations on artificial general intelligence (AGI)
Reading · 5 min read
Is there a path to AGI?
It helps to separate two ideas that often get mixed together. ANI, artificial narrow intelligence, means systems that do one task well: a spam filter, a speech recognizer, a recommender, a chatbot that drafts text. ANI has improved enormously and creates real economic value. AGI, artificial general intelligence, means a system that can do any intellectual task a typical person can. Progress in ANI is sometimes taken as proof that AGI is close; it is not, by itself.
Simulating neurons is not a shortcut either. An artificial neuron is a logistic regression unit, a drastic simplification of a biological neuron, and we do not yet understand how the brain learns. Building ever larger networks of simplified units may or may not lead to general intelligence.
There is one intriguing line of evidence. In animal experiments, when the nerve signal from the eyes was rerouted to the part of the brain that normally processes sound, that region learned to process vision. Devices that translate camera images into patterns of pressure on the tongue let blind people learn to perceive shapes. These results suggest that much of the brain may run one fairly general learning algorithm that adapts to whatever data it receives. If so, finding that algorithm could be a path to AGI. Whether we are close to it is genuinely uncertain, and serious researchers disagree.
Since this specialization was written, language models trained on vast text corpora have made the question feel much more urgent, and some people argue they show early signs of generality while others point to their persistent failures in reasoning and reliability. Treat confident predictions in either direction with caution, and judge systems by careful evaluation, the topic of Course 2 Week 3 and Course 4 Week 3.
Module 10 · optional
Vectorization (optional)
Lecture 1.13 · 5 min read
How neural networks are implemented efficiently
One reason neural networks scaled so well is that their computation is almost entirely matrix multiplication, which parallel hardware does extremely fast. The loop-based dense from the previous lecture computes each unit separately; the vectorized version computes all units, for all examples in a batch, in one product.
Z = Ain W + B, Aout = g(Z)A_in is (m, n_in), W is (n_in, n_out), B broadcasts across rows. One line replaces two nested loops.
import numpy as np, time
rng = np.random.default_rng(0)
A_in = rng.normal(size=(500, 64)); W = rng.normal(size=(64, 25)); b = rng.normal(size=25)
sig = lambda z: 1 / (1 + np.exp(-z))
t0 = time.perf_counter()
loop = np.zeros((500, 25))
for i in range(500):
for j in range(25):
loop[i, j] = sig(A_in[i] @ W[:, j] + b[j])
t1 = time.perf_counter()
vec = sig(A_in @ W + b)
t2 = time.perf_counter()
print("same result:", np.allclose(loop, vec))
print(f"loops {1000*(t1-t0):.1f} ms vectorized {1000*(t2-t1):.2f} ms")
Lecture 1.14 · 9 min read
Matrix multiplication
Everything in a vectorized network rests on the dot product. For two vectors of equal length, multiply element by element and add up the results.
a · w = a1w1 + a2w2 + … + anwn = aTwWriting a as a column vector, its transpose a^T is a row, and the row-times-column product equals the dot product.
Multiplying a row vector by a matrix takes the dot product of the row with each column of the matrix. Multiplying two matrices repeats that for every row of the first matrix: entry (i, j) of the result is row i of the first matrix dotted with column j of the second.
import numpy as np
a = np.array([1, 2]); w = np.array([3, 4])
print("dot:", a @ w) # 1*3 + 2*4 = 11
aT = np.array([[1, 2]]) # 1 x 2 row
W = np.array([[3, 5], [4, 6]]) # 2 x 2
print("row @ matrix:", aT @ W) # [[1*3+2*4, 1*5+2*6]] = [[11, 17]]
A = np.array([[1, -1], [2, -2]]) # each row of A^T is one example
print("matrix @ matrix:\n", A @ W)
Lecture 1.15 · 9 min read
Matrix multiplication rules
Two rules cover almost every shape question. First, the inner dimensions must match: an (m × n) matrix can multiply an (n × p) matrix, and the result is (m × p). Second, order matters: AB and BA are generally different, and one of them may not even be defined.
(m × n) · (n × p) → (m × p)Entry (i, j) = Σk Aik Bkj, a dot product of length n.
A
B
AB
(1 × 2)
(2 × 3)
(1 × 3)
(4 × 2)
(2 × 3)
(4 × 3)
(2 × 3)
(2 × 3)
not defined
(3 × 2)
(2 × 3)
(3 × 3)
In a dense layer the activations of m examples form an (m × nin) matrix and the weights form (nin × nout), so the product has one row per example and one column per unit, exactly the shape you want for the next layer.
import numpy as np
A = np.ones((4, 2)); B = np.ones((2, 3))
print((A @ B).shape)
try:
np.ones((2, 3)) @ np.ones((2, 3))
except ValueError as e:
print("error:", str(e).split(":")[0])
X = np.arange(6).reshape(2, 3); Y = np.arange(6).reshape(3, 2)
print("XY:", (X @ Y).shape, " YX:", (Y @ X).shape)
Lecture 1.16 · 6 min read
Matrix multiplication code
In NumPy, A.T is the transpose, and np.matmul(A, W) and A @ W both compute the matrix product. Avoid np.dot for 2-D arrays only because its name hides what it does; the result is the same.
Here is the whole first layer of the coffee network for one example, vectorized. The input is a 1 × 2 row, W holds one column per unit, and b is a 1 × 3 row.
import numpy as np
def g(z): return 1 / (1 + np.exp(-z))
AT = np.array([[200.0, 17.0]])
W = np.array([[1.0, -3.0, 5.0],
[-2.0, 4.0, -6.0]])
B = np.array([[-1.0, 1.0, 2.0]])
def dense(AT, W, B):
Z = np.matmul(AT, W) + B
return g(Z)
print("Z:", (AT @ W + B))
print("A_out:", dense(AT, W, B).round(3))
The raw temperatures saturate the sigmoid, so every activation comes out as exactly 0 or 1. That is another reminder to normalize inputs before they reach the first layer.
scikit-learn ships 1,797 handwritten digits as 8×8 grayscale images, no download needed. You will build the 64–25–15–1 network twice: forward propagation by hand in NumPy with weights you train in PyTorch.
Step 1Load and filter
from sklearn.datasets import load_digits
digits = load_digits()
mask = digits.target < 2 # keep zeros and ones
X = digits.data[mask] / 16.0 # pixels 0..16 → 0..1
y = digits.target[mask].astype(float)
print(X.shape, y.mean()) # (360, 64), about 0.5
How many trainable parameters does the 64–25–15–1 network have?
Step 3Train
Split 70/30 with train_test_split(..., random_state=0), convert to tensors, train for 200 epochs with Adam at lr 1e-3 and print the loss every 20 epochs. It should fall below 0.05. Report test accuracy; 99–100% is normal for this easy pair.
Step 4Forward propagation by hand
Pull the trained weights out with model[0].weight.detach().numpy().T (note the transpose to the (in, out) convention) and the biases likewise. Run your NumPy forward from “Vectorized forward propagation in NumPy” on the test set and confirm the probabilities match PyTorch's to six decimals. Then draw the ten test images with the largest loss; they are the ones worth looking at.
Checkpoint 2
Your extracted first-layer weight array, after transposing, has shape (64, N). What is N?
Week 2 · Neural network training
Neural network training
Train networks end to end: the training recipe, activation functions, multiclass outputs, better optimizers and, optionally, how backpropagation really computes gradients.
Video lectures · Week 2
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
Backpropagation, intuitively3Blue1Brown · YouTube ↗Backpropagation calculus3Blue1Brown · YouTube ↗Neural Networks Part 6: Cross EntropyStatQuest with Josh Starmer · YouTube ↗The spelled-out intro to neural networks and backpropagation: building microgradAndrej Karpathy · YouTube ↗
Module 1
Neural network training
Lecture 2.1 · 8 min read
Training a network in code
Training a neural network uses the same three steps as training logistic regression in Course 1. Only the model inside changes.
Step
Logistic regression
Neural network
1. Specify the model
f(x) = σ(w · x + b)
a stack of layers
2. Specify loss and cost
log loss, averaged
binary cross-entropy, averaged
3. Minimize the cost
gradient descent
gradient descent or Adam, gradients by backpropagation
Keras packs the three steps into Sequential, compile and fit. This needs TensorFlow, so it is shown for reference only:
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.losses import BinaryCrossentropy
model = Sequential([Dense(25, activation="sigmoid"),
Dense(15, activation="sigmoid"),
Dense(1, activation="sigmoid")])
model.compile(loss=BinaryCrossentropy())
model.fit(X, y, epochs=100)
In PyTorch you write the loop yourself, which makes every step visible. This runs in the page on a small synthetic dataset; watch the loss fall.
import numpy as np, torch, torch.nn as nn
torch.manual_seed(0)
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 2)).astype(np.float32)
y = ((X[:, 0] ** 2 + X[:, 1] ** 2) < 1.0).astype(np.float32).reshape(-1, 1) # inside the unit circle?
X_t, y_t = torch.tensor(X), torch.tensor(y)
model = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 1)) # step 1 (outputs logits)
loss_fn = nn.BCEWithLogitsLoss() # step 2
opt = torch.optim.Adam(model.parameters(), lr=0.05) # step 3
for epoch in range(301):
opt.zero_grad()
loss = loss_fn(model(X_t), y_t)
loss.backward()
opt.step()
if epoch % 100 == 0:
print(f"epoch {epoch:3d} loss {loss.item():.4f}")
acc = ((model(X_t) > 0).float() == y_t).float().mean().item()
print("training accuracy:", round(acc, 3))
BCEWithLogitsLoss combines the sigmoid and the cross-entropy in one numerically stable function, so the last layer outputs raw scores (logits). The lecture on the improved softmax implementation explains why that is better.
Lecture 2.2 · 9 min read
The training loop in practice
An epoch is one pass over the training set. With a batch size of 64 and 10,000 examples, an epoch is 157 steps. Shuffle before each epoch so batches differ. Evaluate on the validation set after every epoch and keep the parameters from the epoch with the lowest validation loss, not the last epoch; this is early stopping, and it is the cheapest regularizer there is.
from torch.utils.data import TensorDataset, DataLoader
train_dl = DataLoader(TensorDataset(X_tr, y_tr), batch_size=64, shuffle=True)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=30)
best, best_state = float("inf"), None
for epoch in range(30):
model.train()
for xb, yb in train_dl:
loss = loss_fn(model(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
sched.step() # decay the learning rate once per epoch
model.eval()
with torch.no_grad():
val_loss = loss_fn(model(X_val), y_val).item()
if val_loss < best:
best, best_state = val_loss, {k: v.clone() for k, v in model.state_dict().items()}
model.load_state_dict(best_state)
Learning-rate schedules start high, when big steps are safe, and decay toward zero, when precision matters; cosine decay is the usual shape. Warmup, a few hundred steps of linearly rising learning rate at the start, protects freshly initialized parameters, or a freshly attached adapter in Course 4, from a huge first step. Dropout, which randomly zeroes a fraction of activations during training, is the other common regularizer for networks; model.train() and model.eval() exist to switch it on and off.
Deep dive · Schedules, dropout and the arithmetic of the loop
Steps and batch bookkeeping
10,000 examples with batch size 64 give ⌈10000/64⌉ = 157 steps per epoch, and the last batch has 10,000 − 156 · 64 = 16 examples. In Lab 2, 1,077 training digits give 17 steps with a last batch of 53. Averaging the 17 batch losses equally would overweight those 53 examples slightly. That is why the lab accumulates loss.item() * len(xb) and divides by the dataset size.
Derivation: cosine decay and warmup
ηt = ηmin + ½(ηmax − ηmin)(1 + cos(πt/T))t counts scheduler steps, T is T_max.
With ηmax = 10−3, ηmin = 0 and T = 30: t = 0 gives 1e-3; t = 10 gives 7.5e-4; t = 15 gives 5e-4; t = 20 gives 2.5e-4; t = 29 gives 2.7e-6. Because sched.step() runs at the end of each epoch, epoch t trains at ηt. The curve is flat at both ends: it keeps a high rate for the early epochs and spends the last few at very small steps. Linear warmup for S steps uses ηs = ηpeak(s + 1)/S for s < S, then hands over to the decay.
Derivation: inverted dropout
During training, each activation is kept with probability 1 − p and zeroed otherwise, and kept values are divided by 1 − p. With mask entry mi ∈ {0, 1}, the output is aimi/(1 − p), whose expectation is ai(1 − p)/(1 − p) = ai. Because the expected activation already matches, evaluation mode can simply pass activations through unchanged. Example with p = 0.2 (scale 1/0.8 = 1.25): a = (2, 4, 6, 8, 10) with mask (1, 0, 1, 1, 0) becomes (2.5, 0, 7.5, 10, 0). Each step trains a different thinned network, so no unit can rely on one specific partner being present.
Weight decay in numbers
AdamW multiplies every weight by 1 − η · λ each step before the Adam update. With η = 10−3 and λ = 0.01 that factor is 0.99999. Over 10,000 steps at constant η, a weight that received no gradient would shrink to 0.9999910000 = 0.905 of its value. Decay is gentle per step and adds up over a long run.
Early stopping with patience
The lecture loop keeps the best checkpoint but still runs all epochs. Adding patience stops once the validation loss has not improved for k consecutive epochs. With k = 10 on a run whose minimum is at epoch 18, training ends after epoch 28 and the epoch-18 weights are restored.
Common mistakes
Saving the state dict without .clone().state_dict() returns references to the live tensors, which keep changing. Symptom: the "best" checkpoint is identical to the last epoch. Fix: clone each tensor, or copy.deepcopy.
Validating in train mode. Dropout stays active, so validation loss is noisy and too high. Fix: model.eval() before evaluation and model.train() after.
Calling sched.step() per batch with T_max in epochs. The rate reaches zero after 30 batches, and because CosineAnnealingLR is periodic it then rises again. Symptom: a sawtooth loss curve. Fix: match the unit of T_max to where you call step().
No shuffling on sorted data. If examples are sorted by class, each batch contains one class and the model chases the latest batch. Fix: shuffle=True.
Peeking at the test set inside the loop. Choosing the checkpoint by test loss turns the test set into a validation set.
Module 2
Practice quiz: Neural network training
Practice quiz · 5 questions
Neural network training
Module 3
Activation functions
Lecture 2.3 · 7 min read
Activation functions
Three activations cover almost every case. Sigmoid outputs (0, 1) and belongs on a binary output. Linear, meaning no activation, belongs on a regression output that may be any real number. ReLU, g(z) = max(0, z), belongs in hidden layers, and the reason is backpropagation.
The sigmoid's derivative g(1 − g) is at most 0.25 and near zero for |z| above about 5. Backprop multiplies derivatives along the chain, so through ten sigmoid layers the gradient reaching the first layer is at most 0.25¹⁰, which is a millionth. The early layers stop learning. This is the vanishing gradient problem. ReLU's derivative is exactly 1 for positive inputs, so gradients pass through unchanged, and it costs one comparison to compute. Networks trained with ReLU converge several times faster, which is why it replaced the sigmoid in hidden layers around 2012.
ReLU's flaw is that a neuron whose input is always negative outputs zero and receives zero gradient: it is dead and cannot recover. Variants such as leaky ReLU (a small slope for negative inputs) and GELU (a smooth version used in transformers, including every model you will fine-tune in Course 4) avoid that. For this course, ReLU in hidden layers, and the output activation dictated by the task.
Deep dive · Vanishing gradients, measured
Derivation
Take a chain of scalar layers al = g(wlal−1). By the chain rule, ∂aL/∂a0 = Πl=1..L wlg′(zl). For vectors each factor becomes a matrix WlTdiag(g′(zl)), but the conclusion is the same: the gradient at layer 1 is a product of L terms. If each term is typically below 1 the product shrinks geometrically; above 1 it grows.
activation
derivative
largest value
value at z = 2
value at z = 5
sigmoid
σ(z)(1 − σ(z))
0.25 at z = 0
0.105
0.0066
tanh
1 − tanh²(z)
1 at z = 0
0.071
0.00018
ReLU
1 if z > 0 else 0
1
1
1
Worked example: gradient norms in a 10-layer network
Ten hidden layers of width 64, batch of 256 random inputs, loss = mean squared output, biases zero. Sigmoid and tanh use Xavier initialization, ReLU uses He. Compare the gradient norm of the first layer's weights with the tenth's:
hidden activation
‖∂L/∂W‖ layer 1
‖∂L/∂W‖ layer 10
ratio
sigmoid
7.4e-08
0.39
1.9e-07
tanh
0.021
0.063
0.34
ReLU
0.097
0.44
0.22
With sigmoid the first layer gets a gradient five million times smaller than the last, a factor of about 0.18 per layer over nine layers. With one learning rate for all layers, the early layers do not move. Tanh and ReLU keep the ratio within a factor of five. Tanh does well here because it is centered at zero and its slope is 1 at the origin; sigmoid's outputs are centered at 0.5 and its slope never exceeds 0.25.
Dead ReLUs
A ReLU unit computes max(0, w · x + b). If a large update pushes b to, say, −10 while the inputs lie in [0, 1] and the weights are small, w · x + b is negative for every example. The output is always 0, the local derivative is always 0, and no gradient ever reaches w or b again. Leaky ReLU, max(0.01z, z), keeps a slope of 0.01 for negative inputs so the unit can recover. GELU, z · Φ(z) with Φ the standard normal CDF, is smooth: GELU(1) = 0.8413, GELU(−1) = −0.1587, GELU(−3) = −0.0040.
Output activations and the loss that goes with them
Pair the sigmoid output with log loss, not squared error. With squared error ½(a − y)², the gradient at z is (a − y) · a(1 − a). For a confidently wrong prediction a = 0.001 with y = 1, that is −0.999 · 0.001 · 0.999 = −0.000998: almost no signal exactly when the model is most wrong. With log loss the gradient is a − y = −0.999.
Common mistakes
Sigmoid in the hidden layers of a deep net. Symptom: training loss flat for many epochs, early-layer weights unchanged. Fix: ReLU or GELU with He initialization.
ReLU on a regression output. The network cannot predict negative values. Symptom: all negative targets predicted as 0. Fix: linear output.
Learning rate so high that many ReLUs die. Symptom: accuracy drops and never recovers; many hidden activations are exactly 0 for every input. Fix: lower the learning rate or use leaky ReLU.
Sigmoid output with MSE. Learning stalls on confident mistakes, as computed above.
Lecture 2.4 · 7 min read · demo
Why nonlinearity matters
The two interleaved crescents below cannot be separated by a straight line, so logistic regression on the raw coordinates tops out around 85% accuracy. A network with a hidden layer bends the boundary. Train it and watch the colored regions form; then set the hidden layer to one unit and train again to see how little a single neuron can do.
Train a network in your browser2 → h → 1 · tanh hidden · sigmoid output
steps 0log loss –accuracy –
What the hidden units are doing: each one draws a straight line through the plane and outputs how far a point is from it, squashed by tanh. The output neuron combines eight such "distance from a line" features into a curved boundary. More units give more lines to combine, which is more flexibility, which is also more capacity to overfit the sixty training points. Nothing from Course 1 has gone away.
Deep dive · Linear collapse, XOR and bumps
Derivation: stacked linear layers are one layer
Without activations, W[2](W[1]x + b[1]) + b[2] = (W[2]W[1])x + (W[2]b[1] + b[2]). The product of the matrices is a single matrix W and the bracket is a single vector b. By induction this holds for any depth.
Numeric check: W[1] = [[1, 2], [0, 1]], b[1] = (1, 0), W[2] = [1, −1], b[2] = 0.5. Then W = W[2]W[1] = [1, 1] and b = 1 · 1 − 1 · 0 + 0.5 = 1.5. For x = (2, 3): the two-layer path gives hidden values (2 + 6 + 1, 3) = (9, 3) and output 9 − 3 + 0.5 = 6.5; the collapsed layer gives 2 + 3 + 1.5 = 6.5.
Derivation: no single linear boundary solves XOR
Suppose w1x1 + w2x2 + b is positive exactly on the XOR-true points. Then (0, 0) gives b < 0; (1, 0) gives w1 + b > 0; (0, 1) gives w2 + b > 0; (1, 1) gives w1 + w2 + b < 0. Adding the middle two: w1 + w2 + 2b > 0, so w1 + w2 + b > −b > 0, contradicting the last inequality. The crescents in the demo fail for the same reason, only less cleanly.
Derivation: why one hidden unit is no better than logistic regression
With h = 1, the output is σ(v · tanh(w · x + b) + c). Both σ and tanh are monotone, so the output is a monotone function of the single number w · x + b. Any threshold on the output is a threshold on w · x + b, which is a straight line in the plane. Setting h = 1 in the demo always gives a straight boundary. The same argument holds for a ReLU unit, because ReLU is also monotone.
Worked example: building a bump from two units
Two sigmoid units with opposite signs make a bump: f(x) = σ(10(x − 0.3)) − σ(10(x − 0.7)).
x
σ(10(x − 0.3))
σ(10(x − 0.7))
f(x)
0
σ(−3) = 0.0474
σ(−7) = 0.0009
0.0465
0.5
σ(2) = 0.8808
σ(−2) = 0.1192
0.7616
1
σ(7) = 0.9991
σ(3) = 0.9526
0.0465
The function is high between 0.3 and 0.7 and low outside. An output layer can scale and add many such bumps, two hidden units each, to approximate any continuous function of one variable on an interval as closely as you like, provided you have enough units. This is the idea behind the universal approximation theorem. It promises that a wide enough network can represent the function; it says nothing about whether gradient descent will find the weights or how many examples that takes.
Counting the demo network
The demo's 2 → 8 → 1 network has 8 · 2 + 8 = 24 hidden parameters and 8 + 1 = 9 output parameters, 33 in total, against sixty training points. That ratio is why the boundary can wrap around individual points when you train long enough.
Common mistakes
Adding depth without activations. The model is still linear. Symptom: same accuracy as logistic regression however many layers you add.
Taking the approximation theorem as a guarantee. A network that could represent the function can still underfit if training is too short or the learning rate is wrong.
Too few hidden units for the shape. h = 2 can draw at most two lines; a crescent boundary needs several. Symptom: training accuracy plateaus well below 100%.
Too many units and too few points. h = 100 on sixty points produces islands around single examples. Check on held-out points.
Module 4
Practice quiz: Activation functions
Practice quiz · 5 questions
Activation functions
Module 5
Multiclass classification
Lecture 2.5 · 4 min read
Multiclass classification
Binary classification answers yes or no. Many problems have more than two possible labels: which of the ten digits is in an image, which of several diseases a patient has, which kind of defect appears on a manufactured part. This is multiclass classification: y takes one of a small number of discrete values, and exactly one of them is correct.
With two classes, logistic regression estimates P(y = 1 | x) and P(y = 0 | x) follows. With n classes we want a probability for each class, P(y = 1 | x), …, P(y = n | x), that add up to one. Geometrically the classifier then divides the feature space into n regions instead of two, separated by decision boundaries.
The tool for this is the softmax output layer, covered in the next lecture, which turns n raw scores into n probabilities.
Lecture 2.6 · 9 min read
Losses: binary cross-entropy and softmax
For two classes the output layer is one sigmoid neuron and the loss is log loss, exactly as in Course 1. For K classes you want K outputs that behave like a probability distribution: each between 0 and 1, all summing to 1. Softmax does that: exponentiate every score so it is positive, then divide by the sum.
ak = ezk / Σj=1..K ezj loss = −log ayCross-entropy: minus the log of the probability assigned to the true class y. With K = 2, softmax reduces to the sigmoid and this reduces to log loss.
Softmax exaggerates differences: scores (2, 1, 0.1) become probabilities (0.659, 0.242, 0.099). Subtracting the largest score from every score before exponentiating changes nothing mathematically (the shift cancels in the ratio) but prevents overflow when scores are large; every library does this, and so should your NumPy version.
def softmax(z): # z: (m, K)
z = z - z.max(axis=1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
def cross_entropy(probs, y): # y: integer labels (m,)
return -np.log(probs[np.arange(len(y)), y]).mean()
In PyTorch, nn.CrossEntropyLoss takes raw logits of shape (m, K) and integer labels; it applies the log-softmax internally in a stable form. The model's last layer should therefore be a plain Linear(..., K) with no softmax after it, just as the binary case ended in a plain logit. Apply softmax only when you want to read probabilities.
Deep dive · Why the softmax gradient is p − y
Derivation
Write the loss for one example with true class y directly in terms of the logits. Since ay = ezy / Σjezj,
L = −log ay = −zy + log Σj ezjThe second term is the log-sum-exp of the logits.
Differentiate with respect to one logit zk. The first term contributes −1 if k = y and 0 otherwise. The derivative of log Σjezj is ezk / Σjezj = ak. So
∂L/∂zk = ak − ykyk is the one-hot label: 1 for the true class, 0 elsewhere. For a batch mean, divide by m.
The same result comes out of the long route. The softmax Jacobian is ∂ai/∂zk = ai(δik − ak), and ∂L/∂ai = −yi/ai. Multiplying and summing over i gives −Σi yi(δik − ak) = −yk + akΣiyi = ak − yk, because the one-hot entries sum to 1. The awkward 1/ai cancels, which is why frameworks fuse softmax and cross-entropy into one operation.
With K = 2, a1 = ez1/(ez1 + ez2) = 1/(1 + e−(z1−z2)) = σ(z1 − z2). Only the difference of the two logits matters, and the gradient a − y is the familiar one from logistic regression.
Gradient: (0.659 − 1, 0.242, 0.099) = (−0.341, 0.242, 0.099). It sums to zero, so a step raises the true logit and lowers the others by the same total.
Stability: for z = (1000, 1001), e1000 overflows to inf and the ratio becomes nan. Subtracting the max gives (−1, 0), probabilities (0.269, 0.731), and log-sum-exp = 1001 + log(e−1 + 1) = 1001.3133.
A sanity check you can run on every new model
A freshly initialized K-class network outputs logits near zero, so all probabilities are near 1/K and the loss is near ln K. For ten digits that is ln 10 = 2.303. If your first printed loss is 23 instead, the logits are far too large (bad initialization or unscaled inputs). If it is 0.69, you are using a binary loss by mistake.
Common mistakes
Softmax in the model and in the loss.CrossEntropyLoss then applies softmax to numbers in [0, 1]. With ten classes the best it can reach is e/(e + 9) = 0.232 for the true class, so the loss cannot fall below −ln 0.232 = 1.461 and gradients are small. Symptom: loss stalls around 1.5 while accuracy looks fine.
Labels from 1 to K. Class index K is out of range. Symptom: "index out of bounds" or a CUDA assert. Fix: labels 0..K−1.
One-hot float targets of the wrong shape.CrossEntropyLoss expects integer labels (m,), or class probabilities with the same shape as the logits. Mixing them gives shape errors.
log(softmax(z)) in two steps. An underflowed probability of 0 gives −inf. Fix: compute log-softmax as z − logsumexp(z).
log base confusion. Losses use natural log; 2.303 for ten classes in nats is 3.32 in bits. Compare like with like.
Lecture 2.7 · 9 min read
Improved implementation of softmax
Computers store numbers with limited precision, and the order of operations matters. Compute 2/10,000 directly, or as (1 + 1/10,000) − (1 − 1/10,000): mathematically equal, but the second loses digits to round-off. Softmax and cross-entropy have the same problem in a much worse form, because they involve exponentials.
import numpy as np
print(f"{2/10000:.18f}")
print(f"{(1 + 1/10000) - (1 - 1/10000):.18f}")
def softmax_naive(z):
e = np.exp(z)
return e / e.sum()
with np.errstate(over="ignore", invalid="ignore"):
print("naive:", softmax_naive(np.array([1000.0, 999.0, 998.0])))
Exponentials overflow for large scores. The fix uses the fact that softmax does not change when you subtract the same number from every score: subtract the largest score first, so the biggest exponent is e0 = 1.
softmax(z)j = ezj − max(z) / Σk ezk − max(z), log softmax(z)j = zj − max(z) − log Σk ezk − max(z)The second form, the log-sum-exp trick, gives the log-probabilities that cross-entropy needs without ever computing a tiny probability and taking its log.
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
def log_softmax(z):
m = z.max()
return z - m - np.log(np.exp(z - m).sum())
z = np.array([1000.0, 999.0, 998.0])
print("stable:", softmax(z).round(4))
print("loss for class 2:", round(-log_softmax(z)[2], 4))
This is why frameworks prefer logits, the raw scores before softmax, as the network output. In Keras you use a linear output layer and SparseCategoricalCrossentropy(from_logits=True); in PyTorch, nn.CrossEntropyLoss always expects logits. At prediction time, apply softmax yourself if you need probabilities; for the predicted class, the largest logit is enough.
Lecture 2.8 · 4 min read
Classification with multiple outputs (optional)
Multiclass and multi-label sound alike but are different problems. In multiclass, exactly one label is correct. In multi-label classification each input can have several labels at once: a street photo might contain a car, a bus and a pedestrian, all at the same time.
You could train three separate networks, one per question. Usually it is better to train one network with three output units, each with its own sigmoid, because the hidden layers can share the visual features that all three questions need. The loss is the sum of three binary cross-entropies.
import numpy as np
logits = np.array([2.1, -1.3, 0.4]) # car, bus, pedestrian
probs = 1 / (1 + np.exp(-logits))
labels = ["car", "bus", "pedestrian"]
print({l: round(float(pr), 3) for l, pr in zip(labels, probs)})
print("present:", [l for l, pr in zip(labels, probs) if pr > 0.5])
print("softmax would force a single answer:", labels[int(np.argmax(logits))])
Module 6
Practice quiz: Multiclass classification
Practice quiz · 5 questions
Multiclass classification
Module 7
Additional neural network concepts
Lecture 2.9 · 9 min read
Optimizers: SGD, momentum, Adam
With a large dataset, computing the gradient over every example before each step is wasteful; the gradient from a random batch of 32 or 256 examples points roughly the same way and costs a thousandth as much. Taking steps on such mini-batches is stochastic gradient descent. The noise in the gradient is not only tolerable but useful: it helps the optimizer escape flat regions and poor local minima that plain gradient descent would settle into.
Momentum keeps a running average of past gradients and steps along that average, so oscillations across a narrow valley cancel while consistent directions accumulate speed. RMSProp keeps a running average of each parameter's squared gradient and divides the step by its square root, giving parameters with small gradients a larger effective learning rate. Adam combines both and corrects the averages for their bias toward zero in the first steps.
m ← β₁m + (1−β₁)g v ← β₂v + (1−β₂)g² w ← w − α · m̂ / (√v̂ + ε)Per parameter. Defaults β₁ = 0.9, β₂ = 0.999, ε = 1e-8. m̂ and v̂ are the bias-corrected averages.
Adam's per-parameter scaling means feature scaling matters less than it did in Course 1, and a single learning rate works across layers whose gradients differ by orders of magnitude. The usual starting point is 1e-3; for fine-tuning pretrained models it is far smaller, 1e-5 to 2e-4, because the weights start near a good solution and large steps destroy it. AdamW, the variant that applies weight decay directly to the weights rather than through the gradient, is the default in Course 4.
Deep dive · Momentum and Adam, three steps by hand
Setup
Minimize f(w) = w² starting from w = 1 with learning rate α = 0.1. The gradient is g = 2w.
Worked example: plain SGD and momentum
Plain gradient descent multiplies w by 1 − 0.1 · 2 = 0.8 each step: 0.8, 0.64, 0.512. Momentum with v ← 0.9v + g and w ← w − αv:
step
g
v
w
1
2.0000
2.0000
0.8000
2
1.6000
0.9 · 2 + 1.6 = 3.4000
0.4600
3
0.9200
0.9 · 3.4 + 0.92 = 3.9800
0.0620
Momentum reaches 0.062 where SGD is at 0.512, because the velocity keeps growing while gradients agree in sign. The same speed makes it overshoot zero on the next steps and oscillate with decreasing amplitude. In a narrow valley, gradient components across the valley change sign every step and cancel in v, while the component along the valley accumulates.
Worked example: Adam
β1 = 0.9, β2 = 0.999, ε = 10−8, m and v start at 0. Bias-corrected m̂ = m/(1 − β1t), v̂ = v/(1 − β2t), step = α m̂/(√v̂ + ε).
t
g
m
v
m̂
v̂
step
w
1
2.000000
0.200000
0.004000
2.000000
4.000000
0.100000
0.900000
2
1.800000
0.360000
0.007236
1.894737
3.619810
0.099588
0.800412
3
1.600824
0.484082
0.009791
1.786282
3.267067
0.098826
0.701586
Check step 2: v = 0.999 · 0.004 + 0.001 · 1.8² = 0.007236; v̂ = 0.007236/(1 − 0.999²) = 0.007236/0.001999 = 3.61981; m̂ = 0.36/0.19 = 1.894737; step = 0.1 · 1.894737/1.902580 = 0.099588. Each step is close to α = 0.1, whatever the size of the gradient. On f(w) = 1000w² the first step is still 0.1. That scale invariance is what lets one learning rate serve layers whose gradients differ by orders of magnitude.
Derivation of the bias correction
Unrolling mt = β1mt−1 + (1 − β1)gt from m0 = 0 gives mt = (1 − β1)Σi=1..tβ1t−igi. If the gradient were constant g, the geometric sum gives mt = g(1 − β1t), so dividing by 1 − β1t recovers g. The same holds for v. Without correction, the first step would be α · 0.1g/√(0.001g²) = 3.16α, more than three times too large, because v starts further below its target than m does. The averages remember roughly 1/(1 − β) steps: about 10 for m and 1,000 for v.
Mini-batch noise
If per-example gradients have variance σ², the mean over a batch of B has variance σ²/B. Going from batch 32 to 256 cuts the gradient's standard deviation by √8 = 2.83 at eight times the cost per step.
Common mistakes
Using Adam's learning rate with SGD, or the reverse. lr 1e-3 is slow for plain SGD on many problems; lr 0.1 usually makes Adam diverge.
Skipping bias correction in a hand-written Adam. Symptom: unstable first few hundred steps. Fix: divide by 1 − βt.
Recreating the optimizer inside the epoch loop. m and v reset to zero every epoch. Create it once.
Adam's weight_decay is not AdamW's. In Adam the decay term λw is added to the gradient and then divided by √v̂, so weights with large gradients are barely decayed. AdamW subtracts αλw from the weights directly.
Lecture 2.10 · 8 min read
Additional layer types
Every layer so far has been dense: each unit sees every activation of the previous layer. A convolutional layer restricts each unit to a small window of the input. For an image, one unit might look only at a 3 × 3 patch; for a heart-rate signal, at 20 consecutive samples. All units share the same small set of weights, sliding the window across the input.
Faster: far fewer multiplications per unit.
Less data needed and less overfitting: far fewer parameters, and the same pattern detector is reused at every position.
Built-in structure: nearby pixels or time steps are processed together, which matches how images and signals work.
Here is a one-dimensional convolution on a toy signal: a window of three weights that responds to sudden rises.
import numpy as np
signal = np.array([0, 0, 0, 1, 1, 1, 0, 0, 3, 3, 0], dtype=float)
kernel = np.array([-1.0, 0.0, 1.0]) # rise detector: right minus left
out = np.array([signal[i:i + 3] @ kernel for i in range(len(signal) - 2)])
print("output:", out)
print("dense layer on 11 inputs -> 9 units would need", 11 * 9, "weights; this layer uses", kernel.size)
Convolutional layers are the backbone of image models. The new Course 5 in this specialization covers them in depth, including how to build a complete convolutional network.
Module 8
Practice quiz: Additional neural network concepts
Practice quiz · 5 questions
Additional neural network concepts
Module 9 · optional
Back propagation (optional)
Lecture 2.11 · 12 min read
What is a derivative? (optional)
The derivative of J with respect to w answers one question: if w goes up by a tiny amount ε, by how much does J go up? If J increases by k·ε, the derivative is k.
Take J(w) = w² at w = 3, so J = 9. Increase w to 3.001: J becomes 9.006001, an increase of about 6 × 0.001. The derivative at w = 3 is therefore 6, which matches the calculus rule d(w²)/dw = 2w. At w = −3 the same experiment gives −6: J goes down when w goes up.
def numeric_derivative(J, w, eps=1e-6):
return (J(w + eps) - J(w)) / eps
for name, J, rule in [("w^2", lambda w: w ** 2, lambda w: 2 * w),
("w^3", lambda w: w ** 3, lambda w: 3 * w ** 2),
("1/w", lambda w: 1 / w, lambda w: -1 / w ** 2)]:
for w in (2.0, 3.0):
print(f"{name:4s} at w={w}: numeric {numeric_derivative(J, w):8.4f} rule {rule(w):8.4f}")
Gradient descent uses this directly: w ← w − α ∂J/∂w. A large derivative means a steep cost, so take a big step against it; a derivative near zero means you are near a flat spot, possibly the minimum. The numeric check above, called gradient checking, is also the standard way to test a hand-written backpropagation.
Lecture 2.12 · 12 min read
Computation graph (optional)
Backpropagation is easiest to see on a computation graph: break the cost into small steps, compute them left to right (forward), then compute derivatives right to left (backward), reusing each result.
Use a one-neuron linear model with x = −2, y = 2, w = 2, b = 8 and cost J = ½(a − y)².
Forward step
Value
Backward: derivative of J
Value
c = w · x
−4
∂J/∂c = ∂J/∂a · 1
2
a = c + b
4
∂J/∂a = ∂J/∂d · 1
2
d = a − y
2
∂J/∂d = d
2
J = ½ d²
2
Then ∂J/∂b = ∂J/∂a = 2 and ∂J/∂w = ∂J/∂c · x = 2 × (−2) = −4. Each step multiplies the derivative arriving from the right by a local derivative: that is the chain rule, applied mechanically.
x, y, w, b = -2.0, 2.0, 2.0, 8.0
c = w * x; a = c + b; d = a - y; J = 0.5 * d ** 2 # forward
dJ_dd = d; dJ_da = dJ_dd; dJ_dc = dJ_da; dJ_db = dJ_da; dJ_dw = dJ_dc * x # backward
print("J =", J, " dJ/dw =", dJ_dw, " dJ/db =", dJ_db)
eps = 1e-6
Jw = 0.5 * ((w + eps) * x + b - y) ** 2
print("numeric dJ/dw:", round((Jw - J) / eps, 4))
Why bother? With N nodes and P parameters, nudging each parameter separately costs about N × P steps. The backward pass reuses intermediate derivatives and costs about N + P. For a network with millions of parameters that is the difference between impossible and routine. The next lecture applies the same procedure to a network with hidden layers.
Lecture 2.13 · 11 min read
Backpropagation
Gradient descent needs ∂loss/∂w for every weight. A network's loss is a long chain of functions: the input goes through a linear map, a nonlinearity, another linear map, and so on into the loss. The chain rule says the derivative of a chain is the product of the derivatives of its links. Backpropagation is the chain rule organized so that each derivative is computed once and reused.
Think of the computation as a graph. Forward propagation walks it left to right, computing each node's value from its inputs and caching it. Backpropagation walks it right to left: starting with ∂loss/∂loss = 1, each node multiplies the gradient flowing in from the right by its own local derivative and passes the result to its inputs on the left. A node with several outputs sums the gradients arriving from each. When the walk reaches a weight, the accumulated product is ∂loss/∂w.
A worked single chain: loss J = (a − y)², a = g(z), z = w·x + b. The local derivatives are ∂J/∂a = 2(a − y), ∂a/∂z = g′(z), ∂z/∂w = x. Multiply: ∂J/∂w = 2(a − y) · g′(z) · x. The term 2(a − y)·g′(z) is shared by every weight feeding z; backprop computes it once. For a dense layer the whole thing is two matrix products: with δ the gradient at the layer's output, the weight gradient is Aprevᵀ δ and the gradient passed to the previous layer is δ Wᵀ, masked by the activation's derivative.
The cost of backpropagation is about twice a forward pass, independent of the number of parameters: that is why training a million-parameter network is possible at all. Computing each ∂J/∂w numerically by nudging w and rerunning the forward pass would cost a million forward passes per step. Libraries implement backprop as automatic differentiation; loss.backward() in PyTorch is this walk over a graph PyTorch recorded during the forward pass.
Deep dive · Backpropagation through a 2-2-1 network, every number
Derivation for the output unit
For a sigmoid output a = σ(z) with log loss L = −y ln a − (1 − y) ln(1 − a): ∂L/∂a = −y/a + (1 − y)/(1 − a) and ∂a/∂z = a(1 − a). Multiplying, the a(1 − a) cancels the denominators and leaves ∂L/∂z = a − y. That is the dZ2 = A2 − y line in the lecture code.
Derivation for a dense layer in matrix form
For a batch, Z = AprevW + b with δ = ∂L/∂Z known. Entry Znk = ΣiAprev,niWik + bk. Weight Wik appears in Znk for every example n, with coefficient Aprev,ni, so ∂L/∂Wik = ΣnAprev,niδnk, which is (AprevTδ)ik. Input Aprev,ni appears in Znk for every neuron k with coefficient Wik, so ∂L/∂Aprev,ni = ΣkδnkWik = (δWT)ni. The bias appears once per example, so ∂L/∂b = Σnδn. Each layer needs two matrix products backwards against one forwards, which is where "about twice a forward pass" comes from.
Worked example by hand
Use the network and forward values from “Forward propagation” (lecture convention, W[1] rows are neurons): x = (1, 0.5), y = 1, a[1] = (0.598688, 0.622459), a[2] = 0.582417, loss 0.540568.
quantity
formula
value
dz[2]
a[2] − y
−0.417583
dW[2]
dz[2] · a[1]
(−0.250002, −0.259928)
db[2]
dz[2]
−0.417583
da[1]
dz[2] · W[2] = −0.417583 · (1.2, −0.7)
(−0.501100, 0.292308)
σ′(z[1])
a[1](1 − a[1])
(0.240261, 0.235004)
dz[1]
da[1] ⊙ σ′(z[1])
(−0.120395, 0.068693)
dW[1]
dz[1] xT
[[−0.120395, −0.060197], [0.068693, 0.034347]]
db[1]
dz[1]
(−0.120395, 0.068693)
Gradient check: nudge W[1]11 from 0.5 to 0.5 ± 10−5, rerun the forward pass, and take (L+ − L−)/(2 · 10−5). The result is −0.1203945, matching the table. One gradient-descent step with learning rate 0.5 on all eight parameters lowers the loss from 0.540568 to 0.386820.
Read the signs: dW[2]2 is negative, so the step increases the weight from hidden unit 2 even though it started at −0.7, because raising it raises the output toward y = 1. The gradient to hidden unit 1's weights is negative and to unit 2's is positive, because they reach the output through weights of opposite sign.
Common mistakes
Forgetting the 1/m. If the loss is a batch mean, dZ must be divided by m. Symptom: the effective learning rate grows with batch size; a gradient check fails by a factor of exactly m.
Using σ′(a) instead of σ′(z). The sigmoid derivative is a(1 − a), written in terms of the output. Computing σ(a)(1 − σ(a)) applies the sigmoid twice. For ReLU, (Z > 0) and (A > 0) are the same mask, which hides this bug until you switch activations.
Not summing the bias gradient over the batch. db must have shape (n_out,), not (m, n_out).
Gradient checks in float32 or with tiny ε. Rounding error dominates. Use float64, ε around 10−5 and a central difference; agreement to about 10−7 relative is a pass.
First entry of softmax((2, 1, 0.1)), to three decimals?
Step 2All ten digits in PyTorch
X = torch.tensor(digits.data / 16.0, dtype=torch.float32)
y = torch.tensor(digits.target) # int64 labels 0..9
model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
loss_fn = nn.CrossEntropyLoss()
Split 60/20/20 into train, validation and test. Train with the full loop from “The training loop in practice”: batches of 64, AdamW at 1e-3, cosine schedule over 60 epochs, early stopping on validation loss. Plot training and validation loss per epoch on the same axes.
Step 3Evaluate
Report test accuracy (97–99% is typical) and print the confusion matrix with sklearn.metrics.confusion_matrix. Which two digits are confused most often? Look at five of those images.
Step 4Experiments
Rerun with sigmoid hidden activations and compare the loss curves; then with learning rate 0.1; then with no shuffling. For each, write one sentence on what changed and why. Keep this notebook: Week 3 reuses it.
Checkpoint 2
How many parameters does the 64–64–32–10 network have?
Week 3 · Advice for applying machine learning
Advice for applying machine learning
What to try next when a model disappoints: evaluate properly, diagnose bias and variance, run the development loop, and handle skewed data.
Video lectures · Week 3
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
Machine Learning Fundamentals: Bias and VarianceStatQuest with Josh Starmer · YouTube ↗ROC and AUC, Clearly ExplainedStatQuest with Josh Starmer · YouTube ↗
Module 1
Advice for applying machine learning
Lecture 3.1 · 4 min read
Deciding what to try next
You trained regularized linear regression to predict house prices, and on new houses it makes unacceptably large errors. What now? There is no shortage of ideas:
get more training examples
try fewer features
add more features
add polynomial features (x², x₁x₂, …)
decrease the regularization λ
increase the regularization λ
Each idea can take days or months. Teams often pick one on gut feeling, for example spending six months collecting data, only to find it did not help. The skill this week teaches is running cheap diagnostics: tests that tell you which of these ideas are likely to work before you invest in them. A diagnostic can take hours to set up, and it routinely saves months.
Lecture 3.2 · 8 min read
Evaluating a model
A model that fits the training data perfectly can still be useless on new data. To measure how well it generalizes, hold some data back: a common split is 70% for training and 30% for testing. Fit the parameters on the training set only, then compute the error on both sets.
Jtrain = (1/2mtrain) Σ (f(x(i)) − y(i))², Jtest = (1/2mtest) Σ (f(xtest(i)) − ytest(i))²Neither includes the regularization term: that term shapes training but is not part of the error you report.
For classification, report the fraction of misclassified examples on each set; it is easier to interpret than log loss. Below, a degree-10 polynomial fits 14 training points almost perfectly, and the test error reveals the problem.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(1)
x = np.sort(rng.uniform(0, 1, 20)).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.2, 20)
x_tr, x_te, y_tr, y_te = train_test_split(x, y, test_size=0.3, random_state=0)
J = lambda m, X, Y: ((m.predict(X) - Y) ** 2).mean() / 2
for d in (1, 3, 10):
m = make_pipeline(PolynomialFeatures(d), StandardScaler(), LinearRegression()).fit(x_tr, y_tr)
print(f"degree {d:2d}: J_train {J(m, x_tr, y_tr):.4f} J_test {J(m, x_te, y_te):.4f}")
Lecture 3.3 · 7 min read
Train, validation and test sets
In Course 1 you chose λ by trying several values and keeping the one with the lowest held-out error. The moment you do that, the held-out error is no longer an honest estimate of performance on new data: you picked the λ that happened to look best on exactly those examples. Any decision you make using a set contaminates that set as a measure.
So split three ways. The training set fits parameters. The validation set (also called dev or cross-validation set) chooses everything else: λ, polynomial degree, network size, learning rate, which features to keep. The test set is touched once, at the end, to report a number you can believe. Typical splits are 60/20/20 for thousands of examples; with millions, the validation and test sets can be a few thousand each and the rest goes to training.
When data is scarce, k-fold cross-validation rotates the validation role across k slices of the training data and averages the error, at the cost of training k models. scikit-learn's cross_val_score does this in one call. Whatever the scheme, the test set stays sealed.
Deep dive · How much choosing on a set costs
Derivation: the optimism of picking the best
Suppose you try k configurations that are all equally good, with true error e. Each validation estimate is an average over n examples, so it is approximately normal with mean e and standard deviation s = √(e(1 − e)/n). You keep the configuration with the lowest observed error. The expected minimum of k independent normals is e − cks, where ck is the expected maximum of k standard normals: c5 = 1.163, c20 = 1.867, c100 = 2.508.
Worked example by hand
e = 0.10, n = 500 validation examples, k = 20 configurations.
Every configuration is a 10% model, yet the winner reports 7.5% on the set used to choose it. The test set exists to measure the winner on data that played no part in the choice. The same arithmetic explains why a public leaderboard that you submit to hundreds of times stops telling the truth.
How precise is a test score?
The 95% interval for an accuracy measured on n examples is about ±1.96√(acc(1 − acc)/n). Lab 2 splits the 1,797 digits into 1,077 / 360 / 360 (test_size 0.2, then 0.25 of the remaining 80%, which is another 20%). For acc = 0.97 on 360 test digits, the half-width is 1.96 · 0.0090 = 0.0176. Two models at 96.9% and 97.8% on that test set are not reliably different.
k-fold cross-validation in numbers
With 5 folds over the 1,437 non-test digits, each model trains on about 1,150 examples and validates on about 287, and every example is used for validation exactly once. The cost is five trainings per configuration. After choosing, retrain once on all 1,437 examples. For classification, use stratified folds so each fold keeps the class proportions; with 10 digit classes and 287 examples per fold, an unlucky unstratified fold can be visibly short of one digit.
Leakage: when the test set is not as sealed as it looks
Preprocessing fit on all data. A scaler or PCA fit before splitting has seen the test rows. Fit it on the training split only, or use a scikit-learn Pipeline inside cross-validation.
Groups split across sets. Several scans from one patient, or several photos of one product, end up on both sides. The model recognizes the patient rather than the disease. Use GroupKFold or split by group ID.
Time. A random split of time-ordered data lets the model train on the future. Split by date: train on the past, validate on the following period, test on the period after that.
Duplicates. Exact or near-duplicate rows on both sides inflate scores. Deduplicate before splitting.
Common mistakes
Tuning on the test set "just once more". Each look spends it. Symptom: test score drifts up over a project while production performance does not.
A validation set too small to resolve the differences you care about. With 100 examples, s ≈ 0.03 at 10% error, so differences of a couple of points are noise.
Reporting cross-validation error after choosing on it. That number is optimistic for the same reason as above. Keep a separate test set, or use nested cross-validation.
Check yourself
With 100 equally good configurations, n = 500 and e = 0.10, what is the expected best observed error?
Answer
0.10 − 2.508 · 0.0134 = 0.066.
Module 2
Practice quiz: Advice for applying machine learning
Practice quiz · 5 questions
Advice for applying machine learning
Module 3
Bias and variance
Lecture 3.4 · 10 min read
Diagnosing bias and variance
Two numbers diagnose almost any model: training error and validation error. Compare them to each other and to a baseline, which is the error a human or a simple existing system makes on the same task.
Baseline
Training error
Validation error
Diagnosis
What helps
2%
10%
11%
High bias
Bigger model, more features, less regularization, train longer
2%
3%
12%
High variance
More data, regularization, fewer features, dropout, early stopping
2%
10%
20%
Both
Bigger model first, then regularize it
10%
11%
12%
Near the baseline
The task may be this hard; check label noise before adding capacity
High bias means the model cannot even fit the training set; it is too simple or undertrained. High variance means it fits training data far better than new data; it has memorized. The gap between training error and the baseline measures bias; the gap between validation and training error measures variance. Neural networks have a convenient property here: making the network bigger almost never hurts if you regularize it well, so the modern recipe is to start with a model large enough to drive training error down, then fix variance with data and regularization.
Regularization λ and model size move you along the same trade-off from opposite ends. Sweep λ on the validation set and plot both errors against it: at λ = 0 variance dominates, at large λ bias dominates, and the validation minimum is in between.
Deep dive · The bias–variance decomposition
Derivation
Assume y = f(x) + ε with E[ε] = 0 and Var(ε) = σ², and let f̂ be the model trained on a random training set D. Fix a point x and average the squared error over both the noise and the training set. Write f̂ for f̂(x) and f̄ = ED[f̂].
The true value at x0 is f = 2 and the noise variance is σ² = 0.1. Train the same model on four different training sets and get predictions 1.5, 2.5, 2.0, 3.0 at x0.
Variance dominates here, so the fixes are the variance fixes: more data, regularization, or averaging several models (which divides the variance term, as “Random forests and gradient boosting” shows).
From the formula to the diagnostic table
You cannot compute f̄ in practice, so the lecture's table uses observable proxies. The baseline stands in for σ²; training error minus baseline approximates bias; validation minus training error approximates variance. Reading the table's four rows that way: the first has 8 points of bias and 1 of variance; the second 1 and 9; the third 8 and 10; the fourth 1 and 1 on top of a 10% baseline. The exact decomposition only holds for squared error. For 0/1 classification error it is not additive, so treat the table as a heuristic that points you at the bigger problem, not as an exact split.
Sweeping λ
At λ = 0 the model is free to chase each training set, so f̂ moves a lot between sets: high variance, low bias. As λ grows the weights are pulled toward zero, f̂ becomes nearly the same for every D (variance falls) but sits further from f (bias rises). Validation error is the sum, so it is U-shaped in λ, and the minimum is where the two rates of change balance.
Common mistakes
Comparing training error to 0 instead of the baseline. 8% training error on a task where humans get 7% is not high bias.
Diagnosing from validation error alone. 15% validation error can be either problem; you need the training error to tell which.
Regularizing a model that underfits. Raising λ or adding dropout to a high-bias model makes training error worse.
Check yourself
Baseline 5%, training 6%, validation 15%. Diagnosis and first fix?
Answer
Bias is 1 point and variance 9 points: high variance. Add data or augmentation, regularize, or stop earlier.
Lecture 3.5 · 10 min read
Regularization and bias/variance
The regularization strength λ moves a model along the bias–variance axis. With a very large λ the penalty dominates, the weights shrink toward zero and the model is nearly a constant: high bias, Jtrain high. With λ = 0 a flexible model overfits: high variance, Jtrain low but Jcv high. The best λ sits in between.
Choose it the same way you choose a polynomial degree: try a range of values, roughly doubling each time, fit on the training set, and pick the λ with the lowest cross-validation error. Then report the test error of that one model.
import numpy as np
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import Ridge
rng = np.random.default_rng(0)
x = rng.uniform(0, 1, 60).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.25, 60)
x_tr, y_tr, x_cv, y_cv = x[:36], y[:36], x[36:], y[36:]
J = lambda m, X, Y: ((m.predict(X) - Y) ** 2).mean() / 2
results = []
for lam in [0, 0.001, 0.01, 0.1, 1, 10, 100]:
m = make_pipeline(PolynomialFeatures(10), StandardScaler(), Ridge(alpha=lam)).fit(x_tr, y_tr)
results.append((J(m, x_cv, y_cv), lam))
print(f"lambda {lam:>7}: J_train {J(m, x_tr, y_tr):.4f} J_cv {J(m, x_cv, y_cv):.4f}")
print("best lambda by J_cv:", min(results)[1])
Plot Jtrain and Jcv against λ and you get a mirror image of the plot against polynomial degree: Jtrain rises with λ, and Jcv is U-shaped.
Lecture 3.6 · 8 min read
Establishing a baseline level of performance
Is a training error of 10.8% good or bad? It depends on how well the task can be done at all. For speech recognition on noisy audio, even humans misrecognize about 10.6% of words, so 10.8% on the training set is excellent.
Baseline (human)
Training error
CV error
Gap to baseline
Train–CV gap
Diagnosis
Case A
10.6%
10.8%
14.8%
0.2%
4.0%
high variance
Case B
10.6%
15.0%
15.5%
4.4%
0.5%
high bias
Case C
10.6%
15.0%
19.7%
4.4%
4.7%
both
Compare the training error with the baseline to judge bias, and the cross-validation error with the training error to judge variance. Good baselines include human-level performance (especially for images, audio and text that people handle well), the performance of a competing or older system, and an educated guess from experience.
Lecture 3.7 · 10 min read
Learning curves
A learning curve plots error against the number of training examples. As m grows, Jtrain usually rises, because fitting every example perfectly gets harder, and Jcv falls, because the model generalizes better.
High bias: both curves flatten out quickly at a high error, above the baseline. Adding data will not help; the model is too simple.
High variance: Jtrain is low, Jcv much higher, and the gap shrinks as m grows. More data is likely to help.
import numpy as np
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(3)
x = rng.uniform(0, 1, 400).reshape(-1, 1)
y = np.sin(2 * np.pi * x).ravel() + rng.normal(0, 0.2, 400)
x_cv, y_cv = x[300:], y[300:]
J = lambda m, X, Y: ((m.predict(X) - Y) ** 2).mean() / 2
print(" m | degree 1: train cv | degree 12: train cv")
for m_tr in (15, 30, 60, 120, 300):
row = []
for d in (1, 12):
mdl = make_pipeline(PolynomialFeatures(d), StandardScaler(), LinearRegression()).fit(x[:m_tr], y[:m_tr])
row += [J(mdl, x[:m_tr], y[:m_tr]), min(J(mdl, x_cv, y_cv), 9.99)]
print(f"{m_tr:4d} | {row[0]:.3f} {row[1]:.3f} | {row[2]:.3f} {row[3]:.3f}")
The straight line (degree 1) is stuck near the same error however much data it sees. The degree-12 model starts with a huge gap that closes as data grows. Plotting learning curves takes a few training runs on subsets, so it is a cheap diagnostic to run before buying more data.
Lecture 3.8 · 10 min read
Bias/variance and neural networks
Before deep learning, practitioners spent a lot of effort balancing bias against variance: a simpler model reduced variance but raised bias, and vice versa. Large neural networks change the picture, because a big enough network trained on a moderate dataset is a low-bias machine: it can fit the training set very well.
Does the model do well on the training set (compared with the baseline)? If not, use a bigger network and train longer.
Does it do well on the cross-validation set? If not, get more data or regularize.
Repeat until both are good.
A bigger network with well-chosen regularization almost never does worse than a smaller one. The costs are computation and, eventually, the availability of data. In Keras regularization is set per layer, for example Dense(25, activation="relu", kernel_regularizer=L2(0.01)); in PyTorch it is usually the optimizer argument weight_decay.
import torch, torch.nn as nn
small = nn.Sequential(nn.Linear(64, 8), nn.ReLU(), nn.Linear(8, 10))
big = nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 10))
count = lambda m: sum(p.numel() for p in m.parameters())
print("small network parameters:", count(small))
print("big network parameters: ", count(big))
opt = torch.optim.SGD(big.parameters(), lr=0.01, weight_decay=1e-4) # L2 regularization
print("optimizer weight_decay:", opt.param_groups[0]["weight_decay"])
Module 4
Practice quiz: Bias and variance
Practice quiz · 5 questions
Bias and variance
Module 5
Machine learning development process
Lecture 3.9 · 10 min read
Learning curves and the development loop
A learning curve plots training and validation error against the number of training examples. Train on 100 examples, then 200, 400, and so on, and watch the two curves. Training error rises with more data (harder to fit every example) while validation error falls. If the curves have converged and both sit well above the baseline, you have high bias and more data will not help; if a wide gap remains, you have high variance and more data will close it. Drawing this curve before buying data has saved many teams a great deal of money.
The development loop is: pick an architecture, train, diagnose with the two errors, change one thing, repeat. The most informative step is error analysis: take a hundred validation examples the model got wrong, look at each one, and tally categories by hand. If sixty of a hundred spam misses are pharmaceutical spam with deliberate misspellings, that is what to fix; if three are, it is not. The categories tell you which data to collect and which features to add far better than any aggregate metric.
Three data techniques recur. Data augmentation creates new examples by distorting existing ones in ways that preserve the label: rotating and warping images, adding noise to audio. Data synthesis builds examples from scratch, such as rendering text in many fonts to train an OCR model. Transfer learning takes a network already trained on a large related dataset, keeps its early layers, and retrains the last layers on your small dataset; the early layers already know edges, textures and shapes. Course 4 is transfer learning for language models at full scale.
Deep dive · Reading and extrapolating a learning curve
Derivation: a power law for validation error
Across many model families, validation error as a function of training-set size n is well described by err(n) ≈ c + a · n−b: a floor c set by noise and model bias, and a term that shrinks as a power of n. Three measurements at sizes in a fixed ratio are enough to solve for all three constants.
Worked example by hand
Validation errors: 0.25 at n = 100, 0.15 at n = 400, 0.10 at n = 1,600.
Each step quadruples n. The drops are 0.25 − 0.15 = 0.10 and 0.15 − 0.10 = 0.05. For a power law, successive drops shrink by the factor 4b, so 4b = 0.10/0.05 = 2 and b = 0.5.
The second drop is a(400−0.5 − 1600−0.5) = a(0.05 − 0.025) = 0.025a = 0.05, so a = 2.
The floor: c = 0.10 − 2 · 1600−0.5 = 0.10 − 0.05 = 0.05.
Predictions: n = 3,200 gives 0.05 + 2/√3200 = 0.0854; n = 6,400 gives 0.05 + 2/80 = 0.075.
Doubling the data from 1,600 to 3,200 buys about 1.5 points; quadrupling buys 2.5; no amount of data goes below 5%. If the baseline is 2%, the remaining 3 points are bias, and capacity, not data, is the next investment. Fit on log axes and treat the extrapolation as a rough guide: it is reliable for a doubling or two, not for a factor of a hundred.
Reading the two curves
At small n the training error is near 0 because a flexible model can memorize a few examples, and validation error is high. As n grows the two curves approach each other. High bias: they meet early, both above the baseline, and the validation curve is flat. High variance: a wide gap remains at the largest n and the validation curve still slopes down.
Error analysis as arithmetic
A model has 10% validation error. You inspect 100 misclassified examples: 60 are category A, 25 category B, 15 category C. Fixing every A error would bring the error to 10% · 0.40 = 4%. A realistic fix that removes half the A errors brings it to 7%. Fixing every C error, the best case for C, only brings it to 8.5%. These ceilings tell you which project can possibly pay off before you start it.
Augmentation must preserve the label
Shifting a digit by one pixel or rotating it by 10 degrees keeps it the same digit. Rotating a 6 by 180 degrees makes a 9, and horizontally flipping text produces characters that do not exist. Check each transform against the label before using it.
Common mistakes
Fixed epochs at every size. With batch 64, 107 examples give 2 steps per epoch and 1,077 give 17. Thirty epochs is 60 updates for the small subset against 510 for the full set, so small subsets may look worse partly because they were undertrained. Fix: fix the number of steps, or train each size to convergence with early stopping.
Non-random subsets. Taking the first n rows of a sorted file changes the class mix with n. Shuffle (or stratify) once, then take prefixes.
One seed per point. Small-n points are noisy. Average two or three seeds before reading a trend.
Measuring training error on the full training set. It must be computed on the n examples the model was trained on.
Lecture 3.10 · 8 min read
Error analysis
Suppose a spam classifier misclassifies 100 of the 500 cross-validation emails. Error analysis means looking at those 100 by hand and sorting them into categories. Categories can overlap.
Category
Count
Pharmaceutical spam
21
Phishing (password theft)
18
Unusual email routing
7
Spam text inside an embedded image
5
Deliberate misspellings ("w4tches")
3
The table changes priorities at once. Fixing misspellings could recover at most 3 of the 100 errors, while better handling of pharmaceutical spam and phishing addresses 39. Collect more examples of those, or add features aimed at them. When there are thousands of errors, sample a few hundred at random; the proportions will be close enough.
Error analysis works best on tasks people can judge. It is harder when humans cannot tell the right answer either, such as predicting which ad someone will click.
Lecture 3.11 · 14 min read
Adding data
Getting more data of every kind is slow and expensive. Three techniques are usually better value.
Targeted collection
Use error analysis to decide which data to collect. If pharmaceutical spam causes most errors, find more pharmaceutical spam rather than more email in general.
Data augmentation
Create new training examples by modifying existing ones in ways that keep the label: rotate, shift, enlarge or add contrast to an image of a letter; add background noise from a café or a car to a speech clip. The distortions should resemble what appears in the test data. Adding purely random pixel noise usually helps less, because real inputs rarely look like that.
import numpy as np, matplotlib.pyplot as plt
from sklearn.datasets import load_digits
img = load_digits().images[3]
shifted = np.roll(img, 1, axis=1) # move one pixel right
brighter = np.clip(img * 1.3, 0, 16)
noisy = np.clip(img + np.random.default_rng(0).normal(0, 1.5, img.shape), 0, 16)
fig, axes = plt.subplots(1, 4, figsize=(8, 2.2))
for ax, im, t in zip(axes, [img, shifted, brighter, noisy], ["original", "shifted", "contrast", "noise"]):
ax.imshow(im, cmap="gray_r"); ax.set_title(t); ax.axis("off")
plt.show()
Data synthesis
Generate entirely new examples. For reading text in photos, render random strings in many fonts, colors and backgrounds. Synthetic data is common in computer vision and increasingly in language tasks.
All three reflect a shift from a model-centric view, where data is fixed and you improve the code, to a data-centric view: the algorithms are often good enough, and the biggest gains come from engineering the data.
Lecture 3.12 · 11 min read
Transfer learning: using data from a different task
You want to recognize handwritten digits but have only a few hundred labeled examples. Transfer learning lets you borrow from a big dataset for a different task. First, a network is trained on, say, a million images in a thousand categories (cats, cars, people…). This is pre-training. Then you copy that network, replace its output layer of 1,000 units with a new layer of 10 units, and train on your digits. This is fine-tuning.
Option 1: freeze all copied layers and train only the new output layer. Best with very little data.
Option 2: initialize all layers from the pre-trained network and train them all. Better with more data.
It works because the early layers of an image network detect edges, corners and simple shapes, which are useful for almost any image task. The input type must match: a network pre-trained on images helps with images, one pre-trained on text helps with text. Course 4 applies exactly this idea to large language models.
import torch, torch.nn as nn
pretrained = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 1000))
model = nn.Sequential(*list(pretrained.children())[:-1], nn.Linear(64, 10)) # new 10-class head
for p in list(model.parameters())[:-2]:
p.requires_grad_(False) # option 1: freeze copied layers
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total = sum(p.numel() for p in model.parameters())
print(f"trainable {trainable:,} of {total:,} parameters")
Lecture 3.13 · 8 min read
Full cycle of a machine learning project
Training a model is one stage of a longer cycle. Taking speech recognition as the example:
Scope the project: decide what to build and how success will be measured.
Collect data: define and gather the audio and transcripts.
Train the model: train, run error analysis, and loop back to collect more targeted data as needed.
Deploy in production: serve the model, usually behind an API that the app calls; then monitor and maintain it, and retrain when performance drifts.
Deployment can be as simple as one server or as complex as millions of users. It brings software engineering concerns: reliable, efficient predictions, logging inputs and outputs (with user consent), monitoring for data that no longer looks like the training data, and pushing updated models safely. The practice of building and maintaining these systems is called MLOps; the new Course 6 is devoted to it.
Lecture 3.14 · 9 min read
Fairness, bias, and ethics
Machine learning systems affect people's lives, and they have caused real harm. Widely reported cases include a hiring screening tool that learned to downgrade résumés mentioning women's organizations, face-recognition systems with much higher error rates for darker-skinned people, and loan or risk models that disadvantaged some groups. There are also deliberate misuses: deepfake videos made without consent, recommenders optimized for engagement that spread toxic content, and models used for fraud.
There is no checklist that guarantees a system is fair, but some practices help a lot:
Assemble a diverse team and brainstorm, before deploying, the ways the system could harm different groups of people.
Search for standards and guidelines in your industry, and for published audits of similar systems.
Audit the system against the risks you identified, for example error rates broken down by group, before launch.
Write a mitigation plan, such as rolling back to an earlier system, and keep monitoring after deployment so problems surface quickly.
Sometimes the right decision is not to build the system at all. Take that option seriously when the harms are significant and cannot be mitigated.
Module 6
Practice quiz: Machine learning development process
Practice quiz · 5 questions
Machine learning development process
Module 7 · optional
Skewed datasets (optional)
Lecture 3.15 · 8 min read
Precision, recall and skewed classes
If 0.5% of transactions are fraud, a model that calls everything legitimate is 99.5% accurate and useless. Accuracy hides the minority class. Count four things instead: true positives (flagged and fraud), false positives (flagged, not fraud), false negatives (missed fraud), true negatives.
precision = TP / (TP + FP) recall = TP / (TP + FN) F1 = 2·P·R / (P + R)Precision: of the alarms, how many were real. Recall: of the real cases, how many were caught. F1 is the harmonic mean, low if either is low.
Raising the decision threshold above 0.5 makes the model flag fewer, surer cases: precision rises, recall falls. Lowering it does the reverse. Which you want depends on the cost of each mistake. A cancer screen wants recall; a spam filter that deletes mail wants precision. Plot precision against recall over all thresholds and choose the point your application needs; the F1 score summarizes the curve in one number when you must compare models automatically. The ROC curve, true-positive rate against false-positive rate, and its area (AUC) do the same job and are less sensitive to the class ratio.
F1 = 2PR/(P + R) is the harmonic mean, 1/F1 = ½(1/P + 1/R). It is dominated by the smaller value. A model that flags one sure case out of a hundred frauds has P = 1, R = 0.01: the arithmetic mean is 0.505, the harmonic mean is 2 · 0.01/1.01 = 0.0198. When recall matters more, use Fβ = (1 + β²)PR/(β²P + R); β = 2 weights recall more heavily, and for the matrix above F2 = 0.690.
Worked example: ROC curve and AUC by hand
Nine examples sorted by score. Positives: 0.9, 0.8, 0.55, 0.4. Negatives: 0.7, 0.5, 0.3, 0.2, 0.1. Lower the threshold one score at a time; each positive passed raises TPR by 1/4, each negative raises FPR by 1/5.
threshold ≥
0.9
0.8
0.7
0.55
0.5
0.4
0.3
0.2
0.1
TPR
0.25
0.50
0.50
0.75
0.75
1.00
1.00
1.00
1.00
FPR
0
0
0.2
0.2
0.4
0.4
0.6
0.8
1.0
The area under this staircase is 0.2 · 0.5 + 0.2 · 0.75 + 0.6 · 1 = 0.85. Equivalently, AUC is the probability that a random positive scores above a random negative. Of the 4 · 5 = 20 positive-negative pairs, only three are misordered (0.55 below 0.7, 0.4 below 0.7, 0.4 below 0.5), so AUC = 17/20 = 0.85. The pair view explains why AUC ignores the threshold and depends only on the ranking.
Why ROC is less sensitive to class ratio than precision
TPR is computed only over positives and FPR only over negatives, so duplicating every negative ten times leaves the ROC curve unchanged. Precision mixes the two classes: the same duplication multiplies FP by ten and precision in the example above falls from 0.80 to 40/140 = 0.29. A precision-recall curve's no-skill line sits at the positive rate (0.06 here), while ROC's sits at the diagonal, AUC 0.5.
Common mistakes
AUC from hard labels.roc_auc_score(y, probs > 0.5) gives a curve with one corner and throws away the ranking. Pass the scores.
Wrong positive class. With labels where 0 means malignant, average="binary" scores class 1 by default. Flip the labels or set pos_label.
Choosing the threshold on the test set. Choose it on validation, then report test once.
Undefined precision. If nothing is flagged, TP + FP = 0. scikit-learn warns and returns 0; your own code divides by zero unless you guard it.
Lecture 3.16 · 11 min read
Trading off precision and recall (optional)
A logistic regression classifier predicts 1 when f(x) ≥ a threshold, usually 0.5. Raising the threshold to 0.7 or 0.9 means predicting positive only when confident: precision goes up and recall goes down. Lowering it to 0.3 catches more positives at the cost of more false alarms. The right threshold depends on the cost of each kind of mistake, which is a product decision rather than a technical one.
To compare classifiers with a single number, use the F1 score, the harmonic mean of precision P and recall R. Unlike the plain average, it is low whenever either one is low.
F1 = 2PR / (P + R)An algorithm that always predicts 1 has recall 1 but tiny precision, and its F1 is close to zero.
Algorithm
Precision
Recall
Average
F1
1
0.5
0.4
0.45
0.444
2
0.7
0.1
0.40
0.175
3
0.02
1.0
0.51
0.039
import numpy as np
rng = np.random.default_rng(0)
y = (rng.random(1000) < 0.1).astype(int) # 10% positives
score = np.clip(0.35 * y + rng.normal(0.3, 0.15, 1000), 0, 1)
for t in (0.3, 0.5, 0.7):
pred = (score >= t).astype(int)
tp = ((pred == 1) & (y == 1)).sum(); fp = ((pred == 1) & (y == 0)).sum(); fn = ((pred == 0) & (y == 1)).sum()
P = tp / max(tp + fp, 1); R = tp / max(tp + fn, 1)
print(f"threshold {t}: precision {P:.2f} recall {R:.2f} F1 {2*P*R/max(P+R,1e-9):.2f}")
Module 8
Week 3 quizzes
Quiz · Week 3 · 5 questions
Week 3 quiz
Practice quiz · Week 3 · 6 questions
Week 3 practice quiz
Module 9
Practice lab: Advice for applying machine learning
Work through the week's diagnostics on real fits: compute training and cross-validation error, choose a polynomial degree and a regularization strength, read learning curves, diagnose against a baseline, and run an error analysis on a digit classifier.
Step 1Three splits and J
Split 120 noisy sine points 60/20/20 and write J(model, X, Y), half the mean squared error without any regularization term.
Step 2Degree and λ
Sweep polynomial degrees 1–10, then λ for a degree-10 Ridge model. Pick each by the lowest cross-validation error and plot both error curves.
Step 3Learning curves and diagnosis
Write learning_curve(degree, sizes) and compare degree 1 with your chosen degree. Then write diagnose(baseline, train, cv) and test it on the speech-recognition table from the lecture.
Step 4Error analysis
Train logistic regression on the digits, count the cross-validation errors by true digit, and look at the misclassified images.
Checkpoint 1
Which polynomial degree has the lowest cross-validation error?
Checkpoint 2
Which λ has the lowest cross-validation error for the degree-10 Ridge model?
Checkpoint 3
How many cross-validation digits does the logistic regression classifier get wrong?
Week 4 · Decision trees
Decision trees
Trees split data with yes/no questions chosen by information gain; ensembles of trees are often the strongest models on tabular data.
Video lectures · Week 4
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
Decision and Classification Trees, Clearly ExplainedStatQuest with Josh Starmer · YouTube ↗Random Forests Part 1StatQuest with Josh Starmer · YouTube ↗XGBoost Part 1: RegressionStatQuest with Josh Starmer · YouTube ↗
Module 1
Decision trees
Lecture 4.1 · 10 min read
Decision trees
A decision tree asks a sequence of yes/no questions about the features and predicts the majority label of the examples that reached each leaf. It is the most readable model in machine learning, and its ensembles, next lecture, are the strongest models for tabular data.
Building a tree is choosing which question to ask at each node. The criterion is purity: a good question splits the examples into groups that are each mostly one class. Measure impurity with entropy. For a node where a fraction p of examples is positive, H(p) = −p log₂ p − (1 − p) log₂ (1 − p); it is 1 bit for a 50/50 mix and 0 for a pure node. A split's quality is the entropy before it minus the weighted entropy after, called information gain.
gain = H(proot) − [ wleft · H(pleft) + wright · H(pright) ]wleft and wright are the fractions of examples sent each way.
Ten animals, three binary features (pointy ears, round face, whiskers), five cats. The root has entropy 1.0. Splitting on ear shape sends five animals each way with four of five cats on one side and one of five on the other: both sides have entropy 0.72, so the gain is 1 − 0.72 = 0.28. Splitting on whiskers gives 0.12 and face shape 0.03. The tree asks about ears first, then recurses on each side until a node is pure, has too few examples, or reaches a depth limit. Those stopping rules are the tree's regularization; an unlimited tree memorizes the training set.
Continuous features are split by a threshold; try the midpoints between sorted values and keep the best gain. Categorical features with k values become k binary features (one-hot encoding). For regression trees, replace entropy with the variance of the targets in each node and predict each leaf's mean.
Deep dive · Entropy, Gini and the cat tree
Worked example: information gain for every root split
The ten animals from the lab: five cats. Root entropy H(0.5) = 1. For each feature, "left" is the examples with value 1.
Second level. On the pointy-ear side (4 cats, 1 not), round face separates it perfectly, gain 0.7219, against 0.171 for whiskers. On the floppy-ear side (1 cat, 4 not), whiskers separates it perfectly, gain 0.7219, against 0.3219 for round face. The depth-2 tree is: ears, then face on one side and whiskers on the other, and it classifies all ten animals correctly.
Derivation: Gini impurity and how it compares
Gini impurity is the probability that two examples drawn at random from the node, with replacement, have different labels: 1 − p² − (1 − p)² = 2p(1 − p).
p
0.1
0.2
0.3
0.5
entropy (bits)
0.469
0.722
0.881
1.000
Gini
0.180
0.320
0.420
0.500
Both are zero for a pure node, peak at p = 0.5 and are strictly concave, so they rank splits the same way almost always. On the cat data the Gini gains are 0.18, 0.0238 and 0.0833: same order as entropy. Gini avoids a logarithm and is scikit-learn's default. Entropy is in bits, which makes the gain readable as information.
Derivation: why not just use the error rate?
Strict concavity guarantees that a split which changes the class mix lowers the weighted impurity (Jensen's inequality). The misclassification rate min(p, 1 − p) is only piecewise linear, so many useful splits score zero. A node with 7 cats out of 10 has error 0.3. Split it into 4 of 5 cats and 3 of 5 cats: the errors are 0.2 and 0.4, weighted 0.3, gain 0. Entropy sees a gain of 0.8813 − ½(0.7219 + 0.9710) = 0.0349, and the left child is now easier to split further.
Continuous features: thresholds at midpoints
x = (2, 3, 5, 6, 8, 9) with labels (0, 0, 1, 0, 1, 1). The candidate thresholds are the midpoints 2.5, 4, 5.5, 7, 8.5, with gains 0.191, 0.459, 0.082, 0.459, 0.191. Thresholds 4 and 7 tie; an implementation keeps the first it finds. With n distinct values there are n − 1 candidates; sorting once makes each candidate's counts an update rather than a recount.
Regression trees
For x = (1, 2, 3, 4) and y = (3, 5, 9, 11) the variance is 10. Splitting at 2.5 leaves {3, 5} and {9, 11}, each with variance 1, so the weighted variance is 1.0, a reduction of 9. Splitting at 1.5 or 3.5 leaves 4.667. The tree picks 2.5 and predicts 4 and 10 in the leaves.
Common mistakes
No stopping rule. An unlimited tree reaches pure leaves of one example each: 100% training accuracy and high variance. Set max_depth or min_samples_leaf on validation.
Treating category codes as numbers. Encoding colors as 1, 2, 3 lets a threshold group 1 with 2 but never 1 with 3. One-hot encode, or use a library with native categorical support.
Reading feature importance as causation. Correlated features split importance between them unpredictably.
log of 0 in your own entropy. 0 · log 0 is defined as 0; guard pure nodes explicitly as the lab does.
Module 2
Practice quiz: Decision trees
Practice quiz · 5 questions
Decision trees
Module 3
Decision tree learning
Lecture 4.2 · 7 min read
Measuring purity
A decision tree splits examples into groups, and a good split produces groups that are as pure as possible: all cats, or all not-cats. Entropy measures impurity. If p1 is the fraction of cats in a node:
H(p1) = −p1 log2(p1) − (1 − p1) log2(1 − p1)By convention 0 · log(0) = 0. Entropy is 0 for a pure node and 1 for a 50/50 node.
Node
p₁
Entropy
3 cats, 3 dogs
0.5
1.00
5 cats, 1 dog
0.83
0.65
2 cats, 4 dogs
0.33
0.92
6 cats, 0 dogs
1.0
0.00
import numpy as np
def entropy(p1):
if p1 in (0, 1):
return 0.0
return float(-p1 * np.log2(p1) - (1 - p1) * np.log2(1 - p1))
for p1 in (0.5, 5/6, 2/6, 1.0, 0.0):
print(f"p1 = {p1:.2f} H = {entropy(p1):.3f}")
Gini impurity, 1 − p1² − p0², behaves almost the same and is the default in scikit-learn. The choice rarely matters in practice.
Lecture 4.3 · 11 min read
Choosing a split: information gain
Information gain is the reduction in entropy produced by a split. Compute the entropy of each branch, weight each by the fraction of examples it receives, and subtract the weighted average from the entropy of the parent node.
gain = H(p1root) − ( wleft H(p1left) + wright H(p1right) )w is the fraction of the parent's examples that go to each branch.
For ten animals, five of them cats, the root entropy is 1. Splitting on ear shape sends five animals left (four cats) and five right (one cat):
Ear shape wins, so it becomes the root split. Weighting by branch size matters: a tiny pure branch should count for less than a large impure one.
Lecture 4.4 · 9 min read
Putting it together
Building a tree is a recursive procedure:
Start with all examples at the root.
Compute the information gain of every possible feature and split on the best one.
Send each example down the matching branch.
Repeat on each branch, as if it were a new, smaller dataset, until a stopping criterion is met.
Common stopping criteria: the node is 100% one class; splitting would exceed a maximum depth; the best gain is below a threshold; or the node has fewer examples than a minimum. Limits on depth and node size keep the tree small, which reduces overfitting.
So far each feature had two values. If ear shape can be pointy, floppy or oval, replace it with three binary features: "is pointy", "is floppy", "is oval". Exactly one of them is 1 for each example, hence the name one-hot. A categorical feature with k values becomes k binary features.
The same encoding feeds categorical data to neural networks and logistic regression, which need numbers as input.
For a numeric feature such as weight, the tree splits on a threshold: weight ≤ t goes left, the rest right. To choose t, sort the examples by the feature, try each midpoint between consecutive distinct values, compute the information gain of each, and keep the best. Then compare that best gain with the gains of the other features as usual.
import numpy as np
weight = np.array([7.2, 8.4, 7.6, 10.2, 9.2, 8.8, 15.0, 18.0, 20.0, 11.0]) # pounds
is_cat = np.array([1, 1, 1, 0, 1, 1, 0, 0, 0, 0])
def entropy(p1):
return 0.0 if p1 in (0, 1) else float(-p1 * np.log2(p1) - (1 - p1) * np.log2(1 - p1))
vals = np.sort(np.unique(weight))
best = None
for t in (vals[:-1] + vals[1:]) / 2:
l, r = is_cat[weight <= t], is_cat[weight > t]
g = entropy(is_cat.mean()) - (len(l) * entropy(l.mean()) + len(r) * entropy(r.mean())) / len(is_cat)
if best is None or g > best[0]:
best = (g, t)
print(f"weight <= {t:5.1f}: gain {g:.3f}")
print("best threshold:", best[1], "gain", round(best[0], 3))
Lecture 4.7 · 9 min read
Regression trees (optional)
Trees can predict numbers too. A regression tree predicts, at each leaf, the average target value of the training examples that reach it. To choose splits, replace entropy with variance: a good split produces branches whose targets are close together.
reduction = Var(root) − ( wleft Var(left) + wright Var(right) )Pick the split with the largest variance reduction, the regression analog of information gain.
A single tree is very sensitive to the data. Change one training example and the best root split can change, which changes everything below it. A model whose structure flips on a single example has high variance.
The remedy is to train many different trees and let them vote. Each tree may make mistakes, but they make different mistakes, and the majority is right more often than any one tree. Such a collection is called a tree ensemble. The next lectures show how to make the trees different from each other.
Lecture 4.9 · 4 min read
Sampling with replacement
To build an ensemble, each tree needs a slightly different training set. Sampling with replacement creates one: put all m training examples in a bag, draw one at random, record it, put it back, and repeat m times. Some examples appear more than once and others not at all. The result is called a bootstrap sample.
import numpy as np
rng = np.random.default_rng(0)
m = 10_000
sample = rng.choice(m, size=m, replace=True)
print("unique examples in one bootstrap sample:", round(len(np.unique(sample)) / m, 3))
print("theory 1 - 1/e =", round(1 - np.exp(-1), 3))
On average a bootstrap sample contains about 63% of the distinct original examples. The ones left out of a given sample are a free validation set for that tree, called out-of-bag examples.
Lecture 4.10 · 9 min read
Random forests and gradient boosting
A single tree is high variance: change a few training examples and the root question can change, and with it the whole tree. The cure is to train many trees and average them. Bagging trains each tree on a bootstrap sample, a random draw of m examples with replacement, so each tree sees a different dataset. A random forest adds a second source of randomness: at each split, only a random subset of about √n features is considered. The trees become less correlated, and averaging a hundred of them is far more stable than any one.
Boosting builds trees in sequence instead of in parallel. Each new tree is trained to fix the mistakes of the ensemble so far: in gradient boosting, it fits the gradient of the loss with respect to the current predictions, which for squared error is simply the residuals. Trees are kept shallow, often depth 3 to 6, and added with a small learning rate. XGBoost and LightGBM are fast, regularized implementations of this idea and win most tabular competitions.
When to use what: trees and their ensembles for tables with mixed numeric and categorical columns, missing values, and up to a few million rows; they need little scaling or tuning and train in seconds. Neural networks for images, audio, text and anything where the input is raw signal rather than engineered columns, and where transfer learning from a pretrained model is available. Both are worth trying on a new tabular problem; the forest is usually the stronger baseline.
Deep dive · Why averaging works, and boosting as gradient descent
Derivation: the variance of an average of correlated trees
Let T1, …, TB be the predictions of B trees at a point, each with variance σ² and pairwise correlation ρ, so Cov(Tb, Tc) = ρσ² for b ≠ c. The variance of a sum is the sum of all entries of the covariance matrix: B diagonal terms σ² and B(B − 1) off-diagonal terms ρσ².
Var((1/B)ΣbTb) = (1/B²)[Bσ² + B(B − 1)ρσ²] = ρσ² + (1 − ρ)σ²/BThe second term vanishes as B grows; the first does not.
ρ (σ² = 1)
B = 1
B = 10
B = 100
B = 1000
0
1
0.1
0.01
0.001
0.3
1
0.37
0.307
0.3007
0.6
1
0.64
0.604
0.6004
Beyond about 100 trees, adding more barely helps; the floor ρσ² does not move. Lowering ρ is the only way to lower the floor, and that is what the random feature subset does: trees that may not use the same dominant feature at the root are less alike. Adding trees never increases the variance, which is why a forest does not overfit by having too many trees.
Bootstrap arithmetic
A bootstrap sample draws m examples with replacement. A given example is missed by all m draws with probability (1 − 1/m)m, which tends to e−1 = 0.368. Each tree sees about 63.2% of the distinct examples (63.24% for m = 569). The remaining 36.8% are that tree's out-of-bag examples, a free validation set for that tree.
Derivation: boosting as gradient descent on predictions
Treat the ensemble's predictions Fi = F(xi) on the training set as the parameters, and minimize ΣiL(yi, Fi). A gradient step would move each Fi by −ν ∂L/∂Fi. A tree cannot move points independently, so fit a small regression tree h to the negative gradients and update F ← F + νh, which also generalizes the step to new x. For squared error L = ½(y − F)², −∂L/∂F = y − F, the residual. For log loss with F as the log-odds, −∂L/∂F = y − σ(F): the label minus the predicted probability.
Worked example by hand
x = (1, 2, 3, 4), y = (3, 5, 9, 11), stumps, learning rate ν = 0.5.
Residuals (−2.5, −0.5, 0.5, 2.5). Same split, leaves −1.5 and +1.5. F2 = (4.75, 4.75, 9.25, 9.25). MSE = 1.5625.
The pattern: the within-group part of the error (1.0) cannot be reduced by this split, and each round removes half of the between-group part (9). MSE after t rounds of this split is 1 + 9 · 0.25t: 3.25, then 1.5625. A third round finds that a different split (x ≤ 1.5) now helps more. A smaller ν needs more trees but averages over more splits, which usually generalizes better.
For classification, start from the log-odds of the positive rate. For breast cancer with 212 malignant out of 569, F0 = ln(212/357) = −0.521.
Common mistakes
Too many boosting rounds without early stopping. Unlike a forest, boosting keeps fitting residuals and eventually fits noise. Monitor validation loss and stop at its minimum.
Deep trees in boosting. Depth 10 trees fit the residuals in one round and leave nothing for the ensemble to average. Use depth 3 to 6.
A forest considering every feature at every split. That is plain bagging; ρ stays high. Keep the default √n features for classification.
Comparing ensembles on training AUC. Both can reach 1.0 on training data. Compare on validation.
Lecture 4.11 · 6 min read
When to use decision trees
Decision trees and tree ensembles
Neural networks
Best data
tabular, structured (spreadsheets, databases)
all types, including images, audio, text
Training speed
fast, so you can iterate quickly
can be slow for large networks
Interpretability
small single trees are readable
hard to interpret
Transfer learning
not applicable
yes, a major advantage
Combining systems
separate models
several networks can be trained together end to end
A practical default: for tabular data, start with gradient-boosted trees such as XGBoost, LightGBM or scikit-learn's HistGradientBoosting; they are strong, fast and need little feature scaling. For images, audio and text, use neural networks, usually starting from a pre-trained model. Tree ensembles with hundreds of trees are not really interpretable either, despite the reputation of single trees.
X = np.array([[1,1,1],[0,0,1],[0,1,0],[1,0,1],[1,1,1],[1,1,0],[0,0,0],[1,1,0],[0,1,0],[0,1,0]])
y = np.array([1,1,0,0,1,1,0,1,0,0]) # 1 = cat; columns: pointy ears, round face, whiskers
def entropy(y):
p = y.mean()
if p in (0, 1): return 0.0
return -p*np.log2(p) - (1-p)*np.log2(1-p)
def information_gain(X, y, feature):
left, right = y[X[:, feature] == 1], y[X[:, feature] == 0]
w = len(left) / len(y)
return entropy(y) - (w*entropy(left) + (1-w)*entropy(right))
Checkpoint 1
Information gain of splitting the root on ear shape (feature 0), to three decimals?
Step 2Grow the tree
Write a recursive build(X, y, depth) that picks the feature with the highest gain, splits, and stops at depth 2, at a pure node, or when a side is empty. Print the tree as nested text. Which feature is asked second on the pointy-ear side?
Step 3Diagnose a real model
Reload the digits notebook from Lab 2. Plot a learning curve: train on 10%, 25%, 50%, 100% of the training set and record training and validation error for each. Write the diagnosis in one sentence using “Diagnosing bias and variance”'s table.
Step 4Project: trees versus networks on a table
from sklearn.datasets import load_breast_cancer # 569 rows, 30 features, ships with scikit-learn
data = load_breast_cancer(); X, y = data.data, (data.target == 0).astype(int) # 1 = malignant# with network access, try a bigger table: fetch_openml("adult", version=2, as_frame=True)
Split 60/20/20 and train three models: a depth-limited DecisionTreeClassifier, a RandomForestClassifier with 200 trees, and XGBClassifier as in “Random forests and gradient boosting”. Report validation precision, recall, F1 and AUC for each. Then do error analysis: print 50 misclassified validation rows from the best model and tally what they have in common. Write a half-page: which model you would ship, at what threshold, and what data you would collect next.
Checkpoint 2
Entropy, in bits, of a node with exactly half cats?
Final exam · 12 questions · pass mark 80%
Final exam
Questions from every week of the course. Pass it to complete the last requirement for the certificate on the Certificates page.
Final exam · 12 questions
Neural Networks and Applied Machine Learning
Pass mark 80%. Passing this exam is one of the requirements for the course certificate. You can retake it as often as you like.
Course 3 of 6 · 3 weeks
Unsupervised Learning, Recommenders and Reinforcement Learning
No labels this time. The first week finds structure in raw data; the second learns from what people clicked; the third learns from reward alone, which is the idea that reappears at the end of Course 4 as RLHF.
44lectures with video
2demos
15quizzes incl. practice + final
3labs
Week 1 · Unsupervised learning
Unsupervised learning
Find structure in unlabeled data: group it with k-means and flag unusual examples with a Gaussian anomaly detector.
Video lectures · Week 1
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
K-means clusteringStatQuest with Josh Starmer · YouTube ↗Principal Component Analysis (PCA), Step-by-StepStatQuest with Josh Starmer · YouTube ↗
Module 1
Clustering
Lecture 1.1 · 4 min read
What is clustering?
In supervised learning every example comes with a label y, and the algorithm learns a boundary between classes. In unsupervised learning there are only inputs x. A clustering algorithm looks at those points and decides on its own which of them belong together.
Applications are everywhere: grouping similar news articles into one story, segmenting customers into groups with different needs, analyzing DNA to group people with similar gene expression, and even grouping galaxies in astronomical data to understand how they formed.
Lecture 1.2 · 9 min read · demo
Clustering with K-means
Given points with no labels, clustering assigns each one to a group so that points in a group are close to each other. K-means does it with two alternating steps. Place K centroids. Assign every point to its nearest centroid. Move every centroid to the mean of the points assigned to it. Repeat until no assignment changes.
Each step lowers, or at least does not raise, one number: the distortion, the average squared distance from each point to its centroid. The assignment step cannot raise it because each point moves to a closer centroid or stays; the update step cannot raise it because the mean is the point that minimizes squared distance to a set. A quantity that only decreases and is bounded below must settle, so K-means always converges. Watch it happen below, one step at a time.
K-means, one step at a time60 points from 3 hidden groups
iteration 0distortion –next assign
J = 1/m · Σi ‖ x(i) − μc(i) ‖²c(i) is the cluster assigned to point i; μk is centroid k. Both steps are coordinate descent on J.
def kmeans(X, k, iters=100, seed=0):
rng = np.random.default_rng(seed)
C = X[rng.choice(len(X), k, replace=False)] # init from data points
for _ in range(iters):
d = ((X[:, None, :] - C[None, :, :]) ** 2).sum(-1) # (m, k) squared distances
labels = d.argmin(1)
new_C = np.stack([X[labels == j].mean(0) if (labels == j).any() else C[j] for j in range(k)])
if np.allclose(new_C, C): break
C = new_C
return C, labels
Deep dive · Why K-means always converges
Derivation
K-means minimizes one cost over two sets of variables: the assignments c(1)…c(m) and the centroids μ1…μK.
J(c, μ) = 1/m · Σi ‖x(i) − μc(i)‖²distortion: mean squared distance from each point to its own centroid
Assignment step. Hold μ fixed. J is a sum of m separate terms and c(i) appears only in term i. Choosing c(i) = argmink ‖x(i) − μk‖² makes each term as small as it can be given μ. The old assignment was one of the candidates, so each term is less than or equal to its old value, and so is the sum.
Update step. Hold c fixed. Now J splits into K separate problems, one per cluster: minimize f(μk) = Σi in cluster k ‖x(i) − μk‖². Take the gradient: ∂f/∂μk = −2 Σ (x(i) − μk) = −2(Σ x(i) − nkμk). Setting it to zero gives μk = (1/nk) Σ x(i), the mean. f is a sum of convex quadratics, so this stationary point is the global minimum, and the old centroid cannot have done better.
Convergence. J never increases and J ≥ 0. There are at most Km possible assignments, and each centroid set is determined by its assignment, so the algorithm can visit only finitely many states. A sequence that never increases through a finite set of values must stop changing. It stops at a point where neither step can improve J alone: a local minimum of this coordinate descent, not necessarily the global one.
Worked example by hand
Six points on a line, x = 1, 2, 3, 7, 8, 12, with K = 2 and starting centroids μ = (1, 4).
Step
Centroids
Clusters
J
assign
1, 4
{1, 2} {3, 7, 8, 12}
(0+1+1+9+16+64)/6 = 15.1667
update
1.5, 7.5
{1, 2} {3, 7, 8, 12}
41.5/6 = 6.9167
assign
1.5, 7.5
{1, 2, 3} {7, 8, 12}
23.5/6 = 3.9167
update
2, 9
{1, 2, 3} {7, 8, 12}
16/6 = 2.6667
assign
2, 9
no change
2.6667, stop
J falls at every half step: 15.17, 6.92, 3.92, 2.67. Point 3 switched clusters in the second assignment because, once the right centroid moved to 7.5, it was 4.5 away from it and only 1.5 away from the left centroid. Of the five ways to cut six sorted points into two contiguous groups, the cut after 3 has the lowest distortion (2.6667; the next best, after 2, gives 6.9167), so here the local minimum is also the global one.
Common mistakes
Using distance instead of squared distance in the update. The mean minimizes squared distance; the point minimizing summed absolute distance is the median (that is K-medians). Symptom: your "proof" of monotone decrease fails in tests. Fix: keep both steps on ‖·‖².
Empty clusters. A centroid that wins no points makes the mean 0/0 and fills the array with NaN. Fix: keep the old centroid, or re-seed it at the point farthest from its centroid.
Checking convergence on J with a tight tolerance. Floating-point noise can make J wobble in the last digit. Fix: stop when assignments stop changing, or compare centroids with np.allclose.
Unscaled features. A feature measured in thousands dominates the distance. Symptom: clusters are slices along one axis. Fix: standardize first.
Check yourself
Start the same six points from μ = (1, 2). Which clustering do you reach?
Answer
Assign: {1} and {2, 3, 7, 8, 12}; update: μ = (1, 6.4). Assign: 2 and 3 are closer to 1 than to 6.4, giving {1, 2, 3} {7, 8, 12}; update: μ = (2, 9). The same optimum, J = 2.6667, one iteration later.
Lecture 1.3 · 7 min read
K-means optimization objective
K-means is not an arbitrary recipe: it minimizes a cost, the average squared distance from each point to the centroid of its cluster, also called the distortion.
J(c(1), …, c(m), μ1, …, μK) = (1/m) Σi ‖x(i) − μc(i)‖²c(i) is the cluster assigned to example i; μ_k is the centroid of cluster k.
Each step minimizes J over one set of variables while holding the other fixed. The assignment step chooses the c(i) that minimize J for fixed centroids: the nearest centroid. The update step chooses the μk that minimize J for fixed assignments: the mean of each cluster. So J can never go up, which gives a useful debugging check, and the algorithm stops when J stops changing.
import numpy as np
rng = np.random.default_rng(3)
X = np.vstack([rng.normal(c, 0.5, (30, 2)) for c in ([0, 0], [4, 1], [2, 4])])
mu = X[rng.choice(len(X), 3, replace=False)]
for it in range(6):
c = np.argmin(((X[:, None] - mu) ** 2).sum(-1), 1)
J = ((X - mu[c]) ** 2).sum(-1).mean()
print(f"iteration {it}: distortion {J:.4f}")
mu = np.array([X[c == k].mean(0) for k in range(3)])
Lecture 1.4 · 7 min read
Initialization and choosing K
Click "New random centroids" a few times in the demo and run to convergence each time. Sometimes two centroids split one group between them while a third claims two groups, and the algorithm sits there, converged, with a distortion well above the best possible. K-means finds a local minimum, and which one depends on where it started.
The standard defense is to run it many times from different random starts, 50 to 1,000, and keep the run with the lowest distortion. Initializing centroids from randomly chosen data points, rather than random coordinates, avoids starting in empty space. The k-means++ initialization goes further and picks each new centroid with probability proportional to its squared distance from the existing ones, which spreads them out; scikit-learn uses it by default.
K itself is not something the data decides. Distortion always falls as K grows (K = m gives zero), so you cannot minimize it over K. The elbow method plots distortion against K and looks for a bend, which is often ambiguous. The better question is downstream: if you are making T-shirts, K = 3 means S/M/L and K = 5 means XS–XL, and the trade-off between fit and manufacturing cost decides, not the plot.
Deep dive · k-means++ and the choice of K
Derivation
k-means++ chooses the first centroid uniformly at random from the data. For every later centroid it computes, for each point x, D(x) = distance from x to the nearest centroid chosen so far, and samples the next centroid from the data with probability
P(x) = D(x)² / Σx′ D(x′)²points already chosen have D = 0 and cannot be picked twice
Points far from every existing centroid are likely, but not certain, to be chosen. Picking the single farthest point instead (a deterministic rule) would chase outliers. Arthur and Vassilvitskii proved that the expected distortion right after k-means++ seeding, before any Lloyd iteration, is at most 8(ln K + 2) times the optimal distortion. Plain random initialization has no such bound.
Worked example by hand
Points 0, 1, 2, 10, 11, 12 on a line, K = 2, and suppose the first centroid is 0. The squared distances are 0, 1, 4, 100, 121, 144, summing to 370.
x
0
1
2
10
11
12
D(x)²
0
1
4
100
121
144
P(x)
0
0.0027
0.0108
0.2703
0.3270
0.3892
The second centroid lands in the right-hand group with probability 365/370 = 0.9865. With uniform random seeding the chance that both centroids come from the same group is 2 · (3/6) · (2/5) = 0.4. If K were 3 and the centroids so far were 0 and 12, the distances squared would be 0, 1, 4, 4, 1, 0 (sum 10), so 1 and 11 each get 0.1 and 2 and 10 each get 0.4.
Choosing K: why distortion alone fails
For these six points the best possible distortion for K = 1…6 is 25.6667, 0.6667, 0.4167, 0.1667, 0.0833, 0. It always decreases, because with one more centroid you could keep the old solution and move the extra centroid onto any point, which cannot increase J. So "minimize J over K" always answers K = m. The elbow is the K after which the decrease becomes small: here the drop from 25.67 to 0.67 is huge and every later drop is tiny, so K = 2. On real data the curve is usually smooth and the elbow is a matter of opinion.
The silhouette is a second hint that does not automatically favour large K. For point i, ai is its mean distance to the other members of its cluster and bi its mean distance to the nearest other cluster; si = (bi − ai) / max(ai, bi). For the point 3 in the clustering {1, 2, 3} {7, 8, 12}: a = (2 + 1)/2 = 1.5, b = (4 + 5 + 9)/3 = 6, s = 4.5/6 = 0.75. Values near 1 mean well separated, near 0 on a boundary, negative probably misassigned.
Common mistakes
Sampling with D instead of D². The squared weighting is what gives the log K guarantee. Symptom: seeds still bunch up on dense groups. Fix: square the distance.
Distance to the first centroid only. D(x) is to the nearest chosen centroid. Using only the first one keeps picking from the same far group.
Comparing distortion across K from single runs. A bad local minimum at K = 4 can be worse than K = 3. Fix: use the best of many restarts per K before plotting.
Choosing K from the plot when the use case decides. If clusters become product sizes or sales regions, the cost of an extra cluster is a business number. Use it.
Check yourself
In the table, why is P(0) exactly 0 and what does that guarantee?
Answer
0 is already a centroid, so D(0) = 0. Any point equal to an existing centroid has probability 0, so k-means++ never picks the same location twice, and no cluster starts empty unless the data has duplicate points.
Optional lab · about 20 min · runs in this page
K-means step by step
Implement the two steps of k-means and watch the centroids move.
Step 1Data and the assignment step
import numpy as np, matplotlib.pyplot as plt
rng = np.random.default_rng(4)
X = np.vstack([rng.normal(c, 0.6, (40, 2)) for c in ([0, 0], [5, 1], [2, 5])])
def find_closest_centroids(X, centroids):
return np.argmin(((X[:, None, :] - centroids[None]) ** 2).sum(-1), axis=1)
centroids = np.array([[1.0, 1.0], [4.0, 0.0], [3.0, 4.0]])
idx = find_closest_centroids(X, centroids)
print("first ten assignments:", idx[:10])
Step 2The update step and the loop
def compute_centroids(X, idx, K):
return np.array([X[idx == k].mean(0) if (idx == k).any() else X[np.random.randint(len(X))] for k in range(K)])
history = [centroids]
for it in range(8):
idx = find_closest_centroids(X, centroids)
centroids = compute_centroids(X, idx, 3); history.append(centroids)
H = np.array(history)
plt.scatter(X[:, 0], X[:, 1], c=idx, s=12, cmap="viridis")
for k in range(3): plt.plot(H[:, k, 0], H[:, k, 1], "kx-")
plt.title("centroid paths"); plt.show()
print("final centroids:", centroids.round(2))
Module 2
Practice quiz: Clustering
Practice quiz · 5 questions
Clustering
Module 3
Anomaly detection
Lecture 1.5 · 8 min read
Finding unusual events
An aircraft engine manufacturer measures each engine as it comes off the line: heat generated, vibration intensity and so on. Almost all engines are fine. Given a new engine, is it like the others, or anomalous and worth inspecting before it is shipped?
Anomaly detection learns what normal data looks like by fitting a probability model p(x) to unlabeled examples that are mostly normal. A new example with very low probability, p(xtest) < ε, is flagged as an anomaly.
Fraud detection: features of each user's activity (logins, pages visited, transactions, typing speed); flag unusual users for review.
Manufacturing: flag unusual parts, circuit boards or engines.
Monitoring computers in a data center: memory use, disk access, CPU load and network traffic; flag machines behaving oddly.
Lecture 1.6 · 10 min read
Gaussian (normal) distribution
The Gaussian, or normal, distribution is the bell-shaped curve. It has two parameters: the mean μ, where the center is, and the variance σ², how wide it is (σ is the standard deviation). The area under the curve is always 1, so a narrow curve is tall and a wide one is flat.
import numpy as np
rng = np.random.default_rng(0)
heat = rng.normal(52, 4, 500) # engine heat readings
mu, var = heat.mean(), heat.var()
p = lambda x: np.exp(-(x - mu) ** 2 / (2 * var)) / np.sqrt(2 * np.pi * var)
print(f"estimated mu = {mu:.2f}, sigma = {np.sqrt(var):.2f}")
for x in (52, 58, 66):
print(f"p({x}) = {p(x):.5f}")
Lecture 1.7 · 9 min read
Anomaly detection
Servers report CPU load and network throughput every minute; one day a machine behaves unlike anything in the logs. Anomaly detection learns what normal looks like from normal data alone and flags anything with low probability under that model. Density estimation: fit p(x), flag x when p(x) < ε.
The simplest p(x) treats each feature as an independent Gaussian. Estimate each feature's mean μj and variance σj² from the data, compute each feature's density, and multiply.
p(x) = Πj 1/√(2πσj²) · exp( −(xj − μj)² / (2σj²) )μj = mean of feature j, σj² = mean of (xj − μj)² over the m training examples.
Why not a supervised classifier, since you probably have a few labeled anomalies? Because anomalies are rare, varied and new: next month's failure will not look like last month's, and a classifier trained on twenty examples of past failures learns those twenty. Density estimation learns the far more plentiful normal data and treats everything else as suspicious. Use the labeled anomalies only to choose ε and to measure precision, recall and F1 on a validation set, since accuracy is meaningless when 99.9% of examples are normal.
Two practical moves. Features that are far from Gaussian (long right tails, like request latency) become usable after a log or square-root transform; plot histograms and transform until they look bell-shaped. And when an anomaly hides in a combination of normal-looking values, such as high CPU with low traffic, build a feature for the combination, CPU ÷ traffic, so that the product of independent densities can see it.
Deep dive · Gaussian estimates, products of densities, and covariance
Derivation: the maximum-likelihood μ and σ²
Given m values x(1)…x(m) of one feature, choose μ and σ² to maximize the probability density of the data. Independence of examples turns the joint density into a product; the log turns it into a sum:
∂ℓ/∂σ² = −m/(2σ²) + Σ (x(i) − μ)² / (2σ⁴) = 0. Multiply by 2σ⁴: −mσ² + Σ (x(i) − μ)² = 0, so σ² = (1/m) Σ (x(i) − μ)². This is the 1/m (population) variance, np.var with its default ddof=0. The 1/(m−1) version is unbiased; for anomaly detection with hundreds of examples the difference is negligible.
Why multiply
If features are independent, P(x1 and x2) = P(x1) · P(x2), and the same holds for densities. The product of per-feature Gaussians is exactly a multivariate Gaussian whose covariance matrix is diagonal. In practice features are rarely independent, but the model still works when each anomaly is unusual in at least one feature.
Worked example by hand
Throughput readings 12.3, 11.8, 13.1, 12.6, 12.0, 12.9, 11.5. Sum 86.2, so μ = 12.3143. Squared deviations sum to 2.0686, so σ² = 0.2955 and σ = 0.5436. For x = 14.0, z = (14.0 − 12.3143)/0.5436 = 3.10 and
The density at the mean is 0.7339, which is above 0.5 and could exceed 1 for a narrower Gaussian. Densities are not probabilities; only their ordering against ε matters.
Take two standardized features with correlation 0.8: Σ = [[1, 0.8], [0.8, 1]], |Σ| = 0.36, Σ⁻¹ = [[2.778, −2.222], [−2.222, 2.778]]. For x = (1, −1) the quadratic form is 2.778 + 2.222 + 2.222 + 2.778 = 10, so p = 0.2653 · e⁻⁵ = 0.00179. For x = (1, 1) the form is 1.111 and p = 0.1522. The diagonal model gives both points the same density, φ(1)·φ(1) = 0.0585, because it cannot see that (1, −1) breaks the correlation. The full model separates them by a factor of 85. The engineered-feature trick in the lecture (CPU ÷ traffic) is a manual way to get the same effect with the cheaper model.
Common mistakes
Fitting on data that contains the anomalies. They inflate σ² and hide themselves. Fit on normal examples only.
Underflow. A product of 50 small densities becomes 0.0. Fix: sum log densities and compare with ln ε.
Singular covariance. With m < n, or duplicated features, Σ is not invertible. Symptom: LinAlgError or huge densities. Fix: drop redundant features, add a small multiple of the identity, or keep the diagonal model.
Choosing ε on the test set. Pick it on validation data with F1, then report test metrics once.
Check yourself
Why does the full model need m clearly larger than n, while the diagonal one does not?
Answer
Σ has n(n+1)/2 free parameters and is singular when m ≤ n. The diagonal model has only n variances, each estimated from all m values.
Lecture 1.8 · 11 min read
Developing and evaluating an anomaly detection system
Choosing features and ε is much easier with a number that measures the system. Even though training is unsupervised, use a few labeled anomalies for evaluation. For the engines: 10,000 normal engines and 20 known flawed ones.
Training set: 6,000 normal engines (a few undetected anomalies are fine).
Cross-validation set: 2,000 normal and 10 anomalous engines, used to choose ε and features.
Test set: 2,000 normal and 10 anomalous engines, for the final estimate.
Because the classes are so skewed, accuracy is useless: predicting "normal" always is 99.5% accurate. Use precision, recall and F1 on the cross-validation set, and choose ε to maximize F1. With very few anomalies, some teams skip the test set and use only cross-validation, accepting a more optimistic estimate.
import numpy as np
rng = np.random.default_rng(1)
normal = rng.normal(0, 1, 2000); anom = rng.normal(4.5, 1, 10)
x_cv = np.concatenate([normal, anom]); y_cv = np.r_[np.zeros(2000), np.ones(10)]
p = np.exp(-x_cv ** 2 / 2) / np.sqrt(2 * np.pi) # model fitted on normal data
best = (0, None)
for eps in np.logspace(-6, -1, 60):
pred = p < eps
tp = (pred & (y_cv == 1)).sum(); fp = (pred & (y_cv == 0)).sum(); fn = (~pred & (y_cv == 1)).sum()
if tp == 0: continue
P, R = tp / (tp + fp), tp / (tp + fn); F1 = 2 * P * R / (P + R)
if F1 > best[0]: best = (F1, eps, P, R)
print(f"best epsilon {best[1]:.2e}: F1 {best[0]:.3f} (precision {best[2]:.2f}, recall {best[3]:.2f})")
Lecture 1.9 · 8 min read
Anomaly detection vs. supervised learning
If you have some labeled anomalies, why not train a classifier? It depends on how many positives you have and whether future anomalies will look like past ones.
Anomaly detection
Supervised learning
Very few positive examples (0–20 is common), many negatives
Enough positive and negative examples
Many different kinds of anomaly; future ones may look unlike any seen so far
Future positives are likely to resemble those in the training set
Fraud (new schemes appear constantly), unseen manufacturing defects, compromised machines
Spam, known manufacturing defects (scratches), weather prediction, disease classification
Lecture 1.10 · 14 min read
Choosing what features to use
Feature choice matters more for anomaly detection than for supervised learning, because the algorithm has no labels to tell it which features are useful.
Make features roughly Gaussian. Plot a histogram; if it is skewed, transform it, for example log(x + 1), √x or x1/3. Apply the same transform to cross-validation and test data.
Run error analysis on missed anomalies. When an anomaly gets a high p(x), look at it and ask what makes it unusual; that suggests a new feature.
Combine features. In a data center, high CPU load with low network traffic is suspicious even if each value alone is normal; the ratio CPU / network captures it.
import numpy as np
rng = np.random.default_rng(2)
x = rng.exponential(2.0, 5000) # skewed feature
def skew(v): return float(((v - v.mean()) ** 3).mean() / v.std() ** 3)
for name, v in [("x", x), ("log(x + 1)", np.log1p(x)), ("x ** 0.4", x ** 0.4)]:
print(f"{name:10s} skewness {skew(v):+.2f}")
Run your kmeans from “Clustering with K-means” with K = 16 on a random sample of 20,000 pixels (the full set works but is slow in pure NumPy). Then assign every pixel to its nearest centroid and rebuild the image from the 16 centroid colors. Display original and compressed side by side. Each pixel now needs 4 bits instead of 24.
Generate 300 normal points with two Gaussian features and 15 anomalies far from them (fix a seed). Fit μ and σ² on the normal points, compute p(x) for all, and sweep ε over 50 values on a log scale, computing F1 against the known anomaly labels at each. Plot F1 against ε and report the best. Then plot the points with contours of p(x) and the flagged anomalies circled.
Checkpoint 2
Using the seven-reading model, what is p(μ), the density at the mean, to four decimals?
Week 2 · Recommender systems
Recommender systems
Predict what people will like: collaborative filtering learned from ratings, content-based filtering from features, and PCA for visualization.
Video lectures · Week 2
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
How does Netflix recommend movies? Matrix FactorizationLuis Serrano Academy · YouTube ↗
Module 1
Collaborative filtering
Lecture 2.1 · 5 min read
Making recommendations
Recommender systems drive a large share of the revenue of online stores, streaming services and news sites. The running example: a film site with nu users and nm movies, where users rate movies from 0 to 5 stars and many ratings are missing.
Movie
Alice
Bob
Carol
Dave
Love at last
5
5
0
0
Romance forever
5
?
?
0
Cute puppies of love
?
4
0
?
Nonstop car chases
0
0
5
4
Swords vs. karate
0
0
5
?
Notation: r(i, j) = 1 if user j has rated movie i, and y(i,j) is that rating. The task is to predict the question marks and recommend the movies each user is predicted to rate highest.
Lecture 2.2 · 11 min read
Using per-item features
Suppose each movie came with features, say x1 = how romantic and x2 = how much action. Then predicting a user's ratings is just linear regression, one model per user: user j has parameters w(j) and b(j), and predicts w(j) · x(i) + b(j) for movie i.
min over w⁽ʲ⁾, b⁽ʲ⁾: ½ Σi: r(i,j)=1 (w(j) · x(i) + b(j) − y(i,j))² + (λ/2) ‖w(j)‖²Sum the cost over all users to learn every user's parameters at once.
Users rate movies from 1 to 5, most entries missing. If each movie came with features, say how much romance and how much action it contains, you could fit one linear regression per user: her rating ≈ w(user) · x(movie) + b(user), trained on the movies she rated. And if instead each user came with a preference vector, you could fit one regression per movie to learn its features. Collaborative filtering notices that you need neither: learn both at once from the ratings alone.
J(w, b, x) = ½ Σ(i,j) rated ( w(j) · x(i) + b(j) − y(i,j) )² + λ/2 Σj ‖w(j)‖² + λ/2 Σi ‖x(i)‖²i indexes movies, j users. The sum runs only over observed ratings. Gradient descent on w, b and x together.
The learned x(i) are not labeled "romance" or "action"; they are whatever directions explain the ratings. But they behave like features: two movies with similar x are liked by the same people, so "movies like this one" is a nearest-neighbor search over x. The number of features is a hyperparameter; 10 to 100 is typical.
import torch
n_users, n_movies, k = 943, 1682, 20
W = (torch.randn(n_users, k) * 0.1).requires_grad_() # scale first, then mark as a leaf
X = (torch.randn(n_movies, k) * 0.1).requires_grad_()
b = torch.zeros(n_users, requires_grad=True)
# ratings as (user_idx, movie_idx, rating) tensors; loss over observed entries only
pred = (W[u] * X[i]).sum(1) + b[u]
loss = 0.5 * ((pred - r) ** 2).sum() + lam/2 * ((W**2).sum() + (X**2).sum())
Deep dive · Gradients and the matrix-factorization view
Derivation
Write e(i,j) = w(j) · x(i) + b(j) − y(i,j) for every rated pair. The cost is ½ Σ e² plus the two regularizers. A given w(j) appears only in the terms of movies that user j rated, and in its own regularizer. By the chain rule, ∂(½e²)/∂w(j) = e · ∂e/∂w(j) = e · x(i). Collecting terms:
∂J/∂w(j) = Σi: r(i,j)=1 e(i,j) x(i) + λ w(j)sum over the movies user j rated
∂J/∂x(i) = Σj: r(i,j)=1 e(i,j) w(j) + λ x(i)sum over the users who rated movie i
∂J/∂b(j) = Σi: r(i,j)=1 e(i,j)
The two vector gradients are mirror images: the user's update uses the movie vectors as inputs, and the movie's update uses the user vectors as inputs. That symmetry is why the problem is not convex in (w, x) jointly but is a convex ridge regression in either one when the other is held fixed. Alternating least squares exploits that by solving each side in closed form: w(j) = (XjᵀXj + λI)⁻¹ Xjᵀ yj.
Worked example by hand
One rating y = 4, with w = (1, 0.5), x = (2, 1), b = 0.5, λ = 0.1. Prediction 2 + 0.5 + 0.5 = 3, so e = −1.
One gradient step with α = 0.1: w = (1.19, 0.595), x = (2.08, 1.04), b = 0.6. New prediction 1.19 · 2.08 + 0.595 · 1.04 + 0.6 = 2.4752 + 0.6188 + 0.6 = 3.694, closer to 4. Note that both w and x moved: one rating teaches both the user and the movie.
The matrix-factorization view
Stack the user vectors as rows of W (nu × k) and the movie vectors as rows of X (nm × k). Every prediction at once is the matrix X Wᵀ (movies × users), plus biases. Collaborative filtering says the full ratings matrix is approximately rank k, and it fits the factors only on the observed entries. For MovieLens 100k with k = 20 there are (943 + 1,682) · 20 = 52,500 vector parameters, against 943 · 1,682 = 1,586,126 cells of which 100,000 (6.3%) are observed. Plain SVD cannot be used directly because it needs every cell; filling the missing ones with zeros tells the model that unrated means "rated 0".
Common mistakes
Summing the loss over all cells. Multiply by the mask or index only observed triples. Symptom: every prediction collapses toward 0.
Initializing all vectors to zero. Then every gradient for w is a sum of e · 0 = 0 and nothing moves except the biases. Fix: small random values.
Using torch.randn(...) * 0.1 with requires_grad=True inside. The multiplication makes a non-leaf tensor whose .grad stays None. Fix: wrap in nn.Parameter or call requires_grad_() after scaling.
Regularizing the bias. Harmless but unnecessary; the lecture's cost leaves b unregularized, as in linear regression.
Check yourself
A movie nobody has rated yet: what does gradient descent do to its x?
Answer
Its only gradient term is λx, so x decays toward zero and the movie's prediction for every user becomes just b(j). Collaborative filtering has no information about it until ratings arrive.
Lecture 2.4 · 8 min read
Binary labels: favs, likes and clicks
Many systems have no star ratings, only binary signals: did the user like, favorite, click, buy, or watch at least 30 seconds? A label of 1 means engaged, 0 means shown but not engaged, and "?" means never shown.
Collaborative filtering adapts exactly as linear regression became logistic regression: predict the probability of engagement with the sigmoid, and use the log loss.
P(y(i,j) = 1) = g(w(j) · x(i) + b(j)), L = −y log f − (1 − y) log(1 − f)Sum the loss over all (i, j) with r(i, j) = 1 and add the usual regularization.
Module 2
Practice quiz: Collaborative filtering
Practice quiz · 5 questions
Collaborative filtering
Module 3
Recommender systems implementation detail
Lecture 2.5 · 7 min read
Mean normalization and binary labels
A new user has rated nothing. Her w is pulled to zero by regularization and the model predicts 0 stars for every movie, which is wrong and useless. Mean normalization fixes it: for each movie, subtract its average rating from every observed rating before training, then add it back when predicting. A new user is now predicted to give each movie its average, which is the sensible default, and her vector begins to specialize with her first rating.
mask = R > 0 # observed entries
movie_mean = (R * mask).sum(1) / mask.sum(1) # one mean per movie
R_norm = (R - movie_mean[:, None]) * mask
Many systems have no ratings at all, only clicks, purchases, watch time: binary signals of engagement. Replace the squared error with log loss and the prediction with a sigmoid of the dot product, exactly the move from linear to logistic regression in Course 1. Everything else in the cost is unchanged. Implicit signals are noisier than ratings (not clicking is not the same as disliking) but there are vastly more of them.
Deep dive · Cold start numbers and the logistic version
Derivation: why a new user predicts zero
A user with no ratings contributes no error terms. Her gradient is only λw (and 0 for b if b is unregularized). Gradient descent gives w ← (1 − αλ)w, which decays to zero, and her predictions w · x + b become b, which also stays at its initial 0. With mean normalization the model predicts w · x + b + μi for movie i, so the same zero vector now yields μi, the movie's average.
Worked example by hand
Three movies, three existing users and a new user, Eve. Rows are movies, as in the lecture.
Movie
Ann
Bob
Cat
μi
Normalized
Eve, raw model
Eve, normalized model
1
5
4
?
4.5
0.5, −0.5, ?
0
4.5
2
?
2
1
1.5
?, 0.5, −0.5
0
1.5
3
4
?
5
4.5
−0.5, ?, 0.5
0
4.5
Eve now gets a sensible ranking (movies 1 and 3 first) before she has rated anything. Normalizing by movie solves the new-user problem. Normalizing by user (the lab does this) instead helps users with unusual rating scales, a harsh critic whose 3 means "good", but gives a new movie a default of each user's own mean. Many systems subtract a global mean plus learned user and item biases, which handles both.
Mean normalization also makes regularization honest. The penalty λ‖w‖² pulls w toward zero, so zero should mean "average opinion". Without normalization, zero means "rates everything 0 stars", a strange default to shrink toward.
Derivation: the binary version
For clicks y ∈ {0, 1}, predict p = σ(z) with z = w · x + b, and use log loss L = −y ln p − (1 − y) ln(1 − p). With σ′(z) = σ(z)(1 − σ(z)):
∂L/∂z = −y(1 − p) + (1 − y)p = p − y
So the gradients are the same as in the squared-error case with e replaced by p − y: ∂L/∂w = (p − y) x, ∂L/∂x = (p − y) w. Example: z = 0.5 gives p = 0.6225. If the user clicked, L = −ln 0.6225 = 0.4741 and ∂L/∂z = −0.3775; if not, L = −ln 0.3775 = 0.9741 and ∂L/∂z = 0.6225. At z = 2 a non-click costs −ln(1 − 0.8808) = 2.1269: confident mistakes are expensive.
Common mistakes
Computing the mean over all cells. Unrated zeros drag the mean down. Divide by the number of observed ratings, not the number of users.
Forgetting to add the mean back. Predictions come out centered near 0, and RMSE looks terrible.
A movie with no ratings. Its mean is 0/0. Fall back to the global mean.
Treating unobserved as negative in implicit data. Not clicking may mean "never saw it". Sample a limited number of negatives, ideally from items that were shown, and weight them lower than positives.
Check yourself
Eve rates movie 2 with 5 stars. With w still near zero, which sign will the first gradient step give her bias, and why?
Answer
Her prediction is about 1.5, so e = 1.5 − 5 = −3.5 and ∂J/∂b = −3.5. Gradient descent subtracts it, so b increases: the model learns she rates higher than average.
Lecture 2.6 · 11 min read
Collaborative filtering in PyTorch
Collaborative filtering learns both the item features x(i) and the user parameters w(j), b(j). Writing the gradients by hand is tedious; automatic differentiation does it for you. Make every parameter a tensor with requires_grad, write the cost, call backward(), and let an optimizer step.
import numpy as np, torch
Y = np.array([[5, 5, 0, 0], [5, np.nan, np.nan, 0], [np.nan, 4, 0, np.nan], [0, 0, 5, 4], [0, 0, 5, np.nan]])
R = torch.tensor(~np.isnan(Y), dtype=torch.float32); Yt = torch.tensor(np.nan_to_num(Y), dtype=torch.float32)
torch.manual_seed(0)
n_m, n_u, k = 5, 4, 2
X = (torch.randn(n_m, k) * 0.1).requires_grad_(); W = (torch.randn(n_u, k) * 0.1).requires_grad_()
b = torch.zeros(1, n_u, requires_grad=True)
opt = torch.optim.Adam([X, W, b], lr=0.1); lam = 0.1
for it in range(300):
pred = X @ W.T + b
J = 0.5 * (((pred - Yt) * R) ** 2).sum() + lam / 2 * ((X ** 2).sum() + (W ** 2).sum())
opt.zero_grad(); J.backward(); opt.step()
print("final cost:", round(J.item(), 3))
print("predicted ratings:\n", (X @ W.T + b).detach().numpy().round(1))
TensorFlow does the same with tf.GradientTape: record the cost computation, ask the tape for gradients, and apply them with an optimizer.
Lecture 2.7 · 6 min read
Finding related items
The learned features x(i) are hard to interpret one by one, but together they place similar items close to each other. To find items related to item i, find the items k with the smallest squared distance ‖x(k) − x(i)‖². "Customers who viewed this also viewed" lists are often built this way.
import numpy as np
titles = ["Love at last", "Romance forever", "Cute puppies of love", "Nonstop car chases", "Swords vs. karate"]
X = np.array([[1.2, -0.1], [1.1, 0.0], [0.9, 0.1], [-0.2, 1.3], [-0.1, 1.1]]) # learned features
i = 0
d = ((X - X[i]) ** 2).sum(1)
for k in np.argsort(d)[1:3]:
print(f"related to '{titles[i]}': {titles[k]} (distance {d[k]:.2f})")
Limitations of collaborative filtering: the cold start problem, since new items and new users have few ratings, and no natural way to use side information such as genre, cast, or user demographics. Content-based filtering, next, addresses both.
Module 4
Practice lab: Collaborative filtering recommender systems
R = np.array([[5, 4, 0, 0], # 3 users × 4 movies, 0 = not rated
[0, 0, 5, 4],
[4, 0, 0, 3]], dtype=float)
mask = R > 0
Compute each user's mean over rated movies (rows here are users). Mean-normalize.
Checkpoint 1
Mean rating of user 0 over the movies they rated?
Step 2A ratings catalog
ratings = pd.read_csv("data/ratings_synth.csv") # 200 users × 60 films, ~2,100 ratings from hidden latent factors# with network access, the same code runs on MovieLens 100k:# pd.read_csv("https://files.grouplens.org/datasets/movielens/ml-100k/u.data", sep="\t", names=["user","item","rating","ts"])
Split 80/20 by row. Implement the model from “Collaborative filtering” with k = 10 and λ = 1, mean-normalized per item, trained with Adam at lr 0.02 for 300 epochs on the full set of observed ratings (vectorized: index W and X by the user and item columns). Report the test RMSE and compare it with the item-mean baseline; on MovieLens expect about 0.93–0.97 with k = 20.
Step 3Use it
Add yourself as user 943 with ratings for five movies you know (titles are in u.item), retrain, and print your top ten predictions. Then pick a movie and list its ten nearest neighbors by cosine similarity of the learned x vectors. Do the neighbors make sense?
Checkpoint 2
How many observed ratings does the toy matrix have in rows 0 and 2 combined?
Module 5
Practice quiz: Recommender systems implementation
Practice quiz · 5 questions
Recommender systems implementation
Module 6
Content-based filtering
Lecture 2.8 · 9 min read
Collaborative filtering vs. content-based filtering
Collaborative filtering recommends items based on the ratings of users who gave similar ratings to you. Content-based filtering recommends items based on features of the user and features of the item, finding good matches between them.
User features xu
Item features xm
age, gender, country
year, genres
movies watched
reviews, critic scores
average rating per genre
average rating from users
The model computes a vector vu from the user features and a vector vm from the item features, and predicts the rating as their dot product vu · vm. The two feature sets can have different sizes, but the two vectors must have the same length.
Lecture 2.9 · 8 min read
Content-based filtering
Collaborative filtering uses only the ratings matrix. Content-based filtering uses what you know about users (age, country, past genres watched) and about items (genre, year, cast, description) and learns how those map to preference. The architecture is two small neural networks: one turns user features into a vector vu, the other turns item features into a vector vm of the same length, and the prediction is their dot product. Train both with squared error on observed ratings, or log loss on clicks.
The two-tower design has a practical payoff. The item tower depends only on item features, so you can run it once over the whole catalog offline and store the vectors. At request time you compute one user vector and take dot products against the stored items, which is a fast nearest-neighbor search even for millions of items. New items with no ratings get a vector from their features immediately, which solves the cold-start problem collaborative filtering cannot.
Most production systems combine both: the ID of a user or item gets an embedding, learned collaboratively, which is concatenated with content features and fed into the towers. Embeddings are the same object as the collaborative-filtering vectors: a learned, dense representation of a discrete thing. Word embeddings in Course 4 are the same idea again.
Deep dive · Two towers, cosine similarity and cold start
Derivation
Let fu be the user tower and fm the item tower, both small neural networks ending in a linear layer of width d. The prediction is ŷ = fu(user features) · fm(item features). With squared error L = ½(ŷ − y)², write vu and vm for the tower outputs. Then ∂L/∂vu = (ŷ − y) vm and ∂L/∂vm = (ŷ − y) vu, exactly the collaborative-filtering gradients, and backpropagation carries them into each tower's weights. Collaborative filtering is the special case where each tower is a lookup table indexed by ID.
The key structural fact: nothing in fm depends on the user. So all item vectors can be computed once and stored, and serving one request costs one forward pass of fu plus a nearest-neighbour search. Ten million items with d = 32 in float32 take 107 · 32 · 4 bytes = 1.28 GB, which fits in memory on one machine.
Dot product versus cosine
cos(a, b) = a · b / (‖a‖ ‖b‖)1 = same direction, 0 = orthogonal, −1 = opposite
The dot product rewards long vectors; the cosine ignores length. Long item vectors often mean "popular", so a raw dot product leans toward popular items. Normalizing both towers' outputs to unit length makes the dot product equal to the cosine.
Worked example by hand
User vector u = (1, 2, 0), ‖u‖ = √5 = 2.2361.
Item
Vector
u · v
‖v‖
cosine
A
(2, 1, 1)
4
2.4495
0.7303
B
(0, 3, −1)
6
3.1623
0.8485
C
(4, 8, 0)
20
8.9443
1.0000
E
(6, 0, 6)
6
8.4853
0.3162
C points exactly along u: cosine 1 regardless of its length. E has a larger dot product than A (6 against 4) only because it is long; by cosine A is much closer (0.7303 against 0.3162). Which ranking you want is a product decision: dot product if magnitude carries useful signal such as quality, cosine if you want pure similarity of taste.
Cold start, concretely
A movie released today has no ratings, so its collaborative x is noise near zero. Its item tower output depends only on genre, year, cast and description, so it gets a vector in the same space as movies with similar metadata the moment it is added. A new user with only age and country gets a user vector the same way. Hybrid systems concatenate a learned ID embedding with the content features; for a new item the ID embedding starts at zero and the content features carry the prediction until ratings accumulate.
Common mistakes
Towers with different output widths. The dot product needs equal d. Symptom: a shape error at the final layer.
A ReLU on the last layer. Non-negative vectors can never have a negative dot product, so the model cannot express dislike. Keep the last layer linear.
Feature leakage across towers. Putting the item's average rating into the item tower is fine; putting the user's rating of this item anywhere is the label.
Stale item vectors. After retraining the towers, recompute and re-index every item vector, or old and new vectors live in different spaces.
Check yourself
If you L2-normalize both tower outputs, what range can the prediction take, and what does that imply for a 1 to 5 rating target?
Answer
The dot product of unit vectors lies in [−1, 1]. Either rescale the target, or add a learned scale and bias after the dot product (ŷ = s · cos + c).
Lecture 2.10 · 7 min read
Retrieval, ranking, and what you are optimizing
With ten million items you cannot score each one per request. Split the work. Retrieval produces a few hundred candidates cheaply: nearest neighbors of items the user liked, the most popular items in her country, items similar to her last ten views. Ranking runs the full model on those candidates and orders them. Measure the trade-off offline: more candidates raise quality and latency, and the knee of that curve is your budget.
The objective you train on is the product you build. A system trained to maximize clicks learns to surface outrage and clickbait; one trained on watch time learns to recommend long videos; one trained on purchases learns to push what is expensive. None of those is the same as what the user would thank you for. Teams that do this well choose a target closer to long-term satisfaction, such as return visits or explicit feedback, measure the effect of the recommender on it with randomized experiments, and treat engagement metrics as proxies to be checked, not goals to be maximized.
Deep dive · Budgets, ranking metrics and objectives
Intuition: why two stages
Suppose the full ranking model costs 1 microsecond per item on one core. Scoring 10 million items is 107 · 10−6 = 10 seconds per request, against a latency budget of perhaps 100 milliseconds. Retrieval cuts the candidate set to a few hundred with cheap methods (approximate nearest-neighbour search over stored vectors, popularity lists, co-occurrence), and the ranking model spends its budget on those. The final quality is bounded by retrieval recall: an item retrieval misses can never be ranked first. So the first offline measurement is recall@N of the retrieval stage, the fraction of items the user later engaged with that appear among the N candidates.
Derivation: ranking metrics
For a ranked list of length k with relevance labels rel1…relk ∈ {0, 1}:
precision@k = (number relevant in top k) / k
recall@k = (number relevant in top k) / (total relevant for this user)
Neither cares about order within the top k. Discounted cumulative gain does: each relevant item contributes 1/log₂(position + 1), so position 1 counts 1, position 2 counts 0.6309, position 3 counts 0.5, position 4 counts 0.4307, position 5 counts 0.3869.
DCG@k = Σp=1..k relp / log₂(p + 1), NDCG@k = DCG@k / IDCG@kIDCG is the DCG of the best possible ordering, so NDCG lies in [0, 1]
Worked example by hand
Top 5 recommendations, relevance 1, 0, 1, 0, 0; the user has exactly two relevant items in total.
Ideal order puts both relevant items first: IDCG@5 = 1 + 0.6309 = 1.6309.
NDCG@5 = 1.5 / 1.6309 = 0.9197.
Swapping the items at positions 2 and 3 would raise NDCG to 1 without changing precision or recall at 5.
What you are optimizing
A model trained on clicks learns P(click | user, item). Ranking by it maximizes expected clicks per impression, which is not the same as satisfaction. Three common gaps: position bias (items shown first get clicked more regardless of quality, so the logs reward whatever the old system ranked high); feedback loops (the model only learns about items it chose to show); and proxy drift (watch time rewards long content, purchases reward expensive items). Practical counters are logging the position and modelling it separately, reserving a small share of traffic for randomized exploration, and evaluating changes with online A/B tests on a long-term metric such as 28-day retention rather than on the training metric alone.
Common mistakes
Evaluating on a random split of interactions. Future interactions leak into training. Split by time: train on the past, test on the next week.
Recommending what the user already has. Exclude seen items before computing precision@k, or the metric rewards repeats.
Comparing NDCG across users with different numbers of relevant items without normalizing. That is what the I in IDCG is for.
Optimizing ranking while retrieval recall is 40%. Measure the stages separately; fix the weaker one first.
Check yourself
Same list, but the user has four relevant items in total. Which of the numbers above change?
Answer
precision@5 stays 0.4 and DCG stays 1.5. recall@5 drops to 2/4 = 0.5. IDCG@5 becomes 1 + 0.6309 + 0.5 + 0.4307 = 2.5616, so NDCG@5 = 1.5/2.5616 = 0.5856.
Lecture 2.11 · 10 min read
Ethical use of recommender systems
Recommenders choose what billions of people see, so their objective matters. Typical goals include recommending items users are most likely to rate highly, buy, or engage with, and sometimes items that generate the most profit. Some of these are benign; some can cause harm.
Ranking by profit or ad payments rather than value to the user can steer people toward worse products. Being transparent with users about why items are shown helps.
Optimizing engagement can amplify conspiracy theories, hate and toxicity, because such content attracts clicks. Filtering problematic content and choosing better objectives help.
A virtuous or vicious cycle: businesses that earn more from recommendations can bid more for exposure, regardless of whether they serve users well.
There is no complete solution, but good practice is clear: ask how the system could harm users or society, prefer objectives aligned with users' long-term interest, and be open about how recommendations are made.
Lecture 2.12 · 4 min read
Content-based filtering in PyTorch
The two-tower model: a user network maps user features to vu, an item network maps item features to vm, both vectors are normalized to length 1, and the prediction is their dot product. Both networks are trained together with squared error on the known ratings.
import torch, torch.nn as nn
torch.manual_seed(0)
user_net = nn.Sequential(nn.Linear(14, 32), nn.ReLU(), nn.Linear(32, 8))
item_net = nn.Sequential(nn.Linear(16, 32), nn.ReLU(), nn.Linear(32, 8))
def predict(xu, xm):
vu = user_net(xu); vm = item_net(xm)
vu = vu / vu.norm(dim=1, keepdim=True); vm = vm / vm.norm(dim=1, keepdim=True)
return (vu * vm).sum(1)
xu, xm = torch.randn(5, 14), torch.randn(5, 16)
print("predictions for 5 user-item pairs:", predict(xu, xm).detach().numpy().round(3))
params = list(user_net.parameters()) + list(item_net.parameters())
print("trainable parameters:", sum(p.numel() for p in params))
Optional lab · about 25 min · runs in this page
Content-based filtering with two towers
Train a small two-tower model on synthetic users and movies and see it learn which users like which genres.
Step 1Synthetic data
import numpy as np, torch, torch.nn as nn
rng = np.random.default_rng(0); torch.manual_seed(0)
n_users, n_items, g = 200, 120, 4
user_pref = rng.dirichlet(np.ones(g), n_users) # each user's taste over 4 genres
item_genre = np.eye(g)[rng.integers(0, g, n_items)] # one genre per movie
pairs = rng.integers(0, [n_users, n_items], (3000, 2))
ratings = 1 + 4 * (user_pref[pairs[:, 0]] * item_genre[pairs[:, 1]]).sum(1) + rng.normal(0, 0.3, 3000)
Xu = torch.tensor(user_pref[pairs[:, 0]], dtype=torch.float32); Xm = torch.tensor(item_genre[pairs[:, 1]], dtype=torch.float32)
y = torch.tensor(ratings, dtype=torch.float32)
print("training pairs:", len(y), " rating range:", round(float(y.min()), 2), "to", round(float(y.max()), 2))
Principal component analysis (PCA) is mostly used to visualize data with many features. Measure cars by length and width: width barely varies, so you could keep only length. Measure length and height of cars of very different sizes: both vary, but together, so a new axis along the direction where they vary most captures nearly everything in one number.
PCA finds such axes, called principal components. Project each example onto the first component and you get one number per example; onto the first two and you can plot the data in 2-D, even if it started with 50 features, such as country statistics (GDP, life expectancy, education …).
Lecture 2.14 · 8 min read
Principal component analysis
Fifty measurements per country, and you want one scatter plot. Principal component analysis finds the direction in the 50-dimensional space along which the data varies most, then the direction perpendicular to it with the next most variance, and so on. Projecting each point onto the first two directions gives two coordinates that keep as much of the spread as any two coordinates could. The directions are the principal components; the coordinates are the scores.
Computing it: center the data (subtract each feature's mean, and usually scale by its standard deviation), form the covariance matrix, and take its eigenvectors; the eigenvalues are the variance along each component. In practice you call a library and read the explained-variance ratio to decide how many components to keep. Two for a plot; enough to retain 95% of the variance when compressing features for a downstream model.
from sklearn.decomposition import PCA
pca = PCA(n_components=2).fit(X_scaled)
Z = pca.transform(X_scaled) # (m, 2)
print(pca.explained_variance_ratio_) # e.g. [0.62, 0.21]
X_approx = pca.inverse_transform(Z) # reconstruction from 2 components
PCA is linear: it can only find flat directions. For data that lies on a curved surface, methods like t-SNE and UMAP make better pictures but do not give reconstructions. Keep the idea of a low-rank approximation in mind: a matrix of weight changes in a large model also tends to be well described by a few directions, which is why LoRA works in Course 4.
Deep dive · PCA from maximizing variance
Derivation
Center the data so every feature has mean zero, and let Σ = (1/m) Xᵀ X be the n × n covariance matrix. Project each point onto a unit vector u: its score is z(i) = uᵀ x(i). The scores have mean zero and variance
Var(z) = (1/m) Σi (uᵀ x(i))² = uᵀ ( (1/m) Σi x(i) x(i)ᵀ ) u = uᵀ Σ u
Maximize uᵀΣu subject to uᵀu = 1 (without the constraint you could scale u forever). The Lagrangian is L = uᵀΣu − λ(uᵀu − 1). Its gradient with respect to u is 2Σu − 2λu; setting it to zero gives Σu = λu. So u must be an eigenvector of Σ. Multiplying both sides by uᵀ gives uᵀΣu = λ uᵀu = λ: the projected variance equals the eigenvalue. The best direction is the eigenvector with the largest eigenvalue. The second component maximizes the same quantity with the extra constraint u2ᵀu1 = 0, which gives the eigenvector with the second-largest eigenvalue, and so on. Because Σ is symmetric, its eigenvectors are orthogonal and its eigenvalues are real and non-negative.
The same components minimize reconstruction error. A point splits into its projection and a perpendicular residual; by Pythagoras ‖x‖² = ‖projection‖² + ‖residual‖². The left side is fixed, so maximizing projected variance is the same as minimizing mean squared residual, which equals the sum of the discarded eigenvalues.
Worked example by hand
Four centered points: (2, 1), (1, 2), (−2, −1), (−1, −2). Then Σxx = (4+1+4+1)/4 = 2.5, Σyy = 2.5, Σxy = (2+2+2+2)/4 = 2, so Σ = [[2.5, 2], [2, 2.5]]. The characteristic equation (2.5 − λ)² − 4 = 0 gives λ = 4.5 and λ = 0.5, with eigenvectors (1, 1)/√2 and (1, −1)/√2. The first component explains 4.5/5 = 90% of the variance.
Scores on PC1: (2 + 1)/√2 = 2.1213 for the first two points and −2.1213 for the others; their variance is 2.1213² = 4.5, the eigenvalue. Reconstructing from one component gives z · u = (1.5, 1.5) for the first point, residual (0.5, −0.5), squared length 0.5. The mean squared residual over the four points is 0.5, the discarded eigenvalue.
The SVD connection
Write the centered data matrix as X = U S Vᵀ. Then XᵀX = V S Uᵀ U S Vᵀ = V S² Vᵀ, so the columns of V are the eigenvectors of Σ and the eigenvalues are S²/m (or S²/(m−1) for the sample covariance, which is what scikit-learn reports). For the four points the singular values are 4.2426 and 1.4142, and 4.2426²/4 = 4.5, 1.4142²/4 = 0.5. The SVD never forms XᵀX, which squares the condition number, so it is the numerically preferred route. The scores are X V = U S.
Common mistakes
Forgetting to center. The first "component" then points at the mean. Symptom: PC1 explains nearly all variance and looks like the average row.
Not scaling mixed units. A feature in dollars beats one in percentages purely by magnitude. Standardize unless the units are shared.
Reading signs. u and −u are equally valid; two libraries can disagree in sign. Compare |u₁ · u₂|.
Fitting PCA on train and test together. That leaks test information into features. Fit on train, apply transform to test.
Check yourself
Add a fifth point (0, 0) to the example. What happens to the explained-variance ratio?
Answer
Σ becomes (4/5) · [[2.5, 2], [2, 2.5]]; both eigenvalues scale by 0.8 to 3.6 and 0.4, and the ratio stays 90%. The directions do not change.
Lecture 2.15 · 11 min read
PCA in code (optional)
With scikit-learn: optionally scale the features, fit PCA, look at explained_variance_ratio_ to see how much variation each component captures, and transform the data. inverse_transform maps the reduced coordinates back to an approximation of the original features.
import numpy as np
from sklearn.decomposition import PCA
X = np.array([[1, 1], [2, 1], [3, 2], [-1, -1], [-2, -1], [-3, -2]], dtype=float)
pca = PCA(n_components=1).fit(X)
print("explained variance ratio:", pca.explained_variance_ratio_.round(3))
z = pca.transform(X)
print("1-D coordinates:", z.ravel().round(2))
print("reconstruction:\n", pca.inverse_transform(z).round(2))
Optional lab · about 20 min · runs in this page
PCA and data visualization
Use PCA to reduce the 64-pixel digits to two numbers per image and plot them.
Step 1Fit PCA
import numpy as np, matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
digits = load_digits()
pca = PCA(n_components=10).fit(digits.data)
print("explained variance, first 10 components:", pca.explained_variance_ratio_.round(3))
print("first two together:", round(pca.explained_variance_ratio_[:2].sum(), 3))
Learn from rewards instead of labels: returns, policies, the Bellman equation, and deep Q-networks that land a lunar module.
Video lectures · Week 3
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
RL Course, Lecture 1: Introduction to Reinforcement LearningDavid Silver · Google DeepMind · YouTube ↗Q-Learning: Model-Free RL and Temporal Difference LearningSteve Brunton · YouTube ↗
Module 1
Reinforcement learning introduction
Lecture 3.1 · 8 min read
States, actions, rewards, return
A robot learning to walk has no dataset of correct motor commands. What it has is a reward: a little for each step forward, a lot of negative for falling. Reinforcement learning is the problem of choosing actions to collect as much reward as possible over time, learning from the consequences of your own choices.
The formalism is a Markov decision process. At each time step the agent observes a state s, chooses an action a, receives a reward R(s), and moves to a new state s′ according to the environment's dynamics, which may be random. A policy π is the rule for choosing actions: π(s) = a. The agent's goal is not the next reward but the return, the sum of all future rewards, with later rewards discounted by a factor γ per step.
return = R₁ + γR₂ + γ²R₃ + γ³R₄ + …γ between 0 and 1, typically 0.9–0.99. A reward n steps away is worth γn−1 as much as one now; γ < 1 makes the agent prefer sooner rewards and keeps the sum finite.
Reward design is where most of the engineering lives. A grid world might pay +10 at the goal, −10 in a trap, and −0.1 per step so that dawdling costs something. A lunar lander pays for soft landings and penalizes fuel use and crashes. The agent will optimize exactly the reward you wrote, including any loophole in it, which is the same lesson as the recommender objective in Week 2.
Deep dive · Discounting, horizons and reward design
Derivation
The return from time t is Gt = Rt+1 + γRt+2 + γ²Rt+3 + … Factor out γ from everything after the first term:
Gt = Rt+1 + γ (Rt+2 + γRt+3 + …) = Rt+1 + γ Gt+1the recursion that becomes the Bellman equation in the next lecture
If every reward satisfies |R| ≤ Rmax, the geometric series bounds the return: |G| ≤ Rmax(1 + γ + γ² + …) = Rmax/(1 − γ). With γ = 0.9 and Rmax = 10 no return can exceed 100, even for an episode that never ends. That finiteness is the mathematical reason for γ < 1 in continuing tasks.
A useful rule of thumb is the effective horizon 1/(1 − γ): about 2 steps for γ = 0.5, 10 for γ = 0.9, 100 for γ = 0.99. Rewards much farther away than that barely affect decisions.
Worked example by hand
A reward of 100 arriving three steps from now (on the fourth reward) is worth 100γ³:
γ
100 · γ³
horizon 1/(1 − γ)
0.5
12.5
2
0.9
72.9
10
0.99
97.03
100
Grid world from the lecture: −0.1 per step and +10 at the goal, γ = 0.9. A path of seven steps followed by the goal on the eighth reward returns
A detour that takes eleven steps before the goal returns 2.4519. Notice that the step penalty contributes little; most of the preference for the short path comes from discounting the goal. The step penalty matters more when γ is close to 1.
Reward design
The agent maximizes the reward you wrote, not the one you meant. Classic failures: a boat-racing agent that circles forever collecting respawning bonus targets instead of finishing; a cleaning robot rewarded for "no visible mess" could learn to cover its camera. Two principles help. Reward outcomes, not methods you guess are useful, because the agent will satisfy the method without the outcome. And if you add shaping rewards to speed up learning, make them a difference of a potential function, F = γΦ(s′) − Φ(s); Ng, Harada and Russell showed that this form leaves the optimal policy unchanged, while arbitrary bonuses can change it.
Common mistakes
Mixing reward conventions. The lecture writes R(s), a reward for being in a state; many libraries give R(s, a, s′) for the transition. The algorithms are the same, but hand-computed numbers shift by one step. Pick one and stay with it.
γ = 1 in a task that can loop forever. Returns diverge or become meaningless. Use γ < 1 or a step limit.
Huge reward scales. Rewards of ±10,000 make value targets enormous and network training unstable. Scale or clip rewards.
Positive living reward. +0.1 per step makes the agent avoid the goal, since ending the episode stops the income.
Check yourself
With γ = 0.9 and a reward of +1 on every step forever, what is the return?
Answer
1/(1 − 0.9) = 10, the bound Rmax/(1 − γ) reached with equality.
Lecture 3.2 · 6 min read
Mars rover example
A simplified Mars rover lives in six states in a row. State 1 holds an interesting rock worth a reward of 100; state 6 holds a less interesting one worth 40; states 2–5 give 0. The rover starts in state 4 and can move left or right. States 1 and 6 are terminal: the day ends when it reaches one.
Every step produces a tuple (s, a, R(s), s′): current state, action, reward in the current state, next state. Going left from state 4 visits 4, 3, 2, 1 with rewards 0, 0, 0, 100. Going right visits 4, 5, 6 with rewards 0, 0, 40. Which is better depends on how much the rover values getting a reward sooner.
Lecture 3.3 · 10 min read
The return in reinforcement learning
The return adds up the rewards of a sequence, discounting later rewards by powers of γ, the discount factor, a number a little below 1. With γ = 0.5 for illustration:
def ret(rewards, gamma=0.5):
return sum(r * gamma ** k for k, r in enumerate(rewards))
rewards = [100, 0, 0, 0, 0, 40]
for s in range(2, 6): # states 1 and 6 are terminal
left = rewards[s - 1::-1]
right = rewards[s - 1:]
print(f"state {s}: return going left {ret(left):6.2f} going right {ret(right):6.2f}")
Discounting makes the agent impatient, which is often what we want: a reward now is worth more than the same reward later. In financial applications γ even has a natural interpretation as an interest rate. Negative rewards are pushed into the future by the same logic.
Lecture 3.4 · 3 min read
Making decisions: policies
A policy π is a function that maps any state s to an action a = π(s). For the Mars rover, one policy is "go left in states 2, 3 and 4, go right in state 5". The goal of reinforcement learning is to find the policy that maximizes the return from every state.
Lecture 3.5 · 5 min read
Review of key concepts
Concept
Mars rover
Helicopter
Chess
States
6 positions
position, orientation, speed
piece positions
Actions
left, right
control stick moves
legal moves
Rewards
100, 0, 40
+1 flying well, −1000 crash
+1 win, 0 draw, −1 loss
Discount γ
0.5
0.99
0.995
Return
R₁ + γR₂ + …
same
same
Policy π
state → move
state → controls
board → move
This formalism is a Markov decision process (MDP): the future depends only on the current state and action, not on how the agent got there.
Module 2
Practice quiz: Reinforcement learning introduction
Practice quiz · 5 questions
Reinforcement learning introduction
Module 3
State-action value function
Lecture 3.6 · 9 min read
The Q-function and the Bellman equation
Define Q(s, a) as the best return you can get if you are in state s, take action a now, and behave optimally afterwards. If you knew Q, acting optimally would be trivial: in every state, pick the action with the largest Q. The whole problem reduces to estimating one function.
The Bellman equation says what Q must satisfy. The return from taking a in s is the immediate reward plus the discounted best return from wherever you land:
Q(s, a) = R(s) + γ · maxa′ Q(s′, a′)s′ is the state reached by taking a in s. With random dynamics, replace the right side by its expected value over s′. At a terminal state, Q = R(s).
A worked example on a one-dimensional world: six cells in a row, rewards of 100 at the left end and 40 at the right end, zero elsewhere, γ = 0.5, deterministic moves. From cell 2 (adjacent to the 100), moving left gives 0 + 0.5·100 = 50; moving right leads to cell 3, from where the best is to return left: 0 + 0.5·(0 + 0.5·50) = 12.5. So Q(2, left) = 50 and Q(2, right) = 12.5. Working outward from the terminal cells fills in every Q value; with γ = 0.5 the agent heads for the 100 from any cell except the one next to the 40.
When the environment is random, say a move goes the intended way 90% of the time, Q is defined through expected returns and the optimal policy becomes more cautious near traps. The equation is the same with an expectation over s′, and the learning algorithm in the next lecture handles the randomness by averaging over experience.
Deep dive · Solving the line world exactly
Derivation
Start from the return recursion Gt = Rt+1 + γGt+1. Q(s, a) is the return when you take a in s and then act optimally. Acting optimally from s′ means choosing the action with the largest Q there, so the return from s′ onward is maxa′ Q(s′, a′). Substituting gives the Bellman optimality equation. With random dynamics the next state is uncertain, so you average over it:
Q(s, a) = R(s) + γ · Σs′ P(s′ | s, a) · maxa′ Q(s′, a′)
Value iteration turns the equation into an algorithm: start with Q = 0, compute the right-hand side for every (s, a) using the current table, replace the table, repeat. Each sweep shrinks the largest error by at least a factor γ (the Bellman operator is a γ-contraction in the max norm), so the table converges to the unique solution from any start.
Worked example by hand: γ = 0.5
Cells 1 to 6, R = 100, 0, 0, 0, 0, 40, cells 1 and 6 terminal (Q = R). The best value V(s) = maxa Q(s, a) after each sweep:
Sweep
1
2
3
4
5
6
1
100
0
0
0
0
40
2
100
50
0
0
20
40
3
100
50
25
10
20
40
4
100
50
25
12.5
20
40
Sweep 5 changes nothing. Information travels one cell per sweep from each end. Cell 4 first sees the 40 (via cell 5: 0.5 · 20 = 10), then one sweep later the 100 (via cell 3: 0.5 · 25 = 12.5), and switches direction. The final table:
Cell
2
3
4
5
Q(s, left)
50
25
12.5
6.25
Q(s, right)
12.5
6.25
10
20
best
left
left
left
right
This confirms the lecture: Q(2, left) = 0 + 0.5 · 100 = 50 and Q(2, right) = 0 + 0.5 · V(3) = 0.5 · 25 = 12.5, and only cell 5, next to the 40, goes right.
Changing γ and adding noise
With γ = 0.9 the Q(s, left) values become 90, 81, 72.9, 65.61 for cells 2 to 5, and Q(5, right) = 0.9 · 40 = 36 < 65.61, so every cell heads for the 100. A patient agent walks farther for the bigger reward.
Now make moves slip: with probability 0.1 the agent goes the opposite way (γ = 0.5). Then Q(2, left) = 0.5 · (0.9 · 100 + 0.1 · V(3)). Iterating to convergence gives Q(2, left) = 46.06, Q(2, right) = 14.56, Q(4, left) = 10.49, Q(4, right) = 9.40, Q(5, right) = 18.52. Every value of the best action drops because some steps are wasted, and cell 4's margin for going left narrows from 2.5 to 1.09.
Common mistakes
Updating terminal states with the recursion. A terminal has no next state; Q = R there. Bootstrapping past it double-counts the reward.
Using max over s′ instead of the expectation. With random dynamics, average over where you might land, then maximize over your own next action. Swapping them gives an optimistic, wrong Q.
In-place versus synchronous sweeps. Updating cells in place (Gauss-Seidel) converges too, often faster, but intermediate numbers differ from the table above. Neither is wrong; just do not compare one against the other step by step.
Stopping on "policy looks right". The greedy policy can settle before values do. Stop on the max change in Q.
Check yourself
At what γ is cell 4 indifferent between left and right in the deterministic world?
Answer
Going left, cell 1 is reached after three moves, so Q(4, left) = γ³ · 100. Going right, cell 6 is reached after two moves, so Q(4, right) = γ² · 40 (cell 5 goes right for any γ below 0.74, where 100γ³ < 40, so near γ = 0.4 it reaches cell 6 in one move). Setting 100γ³ = 40γ² gives γ = 0.4. Check at γ = 0.5: 12.5 against 10, left wins, as in the table.
Lecture 3.7 · 5 min read
State-action value function example
Q(s, a) is the return if you start in state s, take action a once, and then behave optimally. For the Mars rover with γ = 0.5, the values come out as follows, and the best action in each state is the one with the larger Q.
import numpy as np
R = np.array([100, 0, 0, 0, 0, 40.0]); gamma = 0.5
Q = np.zeros((6, 2)) # columns: left, right
for _ in range(50):
V = Q.max(1)
for s in range(6):
if s in (0, 5):
Q[s] = R[s]; continue
Q[s, 0] = R[s] + gamma * V[s - 1]
Q[s, 1] = R[s] + gamma * V[s + 1]
for s in range(6):
print(f"state {s+1}: Q(left) = {Q[s,0]:6.2f} Q(right) = {Q[s,1]:6.2f} best: {['left','right'][int(Q[s].argmax())] if 0 < s < 5 else 'terminal'}")
Change γ or the rewards and the policy changes: with γ = 0.9 the rover is more patient, and with a terminal reward of 40 replaced by 10 it almost always heads for the big rock.
Optional lab · about 15 min · runs in this page
State-action value function
Compute Q(s, a) for the Mars rover and see how the discount factor, the rewards and missteps change the optimal policy.
Step 1A Q-value solver
import numpy as np
def mars_q(left_reward=100, right_reward=40, gamma=0.5, misstep=0.0, n=6):
R = np.zeros(n); R[0], R[-1] = left_reward, right_reward
Q = np.zeros((n, 2))
for _ in range(500):
V = Q.max(1)
for s in range(1, n - 1):
Q[s, 0] = R[s] + gamma * ((1 - misstep) * V[s - 1] + misstep * V[s + 1])
Q[s, 1] = R[s] + gamma * ((1 - misstep) * V[s + 1] + misstep * V[s - 1])
Q[0], Q[-1] = R[0], R[-1]
return Q
def show(**kw):
Q = mars_q(**kw)
pol = ["T"] + ["<" if q[0] >= q[1] else ">" for q in Q[1:-1]] + ["T"]
print(kw, " policy:", " ".join(pol))
show()
The Bellman equation breaks the return into two parts: the reward you get right away, and the discounted best return from the next state.
Q(s, a) = R(s) + γ · maxa′ Q(s′, a′)s′ is the state you reach by taking a in s. At a terminal state, Q(s, a) = R(s).
Check it on the rover with γ = 0.5: Q(4, left) = R(4) + 0.5 · max Q(3, ·) = 0 + 0.5 · 25 = 12.5, matching the direct calculation 0 + 0.5·0 + 0.25·0 + 0.125·100. The intuition: the total return equals the first reward plus γ times the return of the rest of the sequence, and behaving optimally from s′ means taking the best action there.
Lecture 3.9 · 8 min read
Random (stochastic) environment (optional)
Real robots slip. Suppose that when the rover is told to go left it actually goes left with probability 0.9 and right with probability 0.1 (a "misstep"). Then a policy no longer produces one sequence of rewards but a random one, and the goal becomes maximizing the expected return, the average over many runs.
Q(s, a) = R(s) + γ · E[ maxa′ Q(s′, a′) ]The expectation averages over the possible next states.
import numpy as np
R = np.array([100, 0, 0, 0, 0, 40.0]); gamma = 0.5
def solve(misstep):
Q = np.zeros((6, 2))
for _ in range(200):
V = Q.max(1)
for s in range(1, 5):
Q[s, 0] = R[s] + gamma * ((1 - misstep) * V[s - 1] + misstep * V[s + 1])
Q[s, 1] = R[s] + gamma * ((1 - misstep) * V[s + 1] + misstep * V[s - 1])
Q[0], Q[5] = R[0], R[5]
return Q
for m in (0.0, 0.1, 0.4):
print(f"misstep {m}: Q in state 4 (left, right) =", solve(m)[3].round(2))
Lecture 3.10 · 10 min read · demo
Q-learning
Nobody hands the agent the dynamics, so it cannot solve the Bellman equation directly. Q-learning turns the equation into an update rule. Keep a table Q[s, a], initially zero. Act in the environment; after each transition (s, a, R, s′), nudge the stored Q(s, a) toward the Bellman target R + γ maxa′ Q(s′, a′) by a learning rate α. Over many transitions the table converges to the true Q, even though each target used the table's own current, wrong estimates. This is bootstrapping, and it is why temporal-difference methods learn before an episode is over.
Q(s, a) ← Q(s, a) + α · [ R + γ · maxa′ Q(s′, a′) − Q(s, a) ]
Which action to take while learning? Always picking the current best (greedy) means never discovering that an unexplored action is better. ε-greedy takes a random action with probability ε and the greedy one otherwise; start ε high and decay it as the table improves. Train the grid below and watch the arrows: the policy near the goal firms up first, and the values propagate backward from it one cell per episode or so.
Q-learning on a grid5 × 5 · goal +10 · trap −10 · −0.1 per step
episodes 0mean return, last 20 –greedy path –
Set ε to 0 and reset: the agent repeats the first path that happened to reach the goal and never improves it. Set γ to 0.5: cells far from the goal have nearly identical values and the arrows there stay uncertain. Both knobs come back as β and KL penalties in Course 4, where the policy is a language model.
Deep dive · Why Q-learning converges, and exploration
Derivation
Q-learning is a stochastic approximation of value iteration. Value iteration needs the expectation Σs′ P(s′|s, a)[R + γ max Q(s′, ·)], which requires the dynamics. One observed transition gives a single sample of that quantity, the target y = R + γ maxa′ Q(s′, a′). The update Q ← Q + α(y − Q) = (1 − α)Q + αy is a running average of samples. With αn = 1/n on the n-th visit it is exactly the sample mean of the targets seen so far.
Watkins and Dayan proved convergence to the optimal Q with probability 1 under two conditions:
Every state-action pair is visited infinitely often.
The step sizes for each pair satisfy Σn αn = ∞ and Σn αn² < ∞ (the Robbins-Monro conditions). The first lets the updates travel any distance; the second makes the noise die out.
αn = 1/n satisfies both. A constant α violates the second: the table keeps fluctuating around Q* with variance proportional to α, which is often what you want when the environment can change. Q-learning is off-policy: the target uses max regardless of which action the agent will actually take, so it learns the optimal Q while behaving exploratorily.
Worked example by hand
On the lab's 4 × 4 grid, α = 0.5, γ = 0.9, table all zeros. In the first episode, the agent wanders and eventually steps down from (2, 3) into the goal:
Q((2,3), down) ← 0 + 0.5 · (10 − 0) = 5terminal target is just R = 10
Every earlier transition in that episode had target 0 + 0.9 · 0 = 0 and changed nothing. In the second episode, suppose the agent reaches (1, 3), steps down to (2, 3), then down to the goal:
Value has moved one cell further back. Repeated, Q((2,3), down) approaches 10 and Q((1,3), down) approaches 9, the optimal values.
ε-greedy, exactly
With probability ε choose uniformly among all |A| actions (including the greedy one), otherwise choose greedily. The greedy action's total probability is 1 − ε + ε/|A|. For ε = 0.2 and four actions: 0.85 for the greedy action and 0.05 for each other. To satisfy "visited infinitely often" while ending up greedy, decay ε toward zero slowly (GLIE: greedy in the limit with infinite exploration), for example εt = 1/t. A practical schedule multiplies ε by 0.995 per episode; going from 1.0 to 0.05 takes ln 0.05 / ln 0.995 = 598 episodes.
Common mistakes
Bootstrapping from a terminal state. Use y = R when the episode ended. Using R + γ max Q(s′) adds value from a state that has no future. Symptom: values near the goal exceed the goal reward.
Ending the episode at a time limit and treating it as terminal. Hitting a 100-step cap is not a real terminal; the state still had a future. Bootstrap there.
Ties in argmax.np.argmax returns the first maximum, so an all-zero table always picks action 0. Break ties at random or the agent may never try the other actions.
ε = 0 from the start. As the lecture's demo shows, the agent repeats its first lucky path forever.
Check yourself
In the second episode above, why did Q((1,3), down) get 2.25 and not 0.5 · 0.9 · 10 = 4.5?
Answer
The target uses the current estimate max Q((2,3), ·) = 5, not the true value 10. Bootstrapping uses the table's own, still-wrong values; the error shrinks over repeated visits.
Module 4
Quiz: State-action value function
Practice quiz · 5 questions
State-action value function
Module 5
Continuous state spaces
Lecture 3.11 · 6 min read
Example of continuous state space applications
The rover had six discrete states. Most real problems have continuous states. A self-driving car or truck is described by its position x, y, its orientation θ, and their rates of change ẋ, ẏ, θ̇: six real numbers. An autonomous helicopter needs x, y, z, roll, pitch, yaw and their six rates: twelve numbers.
With continuous states, a table of Q-values is impossible: there are infinitely many states. Instead, we learn a function that approximates Q(s, a), and a neural network is the natural choice.
Lecture 3.12 · 5 min read
Lunar lander
The lunar lander is a classic benchmark. The goal is to land a craft safely on a landing pad between two flags. Four actions: do nothing, fire the left thruster, fire the main engine, fire the right thruster. The state has eight numbers: position x, y, velocities ẋ, ẏ, angle θ and angular velocity θ̇, and two flags l, r for whether each leg touches the ground.
Event
Reward
getting to the landing pad
100 to 140
moving toward or away from the pad
positive or negative
crash
−100
soft landing
+100
each leg touching the ground
+10
firing the main engine
−0.3 per frame
firing a side thruster
−0.03 per frame
The task is to learn a policy that maximizes the return, with a discount factor close to 1, such as γ = 0.985.
Lecture 3.13 · 16 min read
Learning the state-value function
Train a neural network to approximate Q(s, a). The trick is to create training data from the Bellman equation itself. Let the lander act, using random actions at first, and store tuples (s, a, R(s), s′) in a replay buffer holding, say, the 10,000 most recent.
For each stored tuple, the input is (s, a) and the target is y = R(s) + γ · maxa′ Q(s′, a′), computed with the current network.
Train the network to predict y from (s, a) by minimizing squared error, exactly like regression.
Set Q to the newly trained network, keep acting and collecting tuples, and repeat.
This is the deep Q-network (DQN) algorithm. At first the targets are based on a random network and are poor, but each round of training makes Q slightly better, which makes the targets better, and the process improves the policy over many iterations.
import numpy as np
from collections import deque
buffer = deque(maxlen=10_000)
rng = np.random.default_rng(0)
for t in range(12_000): # fake transitions just to show the bookkeeping
s = rng.normal(size=8); a = int(rng.integers(4)); r = float(rng.normal()); s2 = rng.normal(size=8)
buffer.append((s, a, r, s2))
batch = [buffer[i] for i in rng.choice(len(buffer), 64, replace=False)]
print("buffer size:", len(buffer), " (oldest examples dropped)")
print("one mini-batch of", len(batch), "transitions; state shape", batch[0][0].shape)
The first version of the DQN takes the state and a one-hot encoding of the action, 8 + 4 = 12 inputs, and outputs a single Q value. Choosing an action then needs four forward passes, one per action. A better architecture takes only the 8 state numbers and has four output units, one Q value per action. One forward pass gives all of them, and computing maxa′ Q(s′, a′) for the Bellman target is equally cheap.
import torch, torch.nn as nn
torch.manual_seed(0)
q_net = nn.Sequential(nn.Linear(8, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 4))
s = torch.randn(1, 8)
q = q_net(s)
print("Q(s, a) for the 4 actions:", q.detach().numpy().round(3), " best action:", int(q.argmax()))
Lecture 3.15 · 8 min read
Algorithm refinement: ε-greedy policy
While learning, which actions should the lander take? Always picking the action with the highest current Q estimate would never try actions that the poorly trained network wrongly believes are bad. The fix is the ε-greedy policy:
With probability 1 − ε, take the greedy action, the one maximizing Q(s, a) (exploitation).
With probability ε, take a random action (exploration).
A common schedule starts with ε = 1, completely random, and gradually decreases it to around 0.01, so the agent explores a lot early and exploits what it has learned later. Reinforcement learning is more sensitive to choices like this than supervised learning is.
import numpy as np
rng = np.random.default_rng(0)
def eps_greedy(q_values, eps):
return int(rng.integers(len(q_values))) if rng.random() < eps else int(np.argmax(q_values))
q = np.array([1.0, 3.0, 2.0, 0.5])
for eps in (1.0, 0.1, 0.01):
picks = [eps_greedy(q, eps) for _ in range(2000)]
print(f"eps {eps:<5} share of greedy action: {np.mean(np.array(picks) == 1):.2f}")
eps_schedule = [max(0.01, 0.995 ** episode) for episode in (0, 100, 500, 1000)]
print("decaying epsilon:", np.round(eps_schedule, 3))
Lecture 3.16 · 11 min read
Algorithm refinement: mini-batch and soft updates (optional)
Two refinements make DQN faster and more stable. Mini-batches: instead of training on all 10,000 stored tuples in every step, train on a random subset of, say, 1,000. Each update is noisier but far cheaper, the same idea as mini-batch gradient descent for supervised learning.
Soft updates: setting Q to the newly trained network all at once can make learning oscillate, since one bad update can make the targets much worse. Instead keep a separate target network and move it a small step toward the new network:
Wtarget ← τ Wnew + (1 − τ) WtargetWith τ = 0.01 the target network changes gradually, which makes the regression targets much more stable.
import numpy as np
w_target, tau = np.zeros(3), 0.01
w_new = np.array([1.0, -2.0, 0.5])
for step in range(1, 301):
w_target = tau * w_new + (1 - tau) * w_target
if step in (1, 10, 100, 300):
print(f"after {step:3d} soft updates: {w_target.round(3)}")
Lecture 3.17 · 9 min read
Deep Q-networks
A table works for 25 cells. A lunar lander's state is eight continuous numbers (position, velocity, angle, leg contacts); there is no table. Replace it with a neural network that takes the state and outputs one Q value per action. Training it is supervised learning on targets the agent manufactures: for each stored transition the input is s and the target for action a is R + γ maxa′ Q(s′, a′), computed with the network itself.
net = nn.Sequential(nn.Linear(8, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 4))
target_net = copy.deepcopy(net) # frozen copy, refreshed every C steps
s, a, r, s2, done = replay.sample(64) # random minibatch of stored transitions
q = net(s).gather(1, a[:, None]).squeeze(1)
with torch.no_grad():
y = r + gamma * target_net(s2).max(1).values * (1 - done)
loss = ((q - y) ** 2).mean()
Three stabilizers make this work. A replay buffer stores the last few hundred thousand transitions and trains on random minibatches from it, which breaks the correlation between consecutive experiences and reuses each one many times. A target network, a frozen copy refreshed every few thousand steps, keeps the targets from moving with every update. And soft updates, blending the target toward the live network slowly, smooth it further. With those, a few hundred thousand frames of play solve the lander.
From here the field branches: policy-gradient methods learn the policy directly instead of Q, actor-critic methods learn both, and PPO is the actor-critic variant that trained the first instruction-following language models. Course 4 picks the thread up there.
Deep dive · Instability, target networks and Double DQN
Intuition: why naive DQN diverges
Three ingredients together can make value learning diverge, which Sutton and Barto call the deadly triad: function approximation (a network generalizes, so updating one state changes others), bootstrapping (the target contains the network's own prediction), and off-policy data (the replay buffer holds transitions from older policies). In a table, updating Q(s, a) changes only that cell. In a network, the gradient step that raises Q(s, a) also raises Q(s′, ·) for similar states, which raises the target for s, which pushes Q(s, a) up again. That loop can grow without bound.
Derivation: what the target network changes
With a live target the loss is L(θ) = (Qθ(s, a) − [r + γ maxa′ Qθ(s′, a′)])². DQN treats the bracket as a constant (torch.no_grad) but it still moves after every step. With a target network θ⁻ held fixed for C steps,
L(θ) = ( Qθ(s, a) − [ r + γ (1 − done) maxa′ Qθ⁻(s′, a′) ] )²
For those C steps this is ordinary supervised regression on fixed labels, which gradient descent handles well. Every C steps the labels jump to the new network's opinion, much like one sweep of value iteration. Soft updates replace the jump by θ⁻ ← τθ + (1 − τ)θ⁻ every step. The old target's weight decays as (1 − τ)n; with τ = 0.005 it halves after ln 0.5 / ln 0.995 = 138 steps, with τ = 0.001 after 693.
Overestimation bias, with numbers
The max in the target is applied to noisy estimates. Even if every action's estimate is unbiased, E[maxa Q̂(a)] ≥ maxa E[Q̂(a)]. Example: ten actions whose true values are all 0, each estimated with independent N(0, 1) noise. The expected maximum of ten standard normals is 1.5388, so the target is inflated by about 1.54 although every action is worth 0. With two actions it is 1/√π = 0.5642. The bias grows with the number of actions and the noise, and bootstrapping propagates it backward through states.
Double DQN
The bias comes from using the same noisy numbers to choose the best action and to value it. Double Q-learning decouples them: one estimator selects, an independent one evaluates. Double DQN uses the networks DQN already has:
y = r + γ (1 − done) · Qθ⁻( s′, argmaxa′ Qθ(s′, a′) )online net picks the action, target net scores it
with torch.no_grad():
a2 = net(s2).argmax(1, keepdim=True) # select with the online network
y = r + gamma * target_net(s2).gather(1, a2).squeeze(1) * (1 - done) # evaluate with the target network
If the online network's noise makes a bad action look best, the target network's independent noise is unlikely to agree, so the inflated value is not used. It is one changed line and on Atari reduced overestimation substantially and improved scores in most games.
Common mistakes
Forgetting (1 − done). The agent bootstraps from the state after a crash. Symptom: Q values far above any achievable return.
Gradients through the target. Without no_grad or detach, the loss also moves the target, and learning becomes erratic.
Replay buffer too small. A buffer of a few thousand transitions is nearly on-policy and correlated, so the main stabilizer is lost. Typical sizes are 10⁵ to 10⁶.
Unclipped rewards or huge losses. One −1,000 reward produces a giant gradient. Clip rewards or use the Huber loss (smooth_l1_loss).
Evaluating with ε still at 0.1. Report the greedy policy's return separately from training returns.
Check yourself
If the target network were refreshed every step (C = 1), what would it be equivalent to?
Answer
To no target network at all: the target is computed with the current weights, which is the naive moving-target setup the target network was introduced to avoid.
Lecture 3.18 · 3 min read
The state of reinforcement learning
Reinforcement learning is exciting, and there is a lot of hype. Some perspective: many research results are in simulated environments, and getting RL to work on real robots is much harder. There are far fewer real-world applications of RL today than of supervised and unsupervised learning, so for most practical problems those are the tools to reach for first.
Still, the potential is large, and one recent success is close to this specialization: reinforcement learning from human feedback and from verifiable rewards is a key step in training modern language models, as Course 4 Week 3 shows.
N = 4 # 4×4 grid, states are (row, col), start (0,0), goal (3,3)
ACTIONS = [(-1,0), (1,0), (0,-1), (0,1)] # up, down, left, right
def step(s, a):
r, c = s[0] + ACTIONS[a][0], s[1] + ACTIONS[a][1]
r, c = min(max(r, 0), N-1), min(max(c, 0), N-1) # walls: bump and stay
done = (r, c) == (N-1, N-1)
return (r, c), (10.0 if done else 0.0), done
Step 2Q-learning
Create Q = np.zeros((N, N, 4)). Run 500 episodes with α = 0.5, γ = 0.9, ε = 0.2, each episode starting at (0, 0) and ending at the goal or after 100 steps. Apply the update from “Q-learning” after every transition. Track the length of each episode and plot it; it should fall toward 6.
Checkpoint 1
After training, the maximum Q value at the start state should approach the optimal return γ⁵ · 10. What is that value, to two decimals?
Step 3Read the table
Print the greedy policy as a 4×4 grid of arrows and the state values maxa Q(s, a) as a 4×4 matrix with two decimals. Explain in one sentence why the values form diagonal bands.
Step 4Project: make it stochastic
Change step so that with probability 0.2 the agent moves in a random direction instead of the chosen one, and add a trap at (1, 2) with reward −10 that ends the episode. Retrain. Compare the policies: where does the stochastic agent detour, and why? Finally, replace the table with a small network (state one-hot → 4 Q values) trained on Bellman targets with a replay buffer, and show it reaches the same policy.
Checkpoint 2
How many moves does the shortest path from (0, 0) to (3, 3) take?
Module 9
Summary and thank you
Lecture 3.19 · 3 min read
Summary and thank you
Across three courses you have built linear and logistic regression, neural networks, decision trees and ensembles, k-means, anomaly detection, collaborative and content-based recommenders, and reinforcement learning with deep Q-networks. You also learned the practical habits that make these work: diagnosing bias and variance, error analysis, and choosing what to try next.
Machine learning is a powerful tool, and with it comes responsibility: use it to build things that help people. The remaining courses go deeper into fine-tuning language models, convolutional networks for vision, and machine learning in production.
Final exam · 12 questions · pass mark 80%
Final exam
Questions from every week of the course. Pass it to complete the last requirement for the certificate on the Certificates page.
Final exam · 12 questions
Unsupervised Learning, Recommenders and Reinforcement Learning
Pass mark 80%. Passing this exam is one of the requirements for the course certificate. You can retake it as often as you like.
Course 4 of 6 · 5 weeks
Fine-Tuning Language Models
Transfer learning from Course 2, at the scale of a model with billions of parameters. You will build a dataset, train a low-rank adapter on a free GPU, align the result with preference data, prove it beats the base model, and serve it on a laptop.
23lectures with video
11quizzes incl. practice + final
5labs
Week 1 · 4 lectures · quiz · lab
From pretrained to adapted
What a language model is made of, what fine-tuning can and cannot change, and the dataset that decides the outcome.
Video lectures · Week 1
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
Intro to Large Language ModelsAndrej Karpathy · YouTube ↗Transformers, the tech behind LLMs3Blue1Brown · YouTube ↗Deep Dive into LLMs like ChatGPTAndrej Karpathy · YouTube ↗
Module 1
When to fine-tune
Lecture 1.1 · 9 min read
Prompt, retrieve, or fine-tune
A pretrained language model has read a large fraction of the public internet and learned to predict the next token. Post-training turned it into an assistant. Both stages cost millions of dollars; your job is to adapt the result to your task for a few dollars, and there are three ways to do it, in order of cost.
Prompting changes the input: instructions, examples, a format to follow. Retrieval-augmented generation (RAG) looks up documents relevant to the request and pastes them into the prompt, so the model answers from facts it never saw in training. Fine-tuning changes the weights, continuing training on examples of the behavior you want. Each is cheaper to iterate on than the next, so try them in that order, and keep the evaluation set you build for the first one; it serves all three.
Fine-tune for behavior: a fixed output format such as JSON or a tool-call schema, a consistent voice, a narrow task where a 1–3B model must match a frontier model at a tenth of the latency and cost, or anything that is easier to show in five hundred examples than to describe in a prompt.
Do not fine-tune for knowledge that changes. Prices, policies and schedules belong in retrieval; a fine-tuned model learns facts slowly and forgets them unpredictably.
The stages of post-training, which this course walks through: supervised fine-tuning on instruction–response pairs; preference optimization on pairs of better and worse responses; reinforcement learning with verifiable rewards for reasoning.
Deep dive · Pricing the three options on one workload
Decision table
Question
Prompt
RAG
Fine-tune
What changes
the input
the input, from a search index
the weights
Iteration time
seconds
hours (build the index)
hours to days (data, run, eval)
Facts that change weekly
only if pasted in
yes, re-index
no, retrain needed
Fixed format, voice, schema
fragile at scale
does not help
strongest
Cost per request
grows with prompt length
grows with retrieved context
short prompt, small model
Up-front cost
none
index and retriever
dataset, GPU hours, eval set
Worked example
Workload: extract order fields as JSON from 50,000 support emails a day. Each email is 300 tokens and each answer 150 tokens. The prices below are assumptions chosen to make the arithmetic concrete; substitute your provider's numbers.
Prompt with a frontier API at $3 per million input tokens and $15 per million output tokens. Instructions and five worked examples add 1,500 tokens, so each request sends 1,800 input tokens. Cost per request = 1,800 · 3·10⁻⁶ + 150 · 15·10⁻⁶ = $0.0054 + $0.00225 = $0.00765. Per day: $382.50. Per 30 days: $11,475.
RAG on top of that, with three retrieved chunks of 400 tokens: 3,000 input tokens, $0.01125 per request, $562.50 per day, $16,875 per 30 days.
Fine-tuned 1.5B model on one rented GPU at an assumed $1.20 per hour, running all day: $28.80 per day, $864 per 30 days. The load is 50,000 / 86,400 = 0.58 requests per second, which one GPU serves easily.
Break-even: the GPU costs a fixed $28.80 a day, the prompt option $0.00765 a request, so fine-tuning is cheaper above 28.80 / 0.00765 ≈ 3,765 requests a day, before counting the one-off cost of building the dataset.
Latency, with assumed speeds (API: prefill 5,000 tokens/s, decode 80 tokens/s; small self-hosted model: prefill 20,000 tokens/s, decode 150 tokens/s):
latency ≈ input tokens / prefill speed + output tokens / decode speedprompt: 1,800/5,000 + 150/80 = 2.24 s · RAG (+0.05 s search): 2.53 s · fine-tune: 330/20,000 + 150/150 = 1.02 s
The decode term dominates all three; shorter prompts help less than a faster model. The fine-tuned model's input is 300 tokens plus about 30 template tokens because the instructions now live in the weights.
Combining them
The options stack. A fine-tuned model can still receive retrieved documents: fine-tune for the output format and the habit of citing the retrieved text, retrieve for the facts. Teaching facts by fine-tuning is the one combination to avoid.
Common mistakes
Fine-tuning before measuring the prompt baseline. Symptom: no way to say whether the fine-tune helped. Fix: build the gold set first and score the best prompt on it.
Training prices or policies into the weights. Symptom: confident, outdated answers months later. Fix: retrieve anything that changes.
Comparing cost per request without volume. Below the break-even volume an idle GPU is the expensive option. Fix: compute fixed and per-request costs separately.
Ignoring the data cost. Five hundred reviewed examples can take more hours than the training run. Budget it.
Check yourself
At 2,000 requests a day, which option is cheaper in the example?
Answer
The prompt option: 2,000 · $0.00765 = $15.30 a day, against $28.80 for the dedicated GPU. The volume is below the 3,765-request break-even.
Module 2
Transformers and tokens
Lecture 1.2 · 10 min read
Inside a transformer: where the parameters live
Text is split into tokens, each mapped to an embedding vector of dimension d (896 for Qwen2.5-0.5B, 4096 for Llama-3.1-8B). A stack of identical layers, 24 to 32 of them, transforms the sequence of vectors. The final vectors go through one more linear map to produce a score for every token in the vocabulary, softmaxed into next-token probabilities, which is the Course 2 classifier with a hundred-thousand-way output.
Each layer has two parts. Attention lets every position read from earlier positions: three linear maps project each vector into a query, a key and a value; a position's output is a weighted sum of values where the weights come from how well its query matches each key. A fourth linear map combines the heads. Then a feed-forward block applies two or three wide linear maps with a nonlinearity between them, the Course 2 network applied to each position independently. Residual connections and normalization layers wrap both parts so that gradients flow through the stack.
The parameter count is dominated by seven linear maps per layer, with the names Hugging Face checkpoints use: q_proj, k_proj, v_proj, o_proj in attention and gate_proj, up_proj, down_proj in the feed-forward block. Those names are what you will pass to LoRA next week. Everything else, embeddings aside, is small.
attention(Q, K, V) = softmax( Q Kᵀ / √dk ) VPer head. Causal masking zeroes attention to later positions so the model cannot see the token it is predicting.
Deep dive · Counting parameters, FLOPs and KV-cache bytes
Derivation: parameters of one layer
Write d for the hidden size, dff for the intermediate size, h for the head dimension and nkv for the number of key/value heads, so the key/value width is kv = nkv·h. With grouped-query attention several query heads share one key/value head, so kv is smaller than d. A layer holds:
q_proj d×d, o_proj d×d, k_proj d×kv, v_proj d×kv
gate_proj d×dff, up_proj d×dff, down_proj dff×d (the SwiGLU block has three matrices, not two)
two RMSNorm weight vectors of length d, and in Qwen2.5 biases on q, k and v
params per layer = 2d² + 2d·kv + 3d·dff + 2d (+ d + 2kv biases)total = L · per layer + V·d (embedding) + d (final norm) [+ V·d if the output head is not tied]
Worked example: Qwen2.5-0.5B
d = 896, L = 24, dff = 4,864, 14 query heads and 2 KV heads of dimension 64, so kv = 128, vocabulary V = 151,936.
Piece
Arithmetic
Parameters
q_proj + bias
896·896 + 896
803,712
k_proj + bias
896·128 + 128
114,816
v_proj + bias
896·128 + 128
114,816
o_proj
896·896
802,816
gate, up, down
3 · 896·4,864
13,074,432
two norms
2 · 896
1,792
one layer
14,912,384
24 layers
24 · 14,912,384
357,897,216
embedding (tied with output head)
151,936 · 896
136,134,656
final norm
896
896
total
494,032,768 ≈ 0.49 B
That matches the published 0.49 B. The feed-forward block holds 88% of each layer, and the embedding holds 27.6% of the whole model; in small models with large vocabularies the embedding is not negligible. Untied, the model would have 630,167,424 parameters.
Attention FLOPs and the KV cache
For one new token at context length n, each linear map of shape a×b costs 2ab FLOPs (a multiply and an add per weight). Scores QKᵀ cost 2·n·dq per layer and the weighted sum of values another 2·n·dq, where dq = 14·64 = 896 is the total query width.
forward FLOPs per token ≈ 2·Nlayers + 2·V·d + 4·L·n·dqQwen2.5-0.5B at n = 1,024: 0.716 + 0.272 + 0.088 = 1.076 GFLOP; at n = 32,768 the attention term alone is 2.82 GFLOP
During generation the keys and values of earlier tokens are cached. Per token that is 2 (K and V) · L · kv · bytes per number.
Without grouped-query attention Llama-3.1-8B would cache kv = 4,096 per layer, four times as much, 512 KiB per token.
Common mistakes
Counting two feed-forward matrices. SwiGLU models have three; the count comes out a third too low.
Using d for k_proj and v_proj. With GQA they map to kv, not d. For Qwen2.5-0.5B that overstates each by 7×.
Thinking GQA cuts attention FLOPs. Every query head still attends over n keys; GQA cuts KV-cache memory and k/v projection cost, not the score computation.
Double-counting tied embeddings. Check tie_word_embeddings in config.json before adding V·d twice.
Check yourself
Llama-3.1-8B: d = 4,096, L = 32, dff = 14,336, kv = 1,024, V = 128,256, no biases, untied head. Does the formula give 8.03 B?
Answer
Per layer: 2·4,096² + 2·4,096·1,024 + 3·4,096·14,336 + 2·4,096 = 218,112,000. Times 32 = 6,979,584,000. Embedding and head: 2·128,256·4,096 = 1,050,673,152. Final norm 4,096. Total 8,030,261,248 ≈ 8.03 B.
Lecture 1.3 · 9 min read
Tokenizers, chat templates and the loss
Tokens are byte-pair-encoded chunks of text, roughly three-quarters of a word in English and far less in Vietnamese or in code. A model's tokenizer is part of the model; training data must be tokenized with the same one, and the vocabulary cannot be changed without retraining the embeddings.
An instruct model was trained with a wrapper around every conversation: special tokens that mark where the system prompt, each user turn and each assistant turn begin and end. That wrapper is the chat template, stored with the tokenizer. If your training examples use a different wrapper, the model spends its capacity learning a second format instead of your task. Always render examples through the template and read the result before training on it.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
msgs = [{"role": "system", "content": "You extract order fields as JSON."},
{"role": "user", "content": "Order #1832 shipped to Hanoi on 12 Oct."}]
text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
print(text) # the exact special tokens the model expects
print(len(tok(text).input_ids), "tokens")
The training loss is next-token cross-entropy, Course 2's softmax loss averaged over the tokens you choose to score. Perplexity is e raised to the loss: a loss of 2.0 means the model is, on average, as uncertain as a uniform choice among e² ≈ 7.4 tokens. There is no universal good value; JSON extraction can train to 0.3 while open-ended writing sits near 1.5. Read trends and task metrics, not absolute loss.
perplexity = exp(loss) loss 2.0 → 7.39 loss 1.0 → 2.72 loss 0.5 → 1.65
Deep dive · Cross-entropy, perplexity and the label mask
Derivation
At position t the model outputs a score vector z of length V. Softmax turns it into probabilities pj = ezj / Σk ezk. The loss for the true next token y is its negative log-probability:
The gradient follows by differentiating each term: ∂(−zy)/∂zj = −1[j = y] and ∂ log Σ ezk/∂zj = ezj/Σ ezk = pj. Example: z = (2.0, 1.0, 0.1), y = 0. Then p = (0.659, 0.242, 0.099), ℓ = 0.417 and the gradient is (−0.341, 0.242, 0.099).
The sequence loss averages over the scored positions S: L = (1/|S|) Σt∈S ℓt. Perplexity is eL, the geometric mean of 1/py. A model that knows nothing assigns 1/V to every token, so its loss is log V: for Qwen's V = 151,936 that is 11.93. A freshly initialised model should start near that value; a pretrained one on your data typically starts between 1 and 3.
Worked example: label masking
A rendered conversation, simplified to one token per word:
position
token
label
0–2
<|im_start|> user \n
−100 −100 −100
3–6
Where is #1832 ?
−100 −100 −100 −100
7–11
<|im_end|> \n <|im_start|> assistant \n
−100 ×5
12–14
It left Hanoi
It left Hanoi
15
<|im_end|>
<|im_end|>
Labels equal the input ids, with −100 wherever the loss must ignore the token; PyTorch's cross-entropy skips −100 by default (ignore_index=-100). The model shifts internally: logits at position t are scored against the label at t+1. Four tokens are scored. If the model gives them probabilities 0.5, 0.8, 0.9, 0.95, the losses are 0.6931, 0.2231, 0.1054, 0.0513, the mean is 0.2682 and the perplexity 1.31.
Without the mask, suppose the four question tokens get probabilities 0.02, 0.1, 0.05, 0.3 (losses 3.912, 2.303, 2.996, 1.204). Averaging all eight gives 1.436: the loss is now dominated by predicting the user's words, which the model cannot know and should not learn to produce.
The <|im_end|> after the answer must keep its label. It is how the model learns to stop.
Common mistakes
Shifting labels yourself. Hugging Face causal LMs shift inside the forward pass. Shifting again trains the model to predict two tokens ahead; loss plateaus high.
Masking the end-of-turn token. Symptom: the model never stops generating. Fix: score the closing token of each assistant turn.
Pad token equal to end-of-sequence, masked as padding. Every real EOS is then masked too. Use a distinct pad token or mask by attention mask, not by token id.
Comparing loss across tokenizers. Per-token loss depends on how many tokens a text becomes. Compare models with the same tokenizer, or use bits per character.
Averaging per sequence instead of per token. Short answers then weigh as much as long ones. Know which one your trainer does.
Check yourself
Eval loss falls from 1.2 to 0.9. By what factor did perplexity fall?
Answer
e1.2/e0.9 = e0.3 = 1.35. Perplexity went from 3.32 to 2.46.
Module 3
Instruction data
Lecture 1.4 · 11 min read
Building an instruction dataset
Hyperparameters move results by a few points. Data moves them by tens. The modern format is one conversation per row as a list of role-tagged messages; older datasets use instruction / input / output columns, and training libraries convert either.
{"messages": [
{"role": "system", "content": "You are a support assistant for Acme Logistics."},
{"role": "user", "content": "Where is order #1832?"},
{"role": "assistant", "content": "Order #1832 left our Hanoi hub on 12 Oct and is due 14 Oct. Tracking: VN8827711."}
]}
Sources, in order of preference. Your own records: tickets paired with the replies people wrote, documents paired with their summaries, questions paired with the SQL that answered them. Public datasets for the general assistant behavior you want to keep. Synthetic data from a stronger model when you lack examples: give it your task description, seed examples and real inputs, generate several candidates per input, keep the ones a checker accepts. Distillation of this kind is the most common reason to fine-tune in industry; check the generating model's terms of use before shipping a product on its outputs.
The pipeline is the same every time: format every row into messages, drop empties and extreme lengths, remove near-duplicates, and hold out 5% as an evaluation set before you look at anything else. Separately, hand-write or hand-verify a fifty-row gold set that represents what production will ask; it is your real test for the whole course. Decontaminate: no training row may share its user turn with the gold set. Then read fifty random rows with your own eyes. Bad rows are found by reading, not by statistics.
Quality beats quantity. A thousand excellent examples usually beat a hundred thousand noisy ones for assistant-style tasks; the LIMA paper made the point with exactly 1,000. The second lever is loss masking: score only the assistant's tokens, so the model learns to answer rather than to predict the question. In TRL that is assistant_only_loss=True for conversational data.
Deep dive · Deduplication, packing and gold-set size
Near-duplicates with Jaccard similarity
Exact matching after normalization catches copies that differ in case and punctuation. Reworded copies need a similarity measure. Split each text into word 3-grams (shingles) and compute the Jaccard similarity J(A, B) = |A ∩ B| / |A ∪ B|.
Worked example. "where is my order 1832 it has not arrived yet" and "where is my order 1832 it still has not arrived" have 10 words each, so 8 shingles each. Shared: "where is my", "is my order", "my order 1832", "order 1832 it", "has not arrived": 5. Union: 8 + 8 − 5 = 11. J = 5/11 = 0.45. At a threshold of 0.8 these are kept as distinct; at 0.4 they would be merged. MinHash estimates J without comparing every pair: the probability that two sets share the same minimum hash value equals J, so the fraction of agreeing values over 128 hash functions estimates it.
Packing and padding
Eight rows of 120, 340, 80, 610, 200, 450, 90 and 300 tokens hold 2,190 real tokens.
Padded to the longest row in the batch: 8 · 610 = 4,880 slots, 55.1% of them padding.
Packed end to end into 1,024-token sequences: 3 sequences, 3,072 slots, 28.7% padding.
Packing saves compute but creates a trap: if attention is not blocked at row boundaries, tokens of one example attend to the previous, unrelated example. Correct packing resets position ids at each boundary and uses a block-diagonal mask (variable-length attention kernels do this). TRL's packing does it when the attention implementation supports it; check before turning packing on.
How large must the gold set be?
A gold-set accuracy p measured on n rows has standard error √(p(1−p)/n). At p = 0.8 and n = 50 the 95% half-width is 1.96 · √(0.16/50) = 0.111, so "80%" means somewhere between 69% and 91%. Fifty rows tell you whether the model works at all and show its failure modes; to resolve a 5-point improvement you need hundreds of rows or a paired test (“Evaluation that predicts production”).
Decontamination beyond exact match
Exact normalized matching misses paraphrases. A stricter check flags any training row that shares a long n-gram (13 words was used for GPT-3's benchmark checks) with a gold question or answer. For a few hundred gold rows, an n-gram set lookup over the training set takes seconds.
How much data
For format and behavior, 500 to a few thousand reviewed examples is typical; LIMA used 1,000. A useful test: train on 25%, 50% and 100% of the data and plot the gold metric. If the curve is still rising at 100%, more data helps; if it is flat from 50%, spend the effort on quality.
Common mistakes
Splitting before deduplicating. Copies land on both sides and eval loss looks too good. Dedupe first, then split.
Deduplicating on the whole row. The same question with two answers survives and teaches inconsistency. Key on the user turn, then decide which answer to keep.
Synthetic data without a checker. The generator's mistakes become the model's habits. Keep only rows a program or a person has accepted.
Packing with cross-example attention. Symptom: answers that drift into content from other rows. Fix: boundary-aware masks or no packing.
Check yourself
The lab holds out 5% of 84 rows. How many evaluation rows is that, and what does it imply for reading eval loss?
Answer
round(4.2) = 4 rows. An average over four rows is noisy; treat eval-loss differences below about 0.1 as noise and rely on the gold set.
A free Colab T4 (16 GB) or Kaggle GPU is enough for the whole course. Apple Silicon runs bf16 LoRA on models up to about 3B through MPS but cannot run 4-bit quantization.
Step 2Build the dataset
from datasets import load_dataset
raw = load_dataset("json", data_files="raw.jsonl")["train"] # your rows: question, answer
def to_messages(row):
return {"messages": [
{"role": "system", "content": "You are a support assistant for Acme Logistics."},
{"role": "user", "content": row["question"]},
{"role": "assistant", "content": row["answer"]},
]}
ds = raw.map(to_messages, remove_columns=raw.column_names)
ds = ds.filter(lambda r: 20 < len(r["messages"][2]["content"]) < 4000)
split = ds.train_test_split(test_size=0.05, seed=42)
split["train"].to_json("train.jsonl"); split["test"].to_json("eval.jsonl")
If you have no data of your own, take 2,000 rows of a public instruction dataset from the Hugging Face Hub and treat them as yours. Either way, write fifty gold rows by hand in a separate file and confirm no user turn appears in train.jsonl.
Step 3Render and count
Render ten training rows through apply_chat_template for Qwen/Qwen2.5-0.5B-Instruct and print them. Tokenize every row and plot a histogram of lengths; record the 95th percentile, which becomes max_length next week.
Checkpoint 1
The base model scores a mean loss of 2.0 on your eval set before training. What is its perplexity, to two decimals?
Checkpoint 2
How many messages does each row produced by to_messages contain?
Week 2 · 5 lectures · quiz · lab
Parameter-efficient fine-tuning
Why updating every weight needs a data center, how LoRA fits the same job on one GPU, and one complete training run.
Video lectures · Week 2
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
LoRA explained visually, with PyTorch code from scratchUmar Jamil · YouTube ↗QLoRA: Efficient Finetuning of Quantized LLMsTim Dettmers · London ML Meetup · YouTube ↗
Module 1
Memory and parameter-efficient methods
Lecture 2.1 · 7 min read
Full fine-tuning and its memory bill
Every parameter must live in GPU memory in some precision: 2 bytes in bf16, 4 in fp32, about half a byte at 4-bit. Holding the weights is the smallest part of the bill. Training with AdamW in mixed precision also keeps a bf16 gradient, an fp32 master copy of the weights and two fp32 Adam moments per parameter, 2 + 2 + 4 + 8 = 16 bytes before a single activation is stored.
Model
Params
bf16 weights
4-bit weights
Full fine-tune, AdamW
Qwen2.5-0.5B
0.49 B
1.0 GB
0.3 GB
7.9 GB + activations
Llama-3.2-1B
1.24 B
2.5 GB
0.7 GB
19.8 GB + activations
Llama-3.2-3B
3.21 B
6.4 GB
1.8 GB
51.4 GB + activations
Qwen2.5-7B
7.62 B
15.2 GB
4.3 GB
121.9 GB + activations
Llama-3.1-8B
8.03 B
16.1 GB
4.5 GB
128.5 GB + activations
Full fine-tuning also moves the model furthest from where pretraining left it, so it forgets general ability fastest: catastrophic forgetting. It remains the right tool for continued pretraining on a large corpus, such as a new language, a code base or a scientific field, when you have the hardware and the data. For teaching a format or a behavior from thousands of examples, the next lecture does the same job in a fraction of the memory.
Deep dive · Where the 16 bytes go, and the activations on top
Derivation: 16 bytes per parameter
Mixed-precision AdamW keeps, for every trainable parameter:
Tensor
Precision
Bytes
Qwen2.5-1.5B (1.54 B)
working weights
bf16
2
3.08 GB
gradients
bf16
2
3.08 GB
master weights
fp32
4
6.16 GB
Adam first moment m
fp32
4
6.16 GB
Adam second moment v
fp32
4
6.16 GB
total
16
24.64 GB
Why keep an fp32 copy? bf16 has 8 significant bits. Near 0.05 the spacing between bf16 numbers is 2−12 ≈ 0.000244. A full fine-tuning update of lr · g = 10−5 · 0.1 = 10−6 is far below half that spacing, so adding it in bf16 rounds back to the old weight and the model never learns. The fp32 copy has spacing about 3.7·10−9 near 0.05 and accumulates the small updates; the bf16 weights are re-derived from it after each step.
8-bit Adam stores m and v in one byte each, giving 2 + 2 + 4 + 2 = 10 bytes per parameter: 15.4 GB for the same model.
Activations
The backward pass needs intermediate results from the forward pass. For batch b, sequence length s and hidden size d, each stored tensor of width w costs b·s·w·2 bytes in bf16.
The SwiGLU block alone stores gate, up and their product at width dff. Qwen2.5-1.5B (dff = 8,960), b = 4, s = 1,024: 4·1,024·8,960·2 = 73.4 MB each, × 3 × 28 layers = 6.17 GB, before attention and norms.
With gradient checkpointing only each layer's input is kept: 28 · 4·1,024·1,536·2 = 0.35 GB, and the rest is recomputed during backward (about one extra forward pass).
The logits are the surprise. b·s·V scores in fp32 = 4·1,024·151,936·4 = 2.49 GB, and the softmax gradient needs as much again. Large-vocabulary models often run out of memory at the loss, not in the layers.
Worked example
Can you fully fine-tune Qwen2.5-0.5B on a 16 GB card? Parameters 0.494 B · 16 = 7.90 GB. Checkpointed activations at b = 4, s = 1,024: 24 · 4·1,024·896·2 = 0.18 GB. Logits and their gradient: about 5.0 GB. Total about 13 GB plus framework overhead: it fits, barely. The 1.5B model at 24.64 GB does not, which is why the next lecture exists.
Common mistakes
Budgeting only the weights. "The model is 3 GB in bf16, so it trains on 8 GB" is off by a factor of eight.
Pure bf16 training without a master copy. Symptom: loss stalls after the first few hundred steps as updates round away. Fix: mixed precision (bf16=True in the trainer keeps fp32 master weights).
Raising batch size to fix out-of-memory. It makes activations larger. Lower per-device batch, raise gradient accumulation.
Forgetting the logits. Out-of-memory at the loss line with long sequences. Fix: shorter max length, smaller micro-batch, or a fused/chunked cross-entropy.
Check yourself
How much optimizer and weight memory does full fine-tuning of Llama-3.1-8B need with 8-bit Adam?
Answer
10 bytes · 8.03 B = 80.3 GB, before activations. Still more than one 80 GB card.
Lecture 2.2 · 12 min read · demo
LoRA: the low-rank update
Freeze every weight matrix W of the base model. For each one you want to adapt, add a trainable correction ΔW = B·A, where A is r × din and B is dout × r, with a rank r far smaller than either dimension. A is initialized randomly and B to zero, so training starts from exactly the base model. Course 3's PCA intuition is the reason this works: the change a fine-tune needs to make to a weight matrix is usually well described by a few directions.
h = W x + (α / r) · B A x trainable per matrix = r · (din + dout)α is a scale, commonly 2r. At inference B·A can be added into W once, so there is no latency cost, and one base model can host many adapters of a few tens of megabytes each.
Three settings matter. Rank 8–64 covers most tasks; higher ranks learn more and overfit more. Target all seven linear maps, not only the attention ones; adapting attention alone leaves quality on the table, a finding from the QLoRA paper. And use a learning rate about ten times higher than for full fine-tuning, 1e-4 to 3e-4, because the adapter starts at zero and has far fewer parameters to move.
LoRA calculator
Parameters you will train, and the memory bill
Target modules
–trainable parameters
–of base parameters
–adapter file, bf16
–effective scale α / r
GPU memory before activations
Full fine-tune–
LoRA, bf16 base–
QLoRA, 4-bit base–
Add 2–8 GB for activations depending on sequence length and batch size.
Deep dive · LoRA math: gradients, initialisation and the α/r scale
Derivation: the gradients
For one adapted layer, h = Wx + s·BAx with s = α/r, A of shape r×din, B of shape dout×r and W frozen. Let g = ∂L/∂h. By the chain rule, with u = Ax:
∂L/∂B = s · g uᵀ = s · g (Ax)ᵀ ∂L/∂A = s · Bᵀ g xᵀW receives no gradient and needs no optimizer state
At initialisation B = 0, so ∂L/∂A = 0 and only B moves on the first step; ∂L/∂B is nonzero because A is random. From the second step both move. If both started at zero, both gradients would be zero forever. If both started random, BA ≠ 0 and the model would start from a perturbed base. Zero B with random A is the one choice that starts exactly at the base model and still learns.
Worked example: one 4096×4096 matrix
Full matrix: 4,096² = 16,777,216 parameters. LoRA with r = 16: A has 16·4,096 and B has 4,096·16, together 131,072, which is 0.78%. In general the fraction for a square d×d matrix is 2r/d.
For Qwen2.5-0.5B with r = 8 on all seven maps: per layer 8·[2(896+896) + 2(896+128) + 2(896+4,864) + (4,864+896)] = 8·22,912 = 183,296; × 24 layers = 4,399,104 parameters, an adapter file of 8.8 MB in bf16.
Why the α/r scale, and rank-stabilised LoRA
The adapter's output on one coordinate is s · Σk=1..r Bik(Ax)k, a sum of r terms. If those terms are roughly independent with similar size, the sum's standard deviation grows like √r. With s = α/r and α fixed, the output then scales like α/√r: doubling the rank shrinks the update, and high ranks learn more slowly at the same learning rate. Rank-stabilised LoRA (Kalajdzievski, 2023) uses s = α/√r, which keeps the output size independent of r. In PEFT it is use_rslora=True.
r
α/r (α = 16)
α/√r (α = 16)
8
2.0
5.66
16
1.0
4.0
64
0.25
2.0
256
0.0625
1.0
The common convention α = 2r fixes s = 2 for every rank, which sidesteps the shrinkage; when you sweep r with α fixed, expect the higher ranks to look worse unless you also raise the learning rate or switch to rsLoRA.
Compute, not only memory
A training step normally costs about 6N FLOPs per token: 2N forward, 2N for gradients with respect to activations, 2N for gradients with respect to weights. Frozen weights skip the last term, so LoRA costs about 4N. For 2.4 M training tokens on a 0.494 B model that is 4.7·1015 instead of 7.1·1015 FLOPs.
Merging
W' = W + s·BA is exact in real arithmetic: W'x = Wx + s·BAx for every x. The merged model has the base model's shapes and speed.
Common mistakes
Changing r and keeping α. The effective scale changes with it; results confound rank with step size.
Full fine-tuning learning rate on an adapter. 1e-5 barely moves a zero-initialised B. Start near 2e-4.
Targeting only q_proj and v_proj. On Llama-3.1-8B at r = 16 that is 6.8 M parameters against 42 M for all seven; quality drops on harder tasks.
Loading an adapter on a different base. Another fine-tune of the same base has identical shapes, so the adapter loads without an error and the outputs are quietly wrong. Record the exact base model id with the adapter.
Check yourself
After one optimizer step from initialisation, which of A and B has changed?
Answer
Only B. ∂L/∂A = s·Bᵀg xᵀ is zero while B = 0, so Adam's update for A is zero. The one exception is weight decay: AdamW's decoupled decay shrinks A slightly even with a zero gradient.
Lecture 2.3 · 8 min read
QLoRA and the rest of PEFT
QLoRA keeps the frozen base model in a 4-bit format (NF4, with the block scales themselves quantized a second time) and dequantizes each matrix on the fly for its multiply, while the adapters, their gradients and the optimizer state stay in higher precision. The paper fine-tuned a 65B model on a single 48 GB GPU with quality matching 16-bit LoRA. The price is speed: each step takes roughly a third longer. On a 16 GB card it is how you fit a 7–8B model.
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import prepare_model_for_kbit_training
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype="bfloat16")
model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb, device_map="auto")
model = prepare_model_for_kbit_training(model) # fp32 norms, gradient checkpointing on
Other parameter-efficient methods trade differently. Bottleneck adapters insert small trainable layers between frozen ones and add inference latency. Prompt and prefix tuning learn virtual tokens and leave every weight untouched, which is cheap but weak on hard tasks. DoRA splits each weight into magnitude and direction and applies LoRA to the direction only, often matching full fine-tuning at the same rank; it is one flag in PEFT (use_dora=True). A careful comparison on code and math found that LoRA learns less from a large new corpus than full fine-tuning but also forgets less general ability, which is the trade you want for instruction tuning.
Deep dive · NF4, block scales and double quantization
Intuition
Trained weights are close to normally distributed. A 4-bit code has 16 values. Uniform spacing wastes codes in the sparse tails; NF4 places its 16 levels at quantiles of a standard normal, so each level is used about equally often. Each block of 64 weights is divided by its largest absolute value (absmax) so it fits in [−1, 1], and the block's absmax is stored as a scale.
The 16 NF4 levels
−1, −0.6962, −0.5251, −0.3949, −0.2844, −0.1848, −0.0910, 0, 0.0796, 0.1609, 0.2461, 0.3379, 0.4407, 0.5626, 0.7230, 1. The set is asymmetric (8 positive, 7 negative and an exact zero) so that zero is representable.
Worked example by hand
Quantize the block (0.010, −0.022, 0.035, −0.004).
Nearest levels: 0.2461 (index 10), −0.6962 (index 1), 1.0 (index 15), −0.0910 (index 6). Store the four 4-bit indices.
Dequantize by multiplying back by 0.035: (0.00861, −0.02437, 0.035, −0.00319).
Errors: (−0.00139, −0.00237, 0, +0.00081).
On simulated Gaussian weights (σ = 0.02, blocks of 64) NF4's root-mean-square error is 0.092σ, against 0.101σ for 16 evenly spaced levels over the same range.
Derivation: bits per parameter
Each block of 64 stores one fp32 scale, 32 bits shared by 64 weights:
On a 65 B model the saving is 0.373 · 65·10⁹ / 8 = 3.03 GB, the figure in the QLoRA paper. Llama-3.1-8B's base at 4.127 bits is 4.14 GB, against 16.06 GB in bf16.
What actually happens in a forward pass
The 4-bit weights are never multiplied directly. For each matrix, the kernel dequantizes blocks to the compute dtype (bf16), multiplies, and discards the result. Gradients flow through the dequantized weights to the input (needed for earlier adapters) but are never applied to the 4-bit storage. The extra dequantization is why steps are slower.
DoRA in one line
DoRA writes the adapted weight as W' = m ⊙ (W + BA) / ‖W + BA‖col, where the norm is taken per column and m is a trainable vector of column magnitudes initialised to ‖W‖col. LoRA then changes direction and m changes length separately.
Common mistakes
Compute dtype left at fp16 or fp32. fp16 can overflow on some layers, fp32 is slow. Set bnb_4bit_compute_dtype to bfloat16 on hardware that supports it.
Skipping prepare_model_for_kbit_training. Norms stay in low precision and training is unstable.
Expecting bitsandbytes on Apple Silicon. 4-bit training needs CUDA; on a Mac use bf16 LoRA on a smaller model.
Merging into the original bf16 base. The adapter was trained against the dequantized NF4 weights, not the original ones. Merge into the dequantized weights (“Merge, quantize, serve”).
Check yourself
Without double quantization, what fraction of the 4-bit model's memory is spent on scales?
Answer
0.5 / 4.5 = 11.1%. With double quantization it is 0.127 / 4.127 = 3.1%.
Module 2
Running supervised fine-tuning
Lecture 2.4 · 12 min read
The training run
This runs on a 16 GB GPU for a 1.5B model in bf16; swap the loading for the QLoRA block to fit 7–8B. Argument names in TRL move between versions; if one is rejected, check SFTConfig for the version you installed.
The knob that matters most. Sweep ×3 and ÷3 before anything else.
Epochs
1–3
Eval loss usually bottoms out in epoch 2 on small sets; more memorizes.
Effective batch
16–64 sequences
Batch × accumulation × GPUs. Accumulate to fit memory.
Warmup
3–5% of steps
Protects the zero-initialized adapter from a huge first update.
Schedule
cosine
Decaying toward zero stabilizes the final checkpoint.
Weight decay
0–0.1
Course 1's λ. Mild regularization.
Max length
p95 of your data
Pay for the tokens you have; truncation silently cuts answers.
Gradient checkpointing
on
About 30% more compute for far lower activation memory.
Tools that wrap this loop: Unsloth rewrites the hot kernels and roughly halves time and memory on one GPU, with free Colab notebooks; Axolotl drives multi-GPU runs from a YAML file; LLaMA-Factory adds a web UI. Learn the raw loop first so you can read their configs.
Deep dive · Effective batch, step counts and the cosine schedule
Gradient accumulation
Run k micro-batches forward and backward, add their gradients, then take one optimizer step. The step sees the same gradient as one batch k times larger, at the memory cost of one micro-batch.
effective batch = per-device batch × accumulation steps × number of GPUsoptimizer steps = ⌈rows / effective batch⌉ × epochs
Worked example: 4,000 training rows, batch 4, accumulation 4, one GPU: effective batch 16, ⌈4,000/16⌉ = 250 steps per epoch, 500 steps for two epochs. With warmup_ratio=0.03 the trainer warms up for ⌈0.03 · 500⌉ = 15 steps.
Normalization across micro-batches
The loss should be the mean over all scored tokens in the effective batch. Suppose micro-batch 1 has 10 scored tokens with mean loss 2.0 and micro-batch 2 has 90 with mean 1.0. Averaging the two means gives 1.5; the token mean is (20 + 90)/100 = 1.1. Averaging means overweights the tokens in short micro-batches. Recent versions of Hugging Face Transformers normalize by the total token count across accumulation steps; older versions did not, which made accumulation and large batches give different results.
Derivation: cosine with warmup
With peak rate η, warmup W steps and total T steps:
η(t) = η · t / W for t < W η(t) = η · ½ [1 + cos(π (t − W)/(T − W))] for t ≥ Wthe form used by get_cosine_schedule_with_warmup
At t = W the cosine is cos 0 = 1 and the rate is η; at t = T it is cos π = −1 and the rate is 0. Halfway through the decay the rate is η/2.
Worked example
η = 2·10−4, W = 15, T = 500.
step t
arithmetic
rate
7
2e-4 · 7/15
9.33·10−5
15
end of warmup
2.00·10−4
100
½(1 + cos(π · 85/485))
1.85·10−4
250
½(1 + cos(π · 235/485))
1.05·10−4
400
½(1 + cos(π · 385/485))
2.03·10−5
500
cos π = −1
0
Gradient clipping
With max norm c, if ‖g‖ > c the whole gradient is rescaled: g ← g · c/‖g‖. A gradient of norm 2.5 with c = 1.0 is multiplied by 0.4. Direction is kept, length capped. In a healthy LoRA run the norm sits below c after warmup; frequent clipping means the rate is too high.
Common mistakes
Warmup in steps copied from a bigger run. 100 warmup steps in a 200-step run spends half of training ramping up. Use a ratio.
Changing accumulation without changing the step count expectation. Doubling accumulation halves the number of optimizer steps per epoch, so checkpoints every 100 steps now come half as often.
Scheduler stepped per micro-batch. In a hand-written loop the schedule ends k times too early. Step the scheduler with the optimizer.
Comparing runs with different effective batch at the same rate. Larger batches tolerate higher rates; sweep the rate for each batch size.
Check yourself
12,000 rows, batch 2, accumulation 8, one GPU, 3 epochs, warmup ratio 0.03. How many steps, and how many warmup steps?
Answer
Effective batch 16, ⌈12,000/16⌉ = 750 steps per epoch, 2,250 in total. Warmup ⌈67.5⌉ = 68 steps.
Lecture 2.5 · 9 min read · demo
Reading the loss curve
Log evaluation loss every hundred steps and plot both curves. Training loss falls for as long as you train; what matters is the step where evaluation loss stops falling. In the run below that is step 600; everything after is memorization, and the checkpoint to keep is the one saved there. This is Course 2's early stopping with a language model.
training lossevaluation lossshaded: evaluation loss rising
Eval loss never falls: learning rate too low, wrong chat template, or every target token masked. Overfit a batch of ten examples first; if the model cannot memorize ten rows, the pipeline is broken.
Spikes in loss or gradient norm: learning rate too high, or a few very long rows. Clip gradients at 1.0 and lower the rate.
Training loss far below eval loss from the first step: duplicate rows across the split. Dedupe.
Loss fine, outputs bad: the model repeats the question (prompt tokens were scored), or never stops (pad token equals end-of-sequence token). Print one rendered example with its label mask.
Deep dive · Signal, noise and diagnosis in the loss curves
Reading the lab's log
The run in trainer_log.json evaluates every 100 steps. Evaluation loss falls from 1.55 at step 100 to 0.93 at step 600, then rises to 1.19 at step 1,000, while training loss ends at 0.563. In perplexity: 2.53 at the best checkpoint, 3.29 at the end, 1.76 on the training data. The final model is noticeably less certain on new data than the step-600 model, although its training loss is lower.
How much of a difference is real?
Eval loss is a mean over rows, so it has a standard error. If the per-row mean loss has standard deviation s across rows, the eval loss over n rows has standard error s/√n.
SE(eval loss) ≈ s / √ns = 0.4: n = 4 → 0.20 · n = 200 → 0.028
The lab's split leaves 4 evaluation rows; with s = 0.4 the standard error is 0.2, larger than every step-to-step change after step 400. The step 600 and step 700 values (0.93 and 0.94) are indistinguishable even with 200 rows. What you can trust is the shape: a minimum followed by a sustained rise over several evaluations. For decisions between close checkpoints, use the gold-set metric.
Diagnosis table
Symptom
Likely cause
Test
Initial loss near 11–12
random weights loaded, or vocabulary mismatch
log V for your tokenizer; generate one sentence before training
Loss flat from step 1
rate too low, all labels −100, or frozen adapter
count labels ≠ −100; print trainable parameters
Train ≪ eval from step 1
duplicates across the split
normalized-key overlap between train and eval
Spikes, grad norm ≫ 1
rate too high, very long rows
lower rate ÷3; sort a batch by length
Eval loss rises, task metric still rises
overconfidence on a few tokens
trust the task metric, but watch both
The ten-row overfit test
Training on ten rows for 30 epochs should drive training loss below about 0.05 (perplexity under 1.05). Ten rows have no generalization requirement, so failure isolates the pipeline: the mask, the template, the rate or the frozen parameters. It costs a minute and saves a day.
Learning-rate sweep
Run the rate at ×3 and ÷3 of the default (6e-4, 2e-4, 7e-5). Compare evaluation minima, not final values. The usual picture: the high rate reaches its minimum earliest and rises fastest, the low rate has not reached its minimum by the end. Pick the rate with the lowest minimum, then the checkpoint at that minimum.
Common mistakes
Keeping the last checkpoint. In the lab's log it is 0.26 worse in eval loss than the best one. Set load_best_model_at_end=True with metric_for_best_model="eval_loss", or pick by hand.
save_total_limit deleting the best checkpoint. With a limit of 2 and no best-model tracking, step 600 is deleted by step 800. Track the best or raise the limit.
Reading single evaluations as trends. A 0.01 change on a few rows is noise.
Smoothing hides spikes. Look at the raw training loss once before trusting a smoothed curve.
Check yourself
Eval loss at three checkpoints is 0.95, 0.93, 0.94 on 50 rows with s = 0.5. Can you tell them apart?
Answer
No. SE = 0.5/√50 = 0.071, several times the differences. Choose between them with the gold-set metric, or keep the earliest for the least drift.
Load Qwen/Qwen2.5-0.5B-Instruct, wrap it with your LoraConfig (r = 8, all seven modules) using peft.get_peft_model, and call model.print_trainable_parameters(). Compare with the calculator in “LoRA: the low-rank update”.
Checkpoint 1
Trainable LoRA parameters for Qwen2.5-0.5B, r = 8, all seven linear modules, in millions (two decimals)?
Step 2Overfit ten rows
Run the “The training run” script on ten training rows for 30 epochs with evaluation off. Training loss must approach zero. If it does not, fix the template, the mask or the learning rate before continuing.
Step 3The real run
Train on train.jsonl with the lecture settings, evaluating every 100 steps. Save the loss history and plot both curves. Identify the evaluation minimum and note which checkpoint directory corresponds to it.
Step 4Sweep and compare
Rerun with learning rates 6e-4 and 7e-5. Build a table of the three evaluation minima. Then generate answers for ten gold-set questions from the base model and from your best checkpoint, with identical sampling settings, and read them side by side.
Checkpoint 2
Memory, in GB, for a full fine-tune of a 1.54 B-parameter model at 16 bytes per parameter, before activations (one decimal)?
Week 3 · 4 lectures · quiz · capstone
Align, evaluate, ship
Teaching preferences with Course 3's reinforcement learning, proving the model is better rather than merely different, and running it where it will be used.
Video lectures · Week 3
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
RLHF explained with math derivations and PyTorch codeUmar Jamil · YouTube ↗Direct Preference Optimization (DPO) explainedUmar Jamil · YouTube ↗
Module 1
Preference tuning
Lecture 3.1 · 11 min read
RLHF and DPO
SFT shows the model what a good answer looks like. Preference data shows it which of two answers is better, a signal that is cheaper to collect (people compare more reliably than they write) and that teaches things no single example can, such as tone and when to refuse. Reinforcement learning from human feedback uses it in three steps: train a reward model to predict human preferences from pairs; run reinforcement learning (PPO, an actor-critic method) on the language model to maximize that reward; and add a KL penalty that keeps the policy near the SFT model so it does not drift into text that games the reward model. The policy is the model, the action is the next token, the reward arrives at the end of the response: Course 3 exactly.
Direct Preference Optimization rewrites that objective so that the reward model disappears. For each (prompt, chosen, rejected) triple, raise the log-probability of the chosen answer relative to the rejected one, measured against a frozen reference model, with a temperature β controlling how far the policy may move. It is a classification loss over pairs, stable on one GPU, with no sampling loop. Run it after SFT with a learning rate about fifty times smaller.
LDPO = −log σ( β · [ log π(yw|x)/πref(yw|x) − log π(yl|x)/πref(yl|x) ] )yw is the chosen response, yl the rejected one, πref the SFT model. β ≈ 0.1.
Write the KL out and divide by −β, turning the maximum into a minimum: Σy π(y) [log π(y)/πref(y) − r(y)/β]. Define Z(x) = Σy πref(y) er(y)/β and π*(y) = πref(y) er(y)/β / Z. Then log πref(y) + r(y)/β = log π*(y) + log Z, and the sum becomes Σ π(y) log(π(y)/π*(y)) − log Z = KL(π ‖ π*) − log Z. Z does not depend on π, and a KL is zero only when its arguments are equal, so the optimum is π = π*:
π*(y|x) = πref(y|x) · er(x,y)/β / Z(x)
Derivation 2: the reward in terms of the policy
Take logs and solve for r: r(x, y) = β log[π*(y|x)/πref(y|x)] + β log Z(x). Any policy defines an implicit reward this way, up to a term that depends only on x.
Derivation 3: Bradley–Terry and the loss
The Bradley–Terry model says the probability that yw is preferred to yl is σ(r(yw) − r(yl)). Substitute the implicit reward; β log Z appears in both terms and cancels:
P(yw ≻ yl) = σ(β log π(yw)/πref(yw) − β log π(yl)/πref(yl))maximum likelihood on preference pairs gives LDPO = −log of this
The intractable Z was the reason RLHF needed a separate reward model and sampling; the cancellation is why DPO needs neither.
The gradient
With margin m = β[(log π(yw) − log πref(yw)) − (log π(yl) − log πref(yl))] and d/dm[−log σ(m)] = −σ(−m):
∇L = −β σ(−m) [∇log π(yw) − ∇log π(yl)]
Each pair is weighted by σ(−m): close to 1 when the policy ranks the pair the wrong way, close to 0 when it already ranks it correctly by a wide margin.
Worked example
β = 0.1. Sequence log-probabilities: chosen −42.0 under the policy, −45.0 under the reference; rejected −50.0 and −48.0. Implicit rewards: 0.1·3 = 0.3 and 0.1·(−2) = −0.2. Margin 0.5. Loss −log σ(0.5) = 0.474; gradient weight σ(−0.5) = 0.378. At the start of training the policy equals the reference, m = 0, the loss is ln 2 = 0.693 and the weight 0.5.
What β does to the optimum: two answers with reference probability 0.5 each and rewards 1 and 0. π*(better) = e1/β/(e1/β + 1): 0.622 at β = 2, 0.731 at β = 1, 0.881 at β = 0.5, 0.99995 at β = 0.1. Small β lets the policy move almost all its mass; large β keeps it near the reference.
Common mistakes
Reference that is not the starting policy. If πref is the base model but training starts from the SFT model, the margin starts nonzero and the loss is meaningless at step 0. Start where the reference is.
SFT learning rate. 2e-4 on DPO wrecks fluency within a few hundred steps; use about 5e-6.
Reading the chosen log-probability alone. Both chosen and rejected log-probabilities often fall while the margin grows. Track the margin and the gold metric.
Length bias. Sequence log-probabilities are sums, and if chosen answers are systematically longer the policy learns length. Balance lengths in the pairs or normalize.
Lecture 3.2 · 8 min read
GRPO and verifiable rewards
Some tasks can be checked by a program: a math answer matches, a unit test passes, a JSON parses against a schema. For those you need no human preferences at all. Group Relative Policy Optimization samples several answers per prompt, scores each with the checker, and pushes the policy toward answers that scored above the group's average and away from those below, with the group's own mean standing in for the value network PPO would need. It is the method behind the recent reasoning models, and TRL ships a trainer for it.
Two relatives worth knowing. ORPO folds the preference term into the SFT loss so one run does both, with no reference model. KTO works from single thumbs-up or thumbs-down labels rather than pairs, which is what production logs actually contain.
Every alignment step moves the model somewhere, and the places it moved away from are invisible unless you test them. Keep three fixed sets that run after every training job: your task gold set, a general-ability sample of a few hundred questions from a public benchmark, and a safety set of requests the model should refuse alongside benign ones it should not. A run that improves the first and silently degrades the others is the most common failure in production; the cost is called the alignment tax, and measuring it is the only way to pay it knowingly.
Deep dive · Group-relative advantages and why a baseline is free
Derivation: a baseline does not bias the gradient
The policy gradient is Ey∼π[r(y) ∇log π(y)]. Subtract any b that does not depend on y. The extra term is b · E[∇log π(y)] = b Σy π(y) ∇log π(y) = b Σy ∇π(y) = b ∇Σy π(y) = b ∇1 = 0. So the gradient's expectation is unchanged, while its variance falls when b is close to the typical reward. PPO learns b with a value network; GRPO uses the mean reward of a group of answers to the same prompt.
The GRPO advantage
Âi = (ri − mean(r1..G)) / std(r1..G)every token of answer i gets the same advantage
The per-token objective is PPO's clipped surrogate with ratio ρ = πθ/πold: min(ρÂ, clip(ρ, 1−ε, 1+ε)Â), minus β times a KL estimate to the reference. A common per-token estimator is k3 = q − log q − 1 with q = πref/πθ; it is never negative and is zero only at q = 1. For q = 0.8 it is 0.0231.
Worked example: a group of 4
Four answers to one math problem; a checker gives 1 to the correct one: r = (1, 0, 0, 0). Mean 0.25. Sample standard deviation √[(0.75² + 3·0.25²)/3] = √(0.75/3) = 0.5.
 = (0.75/0.5, −0.25/0.5, −0.25/0.5, −0.25/0.5) = (1.5, −0.5, −0.5, −0.5)with the population standard deviation 0.433: (1.732, −0.577, −0.577, −0.577)
The advantages sum to zero: the correct answer's tokens are pushed up three times as hard as each wrong answer's tokens are pushed down. Implementations differ on sample versus population standard deviation; torch's std defaults to the sample version.
Other groups: r = (1, 0, 0, 1) gives mean 0.5, sample std 0.577, advantages ±0.866. r = (1, 1, 1, 1) gives std 0 and advantage 0 for everyone (implementations add a small ε to the denominator): a group where every answer is right, or every answer is wrong, teaches nothing.
Why prompt difficulty matters
If the model solves a prompt with probability p and the group has G = 8 answers, the chance that all are wrong is (1−p)8. For p = 0.1 that is 0.430, so 43% of such groups produce no gradient; for p = 0.9 the chance that all are right is also 0.430. The useful prompts are the ones the model solves sometimes. Filter the training set to prompts with intermediate pass rates.
ORPO and KTO in one formula each
ORPO adds to the SFT loss λ · (−log σ(log odds(yw) − log odds(yl))), with odds(y) = P(y)/(1 − P(y)) under the policy itself, so no reference is needed. KTO scores single answers: it raises the implicit reward of thumbs-up answers above a reference point and lowers thumbs-down answers below it.
Common mistakes
A reward the checker can be fooled on. If any string containing a number scores 1, the model learns to print many numbers. Parse strictly and test the checker on adversarial outputs.
Groups of 2. The advantage is then always ±0.707 or 0 (sample std), so the size of a reward difference is lost. Use 8 or more.
No length control. Per-sequence normalization can reward long wrong answers less per token than short ones, and lengths grow. Watch mean completion length.
Only tracking reward. The reward can climb while general ability falls. Run the three fixed evaluation sets after each job.
Check yourself
Rewards (0.9, 0.2, 0.5, 0.0) from a graded checker. Which answers get a positive advantage?
Answer
Mean 0.4, sample std 0.392. Advantages (1.277, −0.511, 0.255, −1.022): the first and third.
Module 2
Evaluate and ship
Lecture 3.3 · 9 min read
Evaluation that predicts production
Loss is a proxy. The question a reviewer will ask is whether the fine-tuned model is better than the base model on the task, and by how much. Answer it in three layers, each cheaper to run than to argue about.
The gold set with a task metric: exact match or field-level F1 for structured outputs, execution accuracy for SQL, a rubric for prose. Run base and fine-tuned with identical prompts and sampling settings.
Pairwise judging: show a strong model both answers in random order and count wins. Cheap, and it correlates well with human preference when the judge is told what matters; randomize the order or the judge favors the first.
A general benchmark through lm-evaluation-harness, compared with the base model's score on the same tasks, to measure forgetting.
pip install lm-eval
lm_eval --model hf --model_args pretrained=out/qwen-merged,dtype=bfloat16 \
--tasks gsm8k,mmlu --batch_size 8 --output_path out/eval # run the base model the same way
Report all three for both models in one table. A fine-tune that wins the task metric by a margin you would defend, stays within two points on the general benchmark, and leaves the safety set unchanged is done. Anything else goes back to the data.
Deep dive · Confidence intervals and paired tests for model comparisons
A win rate with its interval
n prompts, w wins: the win rate p̂ = w/n is a binomial proportion with standard error √(p̂(1−p̂)/n).
Worked example: 39 wins out of 60. p̂ = 0.65, SE = √(0.65·0.35/60) = 0.0616, 95% interval 0.65 ± 1.96·0.0616 = 0.65 ± 0.121, that is [0.529, 0.771]. The Wilson interval, better near 0 or 1 and for small n, is
[p̂ + z²/2n ± z √(p̂(1−p̂)/n + z²/4n²)] / (1 + z²/n)39/60, z = 1.96: [0.524, 0.758]
To get a half-width of ±5 points near p = 0.5 you need n = (1.96 · 0.5 / 0.05)² = 384 prompts.
Ties
With position swapping, a pair is a win only if it wins in both orders. Report wins, ties and losses. Two summaries are common: the score (w + t/2)/n, and a sign test on decisive pairs only. Example: 33 wins, 12 ties, 15 losses. Score (33 + 6)/60 = 0.65. Sign test: 33 of 48 decisive pairs, two-sided binomial p = 0.013 against a fair coin.
Derivation: McNemar's test for paired accuracy
Both models answer the same 100 gold rows. Only discordant rows carry information about the difference: b = rows the fine-tune gets right and the base gets wrong, c = the reverse. Under the null hypothesis of equal accuracy each discordant row is equally likely to fall either way, so b ~ Binomial(b + c, ½). The normal approximation with continuity correction gives
χ² = (|b − c| − 1)² / (b + c), one degree of freedom
Worked example: base 62/100, fine-tune 74/100, with b = 18 and c = 6. χ² = (12 − 1)²/24 = 121/24 = 5.04, p = 0.025; the exact binomial test gives p = 0.023. An unpaired two-proportion z-test on 62% versus 74% gives p = 0.069 and would call the same data inconclusive, because it ignores that both models were tested on the same rows. With b = 14, c = 6 (fine-tune 70/100) McNemar gives χ² = 2.45, p = 0.118: an 8-point gain on 100 rows is not yet evidence.
Bootstrap
For metrics without a formula (field F1, a rubric score), resample the n prompts with replacement 1,000 times, recompute the metric difference between the models on each resample, and take the 2.5th and 97.5th percentiles. Resample prompts, not individual model outputs, so the pairing is kept.
Common mistakes
Reporting a win rate without n. 65% on 20 prompts and on 400 prompts are different claims. Always give the interval.
Different sampling settings for the two models. Temperature differences show up as quality differences. Fix temperature, max tokens and system prompt.
Unpaired tests on paired data. They waste power, as the example shows. Use McNemar or a paired bootstrap.
Tuning prompts on the gold set. After twenty iterations against it, the gold set is a training set. Keep a second, untouched set for the final number.
Trusting the judge without calibration. Label 30 to 50 pairs by hand and measure agreement before using its win rates.
Lecture 3.4 · 9 min read
Merge, quantize, serve
Merging adds B·A into the base weights so the result is an ordinary checkpoint any runtime can load. For laptops and CPU servers, convert it to GGUF with llama.cpp and quantize; Q4_K_M is the usual balance of size and quality, Q8_0 when memory allows. Keep the unquantized merged model as the source of truth.
from peft import PeftModel
base = AutoModelForCausalLM.from_pretrained(model_id, dtype="bfloat16")
merged = PeftModel.from_pretrained(base, "out/qwen-lora/final").merge_and_unload()
merged.save_pretrained("out/qwen-merged"); tok.save_pretrained("out/qwen-merged")
# Modelfile
FROM ./qwen-ft-q4_k_m.gguf
PARAMETER temperature 0.2
SYSTEM "You are a support assistant for Acme Logistics."
# then: ollama create acme-support -f Modelfile && ollama run acme-support
For many concurrent users, vLLM serves the merged bf16 model with continuous batching and can load several LoRA adapters on one base, so a single GPU serves several fine-tunes. Whatever you serve, log prompts and responses with a way for users to flag bad ones. Every few weeks, review the flagged set, write the correct answers, add them to the dataset, retrain from the base model rather than from the last fine-tune, re-run the three evaluation sets, and ship if nothing regressed. The dataset and the adapter are versioned together; the pair is the product.
Deep dive · Merge exactness, rounding and quantized file sizes
Merging: exact in math, rounded in storage
W' = W + (α/r)·BA gives W'x = Wx + (α/r)·BAx for every input, so the merged model computes the same function. The only loss is rounding when W' is stored in bf16. bf16 numbers in [0.5, 1) are spaced 2−8 = 0.0039 apart, so the rounding error is at most half that, 0.00195, a relative error below 2−9 ≈ 0.2%.
Worked example: a weight of 0.5 with a merged correction of +0.001. 0.501 is closer to 0.5 than to 0.50390625, so the stored weight is still 0.5 and that correction is gone. A correction of +0.003 rounds to 0.50390625. Individual small corrections can vanish, but the errors are unbiased and spread over millions of weights; measured differences in outputs are usually tiny. Merge in fp32 and cast once at the end, and compare a few outputs before and after.
Merging a QLoRA adapter
The adapter was trained against the dequantized NF4 weights Q(W), not W. Merging into the original bf16 W gives W + BA, which differs from what was trained, Q(W) + BA, by W − Q(W): on the order of 0.09σ of the weights per entry, from the previous lecture's measurement. The usual practice is to load the base in bf16 and merge, accepting this mismatch, or to dequantize Q(W) and merge into that; whichever you choose, rerun the gold set on the merged model before exporting.
Derivation: quantization error
A uniform quantizer with step Δ makes an error spread evenly over [−Δ/2, Δ/2]. Its mean square is ∫ e² de / Δ over that interval = Δ²/12, so the RMS error is Δ/√12 = 0.289Δ. With 16 levels over a block's range [−a, a], Δ = 2a/15 and RMS = 0.0385a. For Gaussian weights the absmax of a 64-weight block averages 2.60σ, so the predicted RMS is 0.100σ; a simulation gives 0.101σ. At 8 bits Δ = 2a/255, 17 times smaller.
GGUF bits per weight
Format
Layout
Bits per weight
Qwen2.5-0.5B (494 M)
F16
16-bit floats
16
988 MB
Q8_0
blocks of 32 int8 + one fp16 scale: (256 + 16)/32
8.5
525 MB
Q6_K
super-blocks of 256, 6-bit values, 8-bit sub-scales
6.5625
405 MB
Q4_K
super-blocks of 256: 4-bit values, 6-bit scales and mins for 8 sub-blocks, two fp16 numbers: (1,024 + 96 + 32)/256
4.5
278 MB
Q4_K_M stores most tensors as Q4_K and some sensitive ones (parts of the attention value and feed-forward down projections) as Q6_K, so the file averages somewhat above 4.5 bits per weight.
Speed on a laptop
Generating one token reads every weight once, so decode speed is bounded by memory bandwidth / model size. Qwen2.5-7B at 4.5 bits is 4.29 GB; on a machine with 100 GB/s bandwidth the ceiling is about 23 tokens per second. Halving the bits roughly doubles the ceiling, which is why quantization matters more for speed than for disk.
Common mistakes
Quantizing the only copy. Re-quantizing from a quantized file compounds the error. Keep the merged bf16 checkpoint.
Skipping the post-quantization eval. Run the gold set on the GGUF file; small models lose more at 4 bits than large ones.
Template lost in conversion. If the GGUF lacks the chat template, Ollama formats prompts differently from training. Check the rendered prompt in a verbose run.
Serving the adapter on the wrong base. vLLM's multi-LoRA serving needs the exact base the adapter was trained on.
Choose a base model of 3B parameters or fewer so every experiment fits on a free GPU and finishes within an hour. Choose one task from the list, or your own if its output can be checked.
Structured extraction: documents in, a fixed JSON schema out. Metric: field-level F1.
Text-to-SQL for one schema you know. Metric: execution accuracy against the database.
Ticket triage with a one-sentence justification. Metric: label accuracy plus a judged justification score.
A domain assistant in your own language from documents you have the right to use. Metric: pairwise wins against the base model.
Deliverables: the dataset build script, the training config, the evaluation script, the fifty-row gold set, the merged model and its GGUF, and a one-page report with the three evaluation numbers for both the base and the fine-tuned model, the loss curve with the chosen checkpoint marked, and a DPO or GRPO step if the task supports one.
Checkpoint
Trainable parameters of one LoRA adapter on a 4096 × 4096 matrix with r = 16?
When all seven boxes hold, you have done what most fine-tuning tutorials skip: proved the model is better, not only different. Weeks 4 and 5 open the model up: you build the tokenizer and transformer yourself, then quantize and serve it.
Week 4 · 5 lectures · quiz · lab
Inside the model: tokenizer and transformer from scratch
Every component of the models you fine-tuned, built by hand: the tokenizer, position encodings, attention, the block, and a small GPT you train and sample from on a laptop.
Video lectures · Week 4
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
Attention in transformers, step-by-step3Blue1Brown · YouTube ↗Let's build the GPT TokenizerAndrej Karpathy · YouTube ↗Let's build GPT: from scratch, in code, spelled outAndrej Karpathy · YouTube ↗
Module 1
Tokens and embeddings
Lecture 4.1 · 13 min read
Byte-pair encoding, step by step
A language model reads integers, not text. The tokenizer decides which integers. Two extremes fail. One id per character keeps the vocabulary tiny and never meets an unknown word, but sequences become long, attention cost grows with the square of the length, and the model must spend layers assembling letters into words. One id per word makes sequences short, but the vocabulary explodes, every misspelling and new name is unknown, and rare words get too few training examples for their embeddings to mean anything. Byte-pair encoding (BPE) sits between them: frequent strings become single tokens, rare strings fall apart into smaller pieces, and nothing is ever unknown.
The algorithm was a data-compression method before it was a tokenizer, and it is short enough to run by hand. Start with every word split into characters (in a production tokenizer, into bytes). Count every pair of adjacent symbols, weighted by how often the word occurs. Replace the most frequent pair everywhere with a new symbol and record the merge. Repeat until the vocabulary has the size you want. The ordered list of merges is the tokenizer.
A worked run
Take a corpus with four words: low five times, lower twice, newest six times and widest three times. Split into characters it is 79 symbols. The pair counts at the start are led by e s and s t, both 9 (six from newest, three from widest), then w e with 8 (two from lower, six from newest), then l o and o w with 7. With a tie, take the pair seen first in the corpus; that is e s.
Merge
Pair (count)
Corpus after the merge
Symbols
1
e s (9)
l o w · l o w e r · n e w es t · w i d es t
70
2
es t (9)
l o w · l o w e r · n e w est · w i d est
61
3
l o (7)
lo w · lo w e r · n e w est · w i d est
54
4
lo w (7)
low · low e r · n e w est · w i d est
47
5
n e (6)
low · low e r · ne w est · w i d est
41
6
ne w (6)
low · low e r · new est · w i d est
35
Six merges cut the corpus from 79 symbols to 35. Notice what the merges discovered without being told: the suffix est, the stem low, the whole word new. Notice also that counts recompute after every merge. After merge 1, the pair w e fell from 8 to 2, because the e in newest now belongs to es. This is why BPE cannot be computed in one pass over the initial counts.
Encoding new text
To tokenize a string the model has never seen, replay the merges in the order they were learned. Take lowest, which is not in the corpus. Start from characters l o w e s t. Merge 1 applies (e s) giving l o w es t; merge 2 gives l o w est; merge 3 gives lo w est; merge 4 gives low est. Merges 5 and 6 find nothing. The result is two tokens, low and est, a segmentation a linguist would accept. A word with no learned pieces, such as xyz, stays as three characters. Nothing is out of vocabulary, which is the property that matters most.
The rule "apply merges in order of rank" is the whole encoder. An implementation that greedily matches the longest token in the vocabulary is a different tokenizer and produces different ids for some strings; ids that differ from what the model saw in training are a silent bug.
Bytes, not characters
Real tokenizers since GPT-2 run BPE on UTF-8 bytes. The base vocabulary is the 256 possible byte values, so any string in any script, including emoji and binary junk, encodes without an unknown token. A Vietnamese letter such as ộ is three bytes; if the training corpus had enough Vietnamese, merges combine those bytes into one token and then into syllables, and if it had little, each letter costs two or three tokens. That is the mechanical reason the same sentence costs more tokens in some languages than others, and why a model's tokenizer quietly sets its price per word in your language.
Two more details complete the production picture. Pre-tokenization splits text with a regular expression before BPE runs, typically at spaces, punctuation and digit boundaries, so merges never cross word boundaries and a space usually attaches to the start of the following word ( the rather than the ). Special tokens such as <|im_start|> or <|endoftext|> are added outside the merge table and must never be produced by encoding ordinary text; this is how chat templates from “Tokenizers, chat templates and the loss” stay unambiguous.
What the lab measures
In the lab you train BPE on the 7,215-byte story embedded in the notebook, without pre-tokenization so you can watch merges cross spaces. The first merges are e , t, he and the ; by merge 200 there are tokens like was and . The ferryman. Bytes per token climb from 1.00 with no merges to 1.49 after 25, 2.05 after 100 and 2.55 after 200. Each merge buys less than the one before, because each later merge targets a rarer pair. The same diminishing return is why production vocabularies stop around 32,000 (Llama 2), 50,257 (GPT-2) or 128,256 (Llama 3) tokens: beyond that, the embedding and output matrices grow faster than sequences shrink.
bytes per token = len(text in UTF-8) / len(encode(text)) 0 merges → 1.00 25 → 1.49 100 → 2.05 200 → 2.55Measured on the lab's 7,215-byte story. English text with a 100k-token production vocabulary averages about four bytes per token.
For fine-tuning, the practical consequences are three. The tokenizer is fixed by the base model; you cannot change it without retraining the embeddings. Your max_length is in tokens, so measure your data in tokens, not characters. And when you add special tokens for a new format, you add rows to the embedding matrix that start untrained, which is why adapters on embed_tokens and lm_head are sometimes needed alongside LoRA.
Let the corpus be a multiset of symbol sequences w with counts c(w). The training objective at each step is greedy compression: choose the pair (a, b) that maximizes the number of symbols removed. Merging (a, b) removes one symbol per non-overlapping occurrence, so the saving is n(a, b) = Σw c(w) · occ(a, b, w). After merging, recount only the pairs that touched a merged occurrence: in x a b y, the pairs (x, a) and (b, y) each lose one count and the new pairs (x, ab) and (ab, y) each gain one. Efficient trainers update counts incrementally this way; the lab simply recounts, which is fine for a few thousand bytes.
Overlaps matter. In a a a, the pair (a, a) occurs twice in a count of windows but only once can be merged, leaving aa a. Counting with a sliding window therefore overstates the saving for repeated characters, and the merge function must scan left to right and skip past each replacement.
Worked example by hand
Continue the lecture corpus for one more merge. After merge 6 the corpus is low(5) · low e r(2) · new est(6) · w i d est(3). Pair counts: (new, est) 6, (w, i) 3, (i, d) 3, (d, est) 3, (low, e) 2, (e, r) 2. Merge 7 is (new, est) → newest, and the corpus drops from 35 to 29 symbols. Encoding newer with these seven merges: n e w e r → (n e) gives ne w e r → (ne w) gives new e r. Three tokens. The pair (e, r) was never merged because it reached only 2.
Code walkthrough
def encode(text, merges):
ids = list(text.encode("utf-8"))
while len(ids) >= 2:
counts = get_pair_counts(ids)
pair = min(counts, key=lambda p: merges.get(p, float("inf"))) # earliest-learned merge present
if pair not in merges:
break # no learned pair left
ids = merge(ids, pair, merges[pair])
return ids
Choosing the lowest-rank pair at each step reproduces the training-time order. Decoding is a lookup: each id maps to its bytes, concatenate, decode UTF-8. A token boundary can fall inside a multi-byte character, so decode the joined bytes, never token by token.
Common mistakes
Decoding each token separately and joining strings. Symptom: replacement characters in streamed Vietnamese or emoji output. Fix: buffer bytes until they form complete UTF-8 characters.
Encoding by longest match in the vocabulary. Symptom: ids that differ from the reference tokenizer on a few percent of words. Fix: apply merges by rank.
Letting special-token strings in user text become special tokens. Symptom: a user can type <|im_end|> and close the assistant turn. Fix: encode user text with special tokens disabled.
Measuring lengths in characters. Symptom: truncated answers after you set max_length from character counts. Fix: tokenize the dataset and use the token-count percentile.
Check yourself
With the six merges in the table, how many tokens does widest encode to?
Answer
Four: w i d est. Merges 1 and 2 build est; no merge joins w, i or d.
Lecture 4.2 · 13 min read
Embeddings and positional information
Token ids are labels, not quantities: id 500 is not "more" than id 499. The first layer of every language model therefore replaces each id with a learned vector. An embedding table E has one row per vocabulary entry and d columns, and looking up id i returns row i. Mathematically this is a one-hot vector multiplied by E, the Course 2 linear layer with an input that has a single 1; in code it is an index, because multiplying by a vector of zeros is wasted work.
xt = E[ idt ] E ∈ ℝV × d parameters = V · dLlama-2-7B: 32,000 × 4,096 = 131,072,000 parameters. The lab's tiny GPT: 42 × 64 = 2,688.
The rows start random and are trained by the same gradient descent as everything else. Tokens used in similar contexts receive similar gradients and drift toward each other, so after training, nearby rows mean related things. At the other end of the model, the output head maps a d-dimensional vector back to V scores. Some models tie the two matrices (the head is Eᵀ), which saves V · d parameters and helps small models; Llama 2 and 3 keep them separate.
Why position has to be added
Attention, which “Scaled dot-product attention, worked by hand” builds, compares every position with every other through dot products and then takes weighted sums. Nothing in that computation knows which vector came first. Shuffle the input rows and the output rows shuffle the same way; "dog bites man" and "man bites dog" would produce the same set of vectors. The causal mask breaks the symmetry a little, since position 1 sees one token and position 10 sees ten, but a model needs a direct signal of order. Three designs dominate.
Learned absolute positions (GPT-2) add a second table P with one row per position: xt = E[idt] + P[t]. Simple and effective, but the model has never seen a row past its training length, so it cannot run on longer inputs.
Sinusoidal encodings (the original transformer) add a fixed vector built from sines and cosines at geometrically spaced frequencies.
PE[p, 2i] = sin( p / 100002i/d ) PE[p, 2i+1] = cos( p / 100002i/d )Pair i oscillates with wavelength 2π · 100002i/d, from 2π ≈ 6.3 positions for i = 0 up to about 54,000 positions for the last pair when d = 128.
For position p = 1 and d = 4 the vector is [sin 1, cos 1, sin 0.01, cos 0.01] = [0.8415, 0.5403, 0.0100, 0.99995]. The first pair spins fast and distinguishes neighbouring positions; the last pair turns slowly and distinguishes positions far apart, like the hands of a clock. Each pair is a point on a circle, and moving k positions rotates every pair by a fixed angle that depends only on k. That is the property the next design exploits directly.
Rotary position embeddings
RoPE, used by Llama, Qwen, Mistral and most current open models, adds nothing to the embeddings. Instead, inside every attention layer, it rotates the query and key vectors by an angle proportional to their position before the dot product. Split a d-dimensional vector into d/2 pairs and rotate pair i at position p by angle p · θi:
[ x′2i , x′2i+1 ] = [ x2i cos(pθi) − x2i+1 sin(pθi) , x2i sin(pθi) + x2i+1 cos(pθi) ] θi = 10000−2i/dThe same frequencies as the sinusoidal encoding. Values are never rotated, only queries and keys.
The point of rotating is what happens to a dot product. Write R(a) for rotation by angle a. A query at position m and a key at position n become R(mθ)q and R(nθ)k, and their dot product is qᵀ R(mθ)ᵀ R(nθ) k = qᵀ R((n − m)θ) k, because rotating back by m and forward by n is rotating by n − m. The attention score depends on the content of q and k and on their distance, never on absolute position. A pattern learned at the start of a document ("the word two tokens back") works unchanged at position 3,000.
A two-dimensional example with θ = 0.5 radians per position: q = (1, 0) at position 2 rotates by 1 radian to (0.5403, 0.8415); k = (0.6, 0.8) at position 5 rotates by 2.5 radians to (−0.9595, −0.2818). Their dot product is −0.7556. Move both forward by eight positions, q to 10 and k to 13: the rotated vectors change completely, but the dot product is again −0.7556, which equals q · R(1.5) k, a rotation by the offset 3 × 0.5. The lab checks the same property numerically in eight dimensions.
Consequences you will meet
Context extension. A RoPE model trained at 4k tokens has never seen angles beyond 4k · θi for its slow pairs. Position interpolation and its refinements (NTK-aware scaling, YaRN) rescale positions or frequencies so a longer context maps into the trained range, followed by a short fine-tune on long documents. This is the rope_scaling entry in a model's config.
The base. The 10000 in θi is a hyperparameter, rope_theta in configs. Llama 3 raised it to 500,000 to slow the rotations for long context. A fine-tune must use the base model's value; changing it scrambles every learned attention pattern.
Take one pair of coordinates and write it as a complex number z = x0 + i·x1. Rotating by angle a is multiplication by eia. The real dot product of two 2-vectors u and v equals Re(u · v̄), where v̄ is the complex conjugate. For a query pair q at position m and a key pair k at position n:
Re( q eimθ · conj(k einθ) ) = Re( q k̄ ei(m−n)θ )Only the difference m − n survives. Summing over the d/2 pairs, each with its own θi, keeps the property.
Rotations preserve length, so RoPE never changes ‖q‖ or ‖k‖; it only changes the angle between them. With many pairs at different frequencies, the score for a fixed content pair, as a function of distance, is a sum of cosines, and for random vectors it tends to decay with distance. That gives a mild bias toward nearby tokens without any learned bias term.
Worked example by hand
Sinusoidal check: d = 4, position p = 3. Pair 0 has frequency 1, pair 1 has frequency 10000−2/4 = 0.01. PE[3] = [sin 3, cos 3, sin 0.03, cos 0.03] = [0.1411, −0.9900, 0.0300, 0.9996]. RoPE check with θ = 0.5: query (1, 0) at position 2 becomes (cos 1, sin 1) = (0.5403, 0.8415). Key (0.6, 0.8) at position 5 is rotated by 2.5: x′ = 0.6·cos 2.5 − 0.8·sin 2.5 = 0.6·(−0.8011) − 0.8·0.5985 = −0.9595, y′ = 0.6·0.5985 + 0.8·(−0.8011) = −0.2818. Dot product: 0.5403·(−0.9595) + 0.8415·(−0.2818) = −0.7556.
Edge cases
Implementations disagree on which coordinates form a pair. The lab and the RoPE paper pair neighbours (0,1), (2,3), …; Hugging Face Llama code pairs coordinate j with j + d/2 ("rotate half"). Both are valid, but weights trained with one layout give wrong outputs with the other. When you port a checkpoint, check which layout its code uses.
Common mistakes
Rotating the values. Symptom: outputs that drift with position. Fix: rotate q and k only.
Restarting positions at 0 for each new token during cached decoding. Symptom: generation is fine for the prompt and degrades immediately after. Fix: pass the absolute position offset, as the Week 5 lab does with start_pos.
Changing rope_theta or the pairing layout when loading weights. Symptom: perplexity near that of random text. Fix: copy the base model's config exactly.
Adding learned position embeddings on top of RoPE. Symptom: worse extrapolation and no gain. Fix: use one mechanism.
Check yourself
A query and key sit 3 positions apart. You move both 1,000 positions later. By how much does their RoPE score change?
Answer
Not at all. The score depends only on the offset, which is still 3 (up to floating-point rounding).
Module 2
Attention and the transformer block
Lecture 4.3 · 14 min read
Scaled dot-product attention, worked by hand
Attention is the one operation in a transformer that moves information between positions. Everything else, the feed-forward layers and normalizations, acts on each position separately. “Inside a transformer: where the parameters live” gave the formula; this lecture runs it on numbers small enough to check with a calculator, including the causal mask that makes a model generative.
Attention(Q, K, V) = softmax( Q Kᵀ / √dk + M ) V Mij = 0 if j ≤ i, −∞ if j > iQ, K, V are T × dk matrices, one row per position. M is the causal mask. Softmax runs along each row.
Each position asks a question (its query), advertises what it contains (its key), and offers a payload (its value). The query of position i is compared with the key of every position j by a dot product; the scores are scaled, masked, and turned into weights that sum to one; the output for position i is the weighted average of the values. Q, K and V are three different linear maps of the same input vectors, which is what lets a position look for something different from what it offers.
The example
Three tokens, dk = 2. The projections have already been applied:
Step 3, mask. Position i may not see positions after it. Set (1, 2), (1, 3) and (2, 3) to −∞. Row 1 is 0.7071, −∞, −∞; row 2 is 0.7071, 0.7071, −∞; row 3 is unchanged.
Step 4, softmax each row. e−∞ = 0, so masked entries get exactly zero weight. Row 1 has one finite entry, so its weights are [1, 0, 0]. Row 2 has two equal entries: [0.5, 0.5, 0]. Row 3: e0 = 1 and e0.7071 = 2.0281 twice, total 5.0562, so the weights are [1/5.0562, 2.0281/5.0562, 2.0281/5.0562] = [0.1978, 0.4011, 0.4011].
Look at what the mask did to position 2. Its query (1, 1) matches key 3 best (raw score 2). Without the mask its weights would be [0.2483, 0.2483, 0.5035] and it would copy mostly from token 3, the token it is supposed to predict. Training a language model without the mask is training it to read the answer; the loss falls to near zero and the model is useless at generation, where the future does not exist yet.
Why divide by √dk
If the entries of q and k are independent with mean 0 and variance 1, their dot product is a sum of dk terms each with variance 1, so it has variance dk. At dk = 128, typical scores have a standard deviation of about 11. Softmax of numbers that far apart is almost one-hot (softmax of [8, 0] already gives 0.99966), and the gradient of a saturated softmax is nearly zero, so the layer stops learning. Dividing by √dk returns the scores to unit variance at initialization. It is a fixed temperature chosen so training starts in the region where softmax has useful gradients.
Multi-head attention
One attention pattern per layer is limiting: a position may need to attend to the previous word for syntax and to a name ten sentences back for meaning. Multi-head attention splits d into h heads of size d/h, runs the computation above independently in each, concatenates the h outputs and applies an output map WO. The cost in parameters is the same as one big head, 4d² for WQ, WK, WV, WO without biases, because each projection is still d × d; only the reshaping differs. Grouped-query attention, used in Llama 3, keeps many query heads but shares each key and value head among several query heads, which shrinks the KV cache of “The KV cache and why decoding is bandwidth-bound”.
Cost
The score matrix is T × T per head. Doubling the context quadruples attention's compute and its memory for scores. Fused kernels such as FlashAttention never store the full matrix: they process blocks of keys and keep a running maximum and sum for the softmax, which is exact and uses memory linear in T. PyTorch exposes this as F.scaled_dot_product_attention, and the lab checks your hand-written version against it to within 10−6.
Deep dive · softmax, its gradient and numerical stability
Derivation
For one row of scores s, the weights are ai = esi / Σj esj. Differentiate ai with respect to sj by the quotient rule. When j = i, the numerator and denominator both depend on si: ∂ai/∂si = (esi Σ − esi esi) / Σ² = ai(1 − ai). When j ≠ i, only the denominator does: ∂ai/∂sj = −esi esj / Σ² = −aiaj.
∂ai / ∂sj = ai ( δij − aj )δij is 1 when i = j and 0 otherwise.
If one weight is near 1 and the rest near 0, every term ai(δij − aj) is near zero. That is the saturation the √dk scaling prevents. With scores [8, 0], a1 = 0.99966 and the largest derivative is a1(1 − a1) = 0.00034, compared with 0.25 for equal scores.
Numerical stability
ex overflows float32 above x ≈ 88.72. Softmax is unchanged by subtracting a constant from every score, since the constant's exponential cancels between numerator and denominator, so implementations subtract the row maximum first: the largest exponent becomes e0 = 1 and nothing overflows. Masked entries use −∞ (or the most negative finite number) so that e−∞ = 0 exactly. A row in which every entry is masked would give 0/0; causal masks never produce one, because every position may see itself.
Worked example by hand
Unmasked row 2 of the lecture: scores 0.7071, 0.7071, 1.4142. Subtract the max: −0.7071, −0.7071, 0. Exponentials: 0.4931, 0.4931, 1. Sum 1.9862. Weights 0.2483, 0.2483, 0.5035. Output 0.2483·(1, 0) + 0.2483·(0, 2) + 0.5035·(3, 1) = (1.7587, 1.0000). Compare (0.5, 1) with the mask: the first coordinate is dominated by token 3's value when the mask is missing.
Common mistakes
Masking after the softmax by zeroing weights. Symptom: rows that no longer sum to 1. Fix: mask the scores with −∞ before the softmax.
Softmax along the wrong axis. Symptom: columns sum to 1, outputs mix information from the future. Fix: softmax(dim=-1) over keys.
Using triu(0) instead of triu(1). Symptom: a position cannot see itself and the first row is all −∞, producing NaN. Fix: mask strictly above the diagonal.
Forgetting the scale. Symptom: training starts slowly or attention entropy collapses early. Fix: divide by √dk per head, where dk is the head size, not d.
Check yourself
In the example, what weight does position 3 put on itself, and why is it equal to its weight on position 2?
Answer
0.4011. Key 2 = (0, 1) and key 3 = (1, 1) give the same dot product with q3 = (0, 1), namely 1, so their scores and weights are equal.
Lecture 4.4 · 13 min read
The transformer block and counting its parameters
A modern decoder-only transformer is one block repeated L times: 32 times in Llama-2-7B and Llama-3-8B, 24 times in Qwen2.5-0.5B, twice in the lab's tiny GPT. Each block has the same two halves from “Inside a transformer: where the parameters live”, attention and a feed-forward network, wrapped in residual connections and normalization. The details of that wrapping are what make deep stacks trainable, and the shapes of the linear maps determine where the parameters, and therefore LoRA's targets, live.
The block, line by line
h = x + Attention( RMSNorm1(x) ) y = h + SwiGLU( RMSNorm2(h) )Pre-norm: normalize the input of each sublayer, never the residual stream itself.
Residual connections. Each sublayer adds its output to its input instead of replacing it. The derivative of x + f(x) with respect to x is I + ∂f/∂x, so the gradient from the loss reaches the first layer through a path of identities no matter how deep the stack, the same fix for vanishing gradients that Course 2 described for deep networks. A useful picture: the residual stream is a d-dimensional bus that runs from the embedding to the output head, and each sublayer reads from it and writes a correction back. The lab verifies that a block whose output maps are zero is exactly the identity.
Pre-norm. The original transformer normalized after the addition (post-norm), which put a normalization on the residual path and made deep stacks unstable without careful warmup. Normalizing only the sublayer's input keeps the residual path clean, and every current open model does it this way. A final RMSNorm before the output head normalizes the stream once at the end.
RMSNorm. LayerNorm subtracts the mean of the vector, divides by its standard deviation and applies a learned gain and bias. RMSNorm drops the mean and the bias: divide by the root mean square and multiply by a learned gain g. It is cheaper and works as well.
RMSNorm(x) = g ⊙ x / √( mean(x²) + ε )For x = (3, 4): mean(x²) = 12.5, √12.5 = 3.5355, output (0.8485, 1.1314) times g. Parameters: d.
SwiGLU. The Course 2 feed-forward network is two linear maps with a nonlinearity between them, d → 4d → d. Llama and Qwen use a gated variant with three maps: a gate projection and an up projection, both d → h, combined elementwise, then a down projection h → d. The gate uses SiLU, silu(z) = z · σ(z), a smooth ReLU that lets small negative values through (silu(1) = 0.7311, silu(−1) = −0.2689, silu(2) = 1.7616).
SwiGLU(x) = Wdown ( silu(Wgate x) ⊙ Wup x ) parameters = 3 · d · hThese are the gate_proj, up_proj and down_proj modules you targeted with LoRA. Choosing h ≈ 8d/3 makes 3dh = 8d², the same as a two-map network with h = 4d.
Counting parameters
With multi-head attention, no biases, and an untied output head, the whole model is:
N = V·d + L · ( 4d² + 3·d·h + 2d ) + d + d·VEmbedding, L blocks (attention, SwiGLU, two RMSNorm gains), final norm, output head.
Llama-2-7B has V = 32,000, d = 4,096, L = 32, h = 11,008. Per layer, attention is 4 · 4,096² = 67,108,864, SwiGLU is 3 · 4,096 · 11,008 = 135,266,304, and the two norms add 8,192, for 202,383,360 per layer and 6,476,267,520 for all 32. The embedding and the head add 131,072,000 each, and the final norm 4,096. Total: 6,738,415,616, the published 6.74 B. Two-thirds of every layer is the feed-forward network, which is why leaving gate_proj, up_proj and down_proj out of LoRA leaves most of the model untouched.
Grouped-query attention changes only the K and V projections. With nkv key/value heads of size dhead, attention costs 2d² + 2·d·nkv·dhead. Llama-3-8B has d = 4,096, 8 KV heads of size 128, h = 14,336 and V = 128,256: attention 41,943,040 per layer, SwiGLU 176,160,768, total 8,030,261,248 parameters. Its larger vocabulary puts 13% of the parameters in the two vocabulary matrices, against under 4% for Llama 2.
The lab's tiny GPT has V = 42 characters, d = 64, L = 2, h = 176: 2,688 + 2 · (16,384 + 33,792 + 128) + 64 + 2,688 = 106,048 parameters. You compute it from the formula, then confirm it with sum(p.numel() for p in model.parameters()). When the two numbers disagree, you have found either a bias you did not intend or a shape you got wrong, which makes the check a fast unit test for any architecture you write.
The same formula, read in the other direction, explains the shapes model families choose. Depth and width trade off at fixed size: Qwen2.5-0.5B is narrow (d = 896) and 24 layers deep, Llama-2-7B is 4,096 wide and 32 deep. Width grows the per-layer cost as d², so a model twice as wide with the same depth has roughly four times the parameters. When you read a config file, hidden_size, intermediate_size, num_hidden_layers, num_key_value_heads and vocab_size are all you need to reproduce the parameter count, and doing so is a good way to confirm you understand an unfamiliar architecture before fine-tuning it.
What dominates where
Weights per layer grow as d², so large models are almost entirely linear maps; norms are a rounding error.
Compute per token is about 2N FLOPs for the forward pass (one multiply and one add per weight), plus attention's 2·L·T·d for the scores at context T, which matters only when T is comparable to the feed-forward width.
Memory for activations in training grows with batch × T × d × L, which is what gradient checkpointing trades for compute (“The training run”).
Deep dive · residual streams, norms and the counting formula
Derivation
Stack L residual blocks: xL = x0 + Σl fl(xl−1). The Jacobian ∂xL/∂x0 is the product of (I + Jl) over layers, which expands to I plus terms of every order in the Jl. The identity term means the gradient at the input is at least the gradient at the output, however small the Jl. With post-norm, each factor becomes Nl(I + Jl), where Nl is the normalization's Jacobian, and products of L such matrices can shrink or grow geometrically. Pre-norm keeps the bare identity on the main path.
A second reason for pre-norm: since every sublayer adds to the stream, ‖x‖ grows with depth. Normalizing the sublayer's input means each sublayer sees inputs of unit scale regardless of depth, so the same initialization works for layer 1 and layer 32.
Worked example by hand
RMSNorm versus LayerNorm on x = (3, 4), gain 1. RMSNorm: mean(x²) = (9 + 16)/2 = 12.5, divide by 3.5355: (0.8485, 1.1314). LayerNorm: mean 3.5, centred (−0.5, 0.5), standard deviation 0.5, output (−1, 1). LayerNorm discards the shared offset 3.5; RMSNorm keeps the direction of x and fixes only its scale.
The counting formula for a block with d = 32, h = 88 (the lab's test block): 4 · 32² = 4,096 for attention, 3 · 32 · 88 = 8,448 for SwiGLU, 2 · 32 = 64 for the norms, total 12,608. The lab prints exactly this.
Code walkthrough
def count_params(V, d, L, hidden):
attn = 4 * d * d # q, k, v, o: d x d each, no bias
mlp = 3 * d * hidden # gate, up: d x h; down: h x d
norm = 2 * d # two RMSNorm gains per block
return V * d + L * (attn + mlp + norm) + d + d * V
count_params(32000, 4096, 32, 11008) # 6,738,415,616
Common mistakes
Forgetting the untied head. Symptom: your count is short by V·d (131 M for Llama 2). Fix: check tie_word_embeddings in the config.
Leaving bias=True on the linear maps. Symptom: a count that exceeds the formula by a few thousand per layer. Fix: Llama-style models have no biases; Qwen2.5 has biases on q, k and v only, so add them.
Using 4d² for attention in a GQA model. Symptom: Llama-3-8B counts as 8.84 B. Fix: K and V are d × (nkv · dhead).
Normalizing the residual stream in a pre-norm block. Symptom: training is unstable at depth. Fix: normalize only what goes into the sublayer.
Check yourself
How many parameters does one SwiGLU block with d = 896 and h = 4,864 (the Qwen2.5-0.5B shape) contain?
Answer
3 · 896 · 4,864 = 13,074,432.
Module 3
Training a tiny GPT
Lecture 4.5 · 14 min read
Training a tiny GPT, then sampling from it
With a tokenizer, embeddings, attention and blocks, a GPT is three more lines: embed the tokens, run the blocks, apply a final norm and the output head. Training is the Course 2 classifier applied at every position at once. This lecture walks through the lab's run on a 7,215-character story, what its loss numbers mean, and the decoding rules that turn next-token probabilities into text.
The objective
Take a window of T + 1 tokens. The inputs are tokens 1…T, the targets are tokens 2…T+1, the same window shifted by one. Because of the causal mask, position t sees only tokens 1…t, so one forward pass produces T predictions, each of which is a full next-token problem. The loss is cross-entropy averaged over the T positions and the batch. One window of 64 characters gives 64 training examples for the price of one pass, which is why language models learn so much from so little text.
loss = −(1 / BT) Σb,t log pθ( xb,t+1 | xb,1 … xb,t )At initialization every token is about equally likely, so the loss starts near log V. For V = 42 that is 3.738; the lab measures 3.844 on its first batch.
The lab's run
The model is the one from “The transformer block and counting its parameters”: character vocabulary of 42, d = 64, 2 layers, 4 heads, SwiGLU width 176, RoPE positions, dropout 0.1, 106,048 parameters. The first 90% of the story trains, the last 10% validates. AdamW with learning rate 2·10−3, weight decay 0.1, a one-cycle schedule, gradient clipping at 1.0, batches of 32 windows of 64 characters, 400 steps. On a laptop CPU that takes about twenty seconds.
Validation loss bottoms out around 1.80 nats per character after roughly 175 steps and then rises while training loss keeps falling: 6,500 characters is not much text, and the model starts memorizing it. The lab keeps the checkpoint at the minimum, the rule from “Reading the loss curve”. To judge whether 1.80 is good, compare baselines on the same validation text. Character frequencies alone (a unigram model) give 2.87. Predicting each character from the previous one (a bigram model) gives 2.28. The transformer's 1.80 means it uses longer context: a perplexity of e1.80 ≈ 6.0 choices per character against 9.8 for the bigram.
The lab also counts compute. Training costs about 6 FLOPs per parameter per token (2 for the forward pass, 4 for the backward), so 400 steps × 32 × 64 = 819,200 tokens at 106,048 parameters is 5.2 · 1011 FLOPs. A 7B model trained on 2 trillion tokens needs 6 · 7·109 · 2·1012 = 8.4 · 1022, a hundred billion times more. The code is the same.
From probabilities to text
Generation runs the model, takes the logits at the last position, picks a token, appends it, and repeats. The picking rule matters as much as the model. Take a toy distribution over four tokens, p = [0.5, 0.3, 0.15, 0.05], with logits log p.
Greedy always takes the most likely token. It is deterministic and right for short structured outputs such as JSON fields, but on open text it loops: the lab's greedy sample settles into "the stort the schoolmaster the stort" within a line, because once a phrase is likely, repeating it makes it more likely.
Temperature divides the logits by T before the softmax, which is the same as raising each probability to the power 1/T and renormalizing. At T = 0.5 the toy distribution sharpens to [0.685, 0.247, 0.062, 0.007]; at T = 2 it flattens to [0.379, 0.294, 0.208, 0.120]. Entropy rises with temperature from near 0 (greedy) toward log 4 = 1.386 (uniform); at T = 1 it is 1.142.
pi(T) = exp(zi / T) / Σj exp(zj / T) ∝ pi1/TT → 0 approaches greedy, T = 1 is the model's own distribution, T > 1 flattens it.
Top-k keeps the k most likely tokens and renormalizes. With k = 2 the toy becomes [0.625, 0.375, 0, 0]. It removes the long tail of nonsense, but a fixed k is too many when the model is confident and too few when it is not.
Top-p (nucleus sampling) keeps the smallest set of most likely tokens whose total probability reaches p. With p = 0.9: cumulative mass 0.5, 0.8, 0.95, so three tokens survive and renormalize to [0.526, 0.316, 0.158, 0]. With p = 0.75 two survive. The kept set adapts: one token when the model is sure, dozens when it is not. Top-p 0.9 to 0.95 with temperature 0.7 to 1.0 is a common default for chat; temperature 0 or near it for extraction and code.
In the lab, temperature 0.6 with top-k 10 produces mostly real words in story-like order; temperature 1.0 with top-p 0.9 produces plausible but misspelled words; temperature 1.5 produces character soup with capital letters in the middle of words. You will measure it: about 71% of the words sampled at T = 0.5 occur in the training text, 46% at T = 1.0 and 21% at T = 1.5.
For fine-tuning, decoding settings are part of the evaluation. Compare a base model and a fine-tune with the same temperature, top-p and seed, or the comparison measures your sampler rather than your training.
Deep dive · loss at initialization, temperature and nucleus sampling
Derivation
At initialization the output logits are small random numbers, so the softmax is close to uniform over V tokens and every target has probability about 1/V. Cross-entropy is −log(1/V) = log V. For V = 42, log 42 = 3.738; for Llama 2's 32,000 tokens, 10.37; for Llama 3's 128,256, 11.76. A first-step loss far above log V means the logits are too large (bad initialization or a missing norm); far below means the targets leak into the inputs, usually a missing mask or an unshifted label.
Temperature as a power: exp(zi/T) = (exp zi)1/T, and exp zi is proportional to pi, so pi(T) ∝ pi1/T. At T = 0.5 that squares the probabilities: 0.25, 0.09, 0.0225, 0.0025, sum 0.365, normalized 0.685, 0.247, 0.062, 0.007.
Worked example by hand
Top-p implementation detail: sort probabilities descending, compute the cumulative sum, and drop a token when the mass before it already reaches p. For p = 0.9 and [0.5, 0.3, 0.15, 0.05], the mass before each token is 0, 0.5, 0.8, 0.95; only the last has mass before it ≥ 0.9, so three tokens survive with total 0.95. The rule keeps the token that crosses the threshold, and it always keeps the first token, so top-p never empties the distribution. Applied after top-k = 2, top-p 0.9 sees [0.625, 0.375]; mass before is 0 and 0.625, so both stay.
Edge cases
Temperature exactly 0 divides by zero; implementations special-case it as argmax. Top-k with k ≥ V does nothing. Ties at the k-th logit keep all tied tokens in a logits < kth implementation, which is harmless. Repetition penalties, which divide the logits of tokens already generated, are a heuristic on top of these and change the distribution in ways that are hard to evaluate; prefer fixing the model.
Common mistakes
Shifting labels twice. Hugging Face models shift internally when you pass labels=input_ids; shifting yourself as well trains the model to predict two tokens ahead. Symptom: loss stalls high. Fix: shift in exactly one place.
Not cropping the context to the block size in a model with learned positions. Symptom: an index error after T tokens. Fix: feed idx[:, -block_size:].
Comparing models with different decoding settings. Symptom: a "better" model that only had a lower temperature. Fix: fix temperature, top-p and seed across models.
Reporting sampled text from a model evaluated at its last checkpoint instead of its best. Symptom: memorized training sentences in the output. Fix: reload the checkpoint at the validation minimum.
Check yourself
With p = [0.5, 0.3, 0.15, 0.05] and top-p = 0.75, which tokens survive and with what probabilities?
Answer
The first two. Mass before each is 0, 0.5, 0.8, 0.95, so tokens 3 and 4 are dropped. Renormalized: 0.5/0.8 = 0.625 and 0.3/0.8 = 0.375.
Everything runs on a laptop CPU with PyTorch alone, in about a minute and a half. No GPU, no Hugging Face libraries and no downloads: the training text is a short story embedded in the notebook.
Step 1Byte-pair encoding
Write get_pair_counts and merge, then train_bpe, encode and decode. Train 200 merges on the story, print the first ten, and confirm that the story and an unseen sentence with Vietnamese characters both round-trip exactly. Record bytes per token.
Step 2Positions and attention
Implement sinusoidal encodings and RoPE, and check that a RoPE score depends only on the offset between positions. Write causal attention and match F.scaled_dot_product_attention to 10−6. Run it on the “Scaled dot-product attention, worked by hand” matrices.
Build MultiHeadAttention, SwiGLU and the pre-norm Block; prove the layer is causal by perturbing the last token. Assemble TinyGPT with d = 64, 2 layers, 4 heads and SwiGLU width 176, and write count_params from the “The transformer block and counting its parameters” formula.
Checkpoint 2
How many parameters does the tiny GPT have, as reported by both your formula and sum(p.numel())?
Step 4Train and sample
Write train_step, train for 400 steps, plot both loss curves and keep the checkpoint at the validation minimum. Implement temperature, top-k and top-p in filter_logits and generate at four settings. The practice set adds compression curves, sliding-window attention and FLOP counts; the mini-project compares the model with unigram and bigram baselines.
Week 5 · 5 lectures · quiz · lab
Quantization, inference and serving
What happens after training: storing weights in fewer bits without losing the model, why decoding speed is set by memory bandwidth, the KV cache and its bill, and the batching and drafting tricks that let one GPU serve many users.
Video lectures · Week 5
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
Every weight, activation and gradient is stored in some number format, and the format sets three things at once: how much memory a model needs, how fast it runs (bytes moved per token, “The KV cache and why decoding is bandwidth-bound”), and how much the arithmetic can be trusted. Week 2 used the formats as given: bf16 weights, fp32 optimizer state, 4-bit for QLoRA. This week takes them apart.
Floating point
A floating-point number has a sign bit, an exponent field and a mantissa (fraction) field. The value is (−1)sign × 1.mantissa × 2exponent − bias. The exponent bits set the range, how large and how small a number can be. The mantissa bits set the precision, how finely numbers near any given value are spaced. With a fixed budget of 16 bits, you choose between the two.
Format
Bits (sign · exp · mantissa)
Largest value
Smallest normal
Epsilon (gap above 1)
Decimal digits
fp32
1 · 8 · 23
3.40 × 1038
1.18 × 10−38
1.19 × 10−7
7.2
bf16
1 · 8 · 7
3.39 × 1038
1.18 × 10−38
7.81 × 10−3
2.4
fp16
1 · 5 · 10
65,504
6.10 × 10−5
9.77 × 10−4
3.3
int8
8, two's complement
127
integers only
1
–
int4
4, two's complement
7 (min −8)
integers only
1
–
bf16 ("brain float") is fp32 with the bottom 16 mantissa bits cut off. It keeps fp32's 8 exponent bits and therefore its range: anything fp32 can hold, bf16 can hold approximately. fp16 spends three of those bits on the mantissa instead, so it is eight times more precise but overflows above 65,504 and flushes values below about 6 × 10−5 into the subnormal range, where precision drops, and below 6 × 10−8 to zero. The lab shows both effects in two lines: 1 + 0.001 is exactly 1 in bf16 (the gap above 1 is 0.0078) but 1.0009765625 in fp16; 70,000 is inf in fp16 and 70,144 in bf16.
That is why training moved to bf16. Activations occasionally exceed 65,504 and gradients are often smaller than 10−5; fp16 training needed loss scaling (multiplying the loss by a large constant before backward and dividing gradients afterwards) to keep gradients above underflow, and still diverged on overflow. bf16 needs neither. Its poor precision is tolerable because the optimizer keeps an fp32 master copy of the weights (“Full fine-tuning and its memory bill”): small updates that would vanish in bf16 accumulate in fp32.
How much rounding
Rounding to nearest makes the relative error at most half the epsilon: 2−8 ≈ 0.39% for bf16 and 2−11 ≈ 0.049% for fp16. The lab casts 100,001 values spanning seven orders of magnitude and finds a worst case of 0.389% for bf16 and 0.0487% for fp16, just under the bounds. Relative error is constant across magnitudes, which is the point of floating point: 0.001 and 1000 are both stored to about 2.4 significant digits in bf16. The spacing between neighbours scales with the number: in bf16 the numbers between 256 and 512 are 2 apart.
Integers and newer formats
Integer formats have uniform spacing and no exponent. On their own they can only hold whole numbers in a small range, so quantization pairs them with a floating-point scale: store q as an integer and reconstruct ŵ = q × scale. “Absmax and zero-point int8, with the error they cost” builds that. Two 8-bit float formats sit in between and are now common for training and inference on recent GPUs: E4M3 (4 exponent bits, 3 mantissa, largest value 448) for weights and activations, and E5M2 (largest 57,344) for gradients, which need range more than precision.
The memory bill
Format
Bytes per weight
Llama-2-7B (6.74 B) weights
fp32
4
26.96 GB
bf16 / fp16
2
13.48 GB
int8 (+ small scales)
1
6.74 GB
4-bit, block 64, fp16 scales
0.53
3.58 GB
Halving the bytes halves the memory needed to hold the model, and, as “The KV cache and why decoding is bandwidth-bound” shows, roughly doubles decoding speed on the same hardware, because generating each token reads every weight once. That is the whole economic case for quantization: a 7B model that needs a 16 GB GPU in bf16 fits a laptop at 4 bits and runs faster there.
Formats also mix inside a single operation. A bf16 matrix multiply on a GPU multiplies bf16 inputs but accumulates the sums in fp32, because adding thousands of products in a format with 2.4 significant digits would lose most of them; the result is rounded to bf16 only when written out. Normalization layers and softmax are usually computed in fp32 for the same reason, which is what prepare_model_for_kbit_training arranges for QLoRA. Quantized inference follows the same pattern: weights are stored in 4 or 8 bits, expanded to bf16 or fp16 just before each multiply, and accumulated in higher precision. The stored format saves memory and bandwidth; the compute format protects accuracy.
Which format to use where: train in bf16 with fp32 master weights and optimizer state; keep the merged bf16 checkpoint as the source of truth (“Merge, quantize, serve”); serve in bf16 when memory allows, int8 when it is tight, 4-bit on laptops and for QLoRA's frozen base. Never quantize the optimizer state of a full fine-tune casually, and never fine-tune further from a quantized checkpoint when the bf16 one exists.
Deep dive · decoding a bf16 and an fp16 number by hand
Derivation
For a normal number with e exponent bits and m mantissa bits, the stored exponent E runs from 1 to 2e − 2 (all zeros means zero or subnormal, all ones means infinity or NaN), and the bias is 2e−1 − 1: 127 for fp32 and bf16, 15 for fp16. The largest value is the largest mantissa, 2 − 2−m, at the largest exponent, 2e−1 − 1.
Epsilon is 2−m: the next number after 1.000…0 is 1.000…1. Round-to-nearest moves a value by at most half a step, and the step relative to the value is between 2−m−1 and 2−m, so the relative error is at most 2−m−1.
Worked example by hand
Store 0.1 in bf16. 0.1 = 1.6 × 2−4. The mantissa field holds the fraction 0.6 in 7 bits: 0.6 × 128 = 76.8, rounded to 77. The stored value is (1 + 77/128) × 2−4 = 1.6015625 / 16 = 0.10009765625, a relative error of 0.098%. In fp16 the fraction gets 10 bits: 0.6 × 1024 = 614.4, rounded to 614, giving (1 + 614/1024)/16 = 0.0999755859375, error 0.024%. Both match what PyTorch prints.
Common mistakes
Running fp16 inference on a model trained in bf16. Symptom: inf or NaN in a few layers' activations, garbage output. Fix: use bf16, or fp32 on hardware without bf16.
Accumulating sums in bf16. Symptom: a running loss or a long dot product that stops changing. Fix: accumulate in fp32; matrix-multiply kernels already do.
Expecting bf16 weights to round-trip fp32 checkpoints exactly. Symptom: tiny diffs after save and load. Fix: compare with a tolerance of about 0.4% relative.
Confusing range with precision. Symptom: choosing fp16 "for accuracy" and overflowing. Fix: range from exponent bits, precision from mantissa bits; LLM activations need range.
Check yourself
What is the gap between consecutive fp16 numbers in the interval [1024, 2048)?
Answer
1. The exponent is 210, and the mantissa step is 2−10, so the spacing is 210 × 2−10 = 1. Above 2,048, fp16 cannot store odd integers.
Lecture 5.2 · 13 min read
Absmax and zero-point int8, with the error they cost
Quantization maps real numbers onto a small grid of integers plus a scale. The question is always the same: where to put the grid so that the weights that matter land close to a grid point. This lecture builds the two basic int8 schemes on six numbers, computes their error, and shows why the choice of how many values share a scale matters more than the scheme itself.
Absmax (symmetric) quantization
Find the largest magnitude in the tensor, map it to 127, and scale everything else proportionally.
scale = max|w| / 127 q = round( w / scale ) ∈ [−127, 127] ŵ = q · scaleZero maps to the integer 0 exactly. −128 is left unused so the grid is symmetric.
The example vector is x = [0.42, −1.27, 0.08, 2.40, −0.66, 1.13]. The largest magnitude is 2.40, so scale = 2.40 / 127 = 0.018898. Dividing: 0.42 / 0.018898 = 22.22, −1.27 gives −67.20, 0.08 gives 4.23, 2.40 gives exactly 127, −0.66 gives −34.93, 1.13 gives 59.80. Rounding gives the int8 codes [22, −67, 4, 127, −35, 60]. Multiplying back: [0.4157, −1.2661, 0.0756, 2.4000, −0.6614, 1.1339].
The errors are 0.0043, 0.0039, 0.0044, 0, 0.0014 and 0.0039. None can exceed half a step, scale / 2 = 0.0094, because rounding moves a value at most halfway to the next grid point. The largest is 0.0044, on the value 0.08. In relative terms that is 5.5% on the small value 0.08 and 0.34% on 1.13: absmax quantization has constant absolute error, so small weights are relatively the worst served.
Zero-point (asymmetric) quantization
Absmax wastes codes when the values are lopsided. If every value is positive, as after a ReLU, the codes −127…−1 are never used and you have effectively seven bits. Zero-point quantization fits the grid to the actual range [min, max] and shifts it with an integer offset z.
scale = (max − min) / 255 z = round( −min / scale ) q = clamp( round(w / scale) + z, 0, 255 ) ŵ = (q − z) · scaleq is an unsigned byte. The real number 0 maps to the integer z, exactly.
Same vector: min = −1.27, max = 2.40, so scale = 3.67 / 255 = 0.014392 and z = round(1.27 / 0.014392) = round(88.24) = 88. The codes are [117, 0, 94, 255, 42, 167]: −1.27 lands on 0 and 2.40 on 255, so all 256 codes span the data. Reconstruction gives [0.4174, −1.2665, 0.0864, 2.4035, −0.6620, 1.1370]. The step is 24% smaller than absmax's (0.0144 against 0.0189), so the worst-case error bound drops from 0.0094 to 0.0072. On these six numbers the realized maximum error happens to be larger, 0.0070 against 0.0044, a reminder that a bound is not a result: with only six values, where each one falls relative to the grid is luck. On a large matrix, the average error tracks the step size.
The price of zero-point is arithmetic. A matrix product with zero-points expands into the integer product plus correction terms involving z, which kernels must compute. For weights, which are roughly symmetric around zero, absmax is nearly as good and simpler, so weight quantization is usually symmetric; zero-point is common for activations.
Error analysis
For values spread over many grid steps, the rounding error behaves like a uniform random variable on [−Δ/2, Δ/2], where Δ is the scale. Its variance is Δ²/12, so its root mean square is Δ/√12 ≈ 0.29Δ. For the example, Δ/√12 = 0.0055; the realized RMS over the six values is 0.0034. Each extra bit halves Δ, cuts the error variance by four, and adds 10·log104 ≈ 6.02 dB of signal-to-quantization-noise ratio (SQNR). From int8 to int4 you lose about 24 dB. The lab measures 43.2 dB for int8 per row against 19.4 dB for int4 in blocks of 64 on a Gaussian matrix, a gap of 23.8 dB.
Granularity: who shares a scale
The scale is set by the largest value in its group, so the group is the real design decision. One scale per tensor is cheapest to store but lets a single large weight stretch the grid for millions of others. One scale per row (per output channel) costs one float per row, nothing for a 4,096-wide matrix, and confines each outlier to its own row. The lab quantizes a 256 × 256 matrix of Gaussian weights with standard deviation 0.02. Clean, the relative error is 1.04% per tensor and 0.69% per row. Then it plants a single weight of 1.0, fifty standard deviations out. Per-tensor error jumps to 11.15%, because the step is now set by that one value and most weights round to a handful of codes near zero. Per-row error is 0.97%, and only one row of 256 is affected.
Activations are harder than weights. Weights are fixed, so their scales can be computed once, offline, with as much care as you like. Activations change with every input, so their scales must be computed on the fly per token (dynamic quantization) or estimated in advance from calibration data (static quantization), and the outlier dimensions of “Four bits: block-wise quantization, NF4 and outliers” live in the activations. That is why the common deployment formats quantize weights only (W8A16, W4A16: 8- or 4-bit weights, 16-bit activations), and why the speed gain at batch 1 comes from moving fewer weight bytes rather than from integer arithmetic.
On the trained digits MLP in the lab, both int8 variants keep test accuracy at 97.59%, identical to fp32. On the tiny GPT, int8 per row changes validation perplexity from 7.270 to 7.267. Int8 weight quantization with per-channel scales is, for practical purposes, free; the interesting questions start at four bits.
Deep dive · rounding error, SQNR and what it does to a matrix product
Derivation
Let e = ŵ − w be the rounding error. If w is spread over many steps of size Δ, its position within a step is close to uniform, so e is uniform on [−Δ/2, Δ/2]. Its mean is 0 and its variance is ∫ e² de / Δ over that interval, which is (1/Δ) · [e³/3] from −Δ/2 to Δ/2 = (1/Δ) · (Δ³/24 + Δ³/24) = Δ²/12.
For b-bit absmax on values bounded by A, Δ = A / (2b−1 − 1). The signal power of w is σ². SQNR = σ² / (Δ²/12) and in decibels 10·log10(12σ²/Δ²). Each extra bit roughly halves Δ, adding 20·log102 = 6.02 dB. For Gaussian weights, A is the maximum of the group, about 3σ for a group of 64 and larger for bigger groups, which is why smaller groups give higher SQNR.
Now the matrix product. With y = Wx and errors eij independent of each other and of x, the error in output i is Σj eijxj, with variance din · (Δ²/12) · E[x²]. The output itself has variance din · σ² · E[x²]. The ratio is the same Δ²/(12σ²): a matrix product does not amplify relative weight error, it carries it through. Stacking 32 layers does add the errors up, which is why large models are more sensitive than the lab's two-layer one.
Worked example by hand
Absmax on the lecture vector, value 0.08: 0.08 / 0.018898 = 4.233, round to 4, back to 4 × 0.018898 = 0.0756, error 0.0044. Zero-point, same value: 0.08 / 0.014392 = 5.559, round to 6, plus z = 94, back to (94 − 88) × 0.014392 = 0.0864, error 0.0064.
Common mistakes
Using −128 in symmetric quantization. Symptom: the most negative weight gets more error than the most positive. Fix: clamp to [−127, 127].
Computing the scale from a calibration subset, then meeting larger values. Symptom: clipped weights or activations. Fix: for weights use the true max; for activations, calibrate on representative data and clamp.
Forgetting z in dequantization. Symptom: every reconstructed value is shifted by z · scale. Fix: ŵ = (q − z) · scale.
One scale for a whole tensor with outliers. Symptom: accuracy falls sharply at 8 bits on a large model. Fix: per-channel or per-group scales.
Check yourself
A tensor has max |w| = 2.54. What is the absmax int8 scale, and what code does 1.27 receive?
Answer
scale = 2.54 / 127 = 0.02. 1.27 / 0.02 = 63.5, which sits exactly between two codes; round-half-to-even gives 64 (PyTorch's rule). Exact ties are rare in real weights.
Lecture 5.3 · 13 min read
Four bits: block-wise quantization, NF4 and outliers
At eight bits there are 255 codes and almost any reasonable scheme works. At four bits there are 16, and every design decision shows up in the error. Two ideas make 4-bit weights practical: give every small block of weights its own scale, and place the 16 levels where weights actually are rather than evenly. Both are inside QLoRA's NF4 format and inside llama.cpp's Q4 formats you used in “Merge, quantize, serve”.
Block-wise scales
Flatten the weight matrix and cut it into blocks of B consecutive values, typically 32, 64 or 128. Each block stores its own absmax scale in fp16 or fp32, and each weight stores a 4-bit code. The scale is now set by the largest of 64 values instead of the largest of millions, so the step size follows the local magnitude of the weights. The cost is the scales, which add their bits spread over the block.
bits per weight = code bits + scale bits / B 4 + 16/64 = 4.25 4 + 32/64 = 4.5 4 + 16/32 = 4.5Llama-2-7B at 4.25 bits per weight: 3.58 GB, against 13.48 GB in bf16.
Smaller blocks follow the weights more closely and cost more bits. In the lab's mini-project on the digits MLP, 4-bit integer codes keep accuracy within 0.4 points of fp32 at every block size from 32 to 512, while 2-bit codes drop from 76% at block 32 to 17% at block 512. The fewer bits per code, the more the block size matters.
Where to put 16 levels
Evenly spaced int4 levels for a block normalized to [−1, 1] are k/7 for k = −7…7: fifteen levels with zero exact. Trained weights are not uniform; they are close to a normal distribution, with most values near zero and few near the block maximum. Evenly spaced levels spend as many codes on the sparse tails as on the crowded centre.
NormalFloat-4 (NF4), from the QLoRA paper, places the levels at quantiles of a standard normal distribution instead, so that each of the 16 codes is used about equally often by Gaussian weights. Spending codes where the values are is optimal in the information-theoretic sense: every code carries as close to 4 bits as possible. The construction needs one more detail: a symmetric quantile grid has no exact zero, and zero matters (padding, pruned weights). NF4 uses 8 positive levels and 7 negative ones plus an exact 0, then rescales so the extremes are ±1.
NF4 = [−1, −0.6962, −0.5251, −0.3949, −0.2844, −0.1848, −0.0911, 0, 0.0796, 0.1609, 0.2461, 0.3379, 0.4407, 0.5626, 0.7230, 1]Built in the lab from scipy's normal quantile function and checked against the table bitsandbytes ships, to 10−6.
On a 256 × 256 Gaussian matrix with blocks of 64, the lab measures a relative error of 10.74% for int4 and 9.20% for NF4, at the same 4.25 bits per weight. On the digits MLP, NF4 in blocks of 64 keeps the full 97.59% while int4 drops to 97.22%. The improvement is not dramatic in any one layer, but it is free: the codebook is a 16-entry lookup table.
QLoRA adds double quantization: the per-block fp32 scales are themselves quantized to 8 bits in groups of 256, with one fp32 scale per group. The overhead falls from 32/64 = 0.5 bits per weight to 8/64 + 32/(64 · 256) = 0.127, for 4.127 bits per weight in total. On a 65B model that saves 3.03 GB, which was the margin that let the paper fit 65B fine-tuning on one 48 GB GPU.
Why outliers decide everything
At 4 bits, one large value in a block is a disaster for its neighbours. Take a block of 64 standard normal values and replace one with 20. The absmax scale becomes 20/7 = 2.857, half a step is 1.43, and every value with magnitude below 1.43 rounds to code 0. For a standard normal that is 84.7% of values; in the lab's random block, 56 of the 63 ordinary values become exactly zero. Without the outlier, 14% of that block rounds to zero.
Large language models have exactly this problem, and it gets worse with size. Beyond a few billion parameters, a small number of hidden dimensions carry activations tens of times larger than the rest, consistently across tokens, and the weights that read from them are correspondingly unusual. The LLM.int8() paper found that zeroing these few dimensions destroys the model, and that naive 8-bit quantization of activations fails at that scale for this reason. The practical methods all handle outliers somehow:
Mixed precision (LLM.int8()): multiply the few outlier dimensions in fp16 and the rest in int8.
Small blocks (NF4, Q4_K): each outlier spoils only its own block of 32–64 weights.
Activation-aware scaling (AWQ, SmoothQuant): rescale channels so that the difficulty moves from activations to weights or protect the weights that see large activations.
Error-compensating rounding (GPTQ): quantize weights one column at a time and adjust the remaining columns to cancel the error just made, using second-order information from calibration data.
For fine-tuning, the practical rules are short. QLoRA's NF4 base with bf16 adapters loses nothing measurable for training purposes. For serving, Q4_K_M (block-wise 4-bit with 6-bit block scales in groups) is the usual laptop choice, and the one to evaluate on your gold set before shipping, because the loss from 4 bits is model- and task-dependent.
Let Φ−1 be the standard normal quantile function. Pick an offset δ = 0.9677 so the extreme quantiles are finite. The positive half takes 9 evenly spaced probabilities from δ down to 0.5, drops the last (0.5, which maps to 0), and keeps Φ−1 of the remaining 8. The negative half takes 8 probabilities from δ to 0.5, drops the last, and keeps −Φ−1 of the remaining 7. Add an exact 0, sort, and divide by the largest magnitude. That gives 8 + 7 + 1 = 16 levels with ±1 at the ends.
Quantizing a block: compute s = max|w| over the block, normalize u = w / s ∈ [−1, 1], and store the index of the nearest level for each u. Dequantization is a table lookup times s. Because every block is normalized to [−1, 1], the codebook is shared by the whole model; only the scales are per block.
Worked example by hand
A block with max |w| = 0.05 contains w = 0.012. Normalize: 0.012 / 0.05 = 0.24. The nearest NF4 levels are 0.1609 and 0.2461; 0.24 is 0.0061 from the second, so the code is the index of 0.2461 and the reconstruction is 0.2461 × 0.05 = 0.01231, error 0.0003. With int4 levels k/7, the neighbours are 1/7 = 0.1429 and 2/7 = 0.2857; 0.24 is nearer 0.2857, reconstruction 0.01429, error 0.0023, seven times larger. Values near the centre of the distribution are exactly where NF4's denser levels pay off.
Memory arithmetic
Double quantization, per weight: 4 bits for the code, 8 bits for its block's quantized scale shared by 64 weights (0.125 bits), and 32 bits for the second-level scale shared by 64 × 256 weights (0.00195 bits): 4.127 bits. Versus 4.5 bits with fp32 block scales, the saving is 0.373 bits per weight, 3.03 GB for 65 billion weights.
Common mistakes
Assuming 4-bit means 0.5 bytes per weight. Symptom: memory estimates 6–12% too low. Fix: add scale bits / block size.
Quantizing embeddings and the output head as aggressively as linear layers. Symptom: rare tokens degrade first. Fix: most schemes keep these at 6–8 bits or higher.
Comparing quantized models by perplexity alone. Symptom: a 4-bit model that looks fine on perplexity but fails on your structured outputs. Fix: run the gold set.
Fine-tuning from a GGUF or 4-bit checkpoint when bf16 exists. Symptom: adapters fit the quantization noise. Fix: QLoRA quantizes on load from the bf16 source.
Check yourself
Blocks of 32 with fp16 scales and 4-bit codes: how many bits per weight, and how large is Llama-2-7B?
Generating text is a loop: run the model, take one token, append it, run again. Done naively, step t recomputes everything for all t tokens so far, and generating n tokens costs work proportional to n². The KV cache removes the repetition, and in doing so changes what limits speed from arithmetic to memory traffic. Both facts drive every serving decision in “Serving: batching, multi-LoRA and speculative decoding”.
What can be cached
Under the causal mask, the representation of token j at every layer depends only on tokens 1…j. When token t + 1 arrives, nothing about tokens 1…t changes. The only thing a new token needs from the past is, at each layer, the keys and values of every earlier position: its query is compared with their keys, and their values are averaged. So keep them. Each step then processes one new token: compute its q, k and v at every layer, append k and v to the cache, attend with q over the full cache, and continue. With RoPE, keys are stored already rotated at their own positions, and the new token is rotated at its absolute position, which is why the lab passes a start_pos offset.
The cache is exact. The lab feeds a 30-token sequence through the model once, then again as a 10-token prefill followed by 20 single-token steps, and the logits agree to 4.8 × 10−7, which is float32 rounding. Greedy generation of 400 tokens produces identical tokens with and without the cache; on a laptop CPU the cached version runs two to four times faster for this tiny model, depending on the machine, and the gap grows with length and model size.
The memory bill
Each layer stores one key and one value vector per KV head per token.
Llama-2-7B has 32 layers and 32 KV heads of size 128. Per token in fp16: 2 · 32 · 32 · 128 · 2 = 524,288 bytes, exactly half a mebibyte. At 4,096 tokens that is 2,147,483,648 bytes, 2.15 GB (2 GiB) for a single sequence. A batch of eight 4k sequences needs 17.2 GB of cache, more than the 13.48 GB of weights. One 32k-token sequence needs 17.2 GB on its own. For long contexts and many users, the cache, not the model, is what fills the GPU.
Grouped-query attention is the architectural answer. Llama-3-8B has 32 query heads but only 8 KV heads, each shared by 4 query heads. Its cache is a quarter of Llama 2's: 131,072 bytes per token, 0.54 GB at 4k. The lab's memory planner shows the consequence on a 24 GB card with 1 GB reserved: Llama-2-7B in fp16 fits 4 concurrent 4k sequences, Llama-3-8B fits 12; with 4.25-bit weights, 9 and 34. Quantizing the cache itself to 8 bits halves it again and is supported by vLLM and llama.cpp.
Prefill and decode
Serving a request has two phases with opposite characters.
Prefill processes the whole prompt in one forward pass, all positions in parallel, and fills the cache. It does about 2N FLOPs per prompt token, with every weight read once and used for every token: for a 4,096-token prompt on a 7B model, 2 · 6.74 × 109 · 4,096 = 5.5 × 1013 FLOPs, about 0.18 s at a sustained 300 TFLOP/s. Prefill is compute-bound, and it sets the time to first token.
Decode produces one token per forward pass. Every weight must still be read from memory, but each is used for only one token's multiply-add. At batch 1 in fp16, that is 2 FLOPs per 2 bytes read: one FLOP per byte. A GPU that can do 300 TFLOP/s but reads 1,000 GB/s needs 300 FLOPs per byte to keep its arithmetic busy. Decode uses a third of a percent of the compute; it is waiting on memory.
The bandwidth bound
If each decode step must read all weight bytes and the cache once, the step cannot be faster than (bytes read) / (memory bandwidth).
tokens / s ≈ bandwidth / ( weight bytes + KV-cache bytes )An upper bound for batch 1; real systems reach 60–90% of it.
Llama-2-7B, batch 1
Bytes per token
Laptop, 100 GB/s
GPU, 1,000 GB/s
fp16 weights, short context
13.48 GB
7.4 tok/s
74.2 tok/s
fp16 weights + 4k cache
15.63 GB
6.4 tok/s
64.0 tok/s
4.25-bit weights, short context
3.58 GB
27.9 tok/s
279.3 tok/s
This one formula explains most of what you observe in practice. Quantizing to 4 bits speeds up decoding by nearly the compression ratio, 3.8× here, even though dequantizing adds arithmetic, because arithmetic was idle. Apple laptops with high memory bandwidth run local models well despite modest compute. A larger model is slower in proportion to its bytes. And long contexts slow every token, because the cache is read at every step.
It also explains why batching is the main lever for throughput. With B sequences decoding together, the weights are read once per step and used B times. Total throughput becomes B · bandwidth / (weight bytes + B · cache bytes). For Llama-2-7B fp16 at 1,000 GB/s with 4k contexts: 64 tokens/s at batch 1, 261 at batch 8, 334 at batch 16, at nearly the same cost per step. The cache term in the denominator grows with B, and that, plus memory capacity, is what eventually limits the batch.
Deep dive · arithmetic intensity, and the cache by hand
Derivation
Arithmetic intensity is FLOPs performed per byte moved. A linear layer with a din × dout weight in fp16 applied to B tokens performs 2·B·din·dout FLOPs and reads 2·din·dout bytes of weights (activations are small in comparison), so its intensity is B FLOPs per byte. In prefill, B is the number of prompt tokens, thousands; in decode, B is the batch size, often under 64. A device with peak compute P and bandwidth W is compute-bound only when intensity exceeds P / W, the ridge point: 300 for 300 TFLOP/s and 1,000 GB/s. Below it, time is bytes / W.
The cache adds bytes that do not amortize over the batch: each sequence reads its own cache. Per step, bytes = Wbytes + B · KVbytes, and tokens per step = B, which gives the throughput formula in the lecture.
Worked example by hand
Llama-3-8B, 4,096 tokens, fp16 cache: 2 · 32 layers · 8 KV heads · 128 · 4,096 · 2 bytes = 536,870,912 bytes = 0.54 GB. Weights at 8.03 B parameters in fp16: 16.06 GB. On a 1,000 GB/s GPU at batch 1: 1,000 / (16.06 + 0.54) = 60.2 tokens/s. At 4.25 bits: weights 4.27 GB, 1,000 / (4.27 + 0.54) = 208 tokens/s. The lab's tiny GPT: 2 layers · 4 heads · 16 · 2 · 4 bytes (fp32) = 1,024 bytes per token, 410 kB for 400 tokens, which the lab measures from the actual tensors.
Code walkthrough
q, k = apply_rope(q, start_pos), apply_rope(k, start_pos) # absolute positions
if cache is not None:
k = torch.cat([cache[0], k], dim=2) # (B, heads, past + new, d_head)
v = torch.cat([cache[1], v], dim=2)
mask = torch.arange(S)[None, :] <= (start_pos + torch.arange(T))[:, None]
y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
return proj(y), (k, v) # new cache for the next step
Concatenating reallocates the cache every step. Production servers preallocate or, as vLLM does, store the cache in fixed-size pages so memory is not fragmented across requests of different lengths.
Common mistakes
Rotating cached keys again at each step. Symptom: output degrades after the prompt. Fix: store keys post-RoPE and rotate only new ones.
Using is_causal=True for a single new query against a long cache. Symptom: the new token sees only the first key. Fix: with a cache, build the mask from absolute positions, or no mask for one query.
Sizing a server by weight memory alone. Symptom: out-of-memory errors at moderate concurrency. Fix: budget KV bytes × max concurrent tokens.
Benchmarking decode speed with a 20-token prompt. Symptom: production runs much slower than the benchmark. Fix: benchmark at realistic context lengths.
Check yourself
How many bytes per token does the Llama-2-7B cache need in int8, and how many 4k sequences of cache fit in 16 GB?
Answer
262,144 bytes per token, 1.07 GB per 4k sequence, so 14 full sequences (16 / 1.074 = 14.9).
Lecture 5.5 · 14 min read
Serving: batching, multi-LoRA and speculative decoding
“The KV cache and why decoding is bandwidth-bound” ended with the rule that governs serving: a decode step costs about the same whether it advances one sequence or thirty, as long as the cache fits. Everything in a modern inference server is a way to keep that step full of useful work. This lecture covers the three techniques you are most likely to configure: continuous batching, serving many LoRA adapters on one base model, and speculative decoding.
Static batching and its waste
The simple way to batch is to collect B requests, run them together until all are finished, and then take the next B. Requests differ in length, so short ones finish early and their slots sit idle until the longest one ends. The lab simulates twelve requests needing 12, 3, 40, 7, 25, 5, 9, 31, 4, 18, 6 and 22 decode steps on 4 slots. Static batching runs three groups lasting 40, 31 and 22 steps: 93 steps for 182 tokens of work, 49% slot utilization.
Continuous batching
Continuous (in-flight) batching schedules at the level of one decode step. When a sequence finishes, its slot goes to the next waiting request at the very next step; new requests have their prompt prefilled and join the running batch. On the same twelve requests, continuous batching finishes in 56 steps, 40% fewer, at 81% utilization. In a real server the gain also shows up as latency: a short request no longer waits behind a long one.
Continuous batching needs the cache to be managed per sequence, because sequences start and stop independently and grow at different rates. vLLM's PagedAttention stores the cache in fixed-size blocks, like pages of virtual memory, allocated as a sequence grows and freed when it ends. This avoids reserving memory for each request's maximum length and lets sequences that share a prefix, such as a long system prompt, share its cache blocks. With these two ideas, a single GPU serves dozens of concurrent users at a total throughput many times its batch-1 speed, which is the 64 → 261 → 334 tokens/s progression from the previous lecture.
Multi-LoRA serving
A LoRA adapter is a small set of B·A matrices on top of a frozen base. For Llama-2-7B with r = 16 on all seven projections, the adapter has 39,976,960 parameters, 80 MB in bf16, against 13.48 GB for the base. A server can keep one copy of the base weights and dozens of adapters in GPU memory, and run requests for different adapters in the same batch. Each token's base computation is shared; only the low-rank correction (α/r)·B A x differs per request, computed by kernels that gather each request's adapter (the Punica and S-LoRA papers describe how).
The trade-off is the merge question from “Merge, quantize, serve”. A merged model has no adapter overhead per token and is simplest to run, but serves one fine-tune. Unmerged adapters cost a few percent of extra compute per token and let one GPU host a fine-tune per customer, per language or per task. vLLM enables this with enable_lora=True and a per-request adapter name. Because the adapters share the base's quantization, a 4-bit base with many bf16 adapters is a common deployment.
Speculative decoding
Decode is bandwidth-bound, so verifying several tokens in one forward pass costs about the same as generating one: the weights are read once either way. Speculative decoding exploits this. A small, fast draft model proposes k tokens one by one. The large target model then runs once on all k proposals in parallel, which gives its probabilities at every proposed position. Each draft token is accepted or rejected by a rule that makes the final output distributed exactly as if the target had generated alone.
accept draft token x with probability min( 1, p(x) / q(x) ) on rejection, sample from max(p − q, 0) / Σ max(p − q, 0)p is the target's distribution, q the draft's. After the first rejection, the remaining drafts are discarded.
When the draft is right, tokens are accepted and the target has produced several tokens for the price of one pass. When it is wrong, the rejection rule corrects the distribution and you lose only the draft's work. The probability of accepting a draft token is β = Σx min(p(x), q(x)), the overlap of the two distributions. In the lab's toy example, with target [0.40, 0.25, 0.15, 0.10, 0.06, 0.04] and draft [0.30, 0.30, 0.10, 0.15, 0.10, 0.05], β = 0.85, and 40,000 simulated draws reproduce the target distribution to within sampling noise.
With per-token acceptance α and k drafts, the expected number of tokens per target pass is (1 − αk+1) / (1 − α). At α = 0.8 and k = 4 that is 3.36 tokens per pass. If each draft step costs a fraction c of a target pass, the speed-up is 3.36 / (1 + 4c): 2.80 for c = 0.05, 2.40 for c = 0.1. Gains are largest on predictable text such as code, structured outputs and summaries that copy from the input. Variants drop the separate draft model: prompt lookup copies n-grams from the prompt as drafts, and Medusa or EAGLE train small extra heads on the target to propose several tokens at once.
Putting it together
For a fine-tuned model in production: merge or keep adapters depending on how many fine-tunes you serve; quantize weights to 8 or 4 bits and re-run the gold set; size the cache for your real context lengths and concurrency; turn on continuous batching (the default in vLLM, TGI and SGLang); add speculative decoding when latency matters and a draft is available, since it cannot change outputs. Then measure tokens per second and time to first token under a realistic load, not with one short prompt.
One step: draw x from q, accept with probability min(1, p(x)/q(x)), otherwise draw from the residual r(x) = max(p(x) − q(x), 0) / Z with Z = Σ max(p − q, 0). The probability of accepting x specifically is q(x) · min(1, p(x)/q(x)) = min(q(x), p(x)). The total acceptance probability is β = Σ min(p, q), so the rejection probability is 1 − β. Since p − min(p, q) = max(p − q, 0), summing over x gives 1 − β = Z. The probability that the output is x is therefore
P(x) = min(p(x), q(x)) + (1 − β) · max(p(x) − q(x), 0) / Z = min(p, q) + max(p − q, 0) = p(x)Because Z = 1 − β, the factors cancel; min(a, b) + max(a − b, 0) = a for any a, b.
Every emitted token is distributed exactly as the target. The draft only affects speed.
Expected tokens per pass: let each draft be accepted independently with probability α. The number accepted before the first rejection, capped at k, has P(at least i accepted) = αi. The pass also always yields one token from the target (the correction on rejection, or a bonus token when all k are accepted). Expected total = 1 + Σi=1..k αi = (1 − αk+1) / (1 − α).
Worked example by hand
Lab distributions: min(p, q) = [0.30, 0.25, 0.10, 0.10, 0.06, 0.04], sum β = 0.85. Residual max(p − q, 0) = [0.10, 0, 0.05, 0, 0, 0], Z = 0.15 = 1 − β, so r = [2/3, 0, 1/3, 0, 0, 0]. Token 1: 0.30 + 0.15 · 2/3 = 0.40. Token 3: 0.10 + 0.15 · 1/3 = 0.15. Token 2: 0.25 + 0 = 0.25. Each matches p. Tokens per pass at α = 0.9 and k = 4: (1 − 0.95) / 0.1 = (1 − 0.59049) / 0.1 = 4.095.
Edge cases
With greedy decoding the rule reduces to "accept while the draft's token equals the target's argmax", which is how most servers implement it for temperature 0. Draft and target must share a tokenizer, or proposals have to be re-tokenized, which usually costs more than it saves. Batching and speculation compete: at high batch sizes the GPU is no longer idle, so the extra verification work is no longer free and speculation helps less.
Common mistakes
Accepting a draft whenever p(x) > some threshold. Symptom: outputs drift toward the draft model's style. Fix: use min(1, p/q) and the residual distribution.
Sampling the correction from p instead of the residual. Symptom: tokens the draft likes are over-represented. Fix: sample from max(p − q, 0), normalized.
Measuring speed-up at batch 1 and deploying at batch 64. Symptom: no gain in production. Fix: benchmark at the production batch size.
Using static batching with a variable-length workload. Symptom: GPU utilization under 50%. Fix: continuous batching.
Check yourself
With α = 0.6 and k = 4, how many tokens does one target pass yield on average?
CPU only, about a minute of compute. The notebook trains its own small models (a digits MLP in a second, the Week 4 GPT in about ten seconds), so it does not depend on the Week 4 lab's outputs.
Step 1Formats and int8
Tabulate torch.finfo for fp32, bf16 and fp16 and measure worst-case rounding error. Write absmax and zero-point int8 quantizers and run them on the “Absmax and zero-point int8, with the error they cost” vector, then compare per-tensor and per-row scales on a matrix with one planted outlier.
Checkpoint 1
Zero-point int8 quantization of x = [0.42, −1.27, 0.08, 2.40, −0.66, 1.13]: what is the zero point z?
Step 2Four bits
Build the NF4 codebook from normal quantiles and check it against the bitsandbytes table. Write block-wise quantization with any codebook, and compare int4 and NF4 error at 4.25 bits per weight. Fake-quantize the digits MLP and the tiny GPT with six schemes and tabulate accuracy and perplexity.
Step 3KV cache
Implement CachedAttention.forward with absolute RoPE positions and a position-based mask. Prove that prefill plus one-token steps reproduces the full-recompute logits, then time 400 greedy tokens with and without the cache. Write the KV-cache memory calculator and the bandwidth bound on decode speed.
Checkpoint 2
KV-cache size of Llama-2-7B for one 4,096-token sequence in fp16, in GB (109 bytes, two decimals)?
Step 4Decoding and serving
Compare greedy and nucleus sampling by distinct 8-grams, implement the speculative-sampling acceptance rule and verify it reproduces the target distribution. The practice set covers SQNR, double quantization, a serving-memory planner, expected tokens per speculative pass and static versus continuous batching; the mini-project finds the cheapest quantization that keeps the digits model within one point.
Final exam · 12 questions · pass mark 80%
Final exam
Questions from every week of the course. Pass it to complete the last requirement for the certificate on the Certificates page.
Final exam · 12 questions
Fine-Tuning Language Models
Pass mark 80%. Passing this exam is one of the requirements for the course certificate. You can retake it as often as you like.
Course 5 of 6 · 3 weeks
Convolutional Neural Networks
Images are the input that made deep learning famous. This course builds convolutions from scratch, studies the architectures that won ImageNet and run on phones, and applies them to detection, segmentation and face recognition, with a CNN you train in the page.
26lectures with video
10quizzes incl. practice + final
3labs
Week 1 · Foundations of convolutional networks
Foundations of convolutional networks
Build the convolution operation from scratch: filters, padding, stride, volumes, pooling, and a complete LeNet-style network.
Video lectures · Week 1
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
C4W1L01 Computer VisionDeepLearningAI · Andrew Ng · YouTube ↗C4W1L02 Edge Detection ExamplesDeepLearningAI · Andrew Ng · YouTube ↗But what is a convolution?3Blue1Brown · YouTube ↗Image Classification with Convolutional Neural NetworksStatQuest with Josh Starmer · YouTube ↗
Module 1
Convolutions
Lecture 1.1 · 6 min read
Computer vision and why dense layers fail
Computer vision covers image classification (is this a cat?), object detection (where are the cars and pedestrians, with a box around each?), segmentation (which pixels belong to the road?), face recognition, and even generating images in the style of a painting. Ideas first developed for images now also power audio, medical scans and video.
The obstacle is input size. A 64 × 64 color image already has 64 × 64 × 3 = 12,288 numbers. A 1000 × 1000 photo has three million. Feed that into a dense first layer with 1,000 units and the weight matrix alone has three billion entries: too much memory, too much computation, and far too many parameters to learn without overfitting.
1000 × 1000 × 3 inputs × 1,000 units = 3 × 109 weightsOne dense layer on a one-megapixel photo.
Convolutional layers solve this by looking at small windows and reusing the same few weights at every position. The rest of this week builds that operation from the ground up.
Lecture 1.2 · 11 min read
Edge detection with convolution
Start with the simplest useful feature: vertical edges. Take a 6 × 6 grayscale image whose left half is bright (10) and right half dark (0), and a 3 × 3 filter, also called a kernel, with a column of 1s, a column of 0s and a column of −1s.
Place the filter on the top-left 3 × 3 patch, multiply element by element, add up the nine products: that is the first output. Slide one column right and repeat. A 6 × 6 image and a 3 × 3 filter give a 4 × 4 output.
import numpy as np
img = np.array([[10, 10, 10, 0, 0, 0]] * 6, dtype=float)
k = np.array([[1, 0, -1]] * 3, dtype=float) # vertical edge detector
out = np.zeros((4, 4))
for i in range(4):
for j in range(4):
out[i, j] = (img[i:i+3, j:j+3] * k).sum()
print(out)
The output is large exactly where the brightness changes from left to right: the filter has found the edge. Swap the sign of the filter and it finds dark-to-bright edges; transpose it and it finds horizontal edges. Hand-designed variants such as the Sobel filter weight the middle row more.
Two notes. Mathematicians call this operation cross-correlation, because a true convolution flips the filter first; deep learning uses the word convolution anyway. And in a network nobody designs the nine numbers: they are parameters, learned by backpropagation, so the network discovers whatever edge-like or texture-like detectors the task needs.
Lecture 1.3 · 9 min read
Padding
An n × n image convolved with an f × f filter gives an (n − f + 1) × (n − f + 1) output. Two problems follow. The image shrinks with every layer, so a deep network would reduce it to nothing. And corner pixels are covered by only one filter position while central pixels are covered by many, so information at the border is underused.
Padding adds a border of p zeros around the image before convolving.
output size = n + 2p − f + 1"Valid" convolution: p = 0. "Same" convolution: choose p = (f − 1) / 2 so the output has the same size as the input.
With a 3 × 3 filter, p = 1 keeps the size; with 5 × 5, p = 2. This is one reason filter sizes are almost always odd: the padding is symmetric and the filter has a central pixel.
import torch, torch.nn.functional as F
x = torch.randn(1, 1, 6, 6)
for f_, p_ in [(3, 0), (3, 1), (5, 2)]:
y = F.conv2d(x, torch.randn(1, 1, f_, f_), padding=p_)
print(f"f={f_}, p={p_}: 6x6 -> {tuple(y.shape[-2:])} (formula {6 + 2*p_ - f_ + 1})")
Lecture 1.4 · 9 min read
Strided convolutions
The stride s is how far the filter moves between positions. With s = 2 it jumps two pixels at a time, horizontally and vertically, so the output is roughly half as wide and half as tall.
output size = ⌊(n + 2p − f) / s⌋ + 1If the filter would hang off the edge at the last position, that position is skipped: hence the floor.
Example: a 7 × 7 input, a 3 × 3 filter, no padding, stride 2: ⌊(7 − 3) / 2⌋ + 1 = 3, so the output is 3 × 3.
import torch, torch.nn.functional as F
def out_size(n, f, p, s): return (n + 2 * p - f) // s + 1
for n, f_, p_, s in [(7, 3, 0, 2), (8, 3, 1, 2), (32, 5, 0, 1)]:
y = F.conv2d(torch.randn(1, 1, n, n), torch.randn(1, 1, f_, f_), stride=s, padding=p_)
print(f"n={n} f={f_} p={p_} s={s}: formula {out_size(n, f_, p_, s)}, actual {y.shape[-1]}")
Module 2
Practice quiz: Convolutions
Practice quiz · 5 questions
Convolutions
Module 3
Convolutions over volumes
Lecture 1.5 · 10 min read
Convolutions over volumes
A color image is a volume: height × width × 3 channels. The filter becomes a volume too, with the same number of channels: a 3 × 3 × 3 filter has 27 numbers. At each position, multiply all 27 by the 27 pixels under them and add: still one number per position. A 6 × 6 × 3 image and one 3 × 3 × 3 filter give a 4 × 4 output.
To detect several features at once, use several filters and stack their outputs. Two filters (say a vertical-edge and a horizontal-edge detector) give a 4 × 4 × 2 output. In general:
(n × n × nc) * (f × f × nc) × nc′ filters → (n − f + 1) × (n − f + 1) × nc′The number of output channels equals the number of filters.
Note the layout: PyTorch puts channels first, (N, C, H, W); TensorFlow defaults to channels last, (N, H, W, C). The arithmetic is identical.
Lecture 1.6 · 10 min read
One layer of a convolutional network
A convolutional layer applies each filter, adds a bias (one per filter), and passes the result through a nonlinearity such as ReLU. It is the convolutional counterpart of a dense layer: the filters play the role of W, and the image patch plays the role of the input.
Z = W * A[l−1] + b, A[l] = ReLU(Z)Here * is convolution, applied once per filter.
Count the parameters of a layer with 10 filters of size 3 × 3 on a 3-channel input: each filter has 3 × 3 × 3 = 27 weights plus 1 bias, so 28 × 10 = 280 parameters. That number does not depend on the image size: the same 280 parameters work on a 64 × 64 image and a 4000 × 4000 image. This is what makes convolutional networks practical, and it also makes them less prone to overfitting.
Symbol
Meaning
f[l]
filter size
p[l], s[l]
padding, stride
nc[l]
number of filters = output channels
nH[l]
⌊(nH[l−1] + 2p − f)/s⌋ + 1, likewise for width
weights
f × f × nc[l−1] × nc[l], plus nc[l] biases
import torch.nn as nn
conv = nn.Conv2d(3, 10, kernel_size=3)
print("parameters:", sum(p.numel() for p in conv.parameters()))
Lecture 1.7 · 10 min read
Pooling layers
Pooling layers shrink the height and width of a volume without any parameters. Max pooling with f = 2 and s = 2 splits each channel into 2 × 2 blocks and keeps the largest value in each block, halving the size. The intuition: if a feature was detected anywhere in the block, keep that it was detected.
Pooling acts on each channel independently, so the number of channels does not change. Average pooling takes the mean instead; it appears mostly at the very end of modern networks, where it collapses each channel to a single number. The hyperparameters f and s are fixed by hand; there is nothing for gradient descent to learn.
Module 4
Practice quiz: Convolutions over volumes
Practice quiz · 5 questions
Convolutions over volumes
Module 5
A complete convolutional network
Lecture 1.8 · 12 min read
A convolutional network example
Put the pieces together in a network inspired by LeNet-5 for 32 × 32 × 3 images and 10 classes. A common convention counts a convolution and its following pooling as one "layer", since only the convolution has parameters.
Stage
Output shape
Parameters
input
32 × 32 × 3
0
conv 5×5, 6 filters
28 × 28 × 6
(5·5·3 + 1)·6 = 456
max pool 2×2
14 × 14 × 6
0
conv 5×5, 16 filters
10 × 10 × 16
(5·5·6 + 1)·16 = 2,416
max pool 2×2
5 × 5 × 16 = 400
0
dense 120
120
48,120
dense 84
84
10,164
softmax 10
10
850
import torch, torch.nn as nn
net = nn.Sequential(
nn.Conv2d(3, 6, 5), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(6, 16, 5), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(), nn.Linear(400, 120), nn.ReLU(), nn.Linear(120, 84), nn.ReLU(), nn.Linear(84, 10))
x = torch.randn(2, 3, 32, 32)
for layer in net:
x = layer(x)
if isinstance(layer, (nn.MaxPool2d, nn.Linear)):
print(f"{type(layer).__name__:10s} -> {tuple(x.shape)}")
print("total parameters:", sum(p.numel() for p in net.parameters()))
Two trends are typical. Height and width shrink as you go deeper while the number of channels grows. And most parameters sit in the dense layers at the end, not in the convolutions.
Lecture 1.9 · 8 min read
Why convolutions?
Compare the first stage of the example network with a dense layer producing the same output. Mapping 32 × 32 × 3 = 3,072 inputs to 28 × 28 × 6 = 4,704 outputs densely needs 3,072 × 4,704 ≈ 14.5 million weights. The convolution needs 456. Two properties explain the gap.
Parameter sharing: a feature detector that is useful in one part of the image (a vertical edge, say) is probably useful everywhere, so the same filter is reused at every position.
Sparsity of connections: each output value depends only on a small patch of the input, not on every pixel.
Fewer parameters mean less data is needed and overfitting is less likely. Sharing also gives a useful bias: a cat shifted a few pixels to the right produces shifted but similar activations, so the network tends to recognize it either way.
Implement padding, a single convolution step, the forward pass of a convolutional layer and max pooling in NumPy, check each against PyTorch, then run edge filters over real handwritten digits.
Step 1Output size and padding
Write out_size(n, f, p, s) and zero_pad(x, p) for channels-first images.
Step 2Convolution forward pass
Write conv_single_step and conv_forward(x, W, b, stride, pad) and compare with torch.nn.functional.conv2d.
Step 3Pooling and edge filters
Write max_pool, then apply Sobel filters to digits and look at the feature maps.
Checkpoint 1
Output size of a 32×32 input with f = 5, p = 2, s = 2?
Checkpoint 2
Largest value of the vertical-edge output on the 6×6 example image?
Checkpoint 3
Sum of the stride-2, pad-1 output on the random test volume (two decimals)?
Week 2 · Deep convolutional models
Deep convolutional models
Learn from landmark architectures (VGG, ResNet, Inception, MobileNet, EfficientNet) and the practical habits that make vision projects work.
Video lectures · Week 2
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
C4W2L03 ResNetsDeepLearningAI · Andrew Ng · YouTube ↗C4W2L05 Network in Network (1×1 convolutions)DeepLearningAI · Andrew Ng · YouTube ↗
Module 1
Classic and residual networks
Lecture 2.1 · 12 min read
Classic networks: LeNet-5, AlexNet, VGG
Studying a few landmark architectures is the fastest way to build intuition, much as programmers learn by reading good code.
Network
Year
Parameters
What it introduced
LeNet-5
1998
≈ 60 thousand
conv–pool–conv–pool–dense pattern for digit recognition
AlexNet
2012
≈ 60 million
ReLU, GPU training, dropout; won ImageNet by a wide margin and started the deep learning wave in vision
VGG-16
2014
≈ 138 million
uniform design: only 3×3 same convolutions and 2×2 max pools, channels doubling 64 → 128 → 256 → 512
The trend across these networks matches what you saw last week: height and width go down, channels go up, and the network ends with dense layers and a softmax. VGG's simplicity made it easy to reuse, but its size made it slow; the next generation focused on going deeper without becoming impossible to train.
Lecture 2.2 · 12 min read
Residual networks
In theory a deeper network can do at least as well as a shallower one: the extra layers could just copy their input. In practice, very deep plain networks get worse training error as layers are added, because the optimization becomes hard and gradients vanish or explode.
A residual block adds a shortcut: the input of the block skips two layers and is added back before the final ReLU.
a[l+2] = g( z[l+2] + a[l] )If the two layers learn weights near zero, the block outputs ReLU(a[l]) = a[l]: the identity is easy to learn, so adding blocks rarely hurts.
import torch, torch.nn as nn
class ResidualBlock(nn.Module):
def __init__(self, c):
super().__init__()
self.conv1 = nn.Conv2d(c, c, 3, padding=1)
self.conv2 = nn.Conv2d(c, c, 3, padding=1)
def forward(self, a):
z = self.conv2(torch.relu(self.conv1(a)))
return torch.relu(z + a) # the skip connection
block = ResidualBlock(8)
a = torch.relu(torch.randn(1, 8, 6, 6))
print("shape preserved:", tuple(block(a).shape))
with torch.no_grad():
for p in block.parameters(): p.zero_()
print("zero weights -> identity:", torch.allclose(block(a), a))
Because z and a[l] are added, they must have the same shape; "same" convolutions keep it, and where the shape changes a 1 × 1 convolution projects the shortcut. With residual blocks, networks of 50, 101 and 152 layers train well, and the idea now appears almost everywhere, including in every transformer block of Course 4.
Lecture 2.3 · 11 min read
1×1 convolutions and Inception
A 1 × 1 convolution sounds pointless on a single channel, but on a volume it is a small dense layer applied at every pixel across the channels. Its main use is to change the number of channels cheaply: 32 filters of size 1 × 1 × 192 turn a 28 × 28 × 192 volume into 28 × 28 × 32.
Consider applying 32 filters of 5 × 5 to a 28 × 28 × 192 input with same padding. Each of the 28·28·32 outputs costs 5·5·192 multiplications: about 120 million. Insert a 1 × 1 "bottleneck" with 16 filters first and the total drops to about 12.4 million, a tenfold saving, usually without hurting accuracy.
The Inception network uses this to avoid choosing a filter size: each Inception module runs 1 × 1, 3 × 3 and 5 × 5 convolutions and a max pool in parallel, with 1 × 1 bottlenecks in front of the expensive branches, and concatenates the results along the channel dimension.
Module 2
Practice quiz: Classic networks
Practice quiz · 5 questions
Classic networks
Module 3
Efficient networks
Lecture 2.4 · 12 min read
MobileNet: depthwise separable convolutions
Phones and embedded devices need networks that are cheap to run. MobileNet replaces each normal convolution with two steps. A depthwise convolution applies one f × f filter per input channel, separately. A pointwise convolution, a 1 × 1 convolution, then mixes the channels into the desired number of outputs.
cost ratio = 1/nc′ + 1/f²With 512 output channels and 3 × 3 filters the separable version costs about 11% of a normal convolution.
def costs(n_out, f, c_in, c_out):
normal = n_out ** 2 * c_out * f * f * c_in
separable = n_out ** 2 * c_in * f * f + n_out ** 2 * c_out * c_in
return normal, separable
for args in [(4, 3, 3, 5), (14, 3, 256, 512)]:
n, s = costs(*args)
print(f"{args}: normal {n:,} separable {s:,} ratio {s / n:.3f}")
MobileNet v2 adds two refinements: an expansion layer that temporarily increases the channels before the depthwise step, and a residual connection around each block.
Lecture 2.5 · 5 min read
EfficientNet: scaling networks
Given a baseline network and a bigger compute budget, you can scale it three ways: more layers (depth), more channels per layer (width), or larger input images (resolution). Scaling only one of them quickly hits diminishing returns.
EfficientNet scales all three together with fixed ratios found by a small search, called compound scaling. The result is a family of models, from B0 for phones to B7 for servers, so you can pick the most accurate model that fits your device's memory and latency budget. The lesson generalizes: when you have more compute, increase the size of the model and the input in a balanced way rather than one dimension at a time.
Module 4
Practice quiz: Efficient networks
Practice quiz · 5 questions
Efficient networks
Module 5
Practical advice for using CNNs
Lecture 2.6 · 8 min read
Transfer learning for vision
Training a large vision network from scratch takes millions of images and days of GPU time. Others have already done it and published the weights. For a new task, say recognizing your two cats, download a network pre-trained on ImageNet, remove its 1,000-way softmax, and add your own output layer.
Very little data: freeze every pre-trained layer and train only the new head. A useful trick is to run your images through the frozen network once, save the features, and train a small classifier on them.
More data: freeze the early layers and fine-tune the later ones together with the head.
Lots of data: use the pre-trained weights as initialization and train everything.
With torchvision this takes a few lines. It needs real PyTorch, so run it locally or in Colab:
import torch.nn as nn
from torchvision.models import resnet18, ResNet18_Weights
model = resnet18(weights=ResNet18_Weights.DEFAULT) # pre-trained on ImageNet
for p in model.parameters():
p.requires_grad = False # freeze the backbone
model.fc = nn.Linear(model.fc.in_features, 3) # new head: e.g. cat 1, cat 2, neither
Lecture 2.7 · 9 min read
Data augmentation for images
Vision models almost always benefit from more data, and augmentation is the cheapest way to get it. Common transformations:
mirroring (horizontal flips), when left and right do not change the label
random cropping and rescaling
small rotations, shearing and local warping
color shifting: adding small random offsets to the red, green and blue channels to mimic different lighting
In large training jobs, a few CPU threads load images and apply random distortions while the GPU trains on the previous batch, so augmentation costs almost no extra time. The distortions themselves have hyperparameters (how much to rotate, how strong the color shift), and good defaults from published implementations are a sensible starting point.
import numpy as np
from sklearn.datasets import load_digits
img = load_digits().images[0] / 16.0
rng = np.random.default_rng(0)
flipped = img[:, ::-1]
crop = np.pad(img, 1)[rng.integers(0, 3):, rng.integers(0, 3):][:8, :8]
brighter = np.clip(img + 0.2, 0, 1)
for name, im in [("original", img), ("flipped", flipped), ("random crop", crop), ("brighter", brighter)]:
print(f"{name:12s} shape {im.shape} mean {im.mean():.3f}")
print("note: flipping a digit can change its meaning, so pick augmentations that keep the label")
Lecture 2.8 · 7 min read
The state of computer vision
Machine learning systems draw on two sources of knowledge: labeled data and hand engineering (features, architectures, tricks). Speech recognition has lots of data and relatively simple models. Object detection has far less labeled data per task, so the field historically relied more on careful architectures and on transfer learning.
Competitions and benchmarks reward tricks that are rarely worth it in production: ensembling several networks and averaging their outputs, or running the model on many crops of each test image (multi-crop). They add a percent of accuracy at several times the computational cost.
Practical advice: use architectures from the literature, start from open-source implementations and pre-trained weights, and spend your effort on data and evaluation for your specific problem.
Build a two-block CNN in PyTorch, train it on the 8×8 digits with mini-batches, compare it with a dense network of similar size, and visualize the filters it learns. It runs in the page on torchlite, which now includes Conv2d and pooling layers.
Step 1Build the network
Stack conv, ReLU and pooling blocks and work out the input size of the final linear layer from the shapes.
Step 2Train and evaluate
Write the mini-batch training loop with Adam and cross-entropy, and report test accuracy.
Step 3Compare and inspect
Train a dense network the same way, then plot the first-layer filters.
Checkpoint 1
How many parameters does the CNN have?
Checkpoint 2
How many features come out of the Flatten layer?
Checkpoint 3
How many parameters does the comparison dense network have?
Week 3 · Detection, segmentation and recognition
Detection, segmentation and recognition
Find and box objects, label every pixel, verify faces from a single photo, and repaint images in another style.
Video lectures · Week 3
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
C4W3L01 Object LocalizationDeepLearningAI · Andrew Ng · YouTube ↗C4W3L06 Intersection Over UnionDeepLearningAI · Andrew Ng · YouTube ↗C4W3L07 Non-max SuppressionDeepLearningAI · Andrew Ng · YouTube ↗C4W3L09 YOLO AlgorithmDeepLearningAI · Andrew Ng · YouTube ↗C4W4L03 Siamese NetworkDeepLearningAI · Andrew Ng · YouTube ↗C4W4L04 Triplet LossDeepLearningAI · Andrew Ng · YouTube ↗C4W4L06 What is Neural Style Transfer?DeepLearningAI · Andrew Ng · YouTube ↗
Module 1
Object detection
Lecture 3.1 · 11 min read
Object localization and landmark detection
Classification says what is in the image. Localization also says where, with a bounding box. Extend the output layer: instead of only class probabilities, predict whether there is an object at all, the box, and the class.
y = [pc, bx, by, bh, bw, c1, c2, c3]p_c: is there an object? (b_x, b_y): box center; (b_h, b_w): box size, all relative to the image; c_1..c_3: pedestrian, car, motorcycle.
The loss compares all eight numbers when there is an object, and only pc when there is not, because the box is meaningless then. In practice, log loss is used for pc and the classes, and squared error for the box coordinates.
The same idea predicts any set of points, called landmarks: the corners of the eyes for a face filter, or 32 joints for a pose estimator. The network outputs the coordinates of each landmark, which must be labeled consistently across the training images.
Lecture 3.2 · 8 min read
Intersection over union
How good is a predicted box? Intersection over union (IoU) divides the area where the predicted and true boxes overlap by the area covered by either one. IoU is 1 for a perfect match and 0 for no overlap. By convention a detection is often counted as correct when IoU ≥ 0.5.
IoU = area(A ∩ B) / area(A ∪ B)Using corner coordinates (x1, y1, x2, y2): the intersection runs from the larger of the two left edges to the smaller of the two right edges, and likewise vertically.
Detectors usually fire several times on the same object, producing a cluster of overlapping boxes. Non-max suppression keeps one:
Discard boxes whose confidence pc is below a threshold, say 0.6.
Take the remaining box with the highest confidence and output it.
Discard every remaining box with IoU ≥ 0.5 against that box.
Repeat until no boxes remain. With several classes, run it separately per class.
import numpy as np
def iou(a, b):
w = max(0, min(a[2], b[2]) - max(a[0], b[0])); h = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = w * h
return inter / ((a[2]-a[0])*(a[3]-a[1]) + (b[2]-b[0])*(b[3]-b[1]) - inter)
def nms(boxes, scores, score_thr=0.6, iou_thr=0.5):
order = [i for i in np.argsort(scores)[::-1] if scores[i] >= score_thr]
keep = []
while order:
best = order.pop(0); keep.append(int(best))
order = [i for i in order if iou(boxes[best], boxes[i]) < iou_thr]
return keep
boxes = [(10, 10, 50, 50), (12, 12, 52, 52), (11, 9, 49, 51), (100, 100, 140, 150), (102, 98, 141, 148)]
scores = np.array([0.9, 0.75, 0.8, 0.7, 0.95])
print("kept boxes:", nms(boxes, scores))
Lecture 3.4 · 14 min read
Sliding windows, anchor boxes and YOLO
The oldest detection method slides a window over the image at many positions and sizes and classifies each crop. It works but is extremely slow, because overlapping crops are processed again and again. Implementing the classifier convolutionally fixes that: replace the dense layers with equivalent convolutions and one forward pass over the whole image computes the prediction for every window position at once, sharing all the overlapping computation.
YOLO ("you only look once") pushes this further. Divide the image into a grid, say 19 × 19. Each grid cell predicts the objects whose center falls inside it, outputting a localization vector like the one from earlier this week. One forward pass produces predictions for all cells.
A cell might contain the centers of two objects, such as a pedestrian standing in front of a car. Anchor boxes handle this: predefine a few box shapes (tall and thin, wide and short), and give each cell one prediction per anchor. Each object is assigned to the cell containing its center and the anchor with the highest IoU with its shape.
output volume = grid × grid × anchors × (5 + classes)For example 19 × 19 × 5 × (5 + 80) for five anchors and the 80 classes of the COCO dataset. Non-max suppression then cleans up the predictions.
An alternative family, R-CNN and its faster successors, first proposes candidate regions and then classifies them. These two-stage detectors were long the most accurate, while YOLO-style one-stage detectors are faster; modern versions of both are widely used.
Module 2
Practice quiz: Object detection
Practice quiz · 5 questions
Object detection
Module 3
Semantic segmentation
Lecture 3.5 · 6 min read
Semantic segmentation
Detection draws boxes. Semantic segmentation labels every pixel: road, car, pedestrian, sky. Self-driving cars use it to find drivable surface; medical imaging uses it to outline tumors or organs in scans, where a box would be far too coarse.
The output is a map with the same height and width as the input image and one channel per class, holding each pixel's class scores. The network therefore has to shrink the image, as a classifier does, to understand what is in it, and then grow it back to full resolution to say where each thing is. The next lecture shows how.
Lecture 3.6 · 12 min read
Transposed convolutions and U-Net
A transposed convolution goes the other way from a normal one: it turns a small volume into a larger one. Each input value multiplies the whole filter, the result is placed in the output at a position set by the stride, and overlapping contributions add up. The filter values are learned.
output size = (n − 1)·s − 2p + fA 2 × 2 input with f = 2, s = 2, p = 0 becomes 4 × 4.
import numpy as np
def transposed_conv(x, k, s):
n, f = x.shape[0], k.shape[0]
out = np.zeros(((n - 1) * s + f,) * 2)
for i in range(n):
for j in range(n):
out[i*s:i*s+f, j*s:j*s+f] += x[i, j] * k
return out
x = np.array([[1.0, 2.0], [3.0, 4.0]])
k = np.ones((2, 2))
print(transposed_conv(x, k, 2))
U-Net, designed for biomedical images, is the standard segmentation architecture. Its first half is a normal CNN that shrinks the image while increasing channels. Its second half uses transposed convolutions to grow it back. The key ingredient is skip connections: the high-resolution activations from each level of the first half are concatenated onto the matching level of the second half, so the decoder gets both the coarse "what" from deep layers and the fine "where" from early layers. A final 1 × 1 convolution maps each pixel to class scores. Drawn as a diagram, the shape is a U.
Module 4
Practice quiz: Semantic segmentation
Practice quiz · 5 questions
Semantic segmentation
Module 5
Face recognition and neural style transfer
Lecture 3.7 · 10 min read
Face verification and one-shot learning
Face verification answers "is this person who they claim to be?" by comparing one image with one stored identity. Face recognition answers "who is this?" against a database of K people, which is harder: a 99% accurate verifier makes K times as many chances for error.
The challenge is one-shot learning: a company may have a single photo of each employee. Training a softmax classifier with one output per employee would need many photos each, and retraining every time someone joins. Instead, learn a similarity function: d(img1, img2) is small for the same person and large for different people. Verification then checks whether d is below a threshold τ.
A Siamese network implements d. One network maps an image to an encoding, a vector of, say, 128 numbers. Run it on both images and compare the encodings.
d(x(1), x(2)) = ‖ f(x(1)) − f(x(2)) ‖²The same network f, with the same weights, encodes both images.
import numpy as np
rng = np.random.default_rng(0)
alice = rng.normal(size=128)
alice_2 = alice + rng.normal(0, 0.1, 128) # another photo of Alice: nearby encoding
bob = rng.normal(size=128)
d = lambda a, b: float(((a - b) ** 2).sum())
tau = 10.0
print(f"d(alice, alice_2) = {d(alice, alice_2):.1f} -> same person: {d(alice, alice_2) < tau}")
print(f"d(alice, bob) = {d(alice, bob):.1f} -> same person: {d(alice, bob) < tau}")
Lecture 3.8 · 10 min read
Triplet loss
To train the encoder, look at three images at a time: an anchor A, a positive P of the same person, and a negative N of someone else. We want the anchor closer to the positive than to the negative, by at least a margin α.
L(A, P, N) = max( ‖f(A) − f(P)‖² − ‖f(A) − f(N)‖² + α, 0 )The margin prevents the trivial solution of encoding every image as the same vector.
Training needs several photos per person (a training set of many people), even though deployment needs only one. Random triplets are mostly easy and give zero loss, so training picks hard triplets where the negative is close to the anchor. An alternative is to treat verification as binary classification on pairs of encodings.
Lecture 3.9 · 12 min read
Neural style transfer
Neural style transfer generates an image G with the content of one image C and the style of another S, say a photo painted in the manner of an artwork. It uses a pre-trained CNN only as a measuring instrument and runs gradient descent on the pixels of G.
J(G) = α·Jcontent(C, G) + β·Jstyle(S, G)Start G from random noise or from C and minimize J by updating G.
Content cost: the squared difference between the activations of C and G at a middle layer. Similar activations mean similar content.
Style cost: style is captured by correlations between channels. The Gram matrix of a layer's activations holds, for each pair of channels, how often they fire together. The style cost compares the Gram matrices of S and G, summed over several layers.
import numpy as np
rng = np.random.default_rng(0)
a = np.maximum(rng.normal(size=(4, 6, 6)), 0) # activations: 4 channels, 6x6
A = a.reshape(4, -1) # (channels, positions)
gram = A @ A.T # G[k, k'] = sum over positions of a_k * a_k'
print("Gram matrix shape:", gram.shape)
print(gram.round(1))
Visualizing what units respond to shows why this works: early layers react to simple edges and colors, deeper layers to textures and object parts, so matching correlations across several layers reproduces the brushstrokes and textures of the style image.
Module 6
Practice quiz: Face recognition and style transfer
Write the post-processing of an object detector: intersection over union, score filtering of a YOLO-style output volume, and per-class non-max suppression.
Step 1IoU
Implement iou(a, b) for corner-format boxes, including non-overlapping and touching boxes.
Step 2Filter a YOLO volume
Compute class scores p_c × P(class) for every cell and anchor and keep boxes above a threshold.
Step 3Non-max suppression
Implement nms and run it per class, then plot kept and suppressed boxes.
Checkpoint 1
IoU of (2, 1, 4, 3) and (1, 2, 3, 4)?
Checkpoint 2
How many boxes have a score of at least 0.3?
Checkpoint 3
How many boxes remain after per-class non-max suppression?
Final exam · 12 questions · pass mark 80%
Final exam
Questions from every week of the course. Pass it to complete the last requirement for the certificate on the Certificates page.
Final exam · 12 questions
Convolutional Neural Networks
Pass mark 80%. Passing this exam is one of the requirements for the course certificate. You can retake it as often as you like.
Course 6 of 6 · 3 weeks
Machine Learning in Production
A model in a notebook is not a product. This course covers the full lifecycle: deploying safely, monitoring for drift, improving data instead of only models, scoping projects worth doing, and operating them responsibly.
17lectures with video
9quizzes incl. practice + final
2labs
Week 1 · Lifecycle and deployment
The ML lifecycle and deployment
What it takes to move a model from a notebook into production, deploy it safely, and notice when the world changes under it.
Video lectures · Week 1
Every lecture below has a narrated video version: press ▶ Watch next to its title. These talks from the open web cover the same ground from another angle.
A Chat with Andrew on MLOps: From Model-centric to Data-centric AIDeepLearningAI · Andrew Ng · YouTube ↗
Module 1
The machine learning project lifecycle
Lecture 1.1 · 6 min read
From proof of concept to production
A model that works in a notebook is a long way from a system people rely on. A widely cited observation from industry is that the model code is a small box in the middle of a much larger system: data collection and verification, feature extraction, serving infrastructure, configuration, monitoring, and the processes that keep all of it healthy.
Consider a visual inspection system that finds scratches on phones in a factory. The camera takes a photo, a prediction server receives it through an API, runs the model, and returns "defect" or "no defect" to the control software that moves the phone along the line. Every arrow in that sentence is code that has to be written, tested and monitored, and the inputs will change over time as lighting, cameras and products change.
This course is about that gap: the practices, collectively called MLOps, that turn a promising model into a dependable product and keep it that way.
Lecture 1.2 · 8 min read
The machine learning project lifecycle
A machine learning project moves through four stages, with plenty of loops back.
Stage
Key questions
Scoping
What problem, for whom? What does success mean in numbers (accuracy, latency, cost)?
Data
Where does it come from? How are labels defined and kept consistent? What baseline exists?
Modeling
Which model, which hyperparameters? What does error analysis say to fix next?
Deployment
How is it served and monitored? What happens when the data changes?
Take a speech recognition feature for voice search. Scoping decides the key metrics: word error rate, latency, throughput. The data stage discovers that transcription conventions are inconsistent ("um, today's weather" versus "today's weather") and fixes them. Modeling trains, analyzes errors, and often goes back for more targeted data. Deployment puts the model on phones or servers, and monitoring reveals new accents or noise conditions that send the team back to the data stage.
Module 2
Practice quiz: The ML project lifecycle
Practice quiz · 5 questions
The ML project lifecycle
Module 3
Deployment
Lecture 1.3 · 9 min read
Concept drift and data drift
The world a model sees after launch rarely matches its training data for long. Two kinds of change matter.
Data drift (covariate shift): the distribution of inputs x changes. A new phone microphone, a new camera in the factory, a marketing campaign that brings younger users.
Concept drift: the mapping from x to y changes. During a lockdown, the same purchase pattern may stop being suspicious; after inflation, the same house is worth more.
Changes can be gradual, like language evolving, or sudden, like a pandemic or a new product line. Either way the symptom is the same: performance in production quietly degrades while the offline test set still looks fine. Detecting drift needs monitoring of inputs and, when labels are available, of outcomes.
import numpy as np
rng = np.random.default_rng(0)
train_age = rng.normal(40, 10, 5000)
prod_age = rng.normal(33, 9, 5000) # a campaign brought younger users
print(f"training mean age {train_age.mean():.1f}, production mean age {prod_age.mean():.1f}")
bins = np.linspace(10, 80, 8)
tr, _ = np.histogram(train_age, bins); pr, _ = np.histogram(prod_age, bins)
for lo, a, b in zip(bins[:-1], tr / tr.sum(), pr / pr.sum()):
print(f"{lo:4.0f}+ train {a:5.1%} prod {b:5.1%}")
Lecture 1.4 · 10 min read
Deployment patterns
Switching an important system to a new model all at once is risky. Three patterns reduce the risk.
Shadow mode: the model runs alongside the current system (often a human) and its predictions are logged but not used. Compare them before trusting it.
Canary deployment: send a small fraction of traffic, say 5%, to the new model, watch the metrics, and ramp up gradually if all is well.
Blue-green deployment: run the old (blue) and new (green) versions side by side and switch the router from one to the other, which makes rollback instant.
Deployment is also a spectrum of automation, from human only, through shadow mode, AI assistance (the model highlights areas for a person to check) and partial automation (the model decides when confident and defers to a person otherwise), to full automation. Many valuable systems stop at assistance or partial automation.
Monitoring starts with brainstorming everything that could go wrong, then choosing a few metrics that would reveal it. Three families are useful:
Family
Examples
Software metrics
memory, compute, latency, throughput, server load, error responses
Input metrics
average input length or volume, fraction of missing values, image brightness, share of a new language
Output metrics
fraction of empty or "null" outputs, how often users retry a query, switches to typing after voice search, click-through
Set thresholds and alarms on the metrics, and expect to adjust them: the first thresholds are guesses. When an alarm fires, the fix may be a configuration change, a manual retrain with new data, or in mature systems an automatic retrain. Systems with several models in a pipeline (voice activity detection feeding speech recognition, for instance) need metrics for each stage, because a change upstream can break everything downstream.
Monitor a deployed loan-default model over twelve weeks of production data: implement PSI and the KS statistic, flag input drift, and watch accuracy reveal concept drift that the inputs alone cannot show.
Step 1Drift statistics
Implement the population stability index and the Kolmogorov–Smirnov statistic and check them on known distributions.
Step 2Weekly monitor
Build a weekly report of income PSI, accuracy and a drift flag, and plot both.
Step 3Data drift versus concept drift
Show that accuracy falls in weeks where the debt-ratio inputs did not change.
Checkpoint 1
First week where the income PSI exceeds 0.2?
Checkpoint 2
Accuracy drop between weeks 0–5 and weeks 9–11 (two decimals)?
Week 2 · Modeling and data in production
Modeling and data in production
Data-centric development: baselines, error analysis and prioritization, consistent labels, and reproducible data pipelines.
Module 1
Modeling challenges
Lecture 2.1 · 7 min read
Model-centric and data-centric AI
Academic machine learning usually holds the dataset fixed and improves the model: the model-centric view. In applied work it often pays more to hold the model fixed, picking a solid open-source architecture, and improve the data: fix inconsistent labels, add examples where the model fails, remove ambiguity. This is the data-centric view.
The two are complementary, but the balance matters. A team that spends three months tuning architectures on noisy labels usually loses to a team that spends two weeks cleaning labels and collecting data for the worst-performing slice.
Lecture 2.2 · 9 min read
Beyond average test-set accuracy
A model with a good average test score can still fail as a product. Three common reasons:
Disproportionately important examples: a web search engine that gets most queries right but fails on "navigational" queries such as "Stanford" or "Reddit" will frustrate users far more than the average suggests.
Performance on key slices: a loan model must not discriminate by ethnicity or gender; a product recommender must treat small sellers fairly, not only large brands.
Rare classes: in medical diagnosis a rare but serious condition can be missed entirely while overall accuracy stays high.
Before improving a model, find out what is achievable. For unstructured data such as images, audio and text, human-level performance (HLP) is a good baseline because people are good at these tasks. For structured data (spreadsheets, transaction logs) humans are poor judges and the better baseline is an existing system or a simple model.
Speech slice
Model accuracy
Human-level
Gap
Clear speech
94%
95%
1%
Car noise
89%
93%
4%
People noise
87%
89%
2%
Low bandwidth
70%
70%
0%
The table points to car noise: the largest gap to what is achievable. Low-bandwidth audio looks worst in absolute terms but has nothing left to gain if even humans cannot do better.
To get started quickly: search the literature and open-source implementations, start with a reasonable algorithm rather than the latest research, and run a quick sanity check by overfitting a small training set (even a single example) to catch bugs early.
Module 2
Practice quiz: Modeling challenges
Practice quiz · 5 questions
Modeling challenges
Module 3
Error analysis and prioritization
Lecture 2.4 · 10 min read
Error analysis and prioritizing
Production error analysis extends the spreadsheet you saw in Course 2: tag each misclassified example with properties (car noise, accent, low bandwidth, image blur) and count. Then decide what to work on by combining four questions:
How much room for improvement is there (gap to human-level performance)?
Weighting the gap by frequency changes the picture: car noise has the largest gap, but people noise is so common that closing its smaller gap raises overall accuracy more. Combine such numbers with how easy and how important each slice is; then collect data or augment specifically for the chosen slices.
Module 4
Practice quiz: Error analysis and prioritization
Practice quiz · 5 questions
Error analysis and prioritization
Module 5
Data definition and pipelines
Lecture 2.5 · 10 min read
Defining data: label consistency
"What is the correct label?" is often less obvious than it seems. In speech, one transcriber writes "Um, today's weather", another "Um... today's weather", another drops the "um". In phone inspection, one inspector boxes two small scratches separately, another draws one big box around both. Every one of these labels is defensible; mixing them confuses the learning algorithm.
Improving label consistency is one of the most effective data-centric techniques:
Have two or more labelers label the same sample of examples and measure disagreement.
Where they disagree, discuss and write down a clear definition, with examples, in labeling instructions.
Merge classes that cannot be distinguished reliably, or add a class such as "borderline" or "unintelligible" for genuinely ambiguous cases.
import numpy as np
rng = np.random.default_rng(3)
a = rng.integers(0, 2, 200) # labeler A: defect yes/no
b = np.where(rng.random(200) < 0.85, a, 1 - a) # labeler B agrees 85% of the time
agree = (a == b).mean()
p_yes = (a.mean() + b.mean()) / 2
chance = p_yes ** 2 + (1 - p_yes) ** 2
kappa = (agree - chance) / (1 - chance)
print(f"agreement {agree:.1%}, agreement expected by chance {chance:.1%}, Cohen's kappa {kappa:.2f}")
Human-level performance, measured as how often one labeler agrees with another, is partly a measure of label consistency. When a model "beats" HLP, it may only be matching the labeling convention better, not making better decisions.
Lecture 2.6 · 9 min read
Data pipelines, provenance and metadata
Raw data usually passes through several processing steps before training: removing spam accounts, joining tables, cleaning text, computing features. In a proof of concept these steps live in ad-hoc scripts and manual fixes. For production, the exact same processing must run reliably on new data, or the model will see inputs it was not trained on (training-serving skew).
Replicability: script the whole pipeline so the same code runs in training and serving. Tools such as TensorFlow Transform, Apache Beam or dbt help as systems grow.
Provenance and lineage: record where each piece of data came from and which steps produced each feature, so you can trace and fix an error discovered months later.
Metadata: store context with each example (camera model, factory line, time of day, labeler ID). It makes error analysis possible ("errors come from line 17") and helps trace problems back to their source.
import pandas as pd
raw = pd.DataFrame({"user": [1, 2, 3, 4], "text": [" Great phone! ", "spam spam spam", "Battery bad", None],
"camera": ["A", "A", "B", "B"]})
def pipeline(df):
df = df.dropna(subset=["text"]).copy()
df["text"] = df["text"].str.strip().str.lower()
df = df[~df["text"].str.contains("spam")]
df["n_words"] = df["text"].str.split().str.len()
return df
clean = pipeline(raw)
print(clean.to_string(index=False))
print("rows kept:", len(clean), "of", len(raw), "| same function runs at serving time")
Lecture 2.7 · 7 min read
Balanced splits and small data
With large datasets a random split works fine. With small datasets, randomness can distort the class balance: in 100 examples with 30 positives, a random 20-example test set might contain 2 positives or 10. Use a stratified split so each set keeps the same proportion of each class.
import numpy as np
from sklearn.model_selection import train_test_split
y = np.array([1] * 30 + [0] * 70)
X = np.arange(100).reshape(-1, 1)
for strat in (None, y):
_, _, _, y_te = train_test_split(X, y, test_size=0.2, random_state=4, stratify=strat)
print("stratified" if strat is not None else "random ", "test positives:", int(y_te.sum()), "of", len(y_te))
Small datasets also make label quality matter more: with 50 examples, five inconsistent labels are 10% of the data. That is one more reason to apply the label consistency techniques from earlier in this week.
Improve a defect detector without touching its code: measure labeler agreement, clean labels by majority vote, find the weakest camera slice with metadata, and fix it in the data pipeline.
Step 1Agreement and kappa
Implement Cohen's kappa and compare three labelers.
Step 2Clean labels
Train the same model on one labeler and on the majority vote, and compare test accuracy on the true labels.
Step 3Slices and a pipeline fix
Rank cameras by gap × share, then standardize feature 0 per camera for the weak camera and retrain.
Checkpoint 1
Cohen's kappa between labelers A and C (two decimals)?
Checkpoint 2
Test accuracy gained by training on majority-vote labels?
Checkpoint 3
Test accuracy on camera C before the fix?
Checkpoint 4
Camera C accuracy gain from the per-camera standardization?
Week 3 · Scoping and operating ML systems
Scoping and operating ML systems
Choose projects worth doing, serve models in batch or online, audit them before launch, and keep them healthy with retraining.
Module 1
Scoping
Lecture 3.1 · 10 min read
Scoping a project
Scoping decides which project to work on, and it is where the most value is won or lost. A good process for a retail business might look like this:
Brainstorm business problems, not AI problems: "conversion rate is low", "inventory is wasted", "margins are thin".
Brainstorm AI solutions for each: a better product search, demand forecasting, price optimization.
Assess feasibility and value of each solution.
Determine milestones and budget for resources.
Keep the problem and the solution separate. The business owner knows the problem; the ML team knows which solutions are feasible. A good conversation between the two is the first deliverable.
Lecture 3.2 · 9 min read
Feasibility and value
A quick feasibility check uses two questions: is the data unstructured or structured, and is this a new problem or does a system exist already?
Unstructured (images, audio, text)
Structured (tables)
New problem
Human-level performance: can a person, given the same input, do the task?
Are predictive features available? Is there signal?
Existing system
Human-level performance plus history of the project
New predictive features plus history of the project
The human-level test needs care: a person must see exactly the input the model will get. If a self-driving system will only have a front camera image, ask whether a person looking at that image alone can tell whether the traffic light is red; a person standing at the crossing has more information than the model will.
For value, translate between the metrics engineers optimize (word error rate, accuracy) and the metrics the business cares about (user engagement, revenue). Agree on a bridge between them before starting, and write down the ethical considerations: is the project net positive for society, is it fair and free from bias?
Module 2
Practice quiz: Scoping
Practice quiz · 5 questions
Scoping
Module 3
Serving and responsible operations
Lecture 3.3 · 10 min read
Batch and online serving
Two serving modes cover most systems. Batch prediction runs the model periodically over a whole dataset, such as nightly recommendations for every user, and stores the results. Online prediction answers requests as they arrive, such as fraud checks during a payment, and needs low latency.
Batch
Online
When
scheduled (hourly, nightly)
per request
Key metric
throughput, cost
latency (p50, p95, p99)
Freshness
predictions can be hours old
uses the latest input
Typical use
recommendations, reports, scoring a database
search, fraud, chat, voice
Online serving is usually a prediction service behind an HTTP API, scaled horizontally across machines. Hardware and model size set the latency: the quantization, KV-cache and batching techniques from Course 4 Week 5 apply directly. Edge deployment runs the model on the device itself, which saves round trips and protects privacy but limits model size; cloud deployment allows bigger models at the cost of network latency.
import numpy as np, time
rng = np.random.default_rng(0)
W = rng.normal(size=(256, 10)).astype(np.float32)
users = rng.normal(size=(20_000, 256)).astype(np.float32)
t0 = time.perf_counter(); batch_scores = users @ W; t1 = time.perf_counter()
for u in users[:2000]:
_ = u @ W
t2 = time.perf_counter()
print(f"batch: {len(users)/(t1-t0):,.0f} predictions/s")
print(f"one at a time: {2000/(t2-t1):,.0f} predictions/s")
Lecture 3.4 · 8 min read
Performance auditing and model cards
Before a model goes live, audit it against what could go wrong. Brainstorm with the team: accuracy on different genders, ethnicities and accents; performance on different devices; rare but costly mistakes; offensive or harmful outputs. Choose metrics for each concern and compute them on the relevant slices, ideally with stakeholders who know the domain.
Document the result. A model card is a short document that ships with a model and states its intended use, the data it was trained and evaluated on, its metrics overall and per slice, known limitations, and ethical considerations. It helps the next team decide whether the model fits their use case, and it makes the audit reviewable.
import pandas as pd
card = {
"model": "speech-recognizer v3",
"intended use": "voice search on phones, English",
"not for": "medical or legal transcription",
"training data": "licensed read and conversational speech, 2019-2025",
"metrics": "word error rate overall 7.9%; by accent 6.8-11.2% (see table)",
"limitations": "degrades under heavy car noise and low-bandwidth audio",
}
print(pd.Series(card).to_string())
Lecture 3.5 · 7 min read
Retraining and the feedback loop
Production systems age. Monitoring tells you when; the response is usually retraining on newer data. Retraining can be manual (an engineer reviews the alarm, collects data, retrains, evaluates, and deploys through a canary) or automatic on a schedule or trigger, with an automated evaluation gate that blocks a worse model from shipping.
Beware feedback loops: a recommender trained on clicks influences what users see, which influences future clicks; a fraud model blocks transactions, so you never learn which blocked ones were legitimate. Keep a small amount of exploration or a holdout group so the data stays informative, and evaluate new models on data the old model did not shape.
Module 4
Practice quiz: Serving and responsible operations
Practice quiz · 5 questions
Serving and responsible operations
Final exam · 12 questions · pass mark 80%
Final exam
Questions from every week of the course. Pass it to complete the last requirement for the certificate on the Certificates page.
Final exam · 12 questions
Machine Learning in Production
Pass mark 80%. Passing this exam is one of the requirements for the course certificate. You can retake it as often as you like.
Certificates
Earn a certificate for every course
Each course certificate needs four things, all tracked automatically: watch every lecture video (90% of each), 60% or more on every weekly and practice quiz, every practice lab completed (all checkpoints correct), and 80% on the course's final exam. Earn all six and the specialization certificate unlocks. Progress is read from this browser.
Certificates are generated in your browser from the progress stored here, so clearing site data resets them. They record completion of this self-paced program and are not an accredited academic credential. Download as PNG or SVG, or print to PDF.