A network that squeezes data through one narrow layer and rebuilds it finds the same directions as PCA. Add weight decay, and the network quietly pays a nuclear norm penalty.
Learn why compressing data and rebuilding it is a matrix factorisation. See where a neural network meets the singular value decomposition. Then split a matrix into a clean low-rank part and a few wild outliers.
Aim the one-number bottleneck at the cloud with the angle slider, then press Train it and watch a real two-layer network find the best direction by itself. Then we build, piece by piece, PCA, the autoencoder, denoising, the proof that linear means PCA, the dual problem, the nuclear norm and robust PCA.
You need the idea of a matrix (a grid of numbers) and a feel for slopes. We build the rest from zero, including the SVD.
Based on Lecture 17 (2020 offering) of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci. Course slides. Every idea is re-taught here in our own words and devices. It follows Convex Neural Networks.
Toy data: 60 made-up points, seeded so they are the same on every visit, centred on their mean. The network has two layers with no nonlinearity: two numbers in, one number in the middle, two numbers out (4 weights). It trains with plain gradient descent on the average squared error. The dashed purple line comes from the SVD, the lecture’s answer for PCA (Chapter 4).
Chapter 0
See that thousands of measurements can come from two knobs, and meet the matrix words this lecture uses
Picture a motion sensor on your wrist. Every second it records 16 numbers: how hard your arm pushed at 16 moments. One number alone tells you almost nothing. The 16 together draw a curve.
Now watch the curves from a hundred seconds. They look alike. Each one is a slow swing plus a tilt, and only the strength of the swing and the steepness of the tilt change. Two knobs made all 16 numbers. The other 14 numbers were never free.
This idea carries the whole lecture. Real data is often far simpler than its size says. A photo of a handwritten digit has 784 numbers (28 rows of 28 pixels), yet a few strokes explain it. When we find those few knobs, we can store, clean and understand the data with far less.
A matrix is a grid of numbers. In this lecture the grid is the data. Each row is one example (one 16-sample signal, one image). Each column is one measurement (one time, one pixel). The lecture calls it X, with n rows and d columns, written n × d. A hundred wrist signals make a 100 × 16 matrix.
The rank of a matrix counts its independent knobs. If every row is some mix of two fixed curves, the matrix has rank 2, however many rows it has. A rank-2 grid of 1,600 numbers is really two curves and 200 mixing amounts.
The singular values measure how strongly each independent knob shows up. Think of a stereo with a bass dial and a treble dial: a singular value says how loud each dial is in the song. Chapter 1 builds them properly. For now, count the loud ones. That count is the rank you can see.
Below, you set two knobs and add the resulting signal as a row of X. Add several rows with different knob settings. The bars show the singular values of everything so far. Then switch on sensor noise and add more.
Left: the 16 samples your two knobs make. Right: the singular values of the matrix you have built, loudest first. Add rows with different settings, then try noise.
Illustrative signals: sample n of 16 is a × cos(πn/15) + b × (2n/15 − 1). Noise adds a random number from a normal curve of spread 0.05 to every sample. Singular values are computed live in your browser. A value counts as loud when it exceeds 0.15.
With no noise, three rows already show the pattern: two bars stand tall and the rest are zero. A tenth row changes nothing. The matrix has 16 columns, yet only two directions exist in it. That is rank 2.
With noise, every bar gets a small floor, because noise points in all 16 directions at once. But two bars still tower over the floor. This is the situation the lecture lives in: a few strong directions that carry the signal, plus a thin layer of everything else.
The lecture is 21 slides, and this lesson follows them in order. First the classical way to find the knobs, PCA. Then a neural network that does the same job, the autoencoder, and a version that cleans noisy inputs. Then the key fact: with no nonlinearity, the network is PCA. Then what weight decay does to such a network, and how convex duality turns that into a matrix penalty called the nuclear norm. The last chapter splits a matrix into low rank plus sparse outliers, called robust PCA.
Chapter 1
Find the direction along which data spreads most, and keep one number per example instead of two
Two thermometers sit in the same room, one by the window and one by the door. You log three afternoons. Each afternoon is a point on a plane: the window reading on one axis, the door reading on the other. The three points lie almost on a line, because both thermometers feel the same sun.
So one number per afternoon would nearly do. Say how far along the line the afternoon sits, and you can rebuild both readings. That is the whole idea of principal component analysis (PCA): replace each point by a position on a flat sheet that passes close to all the points.
The lecture writes the guess for each example xi as a mean plus a mix of a few fixed directions. A direction here is an arrow of length 1. The sheet is every point you can reach from the mean by sliding along those arrows.
We pick μ, A and every θi to make the guesses as close as possible. Close means the smallest total of squared distances, the lecture’s objective:
minimise over μ, A, θ1, …, θn of ∑i ‖xi − μ − Aθi‖2
The bars ‖·‖2 mean “add up the squares of every entry”. Squared distance punishes one big miss more than two small ones, and it makes the algebra clean.
Take the three afternoons (1, 2), (3, 3) and (5, 7). Their mean is (3, 4). Turn the line below, which always passes through that mean. The pink segments are the misses. Find the angle that makes them smallest.
Blue dots are the afternoons. The warm line passes through the cross (the mean). Pink segments are the misses. The bar shows the spread the line keeps and the spread it loses.
Illustrative points, chosen so the arithmetic is short. For the thermometers the total spread about the mean (3, 4) is 22.0; for the far-away trio about (10, 2) it is 8.0. With the mean switch off, the line is forced through the origin (0, 0) and the totals are measured from there.
Near 53° the misses almost vanish: the total is 0.56 out of 22.0. Near 143°, the line crosses the cloud the wrong way and loses most of it. The spread the line keeps and the spread it loses always add up to 22.0. Move one and the other moves the opposite way.
The Pythagorean rule explains the bar. Each example sits some distance from the mean. That distance splits into a part along the line (the kept part) and a part across it (the miss). Squares add: kept2 + miss2 = distance2. The distances from the mean do not depend on the line. So the smallest miss is the same thing as the largest kept part.
That turns a search over lines into a question about spread. The covariance matrix S records how the measurements move together. Slide 4 gives it as an average of outer products of the centred examples.
The slide’s answer: the mean is μ = x̄, the sheet’s directions are the first k columns of U, and each example’s code is θi = AT(xi − μ). The top eigen-direction is the one with the most spread, so it keeps the most and misses the least.
Subtract the mean (3, 4) from each point. You get (−2, −2), (0, −1) and (2, 3). Now average the outer products. Sxx = (4 + 0 + 4)/3 = 8/3. Syy = (4 + 1 + 9)/3 = 14/3. Sxy = (4 + 0 + 6)/3 = 10/3.
The eigenvalues solve λ2 − (22/3)λ + 4/3 = 0, so λ1 = 7.147 and λ2 = 0.187. Their sum is 7.333, the total spread per example. The top direction is (0.597, 0.802), at 53.3°. The codes are θ = (−2.80, −0.80, 3.60). The squared codes add to 21.44 = 3 × 7.147, and the misses add to 0.56 = 3 × 0.187.
Read that again: the smaller eigenvalue, times n, is the leftover error. Chapter 4 will say the same thing for networks with the SVD.
Symptom: you fit a line to three points that sit exactly on a vertical line, (10, 0), (10, 2) and (10, 4), and the rebuilt points are off. Measurement: with the mean removed, the fit is perfect and the error is 0. Without the mean, the best line must pass through the origin, so it tilts about 12° toward the cloud’s centre. The error becomes 7.7.
The cause: a line through the origin can only point at the cloud, not along its spread. The fix costs one line of code: subtract the mean first, add it back at the end. Choose the far-away trio in the device, switch off “Pass through the mean”, and press Snap to the best line. The pink misses appear and the best total stays at 7.7.
Chapter 2
Build a network whose only job is to rebuild its own input, and see why a small middle layer makes that job useful
Imagine a photocopier with a strange rule. You feed in a handwritten digit. Inside, the picture must pass through a doorway only 32 numbers wide. On the far side, the machine redraws the digit from those 32 numbers alone.
If the redraw looks like the original, the 32 numbers must have captured what matters. That is an autoencoder: a neural network trained so that its output matches its input. Nobody supplies labels. The input is also the answer.
A layer is one matrix multiplication followed by a simple bend. The bend is the activation function φ. The lecture uses ReLU, φ(u) = max(0, u): it keeps positive numbers and turns negative ones into zero. Without a bend, stacked layers collapse into one matrix. Chapter 4 uses exactly that.
Follow the shapes with n examples of d numbers. X is n × d. After layer 1 it is n × m1. After the last layer it is n × d again, the same shape as X. That match is what lets us compare the output to the input. The slide says it in one line: X ≈ f(X).
Slides 6 and 7 draw the network as an hourglass. The first half is the encoder: it squeezes each example down. The narrowest layer holds the compressed representation, the code: m numbers per example, so an n × m matrix for the whole data. The second half is the decoder: it expands the code back to d numbers.
Slide 8 shows the standard test set, MNIST: handwritten digits, each a 28 × 28 picture, so d = 784 numbers. Autoencoders trained on it rebuild blurry but readable digits from a code far smaller than 784.
Try the hourglass below. Pick the depth and the width of the narrow door. Watch what the code costs and what it saves.
Each bar is a layer’s width (square-root scale so small layers stay visible). Choose shallow or deep, then slide the code size.
Illustrative layer widths for 28 × 28 images (d = 784). Weight counts multiply the two widths on each side of every weight grid. Real code also adds a bias vector to every layer; the slides leave biases out, and so do these counts.
At a code size of 32, the shallow network has 784 × 32 + 32 × 784 = 50,176 weights. Each image shrinks 24.5 times. Slide the code to 784 and the door is as wide as the picture. The weights grow 24.5 times, to 1,229,312, and nothing is compressed.
Slide 5 states the problem. Choose the weights Θ to make f(X) close to X, and keep the weights small:
minimise over Θ ℓ(f(X), X) + β ∑l ‖Wl‖F2
The first term is the loss: how badly the output misses the input. The second is weight decay. The Frobenius norm ‖W‖F is the square root of the sum of all squared entries, so its square is the plain sum of squares. The number β sets how hard the penalty pulls every weight toward zero, like a spring. Chapters 5 to 7 are about what this spring really does.
The slide offers two losses. The L2 loss is ‖f(X) − X‖F2: the sum of squared misses. The L1 loss is ‖f(X) − X‖1: the sum of absolute misses. They treat a single huge miss very differently.
Six pixels miss by small amounts, and one pixel misses by the amount you choose. Bars show each pixel’s share of the total loss.
Illustrative misses: 0.1, 0.2, 0.1, 0.2, 0.1 and 0.15 for the six ordinary pixels. The seventh is yours. L2 adds the squares of the misses, L1 adds their absolute values.
At a bad miss of 3.0, the squared loss gives that one pixel about 99% of the total. The absolute loss gives it about 78%. So L2 training spends almost all its effort on one bad pixel. L1 is gentler on outliers, an idea that returns in Chapter 8.
import torch.nn as nn d, m = 784, 32 enc = nn.Sequential(nn.Linear(d, m, bias=False), nn.ReLU()) # X: [n, 784] -> code: [n, 32] dec = nn.Linear(m, d, bias=False) # code [n, 32] -> X_hat: [n, 784] loss = lambda X: ((dec(enc(X)) - X) ** 2).sum() # L2 loss, no labels needed opt = torch.optim.Adam(list(enc.parameters()) + list(dec.parameters()), weight_decay=1e-4) # the beta term
Symptom: training error drops to almost zero, yet the code tells you nothing. Measurement: with a code of 784 for 784-pixel images, the identity map reproduces every pixel, so the error is near 0 while nothing has been compressed. Fix: make the code smaller than d, or add pressure another way, as the next chapter does.
Chapter 3
Corrupt the input on purpose, keep the answer clean, and watch the network learn what clean data looks like
You want a friend to clean up smudged scans of a signal. You could hand over a smudged scan and say “copy this.” Your friend copies the smudges. Or you could hand over a smudged scan and the clean original, again and again, and say “learn to remove the smudge.” Now copying is no longer enough.
That is a denoising autoencoder. Chapter 2’s network was told to rebuild its input. This one gets a noisy input and must rebuild the clean version. The change is tiny in code and large in effect.
The lecture adds a noise matrix N to the input and leaves the target alone.
N has the same shape as X. The slide draws each entry from a normal curve: Nij ∼ 𝒩(0, σ2). Zero mean means the noise has no bias. The number σ is the noise’s typical size. In practice you draw fresh noise at every training step, so the network never sees the same smudge twice.
Think in directions, as in Chapter 1. The clean signals live mostly along a few strong directions. The noise has no favourite: it pushes equally in all of them. In a strong direction the signal towers over the noise. In a weak direction the signal is hidden inside it.
So the sensible policy is: pass strong directions through, and shut weak ones. We can derive exactly how much to pass. Take one direction. The clean value is s. Its variance λ is the average squared size of s, a measure of how much it swings. The noise n has variance σ2, the same measure for the noise. The network multiplies the noisy value by a weight w. The expected squared miss is:
E[(w(s + n) − s)2] = (1 − w)2 λ + w2 σ2
The first term is the damage from shrinking the signal. The second is the noise that leaks through. Set the slope to zero: −2(1 − w)λ + 2wσ2 = 0. This gives w = λ / (λ + σ2).
Let the noise variance be σ2 = 0.09 (so σ = 0.3). A strong direction with λ = 9.84 gets w = 9.84 / 9.93 = 0.991. It passes almost whole. A middle direction with λ = 1.17 gets w = 1.17 / 1.26 = 0.929. A weak direction with λ = 0.05 gets w = 0.05 / 0.14 = 0.357: mostly shut. A direction with no signal at all (λ = 0) gets w = 0, fully shut.
A plain autoencoder has no such preference. If its door is wide it passes every direction with w = 1, noise included. Only a narrow door makes it drop weak directions, and it drops them whether or not noise is there.
Below, the clean signals are 30 samples long. Each one is a mix of three smooth shapes: a flat level, a slope and a curve. We know the exact best linear network of each kind, so the device computes it instantly from 400 training signals. Choose a network, set the code size and the noise, and compare the miss.
Top: the clean signal (blue), the noisy input (pink dots) and the network’s output (warm). Bottom: how much of each of the first eight directions the network lets through.
Illustrative signals, not the lecture’s data. The best rank-m linear network is computed in closed form from the covariance of 400 clean training signals: weight 1 on each of the top m directions (plain) or λ/(λ+σ2) (denoising). Misses are root-mean-square values averaged over 40 test signals, each with its own noise.
Set the code size to 30 and the noise to 0.30 on both sliders. The noisy input is off by about 0.30. The plain network returns exactly its input, so it is off by 0.30 too: it learned to copy. The denoising network is off by only about 0.09. It had no narrow door at all, yet it learned to shut the 27 empty directions.
Now give both a narrow door of 3, the true number of shapes. Both land near 0.095. When the door fits the structure, the plain network denoises too. The denoising trick matters when the door is wide, which is the usual case for big networks.
Slide 10 builds a denoiser for a signal of length 150, x[n] = n2, reshaped into a 15 × 10 image. The network is a stack of convolutions (small filters that slide across the image) with 85,569 trainable parameters, trained on 56,000 samples. The slide itself calls it hugely overparameterised: there are far more weights than numbers in one signal. The noise, not a narrow door, keeps it from copying.
Symptom: the cleaned signal looks smoother than the truth, or worse than the noisy input. Measurement: train the denoiser at noise 1.00, then test at noise 0.05. The output misses by about 0.13, which is worse than the 0.05 miss of the input you started with. Trained at 0.05, the same network misses by 0.016.
Cause: a network trained on heavy noise shrinks every direction, including good ones, because it expects noise there. Fix: train over a range of noise sizes, or match the training noise to what you will meet. Try it: set the first noise slider to 1.00 and the second to 0.05.
Chapter 4
Remove the bend from the network, train it, and watch it land on the same answer as the singular value decomposition
Chapter 1 found the best flat sheet with a pencil-and-paper recipe. Chapter 2 built a network that squeezes and rebuilds. Do they agree? Take away the bends in the network, train it with ordinary gradient descent, and then lay its answer next to PCA’s. The two grids of numbers match.
That is slide 12’s last line: PCA = linear activation neural autoencoder. This chapter shows why. The reason is one clean fact about matrices.
Every matrix X (n × d) can be written as X = U Σ VT. This is the singular value decomposition (SVD). V holds d-number arrows, the right singular vectors: directions in measurement space, ordered from the most spread to the least. These are the PCA directions of Chapter 1. Σ is a diagonal list of singular values σ1 ≥ σ2 ≥ …: how strongly each direction shows up. U holds the matching arrows on the example side.
The thermometer points of Chapter 1, once centred, form a 3 × 2 matrix. Its singular values are σ1 = 4.63 and σ2 = 0.75. Square them: 21.44 and 0.56. Those are the kept spread and the leftover error from Chapter 1. So the squared singular values are the pieces of the total spread.
Slide 11 takes the two-layer network f(x) = φ(xTW1)W2 and sets φ(u) = u: no bend. The weights are W1 (d × m) and W2 (m × d). The target is the input, Y = X. The training problem:
With β = 0 the lecture writes three equal minima. We take them one step at a time.
Step 1. The two layers multiply into one matrix W = W1W2, of size d × d. With no bend, nothing else stands between X and the output. So the loss is just ‖XW − X‖F2.
Step 2. W1W2 passes through a door of width m, so its rank is at most m. The reverse also holds. Any d × d matrix of rank at most m splits into a d × m piece and an m × d piece (use its SVD). So the products W1W2 are exactly the matrices of rank at most m. The two-layer problem becomes: minimise ‖XW − X‖F2 over W with rank(W) ≤ m.
Step 3. For X = UΣVT, the rebuilt data XW has rank at most m too. Among all matrices of rank at most m, the one closest to X is the SVD cut off after m terms: UmΣmVmT. This is the Eckart-Young theorem. Choose W = VmVmT, and XW = UΣVTVmVmT = UmΣmVmT. It attains the bound.
The slide states the result: the optimal W is V1:mV1:mT, built from the top m right singular vectors. The leftover error is σm+12 + σm+22 + …: the spread in the directions we dropped.
Take m = 1. V1 = (0.597, 0.802). Then W = V1V1T = [[0.356, 0.479], [0.479, 0.644]]. The first centred point (−2, −2) times W gives (−1.67, −2.25). The error over all three points is σ22 = 0.56, the number from Chapter 1. Same line, same error, found two ways.
The device trains a two-layer linear network on 40 examples with 4 measurements, by plain gradient descent. Each step moves both weight grids downhill on the error. You see the error fall to the floor that the SVD predicts. You also see two 4 × 4 grids grow alike: the network’s W1W2 and the SVD’s VmVmT.
Top: the rebuild error as training runs (log scale), with the SVD floor dashed. Bottom: the network’s product W1W2 beside the SVD answer. Warm cells are positive, blue cells negative.
Illustrative data: 40 made-up examples in 4 measurements (singular values 19.3, 13.2, 7.5 and 2.4, total squared size 607.4), seeded so they are the same on every visit. Training is plain gradient descent on ‖XW1W2 − X‖F2 with β = 0 and small random starting weights. The floor is the sum of the squared singular values past the code size.
With a code of 2, the floor is σ32 + σ42 = 56.0 + 5.7 = 61.7. Training reaches 61.7 within a few hundred steps, and the distance between the two grids shrinks toward 0. With a code of 3 the floor is just 5.7, and with 1 it is 234.8.
Symptom: you press Train and nothing moves. The error stays at 607.4. Measurement: with W1 = W2 = 0, the slope of the loss with respect to each grid contains the other grid as a factor, so both slopes are exactly zero. The network sits on a flat saddle. Fix: start from small random numbers, as the device does by default. Try the switch.
Chapter 5
Rescale each hidden unit until its two weight vectors match, and a squared penalty turns into a penalty on lengths
Two workers pass a parcel down a line. The first worker stretches the parcel by a factor, the second squeezes it back. What arrives is the same whether the first stretches by 2 and the second by ½, or both do nothing. Now charge each worker by the square of the effort. The cheapest way to deliver the same result is to share the effort evenly.
That story is slide 13. A hidden neuron has an incoming weight vector and an outgoing weight vector. Their product is what the data feels. Their sizes can trade against each other for free. Weight decay charges for the squares, so it picks the even split. And once split evenly, the charge turns into something surprisingly different.
Chapter 4’s network has m hidden units. Write w1j for column j of W1, a d-number vector: the incoming weights of unit j. Write w2j for row j of W2, also d numbers: its outgoing weights. The network output splits into one piece per unit:
So every hidden unit adds one rank-one grid. The weight decay term is also a sum over units: β ∑j (‖w1j‖2 + ‖w2j‖2).
Pick any positive number αj. Replace w1j by w1j/αj and w2j by αjw2j. The product (X w1j)w2jT is unchanged: the 1/α and the α cancel. So the rebuild error does not move. Only the penalty changes:
β ∑j ( ‖w1j‖2 / αj2 + αj2 ‖w2j‖2 )
Because αj costs nothing in the fit, a training run will pick the αj that makes the penalty smallest. Call a = ‖w1j‖ and b = ‖w2j‖. We minimise f(α) = a2/α2 + α2b2. Let s = α2. Then f = a2/s + s b2, with slope −a2/s2 + b2. The slope is zero at s = a/b, where f = ab + ab = 2ab. At that point the two rescaled lengths, a/α and αb, are equal.
Slide 13 writes the result: the penalty becomes 2β ∑j ‖w1j‖2‖w2j‖2. A sum of squares has turned into a sum of products of lengths.
Set the two lengths. Drag α and watch the penalty. The curve always has a single lowest point, at α = √(a/b), where its height is 2ab.
Left: the penalty a²/α² + α²b² as α changes (log scale). Right: the two rescaled lengths. The product of the two vectors never changes.
Illustrative lengths. The penalty is shown for β = 1; any other β scales the whole curve. The rescaling w1 to w1/α, w2 to αw2 leaves the product of the two vectors unchanged, so only the penalty moves.
With a = 2 and b = 0.5, the start (α = 1) costs 4.25. The cheapest α is √(2/0.5) = 2, which costs 1 + 1 = 2 = 2ab. The rescaled lengths are then both 1. Notice what happened: the weight decay did not just shrink the weights. It balanced them.
Slide 14 goes one step further. Scale each unit so that its incoming vector has length exactly 1, and push the length into the outgoing vector: w1j becomes w1j/‖w1j‖, and w2j becomes w2j‖w1j‖. (As printed, the slide divides the second vector. The product only stays fixed if we multiply, so we multiply.) The penalty 2β‖w1j‖‖w2j‖ becomes 2β‖w2j‖.
The lecture names this a group ℓ1 penalty on the second layer. Compare the lasso, which adds up the absolute values of single weights and pushes many exactly to zero. The group version adds up the lengths of whole groups of weights, here one group per hidden unit, and pushes whole groups to zero. A unit whose outgoing vector is zero is gone from the network.
The slide ends on a gift: with the first layer fixed, the problem is convex in the second layer. A convex problem has one valley, with no false bottoms, so descent cannot get stuck. The error is a bowl in W2, the sum of lengths is a bowl, and bowls add to a bowl.
Take six hidden units whose outgoing lengths would be 3.0, 2.2, 1.4, 0.8, 0.4 and 0.15 with no penalty. In the simplest setting, where the units’ codes are independent and equally scaled, the group penalty pulls every length down by 2β and sets it to zero if it would go below zero. Slide β and count the survivors.
Pale bars are the unpenalised lengths. Solid bars are what the group penalty leaves. The dashed line is the cut 2β.
Illustrative lengths, and the idealised case of independent, equally scaled unit codes, where the group penalty acts as a shrink by 2β (“group soft-thresholding”). With real correlated data the units interact, but the same switching-off happens.
At β = 0.2 the cut is 0.4, so units 5 and 6 are gone and four survive. At β = 0.5 the cut is 1.0 and only the top three remain. The network chose its own width. Chapter 7 shows that this width is exactly a matrix rank.
Symptom: you add plain weight decay hoping to prune a wide network, and every neuron stays alive but small. Measurement: a squared penalty on a weight w costs βw2, whose slope near zero is almost nothing, so there is no push to reach exactly 0. A length penalty costs 2β‖w‖, a constant push all the way down. Fix: the pruning comes from the balanced, length-based form, not from the squares. That is the whole reason for Steps 2 and 3.
Chapter 6
Turn the group-penalty problem inside out, and meet the largest singular value as a simple limit on a variable
A shopkeeper wants the lowest cost that still meets an order. A supplier asks the opposite question: what is the highest price I can set without losing the sale? The two questions look different. For many problems they have the same answer. Solving the supplier’s question is sometimes far easier.
That is duality. Every minimisation problem (the primal) has a partner maximisation problem (the dual). When the problem is convex, the two best values are equal. This is called strong duality. (Our convex duality lesson builds the full theory. Here we need one worked case.)
Let the data be a single number: fit y with one weight w, using one input x, and charge a length penalty λ|w|. The primal is min over w of ½(xw − y)2 + λ|w|. Its answer is the soft threshold: shrink x·y toward zero by λ, and stop at zero.
The dual lives on a different variable, v, one number per data point. It asks for the v closest to y, with one limit: |v·x| ≤ λ. So the dual answer is just y, clipped into the interval where |v| ≤ λ/|x|. Try both below.
Left: the primal cost as the weight w changes, with its lowest point. Right: the dual score as v changes, with the allowed interval shaded and its highest point. Both turn out to have the same height.
A one-weight toy of the lecture’s group problem. Primal: ½(xw − y)² + λ|w|. Dual score: ½y² − ½(v − y)² subject to |vx| ≤ λ. The slides drop the constant ½y², which moves no maximum; it is kept here so the two heights match exactly. Values are computed live.
With x = 1, y = 2 and λ = 1, the primal best is w = 1 with cost 0.5 + 1 = 1.5. The dual best is v = 1 (y clipped into [−1, 1]) with score 2 − 0.5 = 1.5. Move any slider and the two numbers stay equal. Set λ large and the primal weight drops to 0 while the dual v rides y all the way out.
Slide 15 does this for the network. Fix the first layer, so each unit j has a fixed code Aj = X w1j (n numbers). Only the outgoing vectors w2j are free. We write each step in words, then in symbols.
Step 1: unfold the square. For any grid R, ½‖R‖F2 = max over V of [ 〈V, R〉 − ½‖V‖F2 ]. (Complete the square: the best V is R itself.) Put R = ∑j Ajw2jT − Y. The problem now has a min and a max.
Step 2: swap them. The error is convex in the w2j and concave in V, so strong duality lets us exchange min and max (slide 16). The proof is in the lecturer’s paper Neural Networks are Convex Regularizers, which the slide cites; we take it as given.
Step 3: minimise over the outgoing vectors. Each w2j now appears only in 〈V, Ajw2jT〉 + λ‖w2j‖, which is (VTAj)·w2j + λ‖w2j‖. If ‖VTAj‖ ≤ λ, the lowest value is 0 (take w2j = 0). If it is bigger, push w2j against VTAj and the value falls to minus infinity, so such V can never win the maximum. What remains is a limit on V.
Substitute V → −V and complete the square again. The result is slide 15’s dual:
Slide 16 swaps the outer minimum over the unit vectors w1j with the maximum over V. A limit that must hold for the best choice of w1j must hold for every unit vector w. So the limits become one limit: max over unit vectors w of ‖VTXw‖ ≤ β.
That quantity has a name. For a grid M, the largest length of Mw over unit w is its largest singular value σmax(M). A grid maps the unit circle to an ellipse. σmax is the long half-axis. Slide 17 writes the neat final form: maxV −½‖V − Y‖F2 subject to σmax(VTX) ≤ β. In words: find the point closest to Y inside a convex set. That is a simple constrained convex program.
Choose a 2 × 2 grid M. The unit circle on the left maps to an ellipse on the right. Sweep the point around the circle and look for the longest image. Then set λ and see whether the whole ellipse fits inside its circle.
Left: a unit vector w (teal) on the unit circle. Right: its image Mw (teal) on the ellipse, and the dashed circle of radius λ. Turn w and search for the longest image.
Illustrative 2 × 2 grid M. The singular values are computed live from M. The longest image has length σmax and the shortest σmin; they sit at right angles on the circle.
With the starting grid, the singular values are about 1.99 and 0.64. The longest image of a unit vector has length 1.99, found by turning w to about 36°. At λ = 2.5 the ellipse sits inside its dashed circle, so M is allowed. Drop λ below 1.99 and the long tip pokes outside: M breaks the limit.
Symptom: you check the limit with a few random unit vectors, and it passes, but the dual answer is wrong. Measurement: five directions of w picked by hand give lengths like 0.65, 1.25, 1.35, 1.84 and 1.93 for the grid above, and none reaches 1.99. The limit must hold for the worst direction. Fix: compute σmax exactly, as one SVD, instead of sampling.
Chapter 7
Dualise once more, and the whole neural problem becomes one convex matrix problem that prefers few singular values
Suppose you could let a network decide its own width. Give it far too many hidden units, charge it for using them, and see how many survive. Chapter 5 showed units switching off one by one as the penalty rose. This chapter names the quantity behind that, and shows that the answer is a matrix rank in disguise.
The name is the nuclear norm. The lecture’s punchline, slide 18: linear activation + weight decay = nuclear norm penalty.
Chapter 6 ended with a dual problem over V: max −½‖V − Y‖F2 with σmax(VTX) ≤ β. Dualise that, and you get the bidual. We need one fact: the largest singular value and the sum of all singular values are partners. For any grid M, σmax(M) = max over W with ‖W‖* ≤ 1 of 〈W, M〉. So the limit σmax(M) ≤ β holds exactly when min over W of [ β‖W‖* − 〈W, M〉 ] is 0, and that min is minus infinity if the limit fails.
Put M = VTX, so 〈W, VTX〉 = 〈V, XW〉. The dual becomes maxV minW of −½‖V − Y‖2 + β‖W‖* − 〈V, XW〉. Swap max and min. For a fixed W the best V is Y − XW, and the inner value is ½‖XW − Y‖2 − ½‖Y‖2. Drop the constant:
This is a convex problem in W: a bowl plus a bowl. The tangled two-layer network has turned into one honest matrix question.
There is a second route to the same place, and it ties Chapters 5 and 7 together. Chapter 5 priced a network at 2β ∑j ‖w1j‖‖w2j‖: the cost of building W = ∑j w1jw2jT from rank-one pieces. Training picks the cheapest set of pieces. The cheapest set is the SVD: the pieces σkukvkT cost σk each, so the total is σ1 + σ2 + … = ‖W‖*. Check on W = diag(3, 1): two pieces, 3 · 1 + 1 · 1 = 4, and ‖W‖* = 3 + 1 = 4.
The nuclear norm of W is ‖W‖* = σ1(W) + σ2(W) + …, the ℓ1 norm of its singular values. It is also called the Schatten 1-norm. Three facts follow.
One. For a positive semidefinite matrix (a symmetric grid with no negative eigenvalues), the singular values are the eigenvalues, so ‖W‖* = ∑λk = trace(W). Two. ℓ1 of a list of numbers pushes many entries to exactly zero. So ℓ1 of the singular values pushes many singular values to zero, and that is low rank. Three. The ball {W : ‖W‖* ≤ 1} has pointed corners, called extreme points, and they are the rank-one matrices. The ℓ1 ball for vectors has corners at the one-sparse vectors, the Dirac basis. Minimising a straight-line cost over a ball tends to land on a corner, and the corners are the simplest objects.
So ℓ1 is to sparse vectors as the nuclear norm is to low-rank matrices. The same idea, one level up.
Here is a 12 × 12 matrix: a rank-3 pattern plus noise. The rule that the nuclear norm induces, singular value thresholding, takes the SVD and subtracts τ from every singular value, with a floor at zero. It is the exact answer to min ½‖W − M‖F2 + τ‖W‖*. Slide τ and watch the small singular values disappear.
Top: the noisy matrix, the thresholded result, and the clean rank-3 truth (warm positive, blue negative). Bottom: the twelve singular values before (pale) and after (solid), with the cut τ.
Illustrative matrix: true singular values 10, 6 and 3.5, random orthogonal directions, plus a normal noise of spread 0.35 on every entry, all seeded so it is the same on every visit. Distances are Frobenius norms (the square root of the sum of squared entries). Singular values are computed live in your browser.
At τ = 0 nothing changes: the result is the noisy matrix, 4.48 from the truth. At τ = 1 the result keeps 6 directions and is 3.17 away. At τ = 2.4 it keeps exactly 3, the true rank, yet it is 4.22 away. Why did the distance rise? Shrinking also thins the three real directions. Switch on “restore kept values” at the same τ and the distance falls to 3.09.
Symptom: the nuclear-norm answer has the right number of directions, but every one is too faint. Measurement: at τ = 2.4 the top singular value drops from 10.19 to 7.79, although it was never noise. Cause: the penalty charges every unit of singular value, real or not. Fix: use the penalty to choose which directions live, then refit their sizes. The two jobs, choosing and sizing, are separate.
For the autoencoder (Y = X), the nuclear-norm problem has a clean answer. Write X = UΣVT and rotate W into V’s directions. The problem splits direction by direction: minimise ½σi2(wi − 1)2 + λ|wi|. Each has the soft-threshold answer wi = max(1 − λ/σi2, 0). It is PCA with each direction weighted. Strong directions pass almost whole. Weak ones, with σi2 ≤ λ, are cut.
The four directions of Chapter 4’s data. Each bar is the weight the nuclear-norm autoencoder gives it. Raise λ and the weak directions go first.
Uses the four singular values of Chapter 4’s illustrative data: 19.3, 13.2, 7.5 and 2.4 (squares 372.7, 173.0, 56.0 and 5.7). The weight formula max(1 − λ/σ², 0) is derived above and was checked against a numerical solver.
At λ = 10 the weights are 0.97, 0.94, 0.82 and 0: three directions survive and the weakest is cut, because its σ2 of 5.7 is below 10. At λ = 100 only the top two remain, at 0.73 and 0.42. Compare Chapter 4, where a hard code size picked exactly m directions at full weight. The nuclear norm picks the same kind of directions but with a soft, tunable edge.
Chapter 8
Pull a steady background apart from a few wild pixels, using the nuclear norm for one part and the sum of absolute values for the other
A camera watches an empty hallway and records 20 frames. A person walks through. Unroll each frame, a 12 × 12 picture, into one column of 144 numbers, and set the 20 columns side by side. You get a 144 × 20 matrix.
Most of that matrix is the hallway, and the hallway does not change. Every column is the same picture, up to a slow flicker of the light. That part has rank 1. The walker covers only a handful of pixels in each frame. That part is sparse: mostly zeros, a few large entries. We want the two parts separately.
PCA is tuned for small errors everywhere, as Chapter 2’s squared loss showed. One wild entry pulls the whole fit toward it. Take the tiny matrix with rows (1, 1, 1), (2, 12, 2) and (3, 3, 3). It is a clean rank-1 pattern with a single entry, the middle 12, pushed up by 10. Its singular values are 13.05 and 3.43, where the clean matrix had 6.48 and 0. Keep the top direction only, and the rebuilt middle entry is 11.6. The rebuilt matrix is farther from the clean one than the clean matrix is from zero: the relative error is 1.58. The outlier hijacked the direction.
The lecture posits that the data matrix is the sum of a low-rank part and a sparse part.
What we truly want is the smallest rank for W and the fewest nonzero entries in S. Both counts are hard to minimise directly. The slide swaps each for its convex stand-in. This is the convex heuristic. The result is a convex program, so it is efficiently solvable: it has one valley and no traps.
On the toy matrix, the clean split costs ‖W‖* + ‖S‖1 = 6.48 + 10 = 16.48. The lecture gives no theorem for when the split is unique, so we add what the source paper says. Candès, Li, Ma and Wright (Robust Principal Component Analysis?, Journal of the ACM, 2011) show that the program recovers both parts exactly under two conditions. The background must not itself be sparse. The outliers must not be low rank and must be spread out. They also weight the second term: minimise ‖W‖* + λ‖S‖1 with λ = 1/√max(n1, n2) for an n1 × n2 matrix. The slide writes λ = 1.
The slides say “efficiently solvable” and show no algorithm. Here is one standard method, ADMM (a method that alternates between the two unknowns). It reuses two tools you already own. It keeps a third grid Y that measures how far the split is from adding up to X.
Each round, W keeps only the strong shared directions, and S catches whatever W cannot explain, if it is big. Y nudges them until X = W + S. The step size μ is n1n2 / (4‖X‖1), the paper’s suggestion.
The device builds a matrix and runs this loop for real, in your browser. In matrix mode, a 24 × 24 rank-r matrix has a fraction of its entries ruined with values of ±5. In video mode, a 12 × 12 hallway with a square walking diagonally is stacked into the 144 × 20 matrix of the opening. You see the observed picture, the robust pieces, and what plain PCA with the right rank gives instead.
Pick a mode. The four pictures are: what you observe, the low-rank part, the sparse part, and plain PCA’s best guess. Press Replay the iterations to watch the split form.
Illustrative data. Matrix mode: entries of a rank-r matrix are random normal numbers; each entry is ruined with the chosen probability by ±5. Video mode: a fixed smooth background with one dark block, light flicker of 15%, and a 3 × 3 square of brightness 1.5 that moves across the frames. Robust PCA is the ADMM loop above with λ = 1/√max(n1, n2) and 150 iterations. Errors are relative: the size of the miss divided by the size of the true low-rank part.
With the starting settings, 10% of the entries are ruined. Robust PCA recovers the low-rank part with a relative error of about 0.00 and finds rank 2. Plain PCA, given the true rank, is off by about 0.43: the ruined entries tilted its directions. Switch to video: robust PCA recovers the hallway and the walker almost exactly, while plain rank-1 PCA leaves a ghost of the walker in the background and misses by about 0.21.
Symptom: the recovered low-rank part shows a visible mess, and its rank is far from the truth. Measurement: raise the corruption to 40% in matrix mode. The relative error jumps to about 0.76 and the rank found is 13, not 2. Plain PCA is off by 1.15, worse than robust PCA but still hopeless. Cause: the outliers are no longer sparse, so they stop being cheap in ‖S‖1 and start to look like structure. Fix: collect cleaner data, or lower the corruption before you decompose. Near 20% to 30% the answer is already degrading.
Chapter 9
Keep the numbers, the checklist and the code, and see where each idea leads next
One thread ran through all 21 slides. Data that looks large is often built from a few knobs. PCA finds the knobs from the covariance. An autoencoder finds them by training a network through a narrow layer, and with no bends it lands on the same answer, by the Eckart-Young theorem. Weight decay on that network is secretly a group penalty on whole neurons. Dualising it twice turns the penalty into the nuclear norm, a sum of singular values that prefers low rank. Add an ℓ1 partner for outliers, and a matrix splits into a steady low-rank part and a sparse part.
| Idea | The rule | The number to remember |
|---|---|---|
| PCA | μ = x̄, A = top k eigenvectors of the covariance, θi = AT(xi − μ) | 3 thermometer points: 0.56 left over of 22.0 |
| Autoencoder shapes | X is n × d, code is n × m, output is n × d | 784 to 32 is a 24.5× squeeze, 50,176 weights |
| Denoising weight | w = λ / (λ + σ2) per direction | λ = 0.05, σ2 = 0.09 gives 0.36 |
| Linear autoencoder | optimal W = VmVmT, error = sum of σi2 for i > m | Code of 2 on the Chapter 4 data: floor 61.7 |
| Balanced weight decay | min over α of a²/α² + α²b² = 2ab | a = 2, b = 0.5: 4.25 falls to 2 |
| Group ℓ1 penalty | 2β ∑j ‖w2j‖ with ‖w1j‖ = 1; whole neurons switch off | β = 0.2 keeps 4 of 6 neurons |
| Dual problem | max −½‖V − Y‖2 subject to σmax(VTX) ≤ β | x = 1, y = 2, λ = 1: both sides 1.5 |
| Nuclear norm | ‖W‖* = sum of singular values; extreme points are rank one | singular values 5, 2, 1 give 8 |
| Nuclear-norm autoencoder | wi = max(1 − λ/σi2, 0) | λ = 10 gives 0.97, 0.94, 0.82, 0 |
| Robust PCA | min ‖W‖* + λ‖S‖1 subject to X = W + S | 10% ruined entries: error 0.00 against plain PCA 0.43 |
import numpy as np
def pca_as_linear_autoencoder(X, m):
"""X: [n, d], columns centred. Returns W [d, d] of rank m."""
U, s, Vt = np.linalg.svd(X, full_matrices=False) # X = U diag(s) Vt
Vm = Vt[:m].T # [d, m] top right singular vectors
return Vm @ Vm.T # X @ W is the best rank-m rebuild; error = sum(s[m:]**2)
def nuclear_autoencoder_weights(s, lam):
return np.maximum(1 - lam / s**2, 0) # soft PCA: weight per direction, lam in the same units as s**2
def svt(M, tau):
"""Singular value thresholding: the proximal step of the nuclear norm."""
U, s, Vt = np.linalg.svd(M, full_matrices=False)
return (U * np.maximum(s - tau, 0)) @ Vt
def soft(M, t):
return np.sign(M) * np.maximum(np.abs(M) - t, 0) # shrink each entry; the proximal step of the l1 norm
def robust_pca(X, iters=150):
"""Principal component pursuit by ADMM. Returns low-rank L and sparse S with X = L + S."""
n1, n2 = X.shape
lam = 1 / np.sqrt(max(n1, n2)) # Candes, Li, Ma, Wright 2011
mu = n1 * n2 / (4 * np.abs(X).sum())
S = np.zeros_like(X); Y = np.zeros_like(X)
for _ in range(iters):
L = svt(X - S + Y / mu, 1 / mu) # low-rank part
S = soft(X - L + Y / mu, lam / mu) # sparse part
Y = Y + mu * (X - L - S) # dual update: how far X = L + S is from holding
return L, S
The autoencoder is the shared root of many modern models. Variational autoencoders and the latent spaces behind image generators add a probability model on the code (see VAE and VQ-VAE). Sparse and dictionary methods ask for few active parts instead of few directions (dictionary learning). Non-negative factorisation demands that every part adds (NMF). The nuclear norm is the engine of matrix completion, the problem behind recommendation systems.
The convex view is the lecturer’s own research thread. Slide 16 cites Neural Networks are Convex Regularizers, which proves the exchange of minimum and maximum used in Chapter 6. The previous lecture, Convex Neural Networks, builds that story with bends included.
Now press Present or Teach and explain, from memory, why a linear autoencoder lands on PCA, what the rescaling trick does to weight decay, and where the largest singular value enters the dual. Then go back to the cloud at the top, press Train it, and say why the network’s line ends up where PCA’s dashed line sits.
This lesson re-teaches Lecture 17 (2020) of EE269: Signal Processing for Machine Learning by Mert Pilanci, Stanford University, from the course slides, in our own words and devices. Anything beyond the slides (the ADMM loop, the closed forms, the λ weight of Chapter 8) is marked where it appears and comes from the sources named there.