A degree 9 curve passes through all 10 training points, so its training error is zero. On new points from the same source its error is 1.29, about 15 times the cubic's 0.09.
Pick a model, then press New training set. Watch which curve stays put and which one jumps. Then we build, piece by piece, the loss, the fit, gradient descent, the validation set, bias and variance, regularization and the probabilistic view.
You need a little Python and what a slope is. We build the rest from zero.
Based on Lecture 3 of CMU 16-831, Introduction to Robot Learning, taught by Guanya Shi: the supervised learning half of the ML and deep learning refresher. The explanations, toys and devices here are our own. It follows Lecture 2, Robot Learning: An Overview.
An illustrative toy. The true curve is sin(3.2x); each label adds noise with standard deviation 0.2. We measure test error on 60 fresh points. The lede's numbers are the first training set.
Chapter 0
See a model score zero on its training data and still fail on new data
You teach a robot car to steer. You record an expert in one parking lot and train a model until it matches every recorded frame. Its error on those frames is zero. Then you drive it to a new lot, and it hits a curb.
The model did not learn to steer. It stored the answers for the frames it saw. Generalization is doing well on data the model did not train on. It is the score that matters, because we already know the answers for the training data.
To measure it, split the data in two. The training set is what the model learns from. The test set stays locked away, and it judges the model at the end.
Blue dots are the recorded lot. Warm rings are a new lot. Pick a model, then drag the new lot away from the old one.
Illustrative toy: steering angle = 0.8 × curvature, plus noise with standard deviation 0.12. The lookup table answers with the stored label of the nearest recorded input.
The lookup table scores zero on the recorded lot at every setting. On a new lot in the same place its error is 0.041, twice the line's 0.021, because it copied the noise. Move the lot fully away and the table's error is 0.40. The line stays at 0.021.
Symptom: training error near zero, poor results in the field.
Measure: the error on a held-out test set drawn from where the robot will run.
Fix: the rest of this lesson: a simpler model, more varied data, a penalty on the weights.
Chapter 1
Name the input, the label, the model and its knobs, and the six ingredients every learner shares
Supervised learning fits a function from labeled examples: inputs paired with their correct outputs, called labels. A teacher supplied the answer for each training input. The model is a function with tunable knobs, the weights θ ("theta"). Training sets the knobs.
| Ingredient | What it is | For a line |
|---|---|---|
| Training data | Pairs of input and label | Points (x, y) |
| Model | A family of functions with knobs θ | slope × x + bias |
| Loss | How wrong one prediction is | (y − prediction)² |
| Objective | Pick θ to make the average loss small | Least squares |
| Optimization | How we find that θ | A formula, or gradient descent |
| Generalization | Does the loss stay small on new data? | Small error on held-out points |
The six ingredients stay the same from a line to a large transformer. Only the model family grows.
Outputs come in two kinds. In regression the label is a real number, such as a steering angle. In classification it is one choice from a fixed set, such as "grasp safe" or "grasp unsafe". Only the output space and the loss change.
Pick a robot task. Drag the weight θ and watch the pink prediction move against the blue label.
Illustrative single examples. Steering: curvature 0.5, label 0.4. Grasp: score 1.5, label 1 (safe), prediction is a probability. Next speed: speed 2.0 m/s, label 1.8 m/s.
In robot learning the label can be an expert's action (imitation learning) or the world's next state (a dynamics model for control). The lecture's warning: how you collect and use that data matters more than which model you pick.
Symptom: the model trains well but fails on the robot.
Measure: compare training inputs with the inputs the robot sees: lighting, speeds, objects.
Fix: collect data under the conditions where the robot will run.
Chapter 2
Score one prediction, then average the scores into the number training makes small
To fit anything we need a score for how wrong one prediction is. That score is the loss. Call the true label y and the model's prediction ŷ ("y-hat"). For regression the standard loss squares the gap.
Ell of y and y-hat equals y minus y-hat, squared.
Subtract y-hat from y. Square the gap to get ell. A miss twice as large costs four times as much.
With made-up numbers: y = 1.0 and y-hat = 0.9 give ell = 0.01. A miss of 2 costs 4; a miss of 4 costs 16.
One example says little. Average the loss over all N training examples. That average is the empirical risk. Choosing θ to make it small is empirical risk minimization (ERM).
R-hat of theta equals one over N, times the sum over i of ell of y-i and f of x-i and theta.
Run the model on each x-i. Score it against y-i with ell. Add the scores and divide by N to get R-hat.
With made-up numbers: labels 0.4, 0.0, 1.0 and predictions 0.5, −0.2, 0.9. Losses 0.01, 0.04, 0.01. R-hat = 0.06 / 3 = 0.02.
Drag turn 2's prediction. Yellow bars are each example's loss; the dashed line is their average. Switch to absolute loss and compare.
The three steering turns of the worked number. Units are radians; we made the values up.
"Empirical" means measured on the data we have. ERM bets that a low training risk buys a low test risk. Chapters 5 to 7 keep that bet honest.
Symptom: one bad label, say a sensor glitch, drags the whole fit.
Measure: list the per-example losses. One of them dwarfs the rest.
Fix: clean the label, or use the absolute loss, which grows only in proportion to the miss.
Chapter 3
Solve for the best line in one step, and check it by hand on three points
The simplest model is a line: prediction = slope × x + bias. Add a constant feature 1 to every input. Then the bias is one more weight, and the prediction is the dot product of θ = [slope, bias] with [x, 1].
Stack the inputs into a matrix X with one row [xi, 1] per example, and the labels into a vector y. For a line under squared loss, the best weights have a formula.
Theta-star equals the inverse of X-transpose X, times X-transpose y.
Build the table X-transpose X and the vector X-transpose y. They give two equations in slope and bias. Their solution is theta-star.
Points (1, 2), (2, 2), (3, 4). X-transpose X = [14 6; 6 3] and X-transpose y = [18; 8]. Solve 14s + 6b = 18 and 6s + 3b = 8: slope s = 1, bias b = 0.667.
The training loss is the sum of (yi − prediction)². At its minimum its slope in every weight is zero. That condition reads XT(Xθ − y) = 0, which is XTX θ = XTy. Multiply both sides by the inverse of XTX.
Check: the line x + 0.667 predicts 1.67, 2.67, 3.67. The misses are +0.33, −0.67, +0.33. They sum to zero, as they must when the model has a bias.
Each yellow square is one point's squared miss. Drag slope and bias to shrink their total, then press Best fit.
The three points of the worked number. Best fit snaps to the normal equations' answer.
The best line leaves a mean squared error of 0.222. No slope and bias do better. Now solve it in code, and measure error on held-out points.
Symptom: the solver reports a singular matrix, or the weights are huge.
Measure: count features against examples, and look for two copies of one feature.
Fix: drop the duplicate, or add the ridge penalty of Chapter 7.
Chapter 4
Walk the weights downhill one step at a time, and find the step size that breaks it
A line has a formula. A neural network with millions of weights has none. Gradient descent walks downhill instead. Picture the loss as a landscape over the weights. The gradient points straight uphill, so step the other way. The step size is the learning rate.
Theta becomes theta minus eta times the gradient of R-hat at theta.
Measure the slope of the loss at theta. Move theta against it by eta times the slope. Repeat until the loss stops falling.
Toy loss R-hat = theta², so the gradient is 2 × theta. Start at theta = 3 with eta = 0.1: 3 − 0.1 × 6 = 2.4, then 1.92. Each step multiplies theta by 1 − 2 × eta = 0.8.
Set the learning rate, then press Run. Teal arrows are the steps. Try 0.1, 0.9, then 1.1.
The toy loss theta², starting at theta = 3, at most 20 steps.
At eta = 1.1 the factor is 1 − 2.2 = −1.2. Theta goes 3, −3.6, 4.32, −5.18: each step overshoots and lands farther out. On this bowl any eta above 1 diverges.
Stochastic gradient descent (SGD) estimates the gradient from a small random mini-batch of examples. Each step is noisier but costs one batch, not the whole dataset. The lecture's rules of thumb:
Symptom: the loss grows, or turns into NaN.
Measure: plot the loss per step, and watch for weights that flip sign each step.
Fix: cut eta by a factor of 10 and run again.
Chapter 5
Sweep the model's flexibility, find the bottom of the U curve, and choose it without touching the test set
Make a model more flexible, for example by raising the degree of a polynomial. A failure waits at each end. Underfitting: the model is too simple for the pattern, so training and test error are both high. Overfitting: the model fits the noise, so training error is tiny and test error is large.
| Case | Training error | Test error | Do this |
|---|---|---|---|
| Underfit | high | high, close to training | add flexibility |
| Good fit | low | low | keep it |
| Overfit | near zero | far above training | simplify, regularize, or add data |
Yellow is training error, warm is test error. Drag the degree. Then turn on validation and see if it finds the same bottom.
The hero's toy, averaged over 30 training sets of 12 points. Each set has its own validation set of 12 points. The vertical axis is logarithmic.
Training error only falls. Test error falls to 0.072 at degree 3, then climbs to 0.805 at degree 9. The bottom of the warm curve is the model you want.
A hyperparameter is a knob the optimizer does not set, like the degree or the learning rate. To pick one we want test error, but a test set we look at stops being a fair judge. So carve a validation set out of the training data:
If data is scarce, use k-fold cross-validation: split the data into k parts, validate on each part in turn, and average. Validation and test data must come from the conditions the robot will meet.
Symptom: a great test score, then poor results on new data.
Measure: count the choices you made while looking at the test score.
Fix: make every choice on validation data. Use the test set once.
Chapter 6
Retrain on many fresh datasets and split the test error into three parts
Train the same model many times, each time on a fresh training set from the same world. The fits differ. Their average and their spread explain the U curve.
Call the true function f(x). Call one trained model's prediction f̂(x) ("f-hat"), and the average over all training sets f̄(x) ("f-bar"). The bias is the gap between f-bar and f. The variance is how far each f-hat strays from f-bar. The noise σ² is the part of the label no model can predict. For squared loss these add up.
The expected value of y minus f-hat of x, squared, equals f-bar minus f, squared, plus the expected value of f-hat minus f-bar, squared, plus sigma squared.
Fit many models on fresh data. Square the gap from their average f-bar to the truth f: that is bias. Average each f-hat's squared gap from f-bar: that is variance. Add the noise sigma squared.
From the device, 12 points, averaged over x: degree 1 gives 0.167 + 0.007 + 0.04 = 0.214. Degree 9 gives 0.003 + 0.071 + 0.04 = 0.114.
Faint pink lines are 40 fits, each on its own training set. The bold line is their average; dashed grey is the truth. Drag the degree, then the data size.
The hero's toy. We average bias and variance over x from −0.9 to 0.9, where the training points lie.
Underfitting is high bias. A model that always predicts 0 has zero variance and large bias. Overfitting is high variance. More data shrinks variance: at degree 9, going from 12 to 30 points cuts it from 0.071 to about 0.011.
The lecture flags one exception. Huge networks, with far more weights than examples, often generalize well. Part of the explanation is the implicit regularization of SGD. Bias and variance are the base, not the final word.
Symptom: retraining on a different slice of the data gives a far different model.
Measure: train five models on resampled data and compare their predictions.
Fix: more data, a simpler model, or a penalty on the weights.
Chapter 7
Add a price on large weights and watch a wild polynomial calm down
You need a flexible model, but the data is fixed. Regularization adds a penalty on the weights to the training loss, so the fit prefers small weights. Call the penalty strength λ ("lambda").
J of theta equals the sum over i of y-i minus theta-transpose x-i, squared, plus lambda times the sum over j of theta-j squared.
Add up the squared misses. Add lambda times the sum of squared weights. Lambda = 0 is plain least squares; a large lambda pulls every weight toward zero.
A line through the origin on (1, 2), (2, 2), (3, 4) has theta = (sum of x times y) / (sum of x² + lambda). Lambda = 0: 18 / 14 = 1.29. Lambda = 4: 18 / 18 = 1.00.
This is ridge regression. It has a formula: add lambda to the diagonal of XTX before you solve. The bump also makes the system solvable when features outnumber examples.
Lasso uses the sum of absolute weights instead. It drives some weights to exactly zero, which switches features off. Either penalty is an inductive bias: a preference set before seeing data. The lecture points to robot learning, where a penalty can ask for smooth dynamics or smooth motions.
A degree 9 fit to 12 points. Dashed grey is the fit with no penalty. Drag lambda and watch the pink fit and the weight bars.
The hero's toy, one training set of 12 points. Test error uses the same 60 fresh points. Bars show each weight's size on a log scale.
At lambda = 10−8 the test error is 1.91. At 10−3 it falls to 0.064. At 10 the fit is too flat and the error climbs back to 0.41.
Symptom: training and test error are both high, and the fit is nearly flat.
Measure: validation error over a grid of lambdas, such as 10−6 to 10.
Fix: pick the lambda with the lowest validation error.
Chapter 8
Derive the loss from a probability model, and use it to classify
Let the model output a probability for each label, given the input. Maximum likelihood estimation (MLE) picks the θ that makes the observed training labels most probable. The log turns the product over examples into a sum. If labels are a line plus Gaussian noise, MLE gives the squared loss, and a Gaussian prior on the weights adds the ridge penalty.
For yes or no labels, a line's raw score s can be any number. Squash it into a probability p that the label is 1.
P equals sigma of s, which equals one over one plus e to the minus s.
Compute e to the minus s, add 1, and take 1 over the result. A large positive s gives p near 1; s = 0 gives one half.
s = 2: e to the minus 2 is 0.135, so p = 1 / 1.135 = 0.88. s = −2 gives p = 0.12.
Train it by MLE. The negative log likelihood of one label is the log loss, also called binary cross-entropy.
Ell equals minus the quantity y log p, plus one minus y times log of one minus p.
If y is 1, the loss is minus log p. If y is 0, it is minus log of 1 minus p. Average it over the examples; making it small is MLE.
Label y = 1. With p = 0.88 the loss is 0.13. With p = 0.12 it is 2.13, about 17 times more.
Filled blue dots are label 1, hollow are label 0. Drag w and b, watch each yellow loss bar, then press Fit.
Illustrative toy: ten points with overlapping labels. Fit runs gradient descent on the average log loss.
For more than two classes the sigmoid becomes the softmax, and the loss becomes multi-class cross-entropy.
Symptom: the loss turns into infinity or NaN.
Measure: look for a predicted p of exactly 0 or 1; log of 0 is minus infinity.
Fix: clip p away from 0 and 1, or compute the loss from the score s with a library function.
Chapter 9
Keep the terms, the numbers, a checklist and the core code in one place
Supervised learning fits weights that make the average training loss small, then checks the loss on held-out data. Every method in 16-831 uses this pipeline, whether the label is a class, the next state, or an expert's action.
| Term | One line | Number from this lesson |
|---|---|---|
| Generalization | Low error on data the model did not train on | Lookup table: 0 on training, 0.40 on a new lot |
| Squared loss | (y − y-hat)² | miss of 2 costs 4 |
| Empirical risk | Average training loss | 0.02 on three turns |
| Normal equations | θ* = (XTX)−1XTy | slope 1, bias 0.667 |
| Gradient descent | θ ← θ − η × gradient | on theta², eta above 1 diverges |
| Overfitting | Low training error, high test error | degree 9: 0.006 against 0.805 |
| Bias and variance | Test error = bias² + variance + noise | degree 1: 0.167 + 0.007 + 0.04 |
| Ridge | Penalty λ × sum of squared weights | test error 1.91 to 0.064 |
| Lasso | Penalty on absolute weights; sets some to zero | switches features off |
| Logistic regression | Sigmoid of a line, trained on log loss | score 2 gives p = 0.88 |
pythonimport numpy as np def fit_ridge(X, y, lam=0.0): # X: (N, d) with a column of ones; y: (N,) d = X.shape[1] # lam = 0 gives the normal equations return np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ y) def fit_gd(X, y, lr=0.05, steps=200): # gradient descent on the mean squared error theta = np.zeros(X.shape[1]) for _ in range(steps): grad = (2 / len(y)) * X.T @ (X @ theta - y) theta = theta - lr * grad return theta def fit_logistic(X, y, lr=0.5, steps=2000): # y in {0, 1}; minimizes the average log loss theta = np.zeros(X.shape[1]) for _ in range(steps): p = 1 / (1 + np.exp(-X @ theta)) theta = theta - lr * X.T @ (p - y) / len(y) return theta
Credit: Lecture 3 of CMU 16-831, Introduction to Robot Learning, taught by Guanya Shi. The lesson re-teaches its supervised learning half in our own words and devices.
Go back to the three fits at the top and predict each read-out before you press. Then explain the U curve aloud with Present, or teach it on the whiteboard with Teach.
"Don't get confused by fancy names: ask yourself what exactly makes this method work." Guanya Shi, Lecture 3