Dictionary Learning

A signal is rarely a crowd. Often it is a few notes. With the right dictionary of atoms, three are enough to rebuild a signal that twelve standard atoms cannot.

Learn how to describe a sound, a picture or a sensor trace as a short recipe of building blocks, how to find the recipe, and how to learn the blocks themselves from data.

Pick a dictionary, then drag the atom budget from 1 to 12. Watch how fast the error falls. Then we build, piece by piece, the recipe, the search for it, and the learning of the dictionary.

You need vectors and dot products (a dot product measures how much two lists of numbers point the same way) and a little Python. We build the rest from zero.

Based on Lecture 20 of Stanford EE269: Signal Processing for Machine Learning (18 November 2020), taught by Mert Pilanci; see the course’s slides page. This lesson re-teaches the deck in our own words and devices; none of the course’s slide images appear here.

Rebuild the signal

3

Illustrative toy: a noise-free signal of 64 samples made from two wave bursts and one spike, all present in the overcomplete dictionary (148 atoms). Atoms are picked by orthogonal matching pursuit (Chapter 9), computed live in your browser.

Chapter 0

A Sound Is a Few Notes

Describe a signal as a short recipe of building blocks, and see why the shortest recipe is the one worth finding

Record two seconds of sound on your phone: one hand clap, then two sung notes. The file holds about 88,000 numbers, one for every 23 millionths of a second. Yet you could describe the whole recording in three short facts. A clap at this moment. A low note from here to here. A high note from here to here.

That gap is the idea of this lecture. The raw list of numbers is long, but the description is short. If we can find the short description, we can store the sound in a few bytes, remove its noise, repair its gaps, and notice when something strange happens in it.

The course calls this lecture Dictionary Learning. It was Lecture 20 of Mert Pilanci’s EE269 at Stanford, given on 18 November 2020. (The course also posts the usual logistics: reading, homework and project dates. They live on the course site; nothing in this lesson depends on them.)

The recipe, in plain words

A signal is a list of numbers that measure something over time or space: the samples of a sound, the pixels of a picture patch, the readings of a vibration sensor. We write one signal as y and its length as m. Our hero signal has m = 64.

An atom is a short template, also a list of m numbers: a click, a pure tone, a burst of a wave. A dictionary is a collection of atoms, like the shelf of ingredients in a kitchen. A code is the recipe: for each atom, how much of it to add. We write the dictionary as a matrix D whose columns are the atoms, and the code as a list x with one number per atom.

y
The signal we want to describe: m numbers.
D
The dictionary: K atoms side by side, so a table of m × K numbers. Column k is the atom dk.
x
The code: K numbers. The number xk says how much of atom k goes into the mix. Zero means “leave it out”.

The product D x is only shorthand for the sum on the right: scale each atom by its code number, then add them up. A matrix times a vector is a mixing desk, and x holds the slider positions.

A recipe with two numbers

Take the smallest possible case, m = 2, so every signal is a point on a sheet of paper. Let the dictionary have K = 3 atoms: d1 = (1, 0) points right, d2 = (0, 1) points up, and d3 = (0.6, 0.8) points up and right. All three have length 1, because 0.6² + 0.8² = 1.

The signal is y = (1.2, 1.6). One recipe is x = (1.2, 1.6, 0): go 1.2 right, then 1.6 up. That uses two atoms. Another recipe is x = (0, 0, 2), because 2 × (0.6, 0.8) = (1.2, 1.6). That uses one atom, and it is exact.

Both recipes are correct. Only one is short. A dictionary with more atoms than the signal has numbers (K = 3 against m = 2) is called overcomplete, and it always allows many recipes. The word sparse describes a code with mostly zeros. We count the nonzeros with a symbol, ‖x‖0, the “zero norm”. For the first recipe it is 2, for the second it is 1.

Now try it yourself. The device below hides a recipe made from two of six atoms. Move the sliders until the warm line sits on the blue one, using as few nonzero sliders as you can.

Mix the recipe

Blue is the signal to match. Warm is your mix. Pink is what is left over. Each slider is one atom’s code number. A slider near zero counts as unused.

Illustrative toy: six atoms of 64 samples (three wave bursts, one slow cosine, two spikes). The hidden recipe is 0.90 of the low burst and −0.70 of the high burst. The error is the leftover energy divided by the signal’s energy.

Most people find the first burst quickly, then add the third. A few reach for the cosine because it overlaps both bursts a little, and the leftover stays pink. That reaching is the problem in a nutshell. A wrong atom can reduce the error a bit while making the recipe longer.

The lecture’s problem, with two unknowns

Now the lecture’s second slide. We have not one signal but n of them, y1 to yn: a thousand sound clips, say. We want one dictionary D that serves all of them, and one short code xi for each clip.

min over xi, D
Choose both the codes and the dictionary. Neither is given. That is why it is called learning.
∑i=1n
Add up the error over all n training signals.
‖D xi − yi‖22
The squared length of the leftover: how far the rebuild D xi lies from signal yi. Zero means a perfect rebuild.
‖xi‖0 ≤ s
Each code may use at most s atoms. The budget s is the knob you dragged in the hero.

The third slide gives the same problem a second face: matrix factorization. Stack the n signals as the columns of a table Y, and the n codes as the columns of a table X. Then the whole problem says D X ≈ Y, where every column of X is sparse.

Y: 64 × 1000  ≈  D: 64 × 148  ×  X: 148 × 1000 (each column of X has at most s nonzeros)

Read the shapes as a story. Y is the data, a thousand clips of 64 samples. D is the shelf of 148 ingredients. X is a thousand recipes, nearly all zeros. Ordinary factorizations such as PCA and the SVD (see the autoencoder and NMF lessons) fit the same picture with different rules for X. Here the rule is: few nonzeros.

Why the right shelf matters

Go back to the hero. Its signal is two bursts and a spike. A dictionary of spikes can build a burst only one sample at a time, so twelve atoms still leave 21% of the energy unexplained. A dictionary of pure cosines needs many tones to build a short burst, and leaves about 24%. The overcomplete dictionary contains the bursts themselves, so three atoms leave 0%.

The symptom of a poor dictionary is a long recipe. You measure it as the error at a fixed budget, the height of the curve in the hero. The fix is a better shelf, and the rest of this lesson is about finding one automatically. Two jobs hide inside the lecture’s formula, and the next chapters take them one at a time: finding a short code given a dictionary, and improving the dictionary given the codes.

The road

  1. Many recipes, one sparsest: why short recipes are hard to find.
  2. Why the corner wins: the L1 relaxation that makes the search possible.
  3. Shrink and repeat: an algorithm that finds the code.
  4. Move the atoms: the gradient step that improves the dictionary.
  5. What the atoms look like: learned dictionaries of images, next to AlexNet.
  6. Cleaning and repairing pictures: denoising and inpainting.
  7. Deep and structured dictionaries: products and convolutions of dictionaries.
  8. Clustering is dictionary learning: k-means in the same notation.
  9. Matching pursuit: the greedy search, one pick per step.
  10. Sparse codes at work: machines, bodies, buildings, and the other tools.
  11. Field guide: numbers, checklist, code, links.
The signal is y = (1.2, 1.6) and the atoms are (1, 0), (0, 1) and (0.6, 0.8). Which statement is right?

Chapter 1

Many Recipes, One Sparsest

Walk along the family of exact recipes, find the sparse ones, and see why searching for them blindly cannot scale

Two engineers look at the same point on a sheet of paper, y = (1.2, 1.6). The first says: “Go 1.2 right and 1.6 up.” The second says: “Go 2 steps along the diagonal atom.” Both are right, and the second is shorter. Chapter 0 showed this. Now we ask a sharper question: how many recipes are there in all, and how do we find the shortest?

The whole family of exact recipes

We have three atoms in two dimensions, so three unknown code numbers but only two equations. The two equations are x1 + 0.6 x3 = 1.2 (the horizontal part) and x2 + 0.8 x3 = 1.6 (the vertical part). One number stays free. Call it t and let it be x3. Then everything else follows:

x(t) = (1.2 − 0.6 t,  1.6 − 0.8 t,  t) = (1.2, 1.6, 0) + t · (−0.6, −0.8, 1)

The vector (−0.6, −0.8, 1) is special. Mix the three atoms with those numbers and you get exactly nothing: −0.6 d1 − 0.8 d2 + d3 = 0. Linear algebra calls such a vector a member of the null space of D, the recipes that produce silence. Add any amount of silence to a recipe and the rebuild does not change. That is why overcomplete dictionaries have a whole line of exact recipes instead of one.

Where are the sparse ones? A recipe has a zero where a coordinate crosses zero. x1 is zero at t = 2 (1.2 − 1.2 = 0). x2 is zero at t = 2 as well (1.6 − 1.6 = 0). x3 is zero at t = 0. So t = 2 kills two coordinates at once and leaves the code (0, 0, 2): one atom. Slide the point yourself and watch the zeros appear.

Walk the line of recipes

The plane shows the three atoms (purple), the signal (blue), and your recipe drawn head to tail: x1 steps along d1, then x2 along d2, then x3 along d3, always landing on the signal. Drag t, rotate the signal, or jump to a named recipe.

0.00
35.0°

Illustrative toy in 2 dimensions: atoms (1, 0), (0, 1), (0.6, 0.8); the signal has length 2. A code number under 0.02 counts as zero. “Sum of sizes” is the L1 norm, previewed here and explained in Chapter 2.

Try “Signal along d3”. At the right t, two bars vanish together. For other signal angles no recipe has fewer than two nonzeros. The count of nonzeros depends on how well the signal lines up with an atom. A good dictionary is one where real signals line up with a few atoms.

Notice the third jump, “Smallest energy”. It picks the recipe with the smallest sum of squares, the one least-squares gives you by default. It lands at (0.6, 0.8, 1.0) when the signal lies along d3: three nonzeros. The default way of solving D x = y is never sparse. This is the first failure mode. The symptom is a dense code. You measure it by counting nonzeros. The fix needs a new way to measure the size of a code, which is the job of Chapter 2.

Why not just try every short recipe?

A natural idea: pick which s atoms to use, solve a small least-squares problem for their coefficients, and keep the best choice. With K atoms there are K!/(s!(K−s)!) ways to choose them. This count is written C(K, s) and read “K choose s”.

Work the hero’s sizes by hand. For K = 148 and s = 3: 148 × 147 × 146 / (3 × 2 × 1) = 529,396 subsets. A laptop does that in a second. For s = 12 the same formula gives about 1.5 × 1017 subsets. If each small solve took one microsecond (a generous guess), the search would take about 4,600 years.

Try every subset

The bar is the time to try every subset of s atoms out of K, on a log scale. Dashed lines mark one second, one hour, one year and the age of the universe.

148
3

Illustrative: one microsecond per least-squares solve, one core. Real solves are slower than this, which makes the picture kinder than the truth. The subset count is exact.

This is not a failure of imagination. Choosing the best s atoms to fit a signal is known to be NP-hard in general (Natarajan, 1995). That means no one knows a method that is fast on every dictionary and every signal. The lecture states the problem with the zero norm and moves straight to two escapes: swap the zero norm for something easier (Chapters 2 to 4), or give up on the best answer and take a good greedy one (Chapter 9).

The hero’s sizes make the point. The dictionary has K = 148 atoms and the signal has m = 64 samples, so the null space has 148 − 64 = 84 dimensions. Every exact recipe sits in an 84-dimensional family of recipes that all rebuild the same 64 numbers. The sparse ones are a thin scatter of points inside it, and finding them is the whole difficulty.

One signal, or a thousand?

Dictionary learning stacks a second difficulty on the first. To learn D we need codes for many signals, and to find codes we need D. Each is easy once the other is fixed, and neither is known at the start. The lecture’s answer, which we reach in Chapter 4, is to alternate: fix D and find the codes, fix the codes and improve D, and repeat.

A dictionary has K = 100 atoms and a signal of m = 10 samples. What is true of the exact recipes?

Chapter 2

Why the Corner Wins

Replace the hard count of nonzeros by the sum of sizes, and see how a diamond-shaped ruler pushes recipes onto the axes

Picture a shop that sells atoms. You may buy as many as you like, but each unit of an atom costs money, and you must rebuild the signal exactly. A shopper who counts how many atoms has a hard puzzle. A shopper who counts how many units in total has an easy one. This chapter is about why the easy shopper often buys the same basket as the hard one.

Three rulers for a recipe

A ruler assigns a size to a code x. We have met one: the zero norm ‖x‖0 counts nonzeros. Two more matter. The L2 norm squared, ‖x‖22 = x1² + x2² + …, adds up squares. The L1 norm, ‖x‖1 = |x1| + |x2| + …, adds up absolute values, the plain total of sizes.

The lecture’s fourth slide makes exactly this swap. The hard problem had a budget, ‖xi‖0 ≤ s. The new one folds the ruler into the score:

min
Over the codes xi and the dictionary D, as before.
∑i=1n
One term for each of the n training signals.
‖D xi − yi‖22
The misfit: how far the rebuild is from the signal. The same term as in Chapter 0.
λ
The price per unit of code size, a number you choose. Big λ: expensive atoms, short recipes, worse fit. Small λ: cheap atoms, long recipes, better fit.
‖xi‖1
The sum of the absolute values of the code: the L1 ruler.

This is called a relaxation: we loosen a hard requirement (exactly s nonzeros) into a soft price. The reward is that the score is now a convex function of x, a bowl with one bottom and no false valleys. For fixed D, any method that walks downhill reaches the true minimum. The next chapter does exactly that.

The L1 choice is not arbitrary. On codes whose entries all lie between −1 and 1, the L1 norm is the largest convex function that never exceeds the zero norm. It is the tightest convex stand-in for counting. Statisticians call the L1-penalised fit the LASSO (Tibshirani, 1996), and signal processors call the exact-fit version basis pursuit (Chen, Donoho and Saunders, 1998).

Why a diamond finds zeros

Work the smallest case by hand. One sample, two atoms: y = 2, a1 = 1, a2 = 0.5, so the exact recipes satisfy x1 + 0.5 x2 = 2. That is a line in the plane of codes.

Two recipes sit on the axes. Buying only atom 1 gives (2, 0), with L1 size 2. Buying only atom 2 gives (0, 4), with L1 size 4. The L1 ruler prefers (2, 0), the one that uses the stronger atom. Now the L2 ruler. The closest point to the origin on the line is y a / ‖a‖² = 2 (1, 0.5) / 1.25 = (1.6, 0.8). Both numbers are nonzero, and its L1 size is 2.4, worse than 2. So L2 gives a dense recipe and L1 gives a sparse one.

Why? Think of inflating a balloon around the origin until it just touches the line. The L2 balloon is a circle. It touches the line at one smooth point, usually off the axes. The L1 balloon is a diamond with its corners on the axes. A straight line almost always meets a diamond at a corner first, and every corner has a zero coordinate. See it:

Inflate the ball

The teal line holds every exact recipe for one signal. Choose a ruler, then tilt the line. The ball grows until it touches the line; the warm dot is the closest recipe under that ruler.

30.0°

Illustrative toy: two atoms, one sample. The line is cos(φ) x1 + sin(φ) x2 = 1, for tilt φ. The closest point is found by scanning the line. L0.5 is not a true norm and not convex; it is shown because it hugs the axes even harder.

Set the tilt to 30 degrees. For L2 the dot lands at (0.87, 0.50): two nonzeros. For L1 it jumps to (1.15, 0): the line first touched the diamond at its right corner. Sweep toward 45 degrees. At exactly 45 degrees the line lies along a diamond edge, and both corners tie. Past it, the dot flips to the other axis. The L0.5 star is pinched so hard toward the axes that even a nearly diagonal line meets a spike first.

The price of the shortcut

