ML / DL Refresher, Part 1

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.

Fit the same points three ways

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

Why a Model Must Generalize

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.

Memorize or learn

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.

0%

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.

The road

  1. The setup: inputs, labels, a model with knobs, and six ingredients.
  2. Loss and empirical risk: one number for how wrong the model is.
  3. The normal equations: the exact best line.
  4. Gradient descent: walk downhill when there is no formula.
  5. Overfitting and validation: the U curve, and how to choose without the test set.
  6. Bias and variance: why the U curve has its shape.
  7. Regularization: ridge and lasso tame a flexible model.
  8. The probabilistic view: likelihood, the sigmoid and logistic regression.
  9. The field guide: terms, numbers, code and links.
A steering model has zero error on its recorded frames but crashes in a new lot. What is the right diagnosis?

Chapter 1

The Supervised Learning Setup

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.

IngredientWhat it isFor a line
Training dataPairs of input and labelPoints (x, y)
ModelA family of functions with knobs θslope × x + bias
LossHow wrong one prediction is(y − prediction)²
ObjectivePick θ to make the average loss smallLeast squares
OptimizationHow we find that θA formula, or gradient descent
GeneralizationDoes 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.

Turn the knob on one example

Pick a robot task. Drag the weight θ and watch the pink prediction move against the blue label.

0.30

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.

A robot predicts the distance to an obstacle in meters. What kind of problem is it, and what separates it from "is the path blocked: yes or no"?

Chapter 2

Loss and Empirical Risk

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.

Say it aloud

Ell of y and y-hat equals y minus y-hat, squared.

ℓ(y, ŷ)
ell of y and y-hat the loss on one example. Never negative.
y
y the true label, such as the expert's steering angle.
ŷ
y-hat the model's prediction for the same input.
( )²
squared the gap times itself.
In plain words

Subtract y-hat from y. Square the gap to get ell. A miss twice as large costs four times as much.

With numbers

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).

Say it aloud

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.

R̂(θ)
R-hat of theta the empirical risk: the average training loss for weights θ.
1/N
one over N divide by N, the number of training examples.
Σi
the sum over i add one term for each example, i from 1 to N.
yi
y-i the label of example i.
f(xi; θ)
f of x-i and theta the model's prediction for input x-i with weights θ.
In plain words

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 numbers

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.

Move one prediction, watch the risk

Drag turn 2's prediction. Yellow bars are each example's loss; the dashed line is their average. Switch to absolute loss and compare.

−0.20

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.

Model A misses one label by 1.0; model B misses it by 2.0. Under squared loss, how much larger is B's loss?

Chapter 3

Linear Regression and the Normal Equations

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.

Say it aloud

Theta-star equals the inverse of X-transpose X, times X-transpose y.

θ*
theta-star the best weights, [slope, bias].
XTX
X-transpose X a 2 by 2 table of sums: sum of x², sum of x, and the count N.
( )−1
the inverse of undoes a matrix multiply, like dividing.
XT
X-transpose X with rows and columns swapped.
XTy
X-transpose y two sums: sum of x times y, and sum of y.
In plain words

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.

With numbers

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.

Where the formula comes from

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.

Shrink the squares

Each yellow square is one point's squared miss. Drag slope and bias to shrink their total, then press Best fit.

0.30
0.50

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.

For the points (1, 2), (2, 2), (3, 4), what does the table XTX hold?

Chapter 4

Gradient Descent and the Learning Rate

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.

Say it aloud

Theta becomes theta minus eta times the gradient of R-hat at theta.

θ
theta the weights, updated in place.
←
becomes replace the old value with the new one.
η
eta the learning rate, the step size, such as 0.1.
∇R̂(θ)
the gradient of R-hat at theta one slope per weight; together they point where the loss rises fastest.
In plain words

Measure the slope of the loss at theta. Move theta against it by eta times the slope. Repeat until the loss stops falling.

With numbers

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.

Find the learning rate that breaks it

Set the learning rate, then press Run. Teal arrows are the steps. Try 0.1, 0.9, then 1.1.

0.10

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:

  1. Average the loss over the examples.
  2. Start with a large step.
  3. Halve eta when the validation error stops improving.
  4. Stop when it no longer improves: early stopping.

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.

On the loss theta², you start at 3 with eta = 1.1. The steps land at −3.6, then 4.32. What is happening?

Chapter 5

Overfitting, Underfitting and the Validation Set

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.

