ECE571 / Week 3 · Linear classification & regression

Week 3 · Linear classification & regression

Linear models

One formula, , does two jobs: read it as a number and you have linear regression; read its sign and you have a linear classifier. This week covers how to fit it both ways.

~35 min read 10 practice questions + 2 problems Reading: Géron Ch. 4 (and Ch. 10, "The Perceptron")
The big picture

The video covers two decks. Lecture 3a (classification) is borrowed from a UIUC course and lecture 3b (regression) from a deep-learning course, so the notation shifts between them. This guide puts them in the order that makes sense: first linear regression, fit exactly with a formula or step by step with gradient descent; then linear classification with the perceptron, which learns by nudging a line every time it makes a mistake; then what happens when you make the perceptron smooth enough for gradient descent, which is where logistic regression comes from.

After this you can
Section 1

One formula, two jobs

Lecture 06:44–08:33, 40:00–42:303b slide 2, 3a slide 12Géron Ch. 4

weights: how much each feature matters, and in which direction
bias (offset, intercept)
TaskOutputExample
Regressionthe number itselfpredict a house price
Classificationits sign: dog (+1) or cat (−1)
The bias trick

Append a constant 1 to every input: and . Then , and the bias is just another weight. Both decks do this. It's why 3a writes with no , and why 3b's matrix has a column of 1s.

Section 2

Least-squares linear regression

Lecture 42:36–44:253b slides 2–4Géron Ch. 4, "The Normal Equation"

Pick the line whose predictions have the smallest total squared error on the training data (the MSE from week 2, without the ):

12345 ŷ = 0.83x + 0.85 total area = SSE = 2.26
"Least squares" is literal. Each orange square has side equal to one prediction miss, so its area is that miss squared. The best line is the one with the smallest total square area. No other line gets below 2.26 for these five points. (Drawn with equal x and y scales so the squares are true squares.)

Setting both partial derivatives to zero gives a closed-form answer (slide 3):

Worked example

Data: , , , . So , , .

Line: . Predictions 1.9, 3.3, 4.7, 6.1; misses 0.1, −0.3, 0.3, −0.1; SSE = 0.2.

Many features: the normal equation

Stack the inputs as rows of a matrix (with the column of 1s from the bias trick) and the targets as a vector . Minimizing by setting its gradient to zero gives:

Check with the example: , , and solving gives , the same answer.

Common trap

The formula needs to be invertible. That fails if one feature is a combination of others (e.g. height in cm and height in inches) or if there are fewer samples than weights. Inverting is also slow for many features (roughly cubic in ). Both are reasons to use gradient descent instead (Géron Ch. 4 covers this trade-off).

Section 3

"Linear" in what?

Lecture 44:42–48:303b slides 5–6Géron Ch. 4, "Polynomial Regression"

"Linear regression" means linear in the weights, not necessarily in the inputs. You can feed in , or as extra features and it's still linear regression, solved with the exact same formula:

ModelLinear regression?
yes
yes: each just multiplies a feature
yes
yes for (this is slide 5's "log-linear regression")
no: the s sit inside and
Heads up: slide 6

Slide 6 lists under "not linear regression models", while slide 5 presents the same thing as "log-linear regression". Both are defensible. It isn't linear for , but it is an ordinary linear regression on the transformed target . On an exam, say exactly that.

Heads up: lecture 46:46 vs the slides and textbook

In the lecture, polynomial regression is grouped with "nonlinear functions" that "cannot have a closed-form solution", so you'd need gradient descent. That's only true for models that are nonlinear in the weights (the last row of the table). A polynomial in is still linear in its weights, so the normal equation solves it exactly. Géron does precisely this in "Polynomial Regression": add as features, then fit ordinary linear regression.

Section 4

Fitting by gradient descent

Lecture 47:08–1:09:403b slides 7–9, 33–41Géron Ch. 4, "Gradient Descent"

Instead of solving exactly, start from and repeatedly step downhill on the loss. (For the step-by-step mechanics see the sample guide on gradient descent.) The loss for linear regression is a convex bowl, so there's one minimum and gradient descent finds it.

Calculus refresher (3b slides 11–32): derivative, chain rule, gradient

Derivative = slope: . E.g. .

Chain rule: . E.g. . The chain rule is all of backpropagation later in the course.

Gradient = vector of partial derivatives. For : , which at is .

Multivariable chain rule: . Slide 29's example (, , ) gives , which matches differentiating directly.

For one training point with loss and , the chain rule gives:

the error: positive if the prediction was too low, so the weights move to raise it
learning rate
Heads up: sign error on 3b slides 7–8

The "vectorized" column writes and then updates . Taken literally, that's , which moves uphill. The gradient is missing a minus sign. The "for-loop" column on slide 8 and slide 9 have it right: . The final rule above is the correct one. (The on those slides is the identity function for linear regression; slide 36 says so.)

One step, by hand

Start , . Training point . Prediction , error .

,   . The new prediction at is : closer to 5, as it should be.

Updating after every single point is online (stochastic) mode. Updating once per pass with the summed gradient is batch mode. Updating on small groups is mini-batch (slide 38), the usual choice in deep learning: it vectorizes well and is less noisy than one point at a time.

Terminology

In the lecture, "batch mode" is used loosely for mini-batch (e.g. 10–20 images per update), and the professor points out that papers saying "SGD" almost always mean mini-batch too. Strictly: batch = the whole training set per update, stochastic = one sample, mini-batch = a small random subset. The gradient formula is the same in all three; only which data you sum over changes. A constant factor like can be folded into .

Flagged in lecture · 48:33

"This is basically the homework you can take: try to think about how to use gradient descent to solve this least-squares regression, no matter if it's linear functions or nonlinear functions." The recipe: write the loss, take its gradient with respect to every weight (chain rule), then loop . Check your linear-regression answer against the normal equation; they should agree.

Why gradient descent is trustworthy here: least-squares loss is convex, so with a small enough it reaches the global minimum. For non-convex losses (later, neural networks) it can get stuck in a local minimum. The professor recommends Boyd & Vandenberghe, Convex Optimization (it's in the textbook folder; Ch. 9 covers gradient descent) for more.

Scale your features

Unscaled features 12 steps, still far from the minimum Standardized features 6 steps, essentially at the minimum
Simulated gradient descent from the same starting point. When one feature has a much larger range, the loss bowl becomes a long, narrow valley. The step size has to be small enough not to bounce across the narrow direction, so progress along the long direction crawls. Standardizing features makes the bowl round (3b slide 41: "always normalize inputs!").
Section 5

Classifying with a line

Lecture 01:43–05:44, 27:20–34:033a slides 3–8, 29–31, 34

The lecture opens with "tell dogs from cats". One feature alone fails: weight (a Maine Coon cat outweighs a Chihuahua) or "comes when called" (some dogs ignore strangers). Combining them works better: with = times it comes when called (out of 40) and = weight in pounds, say "dog if ". The boundary is a straight line, which is why this is called a linear classifier.

w wᵀx + b = 0 wᵀx + b > 0 → +1 wᵀx + b < 0 → −1
The weight vector is perpendicular to the boundary and points to the positive side. grows as you move in the direction of , is zero on the line, and is negative on the other side. The bias slides the line without rotating it.

With more than two classes, give each class its own weights and pick the class with the highest score: . The plane splits into regions with straight-edged borders (slide 31).

Section 6

The perceptron

Lecture 05:44–19:303a slides 10–20Géron Ch. 10, "The Perceptron"

Rosenblatt's perceptron (1958–59) was modeled on a neuron: weighted inputs are summed and the output is a binary "fire or don't". Its big idea was that it learns from examples:

  1. Start with any weights (random or zero). Labels are .
  2. For each training point, predict (bias trick included).
  3. If : do nothing. If wrong: .
  4. Repeat passes (epochs) until a full pass makes no mistakes.

Two conventions from the lecture: the professor defines (a score of exactly zero counts as positive), and in practice you stop after a fixed number of epochs (full passes over the data), whether or not it has converged. He also notes that is "large in practice".

Flagged in lecture · 39:36

"In the homework we have the implementation of this perceptron algorithm." When you code it: append the constant 1 to every , use labels ±1 (not 0/1), loop over epochs and then over samples, update only on mistakes, and stop when an epoch has zero mistakes or the epoch limit is hit. Scaling the features first (see below) makes it behave far better.

Why does adding help? After the update, the score for that point changes by , which moves it in the direction of the correct sign.

The slides' dogs-vs-cats run (η = 1)

= [comes when called /40, weight in lb, 1]. Start with : "dog if it comes more than 20 times".

AnimalxTrue yScore wᵀxPredictionNew w
Presa Canario[1, 100, 1]dog +11 − 20 = −19cat ✗[1,0,−20] + [1,100,1] = [2, 100, −19]
Maltese[40, 10, 1]dog +180 + 1000 − 19 = 1061dog ✓unchanged
Maine Coon[0, 20, 1]cat −10 + 2000 − 19 = 1981dog ✗[2,100,−19] − [0,20,1] = [2, 80, −20]

The slides stop there, but it's worth checking the result. With , the Maine Coon scores : still classified as a dog. The boundary means "dog if it weighs more than about a quarter pound". Every real cat is now a "dog".

Start: w = [1, 0, −20] comes when called lb Presa ✗ dog side boundary: x₁ = 20 After: w = [2, 80, −20] comes when called lb Maine Coon: still "dog" boundary ≈ the axis (0.25 lb)
Why the slides' example ends badly. Circles = dogs, squares = cats; the shaded side is "dog". Weight in pounds (0–100) is a much bigger number than "comes when called" (0–40) or the constant 1, so each update with η = 1 swings the boundary wildly. The fix is the same one as for gradient descent: scale the features, and/or use a smaller η. The extra dogs and cats are illustrative; the Presa, Maltese and Maine Coon numbers are the slides'.
Section 7

When does it work? Separability and XOR

Lecture 19:30–27:20, 30:56–32:403a slides 21–27, 32–33

A dataset is linearly separable if some line (plane, hyperplane) puts every positive on one side and every negative on the other.

  • If the data is separable, the perceptron is guaranteed to find a separating line in a finite number of mistakes, even with . The proof idea (slides 22–26): replace each by , which flips the negatives so that "correct" means for every point. Each mistake adds that point to , turning toward the side where all the flipped points lie.
  • If it isn't separable, the perceptron never settles: some point is always wrong, so keeps getting pushed around. The fix is a decaying learning rate, e.g. for the th update, so the wiggling dies down (slide 27).
x₁ OR x₂ x₁ + x₂ − 0.5 > 0 x₁ AND x₂ x₁ + x₂ − 1.5 > 0 x₁ XOR x₂ no line works not linearly separable
Inputs at the four corners of the unit square (bottom-left is (0,0), top-right is (1,1)); circles = output 1, squares = output 0. OR and AND are each one straight cut. XOR needs the two diagonals on opposite sides, which no single line can do (see Problem 2 for the proof).

This is the famous limitation from Minsky & Papert's 1969 book Perceptrons. Many people read it as "neural networks can't learn XOR" and the field cooled for years, even though the same book showed that a two-layer network handles XOR easily. You'll see that in the multilayer perceptron (week 13).

Section 8

Making it differentiable: toward logistic regression

Lecture 34:18–39:363a slides 36–45Géron Ch. 4, "Logistic Regression"

The perceptron's update rule looks ad hoc. Why not just do gradient descent? Because is a step function: its derivative is zero everywhere except at the jump, so the gradient gives no direction. The fix is to swap the step for a smooth S-curve.

Said twice in lecture (00:33, 39:03)

"Logistic regression here is a classifier. It's not a regressor, it's not linear regression." The name is historical: it regresses a probability, then thresholds it to pick a class.

1−1 −22z sgn(z) tanh(z) σ(z) = 1/(1+e⁻ᶻ)
The step function has no useful slope; the S-curves do. tanh runs from −1 to 1 (matching ±1 labels); the logistic sigmoid σ runs from 0 to 1 (a probability). They're the same shape, rescaled: .

The slides' version (3a, slides 36–44): output , squared-error loss , and using :

Compare it with the perceptron's . Same idea, but the step is scaled by how wrong the output is, , and by how steep tanh is there, . Points the model is already sure about barely move it.

Cross-check with the textbook

The slides call this "logistic regression". Géron (Ch. 4, Eq. 4-13 to 4-18) and most references define logistic regression differently: labels , output read as a probability, and the log loss instead of squared error. That gives the clean gradient , and log loss is convex, while squared error on top of an S-curve is not. Know both. If an exam just says "logistic regression", the textbook version is the safe default.

PerceptronSlides' "differentiable perceptron"Logistic regression (Géron)
Labels±1±10 / 1
Output = P(class 1)
Loss(none; mistake-driven)squared errorlog loss (cross-entropy)
Update on mistakes only
Who updatesmisclassified pointsevery point, a littleevery point, a little

One more correction: slide 44 says that for logistic regression, "if then do nothing". With tanh, is never exactly ±1, so in practice every point contributes a small update. That's the real difference from the perceptron, as the last row shows.

Section 9

Cheat sheet

Linear model; bias trick: append 1 to
Least squares (1-D),
Normal equation; needs invertible
"Linear"linear in the weights; , features are fine
GD update (squared loss),
Online / batch / mini-batchupdate per point / per full pass / per small group
Feature scalingstandardize → round loss bowl → faster GD and saner perceptron updates
Linear classifier; ⟂ boundary, points to + side
Perceptronon a mistake: ; converges iff data separable
Multi-class
XORnot linearly separable; needs two layers
tanh / sigmoid; ;
Logistic regression, log loss, gradient , convex, no closed form
Section 10

Practice

Score: 0 / 0

Q1Why do the slides append a 1 to every feature vector?

Q2Perceptron with sees , . What happens?

Q3Perceptron (η = 1) with sees , . New w?

Q4You train a perceptron with η = 1 on the four XOR points. What happens?

Q5Is a linear regression model?

Q6Your features include temperature in °C and the same temperature in °F. What breaks in the normal equation?

Q7For squared loss , which is the correct gradient-descent update?

Q8Gradient descent zig-zags and converges slowly. One feature ranges 0–1, another 0–10,000. Best fix?

Q9What are tanh(0) and the range of tanh?

Q10Which statement about (textbook) logistic regression is true?

Problem 1: Fit a least-squares line to (0, 1), (1, 3), (2, 4) by hand.

, , , .

Numerator: . Denominator: . So .

.

Check: predictions 1.167, 2.667, 4.167; misses −0.167, 0.333, −0.167, which sum to zero, as least-squares misses always do when there's a bias term.

Problem 2: Prove no line can classify XOR (positive at (0,1) and (1,0), negative at (0,0) and (1,1)).

Suppose one did. The four points require:

(0,0) negative: .   (1,1) negative: .
(0,1) positive: .   (1,0) positive: .

Add the two positive conditions: , so . That contradicts . So no such line exists. ∎