Least-Squares Regression and Autoregressive Models

Fit a line by solving one equation, keep it steady with a small penalty, then aim the same trick at a signal's own past to predict what comes next and fill what is missing.

A stretch of sound has lost 40 samples. Pick a way to guess them back, and see which method turns a hole into a clean wave.

Press each method in turn, then drag the gap longer. A straight line cannot bend. The autoregressive fit can, because it learned the signal's rhythm. Then we build every piece from zero: the squared miss, the leash called ridge, the closed-form answer, and the prediction trick behind the fill.

You need a little linear algebra (a matrix times a vector gives a vector) and a feel for a sine wave. We build the rest from zero.

Based on Lecture 12 of Stanford EE269: Signal Processing for Machine Learning (February 2019, slides numbered Lecture 20 on this site), taught by Mert Pilanci. Lecture slides (PDF), all decks. The audio examples in the deck are credited there to P. Smaragdis. Every idea is re-taught here in our own words, with our own interactive devices.

Fill the gap

40

Illustrative signal: two tones, 0.31 and 0.83 radians per sample (about 395 Hz and 1,057 Hz at an 8 kHz sample rate), plus a trace of noise. The autoregressive weights are fitted by least squares on the samples that survive; the gap is then solved exactly as the lecture describes (Chapter 8).

Chapter 0

A Number to Predict

See how a weighted sum of measurements turns signals into a predicted number, and meet the two jobs this lecture solves with it

A phone listens to ten milliseconds of your voice. A filter splits that snippet into three bands and measures how much energy sits in each: low, middle and high. Three numbers come out. The phone must turn them into one more number, say a loudness score from 0 to 10.

That job has a name. Regression means predicting a continuous number (one that can land anywhere on a scale) from some measurements. Predicting a label such as “cat” or “dog” is classification, the topic of earlier lectures. Here the answer is a quantity: a loudness, a temperature, the next sample of a wave.

This lecture is the twelfth deck of EE269, given by Mert Pilanci on 25 February 2019, and it has seventeen slides. It does two things with one tool. First it builds that tool, least squares, slide by slide, with a penalty called ridge. Then it aims the tool at a signal's own past, which yields autoregressive models that forecast a wave and repair damaged sound.

The words for the data

Each example is a pair. The features are the measurements, written as a vector x with d entries (here d = 3: low, middle, high). The target is the number we want, written y. We hold n such pairs, (x1, y1) up to (xn, yn). The lecture says x lives in Rd and y lives in R: a list of d real numbers, and one real number.

Stack the n feature vectors as the rows of a table and you get a matrix called X, with n rows and d columns. Stack the n targets into a column called y. Every later formula in this lesson is about those two objects.

The simplest guess: a weighted sum

How should a machine turn three numbers into one? The simplest honest rule gives each feature a weight, a number that says how much that feature matters, then adds up. Think of a mixing desk: each band has a fader, and the output is the blend. A big weight means the fader is up.

The lecture writes this as a linear model. The sum runs over the d features, and one extra number w0, the offset (also called the bias or intercept), sets the output when every feature is zero.

f(x)
The prediction: one number for the feature vector x.
wTx
The dot product: multiply each feature by its weight, then add. The small T means the weight list is laid on its side so it lines up with x.
w0
The offset. It lifts or lowers the whole prediction by a fixed amount.
∑ x[n] w[n]
The same dot product written as a sum. x[n] is feature number n, and w[n] is its weight.
w0
The same offset, added once at the end.

Play with the rule on a tiny table of four clips. Each clip has three band energies and a true loudness. Move the three weights and the offset, and watch the guesses move. The bars inside each cell show that feature's share of the guess.

Mix the weights

Each row is one clip: three band energies (the features) and its true loudness. The guess is the weighted sum. Drag the faders until the guesses match the true column, then read how big the leftover miss is.

1.0
1.0
1.0
0.0

Toy numbers, made up for this page: X is a 4 × 3 table, w has 3 entries and the four guesses form a vector of 4. The true loudness values were built from weights (2, 4, 1) and offset 1, so a perfect setting exists. Real data never fits this cleanly, which is what Chapter 1 is about.

Look at the shapes, because they stay the same all lesson. The table above is a matrix X with one row per clip, so four rows and three columns. The weights form a vector with three entries. The matrix times the vector gives four numbers, one guess per clip, and adding the offset to each finishes the job. When the weights are right, those four guesses match the four true values.

Notice what you did by hand. You searched for a good w. The lecture's whole first half is the answer to one question: can a computer find the best w directly, without searching? It can, and the answer is a single equation. First we need to say what “best” means.

The road

The lesson follows the deck in order. Each chapter's slide range sits in the heading comment of its section.

  1. How wrong is a line?: the squared miss, the risk, and why we average over the data we have.
  2. A leash on the weights: the ridge penalty, and the tug of war it creates.
  3. Take the average out: the offset has a closed form, and centring removes it.
  4. One equation solves it: the gradient, the ridge solution, and a way to break it.
  5. Predict what you have never seen: prediction as a step from the average, and choosing lambda.
  6. A signal predicts itself: autoregressive models and forecasting.
  7. A sine wave needs two weights: why AR(2) is exact for a pure tone.
  8. Fill the hole: solving for missing samples. Go back to the hero and try again.
  9. Field guide: numbers, checklist, code, and what comes next.
A clip has features (0.5, 0.5, 0.5), weights (2, 4, 1) and offset 1. What does the linear model predict?

Chapter 1

How Wrong Is a Line?

Score a guess by its squared misses, then see why we average over the data we hold instead of the data we wish we had