The relaxation can fail in three ways, and each has a symptom you can measure. If λ is too large, every code collapses to zero: the rebuild is empty and the error equals the signal’s energy. If λ is too small, the codes stay long and the fit is good but the recipes tell you nothing. If atoms are not kept at unit length, a cheat opens: double an atom and halve its code number, and the misfit does not move, but the halved coefficient is cheaper under L1. Every learner of dictionaries therefore fixes the atom length (Chapter 4).

There is a deeper caveat. L1 gives the same answer as the zero norm only under conditions on the dictionary: its atoms must not look too much alike, a property called low coherence. A dictionary with two near-identical atoms can fool L1 and greedy search alike (Chapter 9 measures this).

A line of exact recipes meets the plane’s axes at (2, 0) and (0, 4), and its closest point to the origin is (1.6, 0.8). Which ruler picks (2, 0)?

Chapter 3

Find the Code: Shrink and Repeat

Solve the L1 problem for one signal with a loop of two moves: fix the misfit, then shrink every number toward zero

You have a dictionary and a signal. You want the sparse code. The fifth slide of the lecture calls this step minimise over xi: an L1 regularised least squares problem, and moves on. That one line hides the most useful trick in sparse coding. We unpack it in three steps: one number, then a perfect dictionary, then a real one.

One number: the soft threshold

Suppose there is a single atom and the best plain fit gives the code number z = 1.0. Now add the price: we want the x that minimises ½(x − z)² + λ|x|. For x above zero the slope of the score is (x − z) + λ. Setting it to zero gives x = z − λ. That answer is allowed only if it is above zero, so only when z is bigger than λ. By the mirror argument, for z below −λ the answer is z + λ. In between, the best choice is exactly zero.

That rule has a name: the soft threshold, Sλ(z). Shrink the size of z by λ, and if that crosses zero, stop at zero. Work three cases with λ = 0.3. z = 1.0 gives 0.7. z = 0.2 gives 0. z = −0.5 gives −0.2.

Shrink one number

The curve maps a raw number z (across) to its shrunk value (up). Drag λ to widen the flat part. Drag z to slide a dot along the curve.

0.30
1.00

Exact formula: S(z) = sign(z) · max(|z| − λ, 0). The score here is ½(x − z)² + λ|x|. The lecture’s score has no ½, which halves the threshold: its λ acts like this page’s λ/2.

A perfect dictionary: every atom on its own

If the atoms are orthonormal (like the cosines in an ordinary DCT), the problem splits. Each atom’s plain code number is zk = dk · y, and each is shrunk on its own. The answer is x = Sλ(DT y). One matrix multiply, one shrink, done. This is how wavelet denoising works (see wavelets): transform, shrink, transform back.

An overcomplete dictionary breaks the split, because atoms overlap and the code numbers pull on each other. So we repeat the one-number trick, again and again, until the pulling settles.

A real dictionary: ISTA

Write the smooth part of the score as f(x) = ½‖y − D x‖². Its gradient, the direction that most increases the misfit, is DT(D x − y). Moving against it with step 1/L reduces the misfit. Then shrink. That gives the loop called ISTA, the iterative shrinkage-thresholding algorithm (Daubechies, Defrise and De Mol, 2004):

x
The current code, K numbers. Start at all zeros.
(1/L) DT(y − D x)
Step one: correct the misfit. D x is the rebuild, y − D x the leftover, and DT asks each atom how much of the leftover it can explain.
λ/L
Step two: the shrink amount. L is the largest eigenvalue of DTD, a safe step size. A bigger L means a smaller, steadier step.

Work it on the plane example: atoms (1, 0), (0, 1), (0.6, 0.8), signal (1.2, 1.6), λ = 0.1. The matrix D DT has trace 3 and determinant 2, so its eigenvalues are 2 and 1, and L = 2. From x = 0 the first gradient is DTy = (1.2, 1.6, 2.0). Divide by L: (0.6, 0.8, 1.0). Shrink by λ/L = 0.05: x = (0.55, 0.75, 0.95). Still dense.

Run the loop on. After 20 rounds x = (0.43, 0.60, 1.14). After 50, (0.25, 0.36, 1.44). After 100, x = (0, 0, 1.899), and it stays there. ISTA slid weight from the two standard atoms onto the diagonal one, until the first two hit zero. Notice 1.899, not 2: the shrink took 0.1 off, exactly λ.

Run ISTA

The hero signal, the 148-atom dictionary. Each stem is one atom’s code number; hollow rings mark the three true atoms. Press Run, then change λ and run again. Press Refit to undo the shrinkage on the atoms that survived.

0.10

Illustrative toy with known answers: the true code is 1.00, 0.80 and 0.70 on three atoms of the overcomplete dictionary. L is computed in your browser (about 3.84). Score = ½‖y − D x‖² + λ‖x‖1.

Set λ = 0.1 and press Run. Within a few dozen rounds the 148 stems collapse to three, sitting on the rings, a little short of them. The shortfall is the shrink: each survivor is about λ too small (0.90, 0.70, 0.60). Raise λ to 0.4 and the survivors shrink to 0.60, 0.41 and 0.31. A price near 0.7 would kill the weakest atom altogether. Press Refit and the survivors jump back to 1.00, 0.80 and 0.70: a plain least squares fit on the atoms ISTA chose.

When it goes wrong, and how to see it

The first symptom is bias. The L1 price shrinks every kept number, so the rebuild is a little too small. You measure it as the gap between the kept coefficients and a plain fit on the same atoms. The fix is the Refit you just pressed: use L1 to choose the atoms, then fit them without the price. The second symptom is speed. In the plane example the loop needed 100 rounds to move weight from two atoms to one. Faster cousins exist (FISTA adds momentum, Beck and Teboulle, 2009), and chapter 9’s greedy method skips the loop entirely.

With price λ = 0.3, a raw code number z = 0.2 goes through the soft threshold. What comes out, and why?

Chapter 4

Learning the Dictionary: Move the Atoms

Hold the codes still and nudge every atom toward the signals that use it, then alternate with the code step

Imagine a thousand customers, each ordering a basket from your shop. Today every customer is served: each basket was chosen, and each is a little off from what the customer wanted. Now you may rearrange the shelf. Which way should you tilt each ingredient? Toward the customers who use it. Every customer who buys a lot of an atom pulls it a bit toward their own order. That is the whole dictionary step.

The gradient, derived

Hold all the codes fixed. The score is F(D) = ½ ∑i ‖D xi − yi‖². We want its slope with respect to D, a table of m × K numbers. Take one atom dk. It appears in each rebuild as xik dk (code number times atom). Differentiating the square gives (D xi − yi) times xik, summed over the signals. Stack the K atoms side by side and the sum becomes one matrix product:

D
The dictionary, m × K. Each column is an atom.
μ
The step size: how far to move. Too small is slow. Too large overshoots.
∑i (D xi − yi) xiT
The gradient. Each signal contributes its leftover (m × 1, rebuild minus signal) times its code as a row (1 × K). The result has the shape of D, so it can be subtracted from D. This is the fifth slide’s update.

Read it atom by atom. Column k of the gradient is ∑i xik (D xi − yi). A signal that never uses atom k has xik = 0 and casts no vote. A signal that uses it heavily casts a big vote, in the direction that would shrink its own leftover.

One atom, three signals, by hand

Take a single atom d = (1, 0) in the plane and three signals that use it: y1 = (1, 0.3), y2 = (2, 0.2), y3 = (1.5, 0.6). With one atom each code number is the dot product d · y, so x = (1, 2, 1.5). The leftovers (signal minus rebuild) are (0, 0.3), (0, 0.2) and (0, 0.6): all point up, none sideways.

The vote for the atom is ∑ xi × leftoveri = 1 × 0.3 + 2 × 0.2 + 1.5 × 0.6 = 1.6, in the up direction. The total weight is ∑ xi² = 1 + 4 + 2.25 = 7.25. A step of μ = 1/7.25 moves the atom to (1, 0.221). Then we restore its length to 1: divide by √(1 + 0.221²) = 1.024, giving (0.976, 0.215). The atom has tilted up by about 12 degrees, toward where the data lie.