CaseTraining errorTest errorDo this
Underfithighhigh, close to trainingadd flexibility
Good fitlowlowkeep it
Overfitnear zerofar above trainingsimplify, regularize, or add data

Sweep the degree

Yellow is training error, warm is test error. Drag the degree. Then turn on validation and see if it finds the same bottom.

1

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.

Choose without the test set

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:

  1. Train each candidate on the rest of the training data.
  2. Score each one on the validation set.
  3. Keep the best. Open the test set once, for the final score.

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.

A model has training error 0.001 and test error 0.8. What is the diagnosis and a valid fix?

Chapter 6

Bias and Variance

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.

Say it aloud

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.

E[(y − f̂(x))²]
the expected value of y minus f-hat, squared the test error at x, averaged over many training sets and many noisy labels.
(f̄(x) − f(x))²
f-bar minus f, squared bias squared: how far the average fit sits from the truth.
E[(f̂(x) − f̄(x))²]
the expected value of f-hat minus f-bar, squared the variance: how much one fit strays from the average fit.
σ²
sigma squared the noise in the labels, 0.04 in the toy.
In plain words

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.

With numbers

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.

Retrain forty times

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.

1
12

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.

A model always predicts 0, whatever the input. What is its bias and variance?

Chapter 7

Regularization

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").

Say it aloud

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.

J(θ)
J of theta the objective that training makes small.
Σi
the sum over i one term per training example.
yi
y-i the label of example i.
θTxi
theta-transpose x-i the prediction: each weight times its feature, summed.
λ
lambda the penalty strength, zero or more.
Σj θj²
the sum over j of theta-j squared the total squared size of the weights.
In plain words

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.

With numbers

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.

θ* = (XTX + λI)−1 XTy,   where I is the identity matrix: ones on the diagonal, zeros elsewhere.

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.

Turn up lambda

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.

−8.0

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.

You add a ridge penalty with a large lambda. What happens to the fit?

Chapter 8

The Probabilistic View: Likelihood and Logistic Regression

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.

Say it aloud

P equals sigma of s, which equals one over one plus e to the minus s.

p
p the probability that the label is 1, between 0 and 1.
σ
sigma the sigmoid function, an S-shaped squash.
s
s the raw score of the line, w times x plus b.
e
e the constant 2.718.
In plain words

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.

With numbers

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.

Say it aloud

Ell equals minus the quantity y log p, plus one minus y times log of one minus p.

ℓ
ell the log loss on one example.
y
y the label, 1 or 0.
log
log the natural log. It is negative below 1, so the minus sign makes the loss positive.
p
p the predicted probability that y is 1.
In plain words

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.

With numbers

Label y = 1. With p = 0.88 the loss is 0.13. With p = 0.12 it is 2.13, about 17 times more.

Fit a classifier by likelihood

Filled blue dots are label 1, hollow are label 0. Drag w and b, watch each yellow loss bar, then press Fit.

0.50
−1.50

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.

Why pass a line's score through a sigmoid for yes or no labels, and how do we then train?

Chapter 9

Field Guide

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.

TermOne lineNumber from this lesson
GeneralizationLow error on data the model did not train onLookup table: 0 on training, 0.40 on a new lot
Squared loss(y − y-hat)²miss of 2 costs 4
Empirical riskAverage training loss0.02 on three turns
Normal equationsθ* = (XTX)−1XTyslope 1, bias 0.667
Gradient descentθ ← θ − η × gradienton theta², eta above 1 diverges
OverfittingLow training error, high test errordegree 9: 0.006 against 0.805
Bias and varianceTest error = bias² + variance + noisedegree 1: 0.167 + 0.007 + 0.04
RidgePenalty λ × sum of squared weightstest error 1.91 to 0.064
LassoPenalty on absolute weights; sets some to zeroswitches features off
Logistic regressionSigmoid of a line, trained on log lossscore 2 gives p = 0.88

Checklist before you trust a model

  1. Split off a test set first, from the conditions the robot will meet.
  2. Choose the model, the degree, eta and lambda on a validation set.
  3. Plot the training loss per step. Cut eta if it grows.
  4. Compare training and validation error: both high means underfit; a wide gap means overfit.
  5. Open the test set once.
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

Keep going

The takeaway. Fit on training data, choose on validation data, judge on test data. The gap between training and test error is the whole story.

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

Introduction to Robot Learning · CMU 16-831 · Lecture 3
Next: ML / DL Refresher, Part 2 · Back to Gleams