Five clips from a sensor sit on a chart. The horizontal axis is a reading x. The vertical axis is the true value y we hoped to predict. You lay a ruler across the dots and draw a line. Is it a good line? A friend draws a different one. Which of you is closer?

You need a score, one number that gets smaller as the line gets better. Then “best line” just means “lowest score”. This chapter builds that score from the deck's third slide.

The miss at one point

Take one example (x, y). The line guesses f(x). The residual is the leftover: y minus f(x). A positive residual means the line guessed too low. A negative one means too high. Zero means a perfect hit.

How do we turn five residuals into one score? Adding them fails. A guess 2 too high and a guess 2 too low add to zero, and a terrible line can score perfectly. We need every miss to count as a cost, whichever way it points.

The lecture squares each residual. The square is never negative, so misses cannot cancel. It also punishes big misses much harder than small ones: a miss of 2 costs 4, but a miss of 0.2 costs only 0.04. And the square is smooth, so we can use calculus on it, which we do in Chapter 4.

From one point to a score called risk

Imagine every clip the sensor could ever produce. The pairs (x, y) follow some unknown pattern of chance, which the lecture calls Px,y. The honest score of a line is its average squared miss over that whole pattern. Statisticians call it the risk, and write E for “the average over chance”. The lecture names the goal minimum mean squared error.

R(w, w0)
The risk of the line with weights w and offset w0. Lower is better.
Ex,y
The expected value: the average over every pair (x, y) that chance could produce, weighted by how likely each pair is.
(f(x) − y)2
The squared miss at one pair. This is the price of one wrong guess.

There is a catch, and the slide says it plainly: Px,y is not known. Nobody hands us the pattern of chance. We hold only n samples from it. So we do the natural thing and replace the average over all possible pairs with the average over the pairs we have. This is the empirical risk, also called the mean squared error (MSE) on the training data.

minw, w0
Search over every weight vector and offset, and keep the pair with the smallest value of what follows.
(1/n) ∑
Add the n squared misses, then divide by n to get their average.
(yi − wTxi − w0)2
The squared residual of sample i. It is the target minus the model's guess, squared.

A worked example, every number

Use five points with x = 1, 2, 3, 4, 5 and y = 2.2, 2.9, 4.4, 4.9, 6.6. Try the line with w = 1 and w0 = 1. Its guesses are 2, 3, 4, 5, 6. The residuals are 0.2, −0.1, 0.4, −0.1, 0.6. Square them: 0.04, 0.01, 0.16, 0.01, 0.36. They add to 0.58, so the empirical risk is 0.58 / 5 = 0.116.

(0.04 + 0.01 + 0.16 + 0.01 + 0.36) / 5 = 0.116 (the line w = 1, w0 = 1)

Now try w = 1.08 and w0 = 0.96. The guesses are 2.04, 3.12, 4.20, 5.28, 6.36. The residuals are 0.16, −0.22, 0.20, −0.38, 0.24. Squares add to 0.316, so the risk is 0.0632. That is about half as large. Chapter 3 shows where those two numbers come from. Now drag the line yourself, and watch the squares.

Grow the squares

Each yellow square has a side equal to one point's miss, so its area is that miss squared. Move the slope and the offset. The score is the average area. Press the button to jump to the best line.

0.40
3.00

The five points are the worked example above (illustrative values). The best line shown, w = 1.08 and w0 = 0.96, is the closed-form answer derived in Chapters 3 and 4 with lambda = 0.

Try to find a line with a lower score by hand. You cannot beat 0.0632. The squares are smallest in total there, and it is the only line with that property, because the score is a smooth bowl in (w, w0) with one lowest point. The sum of the plain signed misses, shown in the read-out, tells you why squaring was needed: it can sit near zero even when the squares are huge.

What the average hides

One worry remains. The empirical risk measures the data we hold, not the data we will meet. A model with a great many weights can thread through every training point and score zero on them, yet guess wildly on a new clip. The next chapter adds a brake against that.

Why does the lecture replace the expectation Ex,y[(f(x) − y)2] with the average over the n training samples?

Chapter 2

A Leash on the Weights

Add a penalty on the size of w, and watch the best answer slide from the data's favourite toward zero

Two microphones sit an inch apart on a table. Both record the same voice, almost sample for sample. You ask least squares to predict loudness from both. It finds a clever trick: weight the first microphone at +50 and the second at −49. The two nearly cancel, and a tiny difference between the microphones gets amplified into a fit that matches your training clips beautifully.

Then a new clip arrives with slightly different noise. The tiny difference changes, the amplifier turns it into nonsense, and the prediction is off by a mile. The weights were doing something no sensible person would trust. We need a way to say: prefer small weights.

Name the symptom, then measure it

The symptom is weights that are huge and of opposite sign. The measurement is the squared length of the weight vector: ||w||22, which means w[1]² + w[2]² + … added together. For the microphone trick that number is about 4,900. For a calm answer such as (0.5, 0.5) it is 0.5.

The fix on slide 4 is to add that number to the score, scaled by a knob called lambda (λ). The new score pays for misses and for big weights. Adding a size cost of this kind is called regularisation. This particular cost, the squared length, gives ridge regression. You will also meet it as Tikhonov regularisation or L2 regularisation.

data term
The empirical risk from Chapter 1. It pulls the weights toward whatever fits the training data best.
λ
The leash. A number at or above zero that says how much one unit of weight size costs. Zero means no leash.
||w||22
The penalty: the sum of the squared weights. It pulls the weights toward zero. The offset w0 is left out on purpose (Chapter 3).

A tug of war in one dimension

Start with one weight and a toy data term (w − 2)², which is smallest at w = 2. Add the penalty λw². The total, (w − 2)² + λw², is a bowl again, and its lowest point is where the slope is zero. The slope is 2(w − 2) + 2λw. Set it to zero and solve: w = 2 / (1 + λ).