That choice μ = 1/∑x² is special: it jumps straight to the best atom for the codes you hold. The lecture uses one global μ; the device below gives every atom its own, scaled by that sum, so “step size 1” means “jump to the best fit”.

The two catches: length and the alternation

First, the length. Double an atom and halve all the codes that use it, and the misfit does not change. But the price λ‖x‖1 halves, so a learner that is free to grow atoms would inflate them all and shrink every code toward nothing. Every real learner therefore keeps each atom at length 1, as we did above.

Second, the alternation. The joint problem over D and the codes is not convex: it has several valleys. But with the codes fixed, the D step is convex, and with D fixed, the code step is convex (Chapter 3). So the heuristic is to alternate: code every signal, move the atoms, repeat. Each half-step lowers the score, so the score never rises. The lecture calls it a heuristic algorithm, honestly: it finds a valley, not necessarily the deepest one.

Two classical refinements are worth knowing. The method of optimal directions (Engan et al., 1999) replaces the gradient step by the exact answer D = Y XT (X XT)−1. K-SVD (Aharon, Elad and Bruckstein, 2006) updates one atom at a time, together with its codes, using a singular value decomposition.

Learn three atoms

Blue dots are signals, drawn from three hidden directions. Purple lines are the atoms. Pink segments are each signal’s leftover after one atom. Press Step to code and move once, or Run to repeat. Then raise the step size past 2, and try other starts.

1.00

Illustrative toy: 90 points on three rays at 15, 80 and 135 degrees with noise, one atom per point (s = 1). Step size 1 sends each atom to the best fit for the points that chose it. The error is the leftover energy divided by the total energy.

Press Step a few times from the first start. The pink segments shrink as each atom rotates onto its ray. With step size 1 it takes two or three steps. With 0.2 it takes about a dozen steps: slower, but safe. Push the step past 2 and each move overshoots the target by more than the distance it started from, so the atoms keep swinging and the error hovers near 10% instead of falling to 0.4%. That is the symptom of a step that is too large. You measure it in the read-out. The fix is to cut the step.

Now press “New start” several times and Run. Some starts put two atoms on the same ray and leave a ray with none. The error then settles near 16 or 17%, far above the best value of 0.4%. That is the other failure: a poor valley. The standard fixes are to restart, to seed the atoms from real data points, and to replace any atom that no signal uses with a signal that is poorly explained.

Why does the dictionary step keep every atom at length 1?

Chapter 5

What the Atoms Look Like

Cut a picture into small squares, learn a dictionary from them, and compare what appears with the first layer of a deep network

Take a photograph and cut it into small squares, eight pixels on a side. Each square is a signal of 64 numbers. A thousand squares make a thousand signals. Now run the learning loop of the last chapter on them. What will the atoms look like? Nobody tells the loop to look for edges. It is only told: explain each square with a few atoms, and keep the leftover small.

The sixth slide of the lecture shows the answer for natural photographs: a wall of small tiles, mostly short oriented strokes, edges and blobs. This result is old. Olshausen and Field found it in 1996 while asking how the visual cortex might code images efficiently (Nature, 381). The atoms that make natural images sparse are the same kind of patterns that cells in the first stage of the visual cortex respond to.

The data flow

Before we play, fix the shapes. Pick a picture of 64 × 64 pixels. Choose 1,000 squares of 8 × 8 at random places. Flatten each square into a column of 64 numbers, then subtract its average brightness. We remove the average because brightness is one extra number, and we want the atoms to describe the pattern, not the lamp.

Y: 64 × 1000  ≈  D: 64 × 32  ×  X: 32 × 1000 (at most s nonzeros per column)

Each loop of the learner does two things. It codes all 1,000 squares with the same dictionary, using the pursuit of Chapter 9 (for speed we use it here instead of ISTA). Then it moves every atom by the Chapter 4 step, with step size 0.8, and keeps each at length 1. If an atom is used by no square, we replace it with a random square, so no tile stays dead.

Grow a dictionary

Each tile is one 8 × 8 atom: warm where it adds light, blue where it removes light. At the start the tiles are copies of random squares. Press Run 25 and watch them turn into edges, then drag the atom budget and train again.

3

Toy picture made on the fly (bars, rectangles and disks on a soft gradient), not a photograph, so the atoms are blocky edges and corners rather than the smooth strokes of the lecture’s figure. 900 patches, mean removed, computed live in your browser.

Watch the first few sweeps. The leftover falls fast, from about 28% to under 20% in three sweeps, and keeps creeping down. The tiles lose their random texture and sharpen into step edges at different positions and orientations: a bright half and a dark half, a thin bar, a corner. If you pick s = 1 each patch must be explained by one tile, and the tiles become coarse, whole-patch prototypes, much like cluster centres (Chapter 8). With s = 5 the tiles can be simpler and more local, because they will be combined.

Taking one patch apart

Learned atoms only matter if they explain real patches. The device below picks a square from the picture, codes it with the tiles you just trained, and shows the sum.

Take a patch apart

Click or drag on the picture to move the square (or use the sliders). The row shows the patch, its sparse code as weighted tiles, and what is left.

20
14

Uses the tiles trained above, at the budget s set above. The patch shown has its average brightness removed, as in training.

Try a patch in the middle of a flat region. The code is almost empty: nothing to explain. Move to an edge and one or two tiles carry nearly all of it. Move to a corner of a rectangle and two or three tiles share the work. The weights are the code, and it is short because the tiles were learned from the same kind of image.

Dictionary learning next to deep learning

The seventh slide sets two pictures side by side: a learned dictionary, and the filters of the first layer of AlexNet, the convolutional network that won the 2012 ImageNet contest. The resemblance is real. AlexNet’s first layer has 96 filters of size 11 × 11 × 3 (Krizhevsky, Sutskever and Hinton, 2012), and many of them look like oriented edges and colour blobs.

There is a link in the arithmetic too, not only in the look. The first step of coding any patch (Chapters 3 and 9) is to take the dot product of the patch with every atom. A convolutional layer does just that, at every position of the picture at once. Its output for one filter is a code number. Then comes the ReLU, max(z − b, 0), which is a one-sided soft threshold with price b. So the layer is the first round of ISTA with one side removed.

Keep the limits straight. AlexNet learned its filters to classify images, not to rebuild them, and later layers do not return to pixels. The two methods meet where they see the same data: both land on edge detectors. What differs is the training goal and what comes after.

When the tiles look wrong

Three symptoms are worth naming. Noise-like tiles after many sweeps mean the data had no structure to find, or the step is too small. A few tiles identical to each other mean the start was crowded; reseed. Many dead tiles (used by no patch) mean K is too big for s and the picture; shrink K or raise s. You can see all three in the device: the grid shows them and the read-out counts the unused tiles.

Why does a convolutional layer resemble the first step of sparse coding?

Chapter 6

Cleaning and Repairing Pictures

Use a learned dictionary to remove noise and to fill in missing pixels, and see where it beats a simple average

An old photograph arrives with two kinds of damage. One is a fine grain of speckle over everything. The other is a scratch, or a line of printed text, that has wiped out some pixels completely. The lecture’s eighth to tenth slides show both repairs, credited to Mairal, Sapiro and Elad (2008): a noisy picture next to its cleaned version, then a photograph covered in red text next to the same photograph with the text gone. Both repairs rest on one fact. A clean patch has a short recipe. Damage does not.

Denoising: stop when only noise is left

A noisy patch is the clean patch plus noise. The clean part is explained by a few atoms. The noise has no favourite direction: it spreads almost evenly over all 64 directions, so no short recipe captures it. So we code the patch with as few atoms as possible and stop when the leftover is about the size the noise should have.