λ = 0: w = 2.00   λ = 0.25: w = 1.60   λ = 1: w = 1.00   λ = 4: w = 0.40

Read it as a tug of war. The data pulls toward 2 and the penalty pulls toward 0. The knob λ sets the strength of the second rope. At λ = 1 the ropes are equally strong, so w lands halfway. As λ grows, w is dragged toward zero but never reaches it. This effect is called shrinkage.

The same war with two weights

With two correlated features, the data term is not a round bowl but a long, thin valley. Think of the two microphones: many weight pairs along the valley floor fit nearly equally well, and the best one is far from the origin. The penalty is a round bowl centred at zero. Their sum has its lowest point somewhere between the valley's bottom and the origin. Slide λ and watch it travel.

Tighten the leash

The blue ovals are levels of the data term; their centre is the least-squares answer. The purple circle passes through the ridge answer (orange dot) and is a level of the penalty. The orange curve is the path the answer takes as lambda grows. Drag lambda.

0.30

Illustrative: two correlated features whose data term is (w − w*)T A (w − w*) with A = [[1, 0.9], [0.9, 1]] and least-squares weights w* = (2.2, −0.6). The ridge answer is (A + λI)−1 A w*, derived in Chapter 4. The slider is logarithmic.

At λ = 0 the dot sits at the valley's centre with weights (2.20, −0.60), the ones that cancel each other. By λ = 1 the dot has slid to about (0.65, 0.40) and the weights have stopped fighting each other. The data term got worse, and that is the price: ridge accepts a slightly poorer fit to training data in return for weights that do not blow up. Chapter 5 shows when that bargain wins on new data.

The score is (w − 2)² + λw². At λ = 1 where is its lowest point, and what happens to w as λ grows?

Chapter 3

Take the Average Out

Differentiate once to find the offset, and discover that centring the data makes the offset disappear

A weather station logs the temperature every hour. The readings sit near 20 degrees. You want a line that predicts the next hour from the hour of day. The line must start high, near 20, even though the hour counter starts at zero. So the offset w0 has real work to do: it carries the average level of the data.

Slides 5 and 6 show that this offset never needs a search. One derivative finds it in closed form, and then a simple move, subtracting the averages, makes it vanish from the problem. This chapter does that derivation slowly.

Step 1: differentiate with respect to the offset

Start from the ridge score of Chapter 2. We want its lowest point. At the lowest point of a smooth bowl the slope is zero, so we take the derivative (the slope, written ∂) with respect to w0 and set it to zero. The penalty does not contain w0, so it drops out of this step. That is the deliberate choice we flagged in Chapter 2: we penalise the weights, not the offset. If we shrank w0 too, the model could not represent a station that sits at 20 degrees without paying a fee for it.

Each squared residual (yi − wTxi − w0)² has slope −2(yi − wTxi − w0) with respect to w0. Add them, divide by n, and set the total to zero. The −2 cancels, and what is left is a plain statement: the residuals must add to zero.

w0*
The best offset for a given w. The star marks “optimal”.
(1/n) ∑ (yi − wTxi)
The average of what the weights leave unexplained. The offset absorbs exactly that average.
ȳ − wTx̄
The same thing using means: ȳ is the average target, x̄ is the average feature vector. (The deck prints these as plain sums; they are means, with the 1/n.)

Read the result as geometry. Rearranged it says ȳ = w0 + wTx̄. The fitted line, at the average input, outputs the average target. The best line always passes through the centre of mass of the data. It may pivot around that point, but it never leaves it.

Step 2: plug it back in

Put w0 = ȳ − wTx̄ into each residual. It becomes yi − wTxi − ȳ + wTx̄. Group the terms: (yi − ȳ) − wT(xi − x̄). Each target and each feature vector now appears minus its own average. The offset has gone, and only w is left to find.

Give the subtracted versions a name, as the slide does. The centred signals are x̃i = xi − x̄ and ỹi = yi − ȳ. Stack the centred features as rows of a matrix X̃ (still n rows and d columns) and the centred targets into a vector ỹ. The squared residuals added together equal ||X̃w − ỹ||22: the squared length of the vector of misses. Multiply the whole score by n, which changes nothing about where the lowest point sits, and the penalty becomes nλ||w||22.

minw
Only the weights remain to be searched. The offset is solved.
||X̃w − ỹ||22
The data term in vector form: the squared length of the vector whose entries are the n centred misses.
nλ ||w||22
The penalty. It carries a factor n because we multiplied the score by n.

See it move

Take the five points of Chapter 1. Their averages are x̄ = 3 and ȳ = 4.2, so the centre of mass sits at (3, 4.2). Subtract it from every point and the cloud lands on the origin: x̃ = −2, −1, 0, 1, 2 and ỹ = −2.0, −1.3, 0.2, 0.7, 2.4. In that picture the best line must go through (0, 0), so no offset is needed. The slope does not change when you slide the whole cloud. Only the offset does.

Slide to the origin

Press Centre the data and watch the cloud and its line slide until the centre of mass sits on the origin. Then press again and drag Shift the cloud right: the slope stays the same while the offset changes.

0.0

The five points are the worked example from Chapter 1 (illustrative). The slope 1.08 is the least-squares slope with lambda = 0 on the centred data: the sum of x̃ỹ is 10.8 and the sum of x̃² is 10, so w = 10.8 / 10.

With the cloud unshifted, the raw intercept is 4.2 − 1.08 × 3 = 0.96, the number you used in Chapter 1. Shift the cloud right by 2 and x̄ becomes 5, so the intercept falls to 4.2 − 1.08 × 5 = −1.20. The picture moved, the slope did not, and the formula tracked it.

A fitted line has slope w = 2 and the data have x̄ = 4 and ȳ = 10. What is the offset, and where does the line pass?

Chapter 4

One Equation Solves It

Take the gradient, set it to zero, and read off the ridge solution, then break it with two nearly identical features

You have a bowl-shaped score and you want its lowest point. A hiker would walk downhill until the ground is flat. Calculus lets us skip the walk: at the lowest point the ground is flat in every direction, so the gradient (the list of slopes, one per weight) is zero. Slide 7 does exactly this and reads off a formula.

Expand, differentiate, set to zero

Start from the centred ridge score. Write it out by multiplying the brackets: ||X̃w − ỹ||² = wTX̃TX̃w − 2wTX̃Tỹ + ỹTỹ. Add the penalty nλwTw. Three kinds of term appear: one with w twice (a bowl), one with w once (a tilt) and one with no w (a constant).

Now take the slope in every weight at once. A term with w twice has slope twice the matrix times w. A term with w once has slope equal to its coefficient vector. A constant has slope zero. The slide writes the result in compact form.

∂/∂w
The gradient: a list of d slopes, one for each weight.
2X̃T(X̃w − ỹ)
The slope of the data term. The bracket is the vector of misses; the matrix X̃T tells each weight which misses it can blame.
2nλw
The slope of the penalty. It always points along w, so it pulls every weight toward zero in proportion to its size.

Divide by 2 and collect the terms that contain w: X̃TX̃w + nλw = X̃Tỹ. Write nλw as nλIw, where I is the identity matrix (ones on the diagonal, zeros elsewhere), so w can be pulled out of both terms. We get (X̃TX̃ + nλI)w = X̃Tỹ. Multiply both sides by the inverse of the bracket and the weights are alone.

w*
The optimal weights, a vector of d numbers. It is the answer to the whole problem.
(X̃TX̃ + nλI)−1
The inverse of a d × d matrix. X̃TX̃ records how the features move together; nλI adds a floor to its diagonal.
X̃Tỹ
A list of d numbers: how strongly each feature moves with the target.

Check it on the five points

Here d = 1 and n = 5, so every matrix is a single number. X̃TX̃ = 4 + 1 + 0 + 1 + 4 = 10. X̃Tỹ = (−2)(−2.0) + (−1)(−1.3) + 0 + (1)(0.7) + (2)(2.4) = 4 + 1.3 + 0.7 + 4.8 = 10.8. With λ = 0 the weight is 10.8 / 10 = 1.08. With λ = 0.2 the bracket is 10 + 5 × 0.2 = 11, so w = 10.8 / 11 = 0.982. With λ = 1 it is 10.8 / 15 = 0.72. Offsets follow from Chapter 3: 0.96, 1.25 and 2.04. The leash shortens the slope and the offset rises to keep the line through (3, 4.2).

w* = 10.8 / (10 + 5λ) λ = 0: 1.08   λ = 0.2: 0.982   λ = 1: 0.72

Data flow, with shapes

Real problems have many features, so look at the shapes. X̃ is n × d and ỹ is n. The product X̃TX̃ is d × d, built in about n·d² multiplications. X̃Tỹ is d. Solving the d × d system costs about d³. The output w is d: one weight per feature, no matter how many samples n you had. In code you ask a solver for the answer to the linear system. You do not form the inverse explicitly, which is slower and less accurate.

Why the leash makes the solve safe

The matrix X̃TX̃ can be singular, meaning it has no inverse. That happens when one feature is a copy of another, or when d is larger than n. Two microphones that record the same sound are the classic case. Adding nλI lifts every eigenvalue of the matrix (its stretch factors along its special directions) by nλ. A zero stretch becomes nλ, so the bracket always has an inverse when λ is above zero. The ratio of the biggest to the smallest eigenvalue is the condition number. A huge one means a tiny change in the data swings the answer wildly. Try it below: make the two microphones near twins and watch the weights.

Break it, then fix it

Twelve clips, two microphones. Both hear the same sound plus a little private noise. The true weights are (1, 1). Drag Mic noise down to make the microphones twins, then raise lambda.

0.50
0

Illustrative data generated in your browser: a shared sound s, microphone readings s plus noise of the chosen size, and a target of 2s plus 0.5 noise. The weights, matrix and condition number are exact for these twelve clips. Test error uses 200 fresh clips from the same recipe. Lambda is logarithmic from 0.0001 to 1.

With the default noise the two weights are lopsided but modest: about (1.36, 0.28), condition number 16. Pull the noise down to 0.05 with lambda at zero and they fly apart to about (4.84, −3.03), one large and positive, the other large and negative, while the condition number climbs to about 1,400. Raise lambda to 0.1 and the pair snaps back to (0.96, 0.80), and the test error drops from 0.363 to 0.295. The leash fixed the symptom, the condition number measured it, and the equation above is why.

Why is X̃TX̃ + nλI invertible for any λ > 0, even when two features are identical?

Chapter 5

Predict What You Have Never Seen

Start at the average and step by how far a new input sits from the average, then choose lambda by testing on held-out data

The weather station has fitted its line. Now a new hour arrives, one the training data never contained, and a number must come out. This is the moment the whole exercise was for. Slides 8 and 9 show how to predict, and a short piece of algebra shows that the prediction has a friendly shape.

Predict with what you stored

After training you keep three things: the weights w*, the offset w0* and the averages x̄ and ȳ. Given a test signal x, the lecture's prediction is the same weighted sum as before: f(x) = w0* + w*Tx.

Now substitute the offset from Chapter 3, w0* = ȳ − w*Tx̄. The prediction becomes ȳ − w*Tx̄ + w*Tx. The two dot products share w*T, so group them. (The slide prints x in the middle step where x̄ belongs; the grouping below is the correct one.)