How big is that? If every pixel carries noise of standard deviation σ, a patch of m = 64 pixels carries noise of energy about m σ², and length about σ√m. For pixels on a 0 to 1 scale and σ = 0.1, that length is 0.1 × 8 = 0.8. Elad and Aharon (2006) stop at 1.15 times that: ε = 1.15 σ √m = 0.92. The 1.15 leaves a small margin because noise fluctuates.

The recipe, then. For every 8 × 8 patch of the noisy picture, subtract its mean, run pursuit until the leftover is shorter than ε, rebuild the patch from its atoms, and add the mean back. Neighbouring patches overlap. With a step of 2 pixels, each pixel is covered by 16 patches, and we average their 16 estimates. That averaging cuts noise further.

Clean the picture

Left, the noisy picture. Right, the result. Pick the dictionary, then drag the noise level. The first time you scroll here, a dictionary of 64 atoms is learned in the background from a different toy picture.

0.12

Toy pictures made on the fly, pixels 0 to 1, Gaussian noise. Quality is PSNR in decibels: higher is better, and every 3 dB halves the error. The lecture trains on the noisy image itself; here the learned atoms come from another toy picture so they are ready in about two seconds. Patches 8 × 8, step 2, stop at 1.15 σ √64, at most 12 atoms.

At σ = 0.12 the learned dictionary gains about 6 dB over the noisy picture, and a little over the cosines. Raise σ to 0.2 and the gap to the cosines grows to over 1 dB: learned atoms are tuned to the picture’s own edges, so they keep edges sharp while the noise goes. Now drag σ down to 0.05. The gap closes, and at very low noise the 121 fixed cosines can beat 64 learned atoms trained on a different picture. This is honest and expected: a dictionary only knows what it was taught.

Inpainting: fill the hole from what you can see

Now the second damage: some pixels are simply gone. We know which. Write the mask as M, a 0 or 1 for each pixel of the patch. We want the code x that makes the visible pixels right: minimise ‖M (y − D x)‖² plus the sparsity price. The hidden pixels do not enter the fit. When x is found, the rebuild D x has a value at every pixel, hidden ones included. Those are the fill.

Work a tiny case with four samples. The atoms are d1 = (1, 1, 1, 1)/2, d2 = (1, 1, −1, −1)/2 and d3 = (1, −1, 1, −1)/2. The true signal is 2 d1 + 1 d2 = (1.5, 1.5, 0.5, 0.5). Hide the fourth sample. We see (1.5, 1.5, 0.5). Cut the atoms to the first three samples: d1′ = (0.5, 0.5, 0.5), d2′ = (0.5, 0.5, −0.5), d3′ = (0.5, −0.5, 0.5). Each now has length 0.866, so we divide each correlation by 0.866 to compare fairly. The correlations with what we see are 1.75, 1.25 and 0.25; divided, 2.02, 1.44 and 0.29. Pick d1 first, then d2. Fitting both on the visible samples gives a + b = 3 and a − b = 1, so a = 2 and b = 1. Rebuild with the full atoms: sample 4 is 2 × 0.5 + 1 × (−0.5) = 0.5. The hidden sample is recovered exactly.

Fill the holes

Black pixels are missing. The middle panel fills each hole with the average of the nearest visible pixels. The right panel uses the learned atoms, coded on the visible pixels only. Choose the damage and raise its level.

5

Toy picture, not a photograph. Random level k hides k × 10% of pixels; scratch level k draws 2k wandering 3-pixel lines. Dictionary: the 64 learned atoms, 4 atoms per patch, patches 8 × 8 with at least 6 visible pixels, step 2. The lecture learns its dictionary from the damaged image; we reuse one from another toy picture.

With random dust the dictionary fill beats the neighbour average by 0.5 to 1 dB at every level: it knows that edges continue. With a few light scratches the plain average is as good, or slightly better. Make the scratches heavy and the dictionary pulls ahead by up to 0.9 dB. A plain average blurs an edge across the hole. A pursuit on the visible pixels notices which edge atom the visible part belongs to and continues it through the gap.

Where it fails, and what you measure

Denoising fails in two directions. If the stopping length is too small, noise stays in the picture (a grainy result, low PSNR). If it is too large, detail is erased (a smooth, waxy result, also low PSNR). The cure is to tie the length to the real noise level. A wrong σ breaks the tie, so estimate σ first. Inpainting fails when a hole is larger than the patch: a patch with no visible pixel has nothing to fit. Real systems then work at several scales, or fill in stages. The count of visible pixels per patch is the number to watch; the device skips patches under 6.

Why does sparse coding remove noise from a patch?

Chapter 7

Deep and Structured Dictionaries

Build a dictionary as a product of smaller ones, or from shifted copies of one template, and count what that buys and costs

A one-megapixel picture has a million numbers. A dense dictionary with ten million atoms for it would need ten trillion numbers of its own. No computer stores that, and no learner can fit it from any data set. The eleventh slide of the lecture shows the way out: the dictionary can be structured, for example hierarchical or convolutional. Structure means the dictionary is built from far fewer free numbers than it has entries.

Deep dictionary learning: a product of dictionaries

The slide writes the dictionary as a product of L smaller matrices and keeps everything else as before:

min
Over the code of every signal and over every factor D1 to DL at once.
D1 D2 … DL
The dictionary, as a chain of matrices multiplied together. The shapes must chain: D1 is m × k1, D2 is k1 × k2, and so on, ending in K columns.
‖xi‖1
Only the code at the far end is sparse. It picks columns of the last factor.

Read the chain from the right. The code x picks a few columns of DL. Each column of DL is a recipe of columns of DL−1. And so on down to D1, whose columns are in signal space. So an atom of the top dictionary is a recipe of recipes: strokes make letters, letters make words. That is why the slide calls it hierarchical.

Now an honest point the slide leaves unsaid. A product of matrices is one matrix. D = D1 D2 … DL is just another m × K table. There is no nonlinearity between the factors, unlike a neural network with ReLUs. So going deeper does not let the dictionary represent anything a single matrix could not. What it changes is how many numbers you must learn, how fast you can multiply, and what structure the learner is pushed toward.

Counting the cost

Take m = 64 and K = 256. A dense dictionary holds 64 × 256 = 16,384 numbers. Write it as D1 (64 × k) times D2 (k × 256), with a middle width k = 32. Then D1 holds 2,048 numbers and D2 holds 8,192, a total of 10,240: 37.5% fewer.

The price is rank. The product of a 64 × 32 and a 32 × 256 matrix has rank at most 32: all its atoms live inside a 32-dimensional slice of the 64-dimensional signal space. A signal that sticks out of that slice can never be rebuilt, however sparse the code. So the middle width must be at least the signal length, or the data must truly live in a slice.

Count the numbers in a dictionary

Each box is a table of numbers, drawn in proportion to its size. Choose a structure and tune its knob. The bar compares the free numbers against the dense dictionary.

32

Exact counts for m = 64 and K = 256. Two factors: 64 × k plus k × 256. Convolutional: 4 filters of length k, each with 64 circular shifts, so 4k free numbers for 256 atoms. The rank of a product is at most its smallest inner width.

Choose “Two factors” and slide k. At k = 64 the product holds 64 × 64 + 64 × 256 = 20,480 numbers, more than the dense table, and the rank is full. The break-even is near k = 51. At k = 16 the count falls to 5,120 but the rank is 16, so three quarters of the signal space is out of reach. The sweet spot depends on how many directions your data really uses.

Convolutional dictionaries: one filter, every position

The other structure the slide names is the convolutional one. Take a single short template w, and make every atom a shifted copy of it. A signal is then w convolved with a sparse spike train x: the spikes say where the template occurs and how strong it is.

Work it with a length-8 signal and the template w = (1, 2, 1). Put a spike of size 3 at position 2 and a spike of −1 at position 6 (positions count from 0, and the signal wraps around at the end). The first spike writes 3 × (1, 2, 1) = (3, 6, 3) at positions 2, 3 and 4. The second writes −(1, 2, 1) = (−1, −2, −1) at positions 6, 7 and 0. The signal is y = (−1, 0, 3, 6, 3, 0, −1, −2). Eight numbers, described by one template and two spikes.

The number of free numbers is the template’s length, not the number of atoms. One filter of length 12 yields an 85-atom dictionary for a 96-sample signal. This is exactly the structure of an electrocardiogram (the same heartbeat shape repeating), of a pulse train from a machine, and of the filters in a convolutional network (Chapter 5). Try finding the pulses below.

Find the pulses

The pulse template (top left) was placed three times in a signal, with different signs and sizes, and noise was added. Pursuit with the shifted-copy dictionary picks three atoms. Drag the noise up until it fails.

0.30

Illustrative toy: 96 samples, a 12-sample pulse placed at 14, 41 and 70 with sizes 3.0, −2.1 and 2.7. Noise is Gaussian with the standard deviation shown, fixed seed. Three atoms picked by orthogonal matching pursuit.

At noise 0.3 the three picks land exactly on 14, 41 and 70. Raise the noise to 1.2 and one pick wanders to 47: a noise bump now correlates with the template as strongly as the weakest real pulse, the one of size −2.1. That is the symptom. You measure it as the gap between a pick’s position and the true one. The fixes are to average more, to lower the noise, or to give the template more samples so it correlates more sharply.

A dictionary is the product D1 D2, with D1 of size 64 × 8 and D2 of size 8 × 256. What is certain?

Chapter 8

Clustering Is Dictionary Learning

Write k-means in the notation of this lesson and see it as the strictest member of the family: one atom per signal, with weight one

A shop owner wants to place three delivery depots so that every customer is near one. Customers are points on a map. The owner picks three depot positions and sends each customer to the nearest depot. Then she moves each depot to the middle of its customers. Then she sends customers again. That loop is k-means clustering, and the twelfth slide of the lecture points out that it is dictionary learning in disguise.

The slide’s formula, read slowly

The slide minimises the total squared distance from every point to the centre of its group, and writes it as a matrix norm:

∑j ∑xi ∈ Cj
For each of the k clusters, visit every point assigned to it.
‖xi − cj‖²
The squared distance from a point to its cluster centre cj.
‖X − C BT‖F2
The same total, as a matrix. The Frobenius norm ‖·‖F squares every entry of a matrix and adds them. The slide calls the data table X; our lesson calls it Y, and we keep Y below. C holds the k centres as columns, and B is the assignment table: Bij = 1 when point i belongs to centre j, else 0.

Now match the pieces to Chapter 0. The data table is Y, with one point per column. The centres C are a dictionary D with k atoms. The table BT is the code table X: column i has a single 1, in the row of the point’s centre, and zeros elsewhere. So k-means solves Y ≈ D X with the strictest possible code: exactly one nonzero per column, and that nonzero must equal 1.

Y: 2 × 150  ≈  C: 2 × 3  ×  BT: 3 × 150 (each column of BT is all zeros except one 1)

The two moves, derived

This is the same alternation as Chapter 4. Hold C fixed, and the cost splits into independent pieces, one per point. Each point lowers its own piece by choosing the nearest centre. That is the assign step. Hold B fixed, and the cost splits by cluster. For one cluster, the slope of ∑‖xi − c‖² with respect to c is ∑ 2(c − xi). Setting it to zero gives c = the average of the points. That is the update step: each centre moves to the mean of its points. In matrix form, C = Y B (BTB)−1, the same least-squares fit as the method of optimal directions in Chapter 4.

Work four points on a line: 1, 2, 9 and 11, with two centres starting at 0 and 10. Assign: 1 and 2 go to the first centre, 9 and 11 to the second. The cost is (1² + 2²) + (1² + 1²) = 7. Update: the centres move to 1.5 and 10. The new cost is (0.5² + 0.5²) + (1² + 1²) = 2.5. Assign again: nobody changes group, so the loop stops. The cost went 7, then 2.5, and never went up.

This one-dimensional case has a name in this series: it is the Lloyd-Max quantizer, taught in the Lloyd-Max lesson of this series. The quantization levels are the centres, and rounding a sample to the nearest level is the assign step. The k-means lesson covers the same loop on its own.

Run k-means

Blue dots are points, purple dots are centres, pink lines join each point to its centre. The strip below is the code table Bᵀ: one purple cell per column. Press Assign then Move centres, or Run. Change k, or try new starts.

Illustrative toy: 150 points from three blobs of spread 0.32. Starts are random data points chosen by a fixed seed. The cost is the squared Frobenius norm ‖Y − C Bᵀ‖². Best costs found over 20 starts: 116.9 at k = 2, 30.8 at k = 3, 25.8 at k = 4.

At k = 3 every start reaches the cost 30.8, because the blobs are well separated. Now choose k = 2. Different starts settle at 116.9, 134.9 or 141.4. Each is a valley, and a poor one is a symptom you can measure: the cost stays above the best one you have seen. The usual fix is to run several starts and keep the best, or to seed the centres smartly (the k-means++ rule).

There is a lesson in the costs across k, too. Going from 2 centres to 3 cuts the cost from 116.9 to 30.8, a fall of 74%. Going from 3 to 4 only reaches 25.8, a fall of 16%. The sharp bend is the clue that the data hold three groups. A learned dictionary behaves the same way: past the right number of atoms the error stops falling fast.

One family, three strictness levels

Dictionary learning relaxes k-means step by step. Keep one atom per signal but let its weight be any number: you get gain-shape clustering, where a group is a direction, not a place (Chapter 4’s three rays). Allow s = 2 or 3 atoms: signals are built from several atoms, which is how the picture patches of Chapter 5 were coded. Each step gives the dictionary more power, at the price of a harder, less stable search.

In the notation Y ≈ D X, which description fits k-means?

Chapter 9

Matching Pursuit, Step by Step

Chip away at a signal with the atom that matches the biggest remaining lump, and fix the method’s one habit that wastes atoms

A sculptor faces a rough block. She does not plan every cut in advance. She finds the biggest lump, takes the chisel that fits it, and removes it. Then she looks again. Matching pursuit works the same way on a signal. The lecture gives it one slide for the algorithm and six more for a worked example, in which one new spike appears in a coefficient plot per slide. We follow it step by step and derive why each step is correct.

The algorithm in six lines

Keep two things. The code x starts as all zeros. The residual r, what is still unexplained, starts as the signal itself. Every atom di has length 1. Then repeat:

  1. Correlate. For every atom, compute the dot product diT r. It says how much of the residual points along that atom.
  2. Select. Take the atom with the largest absolute dot product, î = argmaxi |diT r|.
  3. Update the code. Add the dot product to that atom’s code number: xî ← xî + dîT r.
  4. Update the residual. Remove the atom’s share: r ← r − (dîT r) dî.
  5. Stop when the code has L nonzeros, or the residual is small enough.

Why is step 4 right? Remove c times an atom d from r, with ‖d‖ = 1. The new length squared is ‖r‖² − 2c dTr + c². The smallest value over c is at c = dTr, and it equals ‖r‖² − (dTr)². So each step lowers the leftover energy by exactly the square of the dot product, and step 2 picks the atom that lowers it most. That is the whole case for being greedy.

Worked by hand, and its flaw

Use the plane atoms again: d1 = (1, 0), d2 = (0, 1), d3 = (0.6, 0.8), and the signal y = (1.0, 1.6). Its energy is 1 + 2.56 = 3.56.

Step 1. The dot products are 1.0, 1.6 and 0.6 + 1.28 = 1.88. The biggest is d3. So x3 = 1.88, and r = (1.0, 1.6) − 1.88 (0.6, 0.8) = (−0.128, 0.096). Check the energy: 0.128² + 0.096² = 0.0256, and 3.56 − 1.88² = 0.0256. Good.

Step 2. Now the dot products with r are −0.128, 0.096, and 0 for d3 (a residual is always at right angles to the atom just removed). Pick d1: x1 = −0.128, r = (0, 0.096). Step 3. Pick d2: x2 = 0.096, r = 0. The code is (−0.128, 0.096, 1.88): three atoms, exact, in a plane where two should do.

There is the flaw. Matching pursuit never revisits an earlier coefficient. It gave d3 a coefficient of 1.88, which was a little off, and then spent two more atoms repairing the damage. The cure is orthogonal matching pursuit (OMP). After every pick, it refits all chosen atoms together by least squares. Redo it: after picking d3, then d1, solve y = a d3 + b d1. The vertical part says 0.8a = 1.6, so a = 2. The horizontal part says 0.6a + b = 1, so b = −0.2. The residual is exactly zero after two atoms, with code (−0.2, 0, 2). One atom fewer, and sparser.

Pick atoms one at a time

Top: the signal (blue), the rebuild (warm), the leftover (pink). Middle: a stem for every one of 128 atoms, the same plot as the lecture’s coefficient figure. Bottom: the energy left, step by step, for both methods. Press Pick next atom, then switch method and compare.

Illustrative toy: 64 samples of two cosines at 10.25 and 23.7 half-cycles with a little noise, and a dictionary of 128 cosines on a grid twice as fine as the standard one (neighbouring atoms overlap heavily: coherence 0.90). Computed live in your browser.

Press Pick next atom three times in each mode. The first two picks match: the two big cosines. At the third step the methods part. Matching pursuit leaves 10.0% of the energy and OMP leaves 4.9%. After four picks it is 4.7% against 1.2%. OMP reaches a given accuracy with about one atom fewer. Look at the stems: matching pursuit puts several neighbouring atoms at modest sizes, nudging a frequency that fell between two grid points. OMP tunes all of them together.

Why it works, and when it does not

OMP has a guarantee, which matching pursuit lacks. It never picks an atom twice, and it finishes in at most m steps with a residual of exactly zero, because m independent atoms span the whole space. It also costs more: a small least-squares solve per step. Compute the true cost: with K atoms of length m, step 1 is a K × m correlation (the dominant cost, 128 × 64 = 8,192 multiplies here), and the solve touches only a few atoms.

The deeper question is when greedy picking lands on the right atoms. The answer depends on the coherence of the dictionary: the largest dot product between two different atoms, μ = maxi≠j |diTdj|. A classical result (Tropp, 2004) says OMP finds any s-atom signal exactly when μ(2s − 1) < 1. For s = 3 that needs μ below 0.2. An orthonormal dictionary has μ = 0, so pursuit is trivial. The 128-atom grid in the device has μ = 0.90 and the guarantee says nothing, yet it still works well, because a guarantee for every signal is far stricter than what one friendly signal needs.

You can see the symptom of high coherence in the device: the stems come in crowds of neighbours with alternating signs. You measure it as the number of atoms needed for a fixed accuracy. The fixes are a less coherent dictionary, OMP in place of matching pursuit, or the L1 route of Chapter 3.

In the plane example, matching pursuit used three atoms where orthogonal matching pursuit used two. Why?

Chapter 10

Sparse Codes at Work

Use what a dictionary cannot explain as an alarm, then place dictionary learning among the other tools the course points to

A pump in a plant hums all day. A sensor on its casing records the vibration. Most of the time the hum is a steady chord of two or three tones. One afternoon a bearing cracks and the casing starts to click. The click is tiny next to the hum, and no one is listening. Can a program notice?

Three jobs for one code

The twentieth slide lists where the lecture’s tools get used in practice: mechanical monitoring (engines, elevators, buildings, power plants), medical monitoring (lung sounds, heart sounds, speech) and security surveillance (finding interesting events, detecting accidents). One idea runs through all three, and a sparse code gives it three uses.

  1. Compress. Store the few code numbers instead of every sample. A window of 64 samples becomes 4 atoms and 4 weights.
  2. Describe. Use the code as features for a classifier (see the SVM and Bayes classifier lessons). “This window uses the 5.5 and 12.5 tones” says more than 64 raw numbers.
  3. Detect. Learn the dictionary from normal signals only. When a new window cannot be explained by a few atoms, the leftover is large, and that is the alarm.

Detection is the new idea in this chapter, and it works because of the contrast we built in Chapter 6. Normal behaviour has structure, so a short recipe explains it. A fault is rare and has no reason to match the normal atoms, so it stays in the leftover.

Worked with numbers

Use windows of 64 samples. Normal vibration is two tones: one of amplitude 1.0 and one of 0.6. The energy of a tone of amplitude a over 64 samples is about 32 a². So a window holds about 32 (1 + 0.36) = 43.5 units of energy. The dictionary has cosine and sine atoms on a half-bin grid, so any tone, at any phase, needs two atoms. Four atoms explain the hum, and the leftover is about 0.3% of the window.

Now a click: a spike of height 6 at one sample, followed by −3. Its energy is 36 + 9 = 45, as large as the hum. A spike is spread evenly across all 64 directions of tones, so four atoms capture only about 4/64 of it. Nearly all 45 units stay in the leftover, which is then about half the window’s energy. The device measures it at 48%. A threshold of 10% separates 0.3% from 48% with room to spare.

Sound the alarm

Twelve windows of vibration. Each is coded with 4 atoms of a normal-tone dictionary. The pink bars are the leftover energy share; the yellow line is your alarm threshold. Inject a fault, then see how noise and the threshold change what you catch.

1.00
0.05
10%

Illustrative toy: tones of amplitude 1.0 and 0.6 at 5.5 and 12.5 cycles per window, 12 windows of 64 samples, the mean of each window removed, 124 cosine and sine atoms on a half-bin grid. The click sits in window 8, the new tone fills windows 8 and 9, the drift starts after window 5. Fixed noise seed.

Try each fault at strength 1 and noise 0.05. The click gives a tall bar in window 8. A new tone at 29.7 cycles is weaker, about 15% in window 8 and 8.5% in window 9. The pitch drift is hardest: its bars climb to 5 to 9%, because a shifted tone still looks mostly like a tone. At threshold 10% you catch the click and the new tone in window 8, and miss the drift. Lower the threshold to 4% and you catch the drift in three of its windows.

Now the cost of a low threshold. Push the noise to 0.3 with no fault. Random noise is spread over all directions and cannot be explained by four atoms, so every bar rises to 8 to 15%. A 10% threshold now fires on healthy windows. That is a false alarm, and it is the symptom of a threshold set below the noise floor. You measure it by running the detector on data you know is healthy. The fix is to set the threshold from healthy data (a little above its largest bar), and to cut the noise at the sensor if you can.

A second failure is slower. A machine ages, and its normal hum drifts. A dictionary learned in January starts to flag healthy March windows. Systems of this kind retrain on a window of recent normal data.

Where this sits among the tools

The twenty-first slide lists other signal-processing and machine-learning methods. Each connects to something you have seen:

The last slide names the courses to take next: EE270 (large-scale matrix computation, optimization and learning), EE364a and EE364b (convex optimization), EE264 (digital signal processing), EE373A (adaptive signal processing), CS229 (machine learning) and CS230 (deep learning).

One modern descendant deserves a mention. Researchers who study what a large language model computes inside train a sparse autoencoder on its internal activations: a wide dictionary, an encoder that finds a sparse code, and an L1 price, which is the Chapter 2 objective at a new scale. The sparse autoencoders lesson tells that story.

A detector is built from a dictionary learned on healthy vibration. Healthy windows start to trigger alarms after the sensor gets noisier. What is the likely cause, and the fix?

Chapter 11

Field Guide

Review the lecture on one page: the summary, the numbers to remember, a checklist, the code, and where to go next

You can now rebuild Lecture 20 of EE269 from memory. A signal is a short recipe of atoms. The shortest recipe is hard to find, so we trade the count of nonzeros for the sum of sizes, and then solve by shrinking. With the codes in hand, we move the atoms and repeat. The same machinery denoises, repairs and flags anomalies, k-means is its strictest case, and matching pursuit is the greedy shortcut.

The one-paragraph summary

A dictionary D holds K unit-length atoms. A signal y is rebuilt as D x, where the code x is sparse: at most s nonzeros. Learning minimises ∑‖D xi − yi‖² over both D and the codes; as a matrix problem, D X ≈ Y with sparse columns in X. The zero norm makes the code search NP-hard, so the L1 relaxation adds λ‖x‖1, whose diamond ball touches exact-fit lines at corners with zeros. ISTA solves it by a gradient step then a soft threshold. The dictionary moves by D ← D − μ ∑(D xi − yi)xiT, keeping atoms at length 1. On image patches the atoms become edges, as AlexNet’s first filters do. Structure (products, convolutions) cuts parameters, not expressiveness. Matching pursuit picks the best-matching atom each step; OMP also refits.

The numbers that matter

Every number below comes from this lesson’s own toy devices, not from the lecture, which gives none. They are labelled illustrative and reproducible in your browser.

What (chapter)NumberWhy it matters
Hero signal, 3 atoms (0)overcomplete 0.0%; spikes 58.8%; cosines 67.8% energy leftThe right shelf makes the recipe short
Subsets of atoms (1)C(148, 3) = 529,396; C(148, 12) ≈ 1.5 × 1017, about 4,600 yearsBlind search over supports cannot scale
Plane example, ISTA (3)L = 2; x = (0.55, 0.75, 0.95), then (0, 0, 1.899) after 100 roundsShrinking moves weight onto one atom; bias equals λ
ISTA on the hero signal (3)λ = 0.1: 3 nonzeros by round 40; 0.90, 0.70, 0.60 against 1.0, 0.8, 0.7Refit the survivors to remove the bias
Atom step, one atom (4)d = (1, 0) becomes (0.976, 0.215), a tilt of about 12°Atoms rotate toward the signals that use them
Three-atom learner (4)19.5% to 0.4% in 3 steps at step size 1; stuck near 10% above 2; 16 to 17% from poor startsStep size and start decide the valley
Patch dictionary (5)about 28% to under 20% leftover in 3 sweeps; 64 pixels per patchEdges emerge from the objective alone
Denoising, σ = 0.1 (6)noisy 20.0 dB; cosines 25.0 dB; learned 25.8 dB; stop at 1.15 σ √64Stop coding when only noise is left
Inpainting, 49% missing (6)neighbour fill 23.3 dB; dictionary fill 24.2 dBFit the visible pixels, fill from the full rebuild
Parameters, m = 64, K = 256 (7)dense 16,384; two factors at k = 32: 10,240 (rank at most 32); 4 filters of length 8: 32Structure saves numbers, not power
k-means cost, 150 points (8)k = 2: 116.9; k = 3: 30.8; k = 4: 25.8The bend marks the true number of groups
MP against OMP (9)4 picks: 4.7% against 1.2% left; plane example: 3 atoms against 2Refitting spends fewer atoms
Vibration alarm (10)healthy 0.3 to 0.6% left; a click 48.2%; noise 0.3 lifts healthy to 8 to 15%Set the threshold from healthy data

A checklist before you trust a sparse code

  1. Atoms at unit length? If not, the L1 price can be cheated by scaling.
  2. Mean removed? Patches and windows should lose their average first, or the atoms learn brightness.
  3. Budget or price set from data? Pick s or λ by the error curve, as in the hero, not by habit.
  4. Dead atoms re-seeded? An atom nobody uses is wasted shelf.
  5. Several starts? The learner finds a valley. Keep the best of a few starts.
  6. Shrinkage bias refit? After L1 chooses the atoms, fit their weights without the price.
  7. Thresholds from healthy data? For denoising and for alarms alike.

The core, as code

The whole lecture fits in three short functions: the shrink loop, the greedy pursuit with refit, and the learner that alternates them. Shapes: D: m × K, Y: m × n, X: K × n.

pythonimport numpy as np

def soft(z, t):                                   # Chapter 3: shrink toward zero, stop at zero
    return np.sign(z) * np.maximum(np.abs(z) - t, 0)

def ista(D, y, lam, iters=300):                    # L1 code for one signal
    L = np.linalg.norm(D, 2) ** 2                 # largest eigenvalue of D^T D
    x = np.zeros(D.shape[1])
    for _ in range(iters):
        x = soft(x + D.T @ (y - D @ x) / L, lam / L)   # fix the misfit, then shrink
    return x

def omp(D, y, s):                                  # Chapter 9: greedy pick, refit all
    r, idx = y.copy(), []
    for _ in range(s):
        idx.append(int(np.argmax(np.abs(D.T @ r))))        # best match to the residual
        c, *_ = np.linalg.lstsq(D[:, idx], y, rcond=None)  # refit every chosen weight
        r = y - D[:, idx] @ c
    x = np.zeros(D.shape[1]); x[idx] = c
    return x

def learn_dictionary(Y, K, s, sweeps=30, rho=0.8, seed=0):   # Chapter 4: code, then move atoms
    rng = np.random.default_rng(seed)
    D = Y[:, rng.choice(Y.shape[1], K, replace=False)]     # start from real signals
    D = D / np.linalg.norm(D, axis=0)
    for _ in range(sweeps):
        X = np.stack([omp(D, Y[:, i], s) for i in range(Y.shape[1])], axis=1)  # K x n, sparse columns
        R = Y - D @ X                                      # leftovers, m x n
        w = (X ** 2).sum(axis=1)                            # how heavily each atom is used
        for k in range(K):
            if w[k] == 0: D[:, k] = Y[:, rng.integers(Y.shape[1])]   # re-seed a dead atom
            else: D[:, k] += rho * (R @ X[k]) / w[k]               # Chapter 4's gradient step, per atom
        D = D / np.linalg.norm(D, axis=0)                  # keep every atom at length 1
    return D

Read it line by line and name the chapter behind each choice. The shrink in soft is the closed-form answer to the one-number problem. The step 1/L is safe because L bounds the curvature of the misfit. omp picks greedily and refits, so its residual is at right angles to every chosen atom. In learn_dictionary, R @ X[k] is the vote of every signal for atom k, divided by the atom’s total weight, which is the exact step size 1 of Chapter 4 when rho is 1.

Where this sits

Dictionary learning is the sparse member of the matrix-factorization family this course has been walking. Autoencoders and robust PCA compress with a narrow bottleneck. Non-negative matrix factorization demands non-negative parts. Here we ask for few active parts. All three read Y ≈ D X with a different rule on X. The transform lessons gave us fixed dictionaries: the DFT (cosines and sines), the STFT (windowed tones) and wavelets (short bursts). Dictionary learning replaces the fixed shelf with a learned one.

Keep going

Sources and credit

This lesson follows the Dictionary Learning deck of Stanford EE269, Signal Processing for Machine Learning, Lecture 20, taught by Mert Pilanci on 18 November 2020. Read the slides page and the course site for the original; the explanations, devices and toy numbers here are our own. The deck credits its denoising and inpainting figures to Mairal, Sapiro and Elad (2008). Further references named in the text, cited by author and year so you can look them up: Olshausen and Field (1996); Natarajan (1995); Tibshirani (1996); Chen, Donoho and Saunders (1998); Daubechies, Defrise and De Mol (2004); Tropp (2004); Elad and Aharon (2006); Aharon, Elad and Bruckstein (2006); Engan, Aase and Husoy (1999); Beck and Teboulle (2009); Krizhevsky, Sutskever and Hinton (2012).

The takeaway. Signals are rarely crowds. Find the short recipe: pick atoms that match the data, count size with the L1 ruler so zeros appear, shrink or pursue to find the code, then move the atoms toward the signals that use them. What the recipe cannot explain is noise, or a fault.
You have 10,000 vibration windows of healthy machines and want a detector for faults. Which plan follows this lecture?

Now press Present or Teach and explain, from memory, how a sparse code is found and how a dictionary is learned. Then go back to the signal at the top, choose the spikes dictionary, drag the budget to 12, and say aloud why it still leaves 21% while three overcomplete atoms leave none.

EE269 Lecture 20: Dictionary Learning
The course site · Lecture slides · Back to Gleams