f̂(x)
The prediction for a new input x. The hat means “estimated from data”.
ȳ
The starting guess: the average target in the training data.
w*T
The learned weights. They convert a distance in feature space into a change in the answer.
(x − x̄)
How far the new input sits from the average training input, one entry per feature.

This reads as a recipe. Start at the average answer. Then move by how unusual the input is, weighted by what each feature is worth. An average input gets the average answer. Training data supplies the starting point and the weights supply the slope.

Worked numbers

For the five points, x̄ = 3 and ȳ = 4.2. A new input x = 6 sits 6 − 3 = 3 above the average input. With λ = 0 the weight is 1.08, so the prediction is 4.2 + 1.08 × 3 = 7.44. With λ = 0.2 the weight is 0.982 and the prediction is 4.2 + 0.982 × 3 = 7.15. With λ = 1 the weight is 0.72 and it is 4.2 + 0.72 × 3 = 6.36. As λ becomes very large, w goes to zero and every prediction collapses to ȳ, the plain average. Move the test point and the leash below.

The data flow at test time

Follow one test clip through the machine. It arrives as a vector x of d numbers. Subtract the stored average x̄, also d numbers, and you have the centred input. Take its dot product with w*, which gives a single number. Add ȳ. That is the whole pipeline: one subtraction, one dot product, one addition, and the model needs only 2d + 1 stored numbers.

Notice what the model never keeps: the training samples themselves. Every example was squeezed into d weights and two averages. That is why prediction is so cheap, and also why a new input that looks nothing like the training data gets a confident answer anyway. The formula has no way to say “I have never seen anything like this”. A weather line trained on afternoons will happily predict midnight.

Walk from the average

The pink dot is the centre of mass. From it, the teal leg walks sideways to your test input; the orange leg climbs by the weight times that distance. Drag the test input and the leash.

6.0
0.00

The five training points are the running example (illustrative). The weight is 10.8 / (10 + 5λ), from Chapter 4, so the prediction at x = 6 is 7.44 at lambda 0, 7.15 at 0.2 and 6.36 at 1.

Failure mode: a great fit that predicts badly

The symptom: the training error is tiny and the error on new data is large. The measurement: set aside a few examples the fit never saw, called the held-out or validation set, and compute their average squared miss. Compare it with the training miss. A wide gap means overfitting. The fix is lambda, and you pick it by looking at the held-out curve.

The next device builds a hard case on purpose: 20 training clips and 15 features, with only three features that truly matter. The plot sweeps lambda from 0.001 to 100. Training error (blue) can only rise as the leash tightens. Held-out error (yellow) first falls, then rises again, forming a U. The bottom of the U is the lambda to use.

The held-out set is simply data you hide from the fit. A common recipe splits the clips into five groups, trains on four, scores on the fifth, and rotates. Averaging the five scores gives a steadier estimate than any single split, and it works for every value of lambda you want to try.

Find the bottom of the U

Blue is the error on the 20 training clips. Yellow is the error on 400 held-out clips. The teal line is your lambda; the green dot is the best held-out lambda. Slide, then press New data to see if the bottom stays put.

0.002

Illustrative: 20 training and 400 held-out clips with 15 Gaussian features, true weights (2, −1.5, 1, 0, … 0) and noise of size 1, generated in your browser. Each point on the curves is a full ridge solve of Chapter 4. Real data will not be this clean; the shape of the U is what carries over.

Training error at tiny lambda is far below the noise level (a noise variance of 1), because 15 weights can bend to 20 points. Held-out error at the same lambda is typically three to twelve times the noise, depending on the draw. As lambda grows the gap closes from both sides, until too much leash starts hurting the fit on both curves. That is the bias and variance trade in one picture: more leash means more bias, less leash means more variance, and the held-out set tells you where they balance.

The training data have x̄ = 3 and ȳ = 4.2, and the fitted weight is 0.72. What does the model predict for a new input x = 5?

Chapter 6

A Signal Predicts Itself

Use the last few samples of a signal as the features and the next sample as the target, then forecast by feeding predictions back in

A guitar string rings. Its next sample, one 8,000th of a second from now, is not random: it looks a lot like the last few samples, nudged along the wave. If you knew the nudge rule you could predict the whole note. Slide 10 turns that hunch into regression, and it needs no new mathematics.

The idea: the past is the feature list

So far each example had a feature vector x and a separate target y. Now the signal supplies both. The target is the current sample x[n]. The features are the p samples just before it: x[n−1], x[n−2], up to x[n−p]. Each weight wk says how much the sample k steps back counts. The lecture calls this an autoregressive model (AR): auto because the signal is regressed on itself, and the number p is its order.

x[n]
The sample at time n. This is the number we want to predict.
∑ wk x[n − k]
A weighted average of the past: the sample k steps back, times its weight, added over k = 1 to p. The lecture says “predict current sample from the past using a weighted average”.
en
The error term: whatever the past cannot explain, such as noise. It is the residual of Chapter 1.

Stack it into a matrix

Slide 10 writes the same thing for all times at once: x = Aw + e. Build the matrix A one row per time. The row for time n is the window [x[n−1], x[n−2], …, x[n−p]]. With N samples, the first p have too little past, so A has (N − p) × p entries, the vector x of targets has N − p entries and w has p. Sliding the window one step down gives the next row, so each column is the signal shifted by one more sample.

Then the fit is the problem of Chapter 4 with new names: w* = arg min ||Aw − x||22. (arg min means “the w that gives the smallest value”.) A plays the role of X̃ and x plays the role of ỹ. Audio and other zero-average signals need no centring and no offset. If your signal has a baseline, subtract its average first, exactly as in Chapter 3. You can add a tiny ridge term for stability.

A tiny worked fit

Take seven samples of a slow sine wave sampled every 30 degrees: 0, 0.5, 0.866, 1, 0.866, 0.5, 0. Use order p = 2. Each row pairs the two previous samples with the current one. For time 2 the row is (0.5, 0) with target 0.866. For time 3 it is (0.866, 0.5) with target 1. Time 4 gives (1, 0.866) with target 0.866, time 5 gives (0.866, 1) with target 0.5, and time 6 gives (0.5, 0.866) with target 0. Solving the least-squares problem gives w = (1.732, −1). Check time 3: 1.732 × 0.866 − 1 × 0.5 = 1.5 − 0.5 = 1.0. It lands on the target, and so does every other row. Chapter 7 proves why.

x[n] = 1.732 x[n−1] − 1.000 x[n−2] (residual 0 on all five rows)

Forecasting: feed the answers back

Slide 11 is titled forecasting. To predict one step beyond the data, apply the formula to the last p samples. To predict two steps, slide the window and use the first prediction as if it were real data. This is a free run: the model drives itself, and every guess carries the errors of the guesses before it. A one-step prediction is easier, because each step is given the true past.

The device trains an AR model on the first 120 samples of a two-tone signal, then predicts the last 80. Flip between the two modes, move the order, and add noise. A tone is a pure repeating wave, and every tone needs two weights, so two tones should need order 4.

Predict the next samples

Blue is the true signal; the shaded part is the training data. The orange line is the model's prediction of the remaining 80 samples. Choose a mode, then raise the order, then add noise.

2
0.000

Illustrative signal: tones at 0.31 and 0.83 radians per sample with amplitudes 1 and 0.55, plus noise of the chosen size. Weights come from least squares on the first 120 samples with a tiny ridge of 10−6. The same signal drives the hero and Chapter 8.

At order 2 with no noise the model nails neither mode: a single rule can only carry one tone, so the free run drifts to an error near 0.82 against a signal size of 0.79, slightly worse than guessing zero. At order 4 it becomes exact in both modes, because two tones need four weights. Now add noise 0.02 and stay at order 4: the one-step error stays small, near 0.11, but the free run decays to about 0.78. The noise pulled the fitted wave inward, and a model that loses a little energy each step goes flat. Raise the order to 8 and the free run recovers, to about 0.05. Extra weights give the fit room to absorb the noise.

An AR(p) fit on N samples builds a matrix A. What are its rows, its size, and what does the fit solve?

Chapter 7

A Sine Wave Needs Two Weights

Prove with one trigonometric identity that two past samples predict a pure tone exactly, and see the fit recover the frequency

A tuning fork hums at one pure pitch. Its samples trace a sine wave, and a sine wave is the most predictable thing in signal processing. Look at three samples in a row: the one before, the current one and the next one. They are tied by a fixed rule. Slides 12 to 14 show the rule, and it needs only two weights.

The claim

Take the autoregressive model of Chapter 6 with just two non-zero weights and no error term. This is AR(2) with en = 0. The deck writes it with minus signs: x[n+1] = −w0x[n] − w1x[n−1]. In this lesson's convention, where each weight multiplies its sample directly, the same rule reads x[n+1] = c1x[n] + c2x[n−1], so c1 = −w0 and c2 = −w1. The claim is that the pure tone x[n] = sin(αn) obeys this rule exactly, for the right c1 and c2. Here α is the tone's frequency in radians per sample: how far around the circle the wave turns in one sample.

The proof, one identity

The lecture reminds us of a trigonometric identity: sin(a + b) + sin(a − b) = 2 cos(b) sin(a). It follows in two lines. Expand each sine by the angle-sum rule: sin(a + b) = sin a cos b + cos a sin b, and sin(a − b) = sin a cos b − cos a sin b. Add them. The cos a sin b terms cancel and 2 sin a cos b is left.

Now choose a = αn and b = α. Then a + b = α(n + 1), which is the next sample, and a − b = α(n − 1), which is the previous sample. The identity says x[n+1] + x[n−1] = 2 cos(α) x[n].

x[n + 1]
The next sample of the tone, sin(α(n + 1)).
2 cos(α)
The first weight c1. It depends only on the frequency α. A slow tone has α near 0, so the weight is near 2.
x[n]
The current sample.
x[n − 1]
The previous sample, with weight c2 = −1 for every tone.

A check on the sign, since the printed slide's last line carries −2 cos(α) on the middle term. Take a very slow tone, α close to 0. Then cos(α) is about 1 and the rule says x[n+1] = 2x[n] − x[n−1]. That is straight-line extrapolation, which is right for a wave that barely curves. With −2cos the slow wave would flip sign every step. So the middle weight is positive: c1 = 2 cos(α), which in the deck's convention means w0 = −2 cos(α) and w1 = +1.

Numbers, and the surprise

Let α be 30 degrees, which is π/6 radians. Then 2 cos(α) = 1.732. The samples are 0, 0.5, 0.866, 1, 0.866, 0.5. Predict x[3] from x[2] and x[1]: 1.732 × 0.866 − 0.5 = 1.5 − 0.5 = 1.0. Correct. Predict x[4]: 1.732 × 1 − 0.866 = 0.866. Correct. This is the fit found in Chapter 6, now explained.

The surprise is what the weights do not depend on. The identity works for A sin(αn + φ) with any amplitude A and any starting phase φ, because the same two sines appear in the same combination. Two samples set the amplitude and phase. The weights set only the frequency. So an AR(2) fit is a frequency detector: from the weights you can recover α = arccos(c1 / 2), then convert to Hertz as α / (2π) times the sample rate.

Two tones need two such rules multiplied together, which gives four weights, so order 4. That is why Chapter 6's two-tone signal became perfectly predictable at order 4 and not before. In general, k pure tones need order 2k. Try it below on a single tone: set the frequency, let the fit run, and compare the recovered number with the truth.

Recover the frequency

The stems are 60 samples of a sine wave. The orange dots are what the two fitted weights predict from the two previous samples. Pick a frequency, then add noise. Slide the probe to check the rule on any three samples in a row.

0.52
0.00
12

Illustrative: x[n] = sin(αn + 0.6) for n = 0 to 59, plus noise of the chosen size, with the two weights fitted by least squares on all 60 samples. At an 8 kHz sample rate, α = 0.52 would be about 662 Hz. The weights depend on α alone, never on the phase 0.6.

With no noise the fitted first weight equals 2 cos(α) to many decimal places and the second equals −1, so the recovered α matches the truth. The probe line shows the rule holding sample by sample. Add noise and the weights drift a little, because the fit now sees noisy samples where the rule assumes clean ones. The recovered frequency stays close, which is why this idea is a practical way to estimate a pitch.

A pure tone has α = π/3 radians per sample (cos α = 0.5). Which AR(2) rule predicts it exactly?

Chapter 8

Fill the Hole

Turn the fitted model into a banded system of equations and solve it for the samples that went missing

A recording has a dropout. A burst of electrical noise ate 40 samples, a few milliseconds of sound, and the player clicked. You still have the samples on both sides. Can the gap be filled with something so natural that nobody hears the repair? Slides 15 to 17 say yes, and the hero at the top of this page is the answer in action.

One equation per time step

Once the AR model has been fitted, every sample obeys its own equation: x[n] = ∑k wkx[n−k]. Move the sum to the left side and each time n gives a statement that must equal zero: x[n] − w1x[n−1] − … − wpx[n−p] = 0. Each statement involves only p + 1 neighbouring samples, with coefficients (−wp, …, −w1, 1) in order.

Write all the statements as rows of one matrix H. The first row has the coefficients at positions 0 to p, the second row has them shifted one place right, and so on. The slide shows exactly this: a matrix whose rows are the same short pattern sliding down the diagonal, with zeros everywhere else. The result is a banded matrix (non-zero entries only in a narrow strip around the diagonal) of size (N − p) × N, and the whole model is the single statement Hx = 0.

H
The banded matrix with N − p rows and N columns. Each row tests whether one sample agrees with the p before it.
x
The whole signal as a vector of N samples. Some entries are known and some are missing.
−wp, …, −w1, 1
The strip of non-zero entries in row n, sitting under samples n−p to n.

A hole is a linear system

Now some entries of x are missing, say the samples from index m1 to m2. Split the columns of H into two groups: the columns that multiply known samples, Hk, and the columns that multiply missing ones, Hm. Then Hx = 0 becomes Hmxm + Hkxk = 0, or Hmxm = −Hkxk. The right side is a list of numbers we know. The only unknowns are the missing samples. This is a linear system, and the lecture says we can solve it.

Only the rows that touch a missing column matter, since the others involve known samples alone and are already satisfied. A missing sample appears in p + 1 rows, which is more rows than unknowns, and noise makes the rows disagree slightly. So we solve in the least-squares sense of Chapter 4: xm = −(HmTHm)−1HmTHkxk. It is the same machine again, applied to the unknown samples rather than the unknown weights.

The smallest example

Take the tone of Chapter 7 at 30 degrees, with weights c1 = 1.732 and c2 = −1. The samples x[0] to x[5] are 0, 0.5, ?, 1, 0.866, 0.5, with x[2] missing. Three equations contain x[2]. Row n = 2 says x[2] = 1.732 × 0.5 − 0 = 0.866. Row n = 3 says x[3] = 1.732 x[2] − x[1], so x[2] = (1 + 0.5) / 1.732 = 0.866. Row n = 4 says x[4] = 1.732 x[3] − x[2], so x[2] = 1.732 − 0.866 = 0.866. All three agree. The one before and the two after the hole each vote, and the answer uses information from both sides.

x[2] = 0.866   from the past, from the next sample, and from the one after (three equations, one answer)

That two-sided evidence is the real strength of gap filling over forecasting. A forecast sees only the past. A repair also sees the future, so errors cannot run away across the hole: the far edge pulls the fill back on course. Use the device to damage the signal and watch which rows of H are involved.

Damage it, repair it

Top: the signal, the pink missing samples and the orange repair. Bottom: a patch of the banded matrix H around the first missing sample. Pink cells touch a missing sample; those rows are the equations the repair solves. Pick a damage pattern, an order and a size.

36

Same illustrative two-tone signal as the hero (noise 0.002). Weights are fitted by least squares on the rows made only of known samples; the missing samples are then solved by least squares as above. The straight-line comparison joins the two known neighbours of each missing run. Dropout positions are pseudo-random but fixed.

With one gap of 36 samples at order 4 the average miss is about 0.03, while the straight line misses by about 1.29, more than the signal's own size of 0.81, because it cannot bend. At order 2 the model has only one tone's worth of memory, so it fails on this two-tone signal (a miss of about 0.91). Scattered dropouts are the easy case: each hole is a few samples wide with known neighbours close by, so the straight line does tolerably (about 0.21 for 36 dropouts) and the AR fit does far better (about 0.004 at order 4).

Where it breaks: the fit assumes the signal keeps the same rhythm throughout. Speech and music change from moment to moment, so for a real recording the gap must be short enough that the rhythm survives it. The measurement is the repair error; the fixes are a shorter gap, a model fitted close to the gap and a higher order for richer sounds.

Why does the repair solve for the missing samples by least squares rather than reading one value from one equation?

Chapter 9

Field Guide

Keep the numbers, the checklist and the code on one page, and see where regression leads next in the course

One idea carries the whole lecture: write the prediction as a weighted sum, score it by squared misses, add a leash, and solve one linear system. Centring removes the offset. Prediction is a step from the average. Aim the same machine at a signal's own past and you get autoregressive models, which forecast waves, reveal pitch with two weights per tone, and repair gaps by solving a banded system.

Pick the tool

Choose a situation and the page names the tool, the formula and the chapter that explains it.

Which tool fits?

Press a situation.

A memory aid built from this lesson's chapters; no new facts.

The numbers

QuantityValueWhere
Running examplex = 1 to 5, y = 2.2, 2.9, 4.4, 4.9, 6.6Chapters 1 to 5
Averagesx̄ = 3, ȳ = 4.2Chapter 3
Centred sums∑x̃² = 10, ∑x̃ỹ = 10.8Chapter 4
Slope at λ = 0, 0.2, 11.08, 0.982, 0.72w = 10.8 / (10 + 5λ)
Offset at λ = 0, 0.2, 10.96, 1.25, 2.04ȳ − w x̄
Risk of the best line0.0632 (against 0.116 for w = 1, w0 = 1)Chapter 1
Prediction at x = 67.44, 7.15, 6.36 at λ = 0, 0.2, 1Chapter 5
AR(2) for a 30 degree toneweights (1.732, −1)Chapters 6 and 7
Order for k tones2kChapter 7
36-sample gap, two tones, order 4miss 0.03; straight line 1.29; signal size 0.81Chapter 8 (illustrative)

The terms

TermPlain meaning
ResidualTarget minus guess for one example.
Risk, empirical riskAverage squared miss over all possible data, or over the data we hold.
Ridge, lambdaA penalty on squared weights, and the knob that sets its strength.
CentringSubtract the average input and target so the offset drops out.
Condition numberRatio of biggest to smallest stretch of a matrix; large means unstable weights.
Autoregressive (AR) modelPredict a sample as a weighted sum of the p samples before it.
Free runA forecast that feeds its own predictions back in.
Banded matrix HOne row per sample, a narrow strip of AR coefficients; Hx = 0.

Checklist

  1. Centre first. Subtract the training average of x and y. Keep both averages for prediction time.
  2. Add the leash. Solve (X̃TX̃ + nλI)w = X̃Tỹ. Use a solver, not an inverse.
  3. Pick lambda on held-out data, then retrain on everything.
  4. Predict as ȳ + wT(x − x̄). Distrust inputs far outside the training range.
  5. For signals, build the window matrix A, fit AR by the same solve, and set the order to at least twice the number of tones.
  6. Judge forecasts by a free run, and repair gaps by solving the banded system with the known samples on both sides.

The core as code

The whole lesson fits in four short functions. Shapes are in the docstrings; each comment names the chapter.

python
import numpy as np

def ridge_fit(X, y, lam):
    """X: (n, d) features, y: (n,) targets. Returns weights (d,) and offset."""
    n = len(y)
    xbar, ybar = X.mean(axis=0), y.mean()
    Xc, yc = X - xbar, y - ybar                      # centre (Chapter 3)
    A = Xc.T @ Xc + n * lam * np.eye(X.shape[1])     # (d, d), made safe by n*lam*I
    w = np.linalg.solve(A, Xc.T @ yc)                # solve, never invert (Chapter 4)
    return w, ybar - w @ xbar                        # offset = ybar - w.xbar

def predict(X, w, w0):
    return X @ w + w0                                # = ybar + (X - xbar) @ w (Chapter 5)

def ar_fit(x, p, lam=1e-9):
    """x: (N,) signal. Returns p weights, w[0] multiplies x[n-1]."""
    A = np.stack([x[p - k : len(x) - k] for k in range(1, p + 1)], axis=1)   # (N-p, p)
    return np.linalg.solve(A.T @ A + lam * np.eye(p), A.T @ x[p:])          # Chapter 6

def ar_fill(x, w, missing):
    """Solve H x = 0 for the missing indices (Chapter 8)."""
    p, N = len(w), len(x)
    H = np.zeros((N - p, N))
    for r in range(N - p):
        H[r, r : r + p + 1] = np.r_[-w[::-1], 1.0]   # (-w_p ... -w_1, 1) sliding down the band
    known = np.setdiff1d(np.arange(N), missing)
    xm = np.linalg.lstsq(H[:, missing], -H[:, known] @ x[known], rcond=None)[0]
    out = x.copy(); out[missing] = xm
    return out

Where it sits in the field

Ridge regression is the base case of many later ideas. Add kernels and it becomes kernel ridge, the subject of the kernels and RKHS lectures. Update the weights one sample at a time and it becomes the adaptive filters of the next lectures. The AR weights are a linear filter, and their tones live in the frequency domain.

Keep going with the broader lessons on this site: least squares, regularisation, regularisation and optimisation, bias and variance, linear regression and LMS, nonlinear least squares and the SVD. Earlier in this course: SVMs and convex duality, where the same squared-length penalty reappears.

The takeaway. Fitting is solving: one gradient, one linear system. The leash makes the system safe, centring makes the offset free, and a signal's own past makes the same machine a forecaster and a repair tool.

Now press Present or Teach and explain the chain from squared misses to a repaired gap out loud, from memory. Then go back to the hero and fill the gap again, this time knowing why order 4 wins.

EE269 Lecture 20 (deck Lecture 12): Least-Squares Regression and Autoregressive Models
The course site · Lecture slides · All decks · Previous: Kernels · Next: RKHS