A Fourier transform tells you which pitches a sound holds, but not when. Wavelets tell you both, with tiles that stretch for deep notes and shrink for sharp clicks.
Pick a window, then watch the same signal change shape. A short window finds the click but smears the pitch. A long window finds the pitch but smears the click. The wavelet does neither. Then we build it piece by piece, from one stretching ruler to the eight-number table of the Haar transform, and on to images.
You need what a sine wave is and what an average is. We build the rest from zero.
Based on the wavelets lecture of Stanford EE269: Signal Processing and Quantization for Machine Learning, taught by Mert Pilanci. The slides are the course’s; every figure here is our own.
The signal is the lecture’s example: a 32 Hz burst from 0.1 to 0.3 s and a 64 Hz tone from 0.7 s, sampled at 1,000 Hz. We added one click at 0.5 s so timing has something to resolve. Windows are Gaussian; the wavelet is a Morlet wavelet whose window is 0.8 cycles wide. Brightness is scaled so a pure tone of amplitude 1 reads 0.5 at every pitch.
Chapter 0
See why a fixed analysis window must blur either the timing or the pitch, and why a window that changes size fixes it
Picture a recording of a drum kit. A kick drum thumps at about 60 Hz and rings for a tenth of a second. A hi-hat ticks at several thousand hertz and is over in a few thousandths of a second. (These two numbers are illustrative, but real drums look like this.) You want a picture of the recording that shows both sounds, each at the right pitch and the right moment.
A signal is a list of numbers that records something over time: sound pressure, a heartbeat, one row of pixels. Frequency counts how many times per second a wave repeats. We measure it in hertz (Hz). A higher frequency sounds like a higher pitch.
The Fourier transform answers one question: how much of each frequency is in the whole signal? It is a superb tool. But it throws away when. A single kick and a single hi-hat, played in either order, give the same list of frequencies.
The usual repair is the short-time Fourier transform, or STFT (our Lecture 8 lesson builds it). Slide a small window along the signal. The window is a bump that lets you look at one short piece. Take a Fourier transform of each piece. The result is a map with time across and frequency up.
The flaw is the window’s size, and you choose it once. A long window sees many cycles, so it measures pitch well. But it averages over a long stretch, so it cannot say when something happened. A short window pins down the moment, but it sees so few cycles that the pitch becomes a blur.
Try it in the hero at the top. With the 10 ms window, the click stays sharp and the 32 Hz burst smears across a wide band of pitches. With the 80 ms window the burst is crisp and the click spreads across a fifth of a second. You cannot win with one size.
This is not a flaw of the STFT alone. It is a law, the uncertainty principle. Let Δt be how widely a window spreads in time and Δf how widely it spreads in frequency (both as standard deviations of the energy). Then their product can never drop below 1/(4π), about 0.08. A Gaussian bump reaches that floor. Squeeze it in time and it widens in frequency by the same factor.
Each box on the time and frequency map, with width Δt and height Δf, is a tile. Its area is stuck. But the law says nothing about the shape of the tile. The STFT uses the same shape everywhere. Why? Nothing in the physics asks for that.
Ask what the signal wants. A deep note, such as the kick, needs a long look to measure its pitch, and it is slow, so a blurry moment does no harm. A high tick is fast, so you need a short look to find it, and many cycles fit in a short look anyway. The ideal tile is wide and short in frequency at low pitch, narrow in time and tall in frequency at high pitch. The window should shrink as the pitch rises.
That is the whole idea of wavelets. A wavelet is a short wave that starts and ends, like a blip on a heart monitor. We stretch it to look for slow features and squeeze it to look for fast ones. Slide 5 of the lecture shows the picture: a wavelet slides along a signal, and where the two have the same shape the match number is high. Chapter 1 turns that picture into a formula.
Each box is one tile on the map of time (across) and frequency (up). Choose how the plane is cut, then drag the pitch to light the tiles at that frequency. Compare the shapes, then the areas.
Illustrative units: one second wide, 0 to 32 Hz tall, 32 tiles, every tile of area 1 (width in seconds times height in hertz). The octave bands of the wavelet layout are 16 to 32, 8 to 16, 4 to 8, 2 to 4 and 0 to 2 Hz, the dyadic layout this lecture builds toward.
Both layouts hold the same 32 tiles, so both hold the same amount of information. The fixed layout spends it evenly. The wavelet layout spends more time resolution where sounds are fast, and more pitch resolution where sounds are slow. Real signals tend to be built that way: heartbeats, speech, earthquakes and drums all have slow, deep parts and quick, high parts.
The lecture does this in two moves. First the continuous wavelet transform, a smooth version where the wavelet can take any size and any position. It is the best for looking. Then the discrete wavelet transform on the simplest wavelet, the Haar wavelet, where everything reduces to averages and differences of neighbouring numbers. It is the best for computing and compressing. We finish with an image.
Chapter 1
Stretch and slide one small wave, and measure how well each copy matches the signal
You hold a recording and ask a narrow question: is there a 32 Hz wiggle near the 0.2 second mark? A direct way to answer is to build a short 32 Hz wave, lay it on the recording at 0.2 s, and measure how well the two agree. If they rise and fall together, the answer is yes. If one is high when the other is low, they cancel.
To ask the same question everywhere, you slide the template to every moment. To ask it for every pitch, you stretch or squeeze the template. That is the continuous wavelet transform, in plain words: one template, many sizes, many positions, one match number for each.
Start with one function ψ(t), the mother wavelet. It is a short wave that dies away on both sides. Two properties make it a wavelet. Its total area is zero, so it has equal positive and negative parts. And it has finite energy, so it fades to nothing and the integral of ψ(t)² stays finite.
The zero area matters. A template with positive area would give a big match to a flat signal, which carries no wiggle at all. That is a false alarm, so the area must be exactly zero.
Our running example is the Morlet wavelet: a cosine under a Gaussian bump. It oscillates once per unit of time and fades with a width of 0.8. Another common shape is the Mexican hat, the negative second derivative of a Gaussian. The simplest is the Haar wavelet in Chapter 4, one up step and one down step.
Two numbers turn the mother into a whole family. The scale s stretches the wave: s above 1 makes it longer and slower, s below 1 makes it shorter and faster. The translation τ slides it along the time axis. Slide 2 of the lecture writes the family as one line.
Take s = 2. The argument t/2 reaches a given point twice as late, so the wave is twice as wide and the pitch is half. Take s = 0.25. The wave is four times narrower and the pitch is four times higher. If the mother’s own pitch is f0, the copy at scale s has pitch f0/s. Large scale means low frequency. This feels backwards at first, and it is the single most common slip.
Why 1/√s? Stretching by s makes the wave s times wider, and the area under its square would grow s times. Dividing the height by √s divides the squared height by s. The two cancel, so the energy ∫|ψs,τ|²dt is the same for every s. At s = 2 the height is 1/√2 ≈ 0.707 of the mother’s. At s = 0.25 it is 1/√0.25 = 2 times as tall. Every copy is an equally loud question.
Now measure the agreement. Multiply the signal by the copy at every instant and add up (integrate) the products. Where the two have the same sign, the products are positive. Where they differ, negative. Slide 3 names the result.
Read the shape of the answer. The input f(t) has one variable, time. The output W(s,τ) has two: scale and translation. The lecture says it in one line: a continuous function of one variable becomes a continuous function of two. That is a surface, and Chapter 2 learns to read it.
Try one point of that surface yourself. Move the pitch and the time, and watch the wave, the product, and the number.
Blue is the signal. The warm wave is the copy at the pitch and time you pick. The purple area below is signal times copy, and its total is the match. Park the copy on the 32 Hz burst, then on the 64 Hz tone, then on silence.
The signal is the lecture’s (32 Hz burst 0.1 to 0.3 s, 64 Hz from 0.7 s). The copy is the real part of a Morlet wavelet at scale s = 1/pitch (mother pitch f0 = 1 Hz, width 0.8). The number shown is the full complex match, computed with the 1/√s of the definition.
Park the copy on the burst at the right pitch and the product is mostly purple above the line. Move it off the burst and the positive and negative parts cancel. Move the pitch a little wrong, say 20 Hz, and the copy drifts out of step with the signal, so the match shrinks. This is the whole transform: a measure of agreement, taken at every pitch and every moment.
The transform loses nothing. Slide 4 shows the inverse: add up every copy, each weighted by its match number. In symbols, f(t) is the double integral of W(s,τ)ψs,τ(t) over τ and s. The slide leaves out a constant and a weight that depends on s. We keep the idea: the signal is a sum of wavelets.
The last bullet of slide 3 gives a design rule. For a compact answer, choose the mother wavelet to match the signal’s shape. A wave-like signal fits a Morlet wavelet with few terms. A signal with jumps fits the blocky Haar wavelet. Chapter 8 measures this.
There is also a cost. W is a surface with two continuous variables, much bigger than the signal. The copies overlap and repeat each other. The continuous transform is wonderful to look at but wasteful to store. The discrete transform of Chapters 3 to 7 fixes that.
Chapter 2
Stack the match numbers of every scale into one picture, and learn where to trust it
A single match number W(s,τ) answers one small question. To see the whole signal you need all of them. Slides 6 and 7 do exactly that on a test signal, and we will too.
The slide gives the recipe in three lines of MATLAB. The sample rate is 1,000 Hz. The time runs from 0 to 1 s. The signal is a 32 Hz cosine that is switched on only between 0.1 s and 0.3 s, plus a 64 Hz sine that is switched on after 0.7 s. Then one call, cwt(x, 1000), draws the answer. It is the same signal as in the hero.
Here is the data flow. The input x is a list of 1,000 numbers, shape (1000,). Pick a list of scales, say 80 of them, shape (80,). For each scale, slide the copy along the whole signal and write down the match at every sample. That gives one row of 1,000 numbers. Stack the 80 rows and the output is a table of shape (80, 1000). The numbers are complex for a Morlet wavelet, so we plot their size, |W|.
That picture is the scalogram (the slide calls it the magnitude scalogram). Time runs across. Pitch, which is the inverse of scale, runs up. Brightness shows |W|, the size of the match. It is the wavelet cousin of the spectrogram you met with the STFT.
pythonimport numpy as np def scalogram(x, fs, pitches): """x: (N,) signal. pitches: (S,) in Hz. Returns |W|: (S, N).""" out = np.zeros((len(pitches), len(x))) for i, f in enumerate(pitches): s = 1.0 / f # scale: seconds per cycle of the mother (f0 = 1) t = np.arange(-4*0.8*s, 4*0.8*s, 1/fs) # the copy, 4 widths each side psi = np.exp(2j*np.pi*t/s) * np.exp(-(t/s)**2 / 1.28) / np.sqrt(s) # correlate with the signal (the conjugate of psi), same length out out[i] = np.abs(np.convolve(x, np.conj(psi[::-1]), mode="same")) / fs return out
Slide 7 shows the result: two bright blobs on a dark field. The left blob sits at a lower pitch, at the times 0.1 to 0.3 s. The right blob sits at twice that pitch, from 0.7 s on. Reading the picture is easy. Find a bright spot. Its horizontal position says when. Its height says which pitch.
The pitch axis is usually drawn on a log scale, as it is in the slide and in our device. Doubling the pitch always moves you up by the same distance. This matches how we hear, one octave per doubling. It also matches how the wavelet works: its pitch resolution is a fixed fraction of the pitch itself.
Look at the blobs’ shapes. The 64 Hz blob has sharper left and right edges than the 32 Hz blob. The high copy is half as wide in time, so it locates an edge more exactly. The low copy is twice as wide, so it blurs the edge but measures the pitch more narrowly. That is the tile shape of Chapter 0, now visible in real data. Try it below.
The map shows |W| for the lecture’s signal. Drag the pitch to move the teal row, and read that row as a curve below. Then switch on the true bursts and the cone of influence.
Computed here with a Morlet wavelet of width 0.8 cycles, at 80 pitches from 4 to 200 Hz. The slide used MATLAB’s default wavelet, so the blob shapes differ slightly. Our rule for the cone: within two wavelet widths (1.6 divided by the pitch, in seconds) of either end of the recording.
Drag the pitch to 32 Hz and the row lights up between about 0.1 and 0.3 s, then goes dark. Move to 64 Hz and it lights up after 0.7 s. At 45 Hz, between the two, both blobs fade to a faint glow. The wavelet at that pitch matches neither signal.
Why bother, when the STFT already draws a map? Compare the numbers from the hero. A 10 ms window gives a click 24 ms wide but smears the 32 Hz burst over 38 Hz of pitch. An 80 ms window gives the burst a 7 Hz blur but smears the click over 188 ms. The wavelet gives the click 11 ms and the burst 16 Hz at the same time. It does not beat the trade at one pitch. It picks the best side of the trade for each pitch, and a signal with both a low tone and a high click gets the best of both.
The slide draws a dashed curve shaped like a parabola, with grey outside it. This is the cone of influence. Here is the symptom: near the start and the end of the recording the picture fades, and bright features there look weaker than they are.
The cause is simple. A copy at time τ is a wave about 1.6/f seconds wide. Near an edge, part of the copy hangs off the end of the data, where there is no signal. The sum has fewer terms, so the match drops. The measurement: for the 8 Hz row, the cone reaches 0.2 s in from each end. For the 64 Hz row, only 25 ms. Lower pitches lose more.
The fix is honesty. Mark the region, as the slide does, and do not read features inside it as facts. You may also pad the signal with zeros or with a mirror copy, but padding invents data, so the cone still applies.
Chapter 3
Build the simplest wavelet world from one box, and see how a finer grid of boxes holds a finer picture
Think of a digital photo shrunk to 8 pixels across. Each pixel is one flat grey. Double the width to 16 pixels and each old pixel splits into two, so the picture can hold finer detail. Every coarse picture is also a legal fine picture: just give the two halves the same grey.
The lecture builds exactly this with functions instead of pixels, and it uses the simplest brick there is. Slide 8 defines it.
Shift the box by whole steps and you get φ(x − k): one box over [k, k+1]. Now mix them. Give each box its own height ak and add them up: g(x) = Σ ak φ(x − k). Slide 9 draws the result, a staircase that is flat on every interval between whole numbers.
Slide 10 gives the set of all such staircases a name, V0. It holds every function with finite energy that is constant on each integer interval. “Square integrable”, the phrase on the slide, simply means ∫g(x)²dx is finite: the energy is finite. V0 is a space (a vector space of functions): add two staircases or scale one, and you still have a staircase. The heights ak are its coordinates.
Replace x by 2x and the box becomes half as wide: φ(2x − k) is a box over [k/2, (k+1)/2]. Slide 11 calls the staircases made of those boxes V1: constant on half-integer intervals. Slide 12 generalises.
So V0 has steps 1 wide, V1 has steps ½ wide, V2 has steps ¼ wide. A big j is a fine grid. And V2 contains V1: one box of width ½ is the sum of two boxes of width ¼ with equal heights, which is the identity φ(x) = φ(2x) + φ(2x − 1). Stacked from coarse to fine, the spaces nest, V0 inside V1 inside V2. The lecture draws this as ovals inside ovals (slide 13), which is where Chapter 4 starts.
Given a curve f(x), which heights ak make the staircase closest to it? Take one interval, with width h. We want the single height a that minimises the squared error ∫(f − a)²dx over that interval. Differentiate with respect to a and set it to zero: −2∫(f − a)dx = 0, so a = (1/h)∫f dx. The best height is the average of f over the interval.
A worked case with f(x) = x² on [0, 1). At j = 1 the averages are ∫01/2x²dx / ½ = (1/24)/(1/2) = 1/12 ≈ 0.083 and (7/24)/(1/2) = 7/12 ≈ 0.583. At j = 2 four averages appear: 1/48 ≈ 0.021, 7/48 ≈ 0.146, 19/48 ≈ 0.396 and 37/48 ≈ 0.771. Notice that the first j = 1 height, 1/12, is the mean of the first two j = 2 heights, (1/48 + 7/48)/2 = 1/12. Coarser heights are always averages of finer ones. That fact is the seed of the whole discrete transform in Chapter 5.
Count what you store. A staircase in Vj on [0, 1) has 2j heights, so V0 is 1 number, V3 is 8 numbers and V6 is 64 numbers. Each level doubles the bill and halves the box. That is the price of resolution. The question for the rest of the lesson is how to spend that bill only where the signal needs it.
Choose a curve, then raise j. The purple staircase is the best copy in Vj: each step is the average of the curve over its interval. Watch how the error falls for each curve.
Toy functions on [0, 1). Error energy is ∫(f − staircase)²dx, computed on a grid of 4,096 points and shown as a share of the function’s own energy ∫f²dx. The step height of each box is the interval average, as derived above.
Look at the failure mode. The spike is 0.02 wide. At j = 3 each box is 0.125 wide, so the box under the spike averages it with silence and shows a bump only 16% as tall. Symptom: the feature is flattened. Measurement: the error stays near 100% of the energy until the boxes are about as narrow as the spike. Fix: go to a finer level. A coarse level cannot see a narrow thing.
Compare the smooth curves with the jump. For the parabola, every extra level cuts the error by about four. For the jump at 0.3, which is not on a dyadic boundary, one box always straddles it, and each level only halves the error. Smooth things converge fast and edges converge slowly. That contrast returns in Chapter 8, where it decides what compresses.
Chapter 4
Split each fine picture into a coarse one plus exactly what the coarse one is missing
Look at a sharp photo and a blurred copy of it. The sharp one holds everything the blurred one holds, plus something extra: the fine edges. If you could write down only that extra part, you could rebuild the sharp photo from the blur. That extra part has a name in the lecture: the detail.
Chapter 3 gave us nested spaces V0 inside V1 inside V2, each a finer staircase world. Slide 13 draws them as ovals inside ovals. The ring between two ovals is the detail. Slide 13 names the ring W0 and writes V0 ⊕ W0 = V1. Slide 14 repeats it at every level.
Orthogonal is the key word. Two functions are orthogonal when their product integrates to zero: the positive and negative parts cancel. Then their energies simply add, like the two short sides of a right triangle: ‖fine‖² = ‖coarse‖² + ‖detail‖². Nothing is counted twice.
Stack the levels and the pieces chain together: Vj = V0 ⊕ W0 ⊕ … ⊕ Wj−1. Slide 15 states the full theorem: every square-integrable function can be written uniquely as a sum of pieces wj, one from each detail space Wj. A signal is a pile of details at every resolution.
Pick a curve and a level j. The fine staircase (thin outline, Vj+1) equals the coarse one (purple, Vj) plus the pink detail below. Check the energies on the line underneath.
The same toy functions as Chapter 3. Each staircase is the interval average. Energies are ∫g²dx on a grid of 4,096 points. The detail is the fine staircase minus the coarse one.
The read-out is a Pythagoras check. The fine staircase’s energy equals the coarse energy plus the detail energy, to the digits shown. Smooth curves have tiny detail at fine levels. A jump or a spike keeps its detail energy.
Now tie this to numbers you can hold. Eight samples are the heights of a staircase in V3, with boxes 1/8 wide. Averaging pairs gives the heights of the best staircase in V2, four boxes of 1/4. Averaging again gives V1, and once more V0, the single overall mean. Each time we step down, we throw away a layer of detail, and that layer is a Haar wavelet series. The next two chapters compute exactly this on the lecture’s numbers.
What do the detail functions look like? Take two neighbouring fine boxes with heights a and b. Add and subtract half of each: aφ(2x) + bφ(2x−1) = ½(a+b)[φ(2x)+φ(2x−1)] + ½(a−b)[φ(2x)−φ(2x−1)]. The first bracket is one wide box, φ(x). The second bracket is a new shape: up for the first half, down for the second.
So the average goes to the coarse space and the half-difference goes to the detail space. Remember this split: it is the entire discrete transform of Chapter 5. A worked case: f is 6 on [0, ½) and 2 on [½, 1). Then f = 4φ(x) + 2ψ(x): on the left 4 + 2 = 6, on the right 4 − 2 = 2. The energy checks: ∫f² = ½·36 + ½·4 = 20 and 4² + 2² = 20.
Slide 16 then says that the family 2j/2ψ(2jx − k), over all positions k, forms an orthonormal basis for Wj. Orthonormal means two things: different members are orthogonal, and every member has energy 1. The factor 2j/2 does the second job. Squeezing ψ to ψ(2jx) makes its squared integral 2−j, so we multiply the height by 2j/2 to bring it back to 1. It is the same 1/√s as Chapter 1, with s = 2−j. Put the pieces together and slide 18 writes a signal as f = ΣjΣk ajkψjk(x). The lecture calls this multiresolution analysis: a signal as coarse shape plus details at every scale.
Pick one function in each row. The purple area is their product. Its signed total is the inner product. Try a function against itself, against its neighbour, and against a wavelet that sits inside it.
The eight functions are φ (the box) and ψj,k = 2j/2ψ(2jx − k) for j = 0, 1, 2. Integrals are summed exactly on a grid of 1,024 points, enough to land on every jump.
Every pair of different functions gives 0, and every function with itself gives 1. Two cases are worth a close look. Take ψ1,0 and ψ2,0. The narrow one sits wholly inside the first half of the wide one, where the wide one is constant +1, so the product is just the narrow wavelet, whose positive and negative parts cancel. Neighbours do not overlap, so the product is zero everywhere.
Chapter 5
Take one step of the discrete Haar transform by hand, and see why it loses nothing
You must send eight numbers over a thin line. The line has room for only four. What do you send? The lecture’s answer, on slide 19, is the natural one: send a smaller version of the signal. Slides 20 and 21 make it exact. Average each pair of neighbours.
The slide’s example is x = [6, 12, 15, 15, 14, 12, 120, 116]. The pairs are (6, 12), (15, 15), (14, 12), (120, 116). Their averages are 9, 15, 13 and 118. So x becomes s = [9, 15, 13, 118]. It still has the shape of the signal, with a big jump at the end. But it cannot be undone: from 9 you cannot tell whether the pair was (6, 12) or (9, 9).
Suppose the line allows N/2 more numbers. Slide 22 sends the half-difference of each pair, and the pair is then fully recoverable.
Check it on the example. The differences are (6 − 12)/2 = −3, (15 − 15)/2 = 0, (14 − 12)/2 = 1 and (120 − 116)/2 = 2. The pair (6, 12): 9 + (−3) = 6 and 9 − (−3) = 12. The pair (120, 116): 118 + 2 = 120 and 118 − 2 = 116. Nothing is lost. The lecture writes the result as [s | d] = [9, 15, 13, 118 | −3, 0, 1, 2], a new list of the same length.
A note on signs. The formula printed on slide 22 is first minus second, which gives −3, 0, 1, 2. The numbers printed beside it, 3, 0, −1, −2, have the opposite sign, as does the matrix on slide 24 (second minus first). The table in Chapter 6 uses first minus second. Either choice works if you rebuild with the matching signs. We use first minus second, which matches the Haar wavelet of Chapter 4.
Now connect this to Chapter 4. Two fine boxes with heights a and b equal a coarse box of height (a + b)/2 plus a Haar wavelet with weight (a − b)/2. So the averages s are the coefficients in Vj, and the differences d are the coefficients in Wj. The pairwise trick is the split Vj+1 = Vj ⊕ Wj, done with arithmetic.
Pick a signal of eight numbers. The purple bars are the four averages, the pink bars the four differences. Then switch off the differences and watch the rebuild lose its detail.
The lecture example is slide 21’s. The other three are toy signals. Differences are first minus second, half the gap. Error energy is the sum of squared rebuild errors, shown as a share of the sum of squares of x.
Look at which signals have small differences. The ramp has the same difference, −5, for every pair, because neighbours are close. The jump has a nonzero difference in one place only, where the pair straddles the jump. The alternating signal has huge differences everywhere, because every neighbour pair disagrees. Differences are small where the signal is smooth. That single fact powers every use of the transform.
This split also gives a way to send a signal in stages. Send the averages first. The receiver already has a half-length preview of the whole signal. Then send the differences, and the receiver rebuilds the full signal exactly. A viewer who stops after the first stage still sees a fair picture. This is called progressive transmission, and it is what slide 19 means by a length N/2 approximation “for transmission”.
Slide 24 writes the step as a matrix times a vector. Here is the four-number version, with x = [x1, x2, x3, x4]:
The top half of the matrix takes averages. The bottom half takes half-differences. Every row looks at only two neighbours, so the matrix is mostly zeros, and the step costs about one addition and one subtraction per pair.
What if you skip the differences? The rebuild gives every pair its average: [9, 9, 15, 15, 13, 13, 118, 118]. The errors are ±3, 0, ±1 and ±2, exactly the differences. The error energy is 2 × (9 + 0 + 1 + 4) = 28, against 28,826 for the signal itself: 0.097%. Symptom: the picture looks almost right. Measurement: all the lost energy sits in d. Fix: keep the differences that matter. Chapter 8 returns to this trade.
Chapter 6
Repeat the averaging on the averages, and watch eight numbers sort themselves by scale
After one step you hold four averages and four differences. The four averages are a smaller picture of the signal. And a small picture is itself a signal. So do the same thing to it: average its pairs, take its half-differences, and keep going. The lecture says it in one line on slide 31: repeat the same process on the averages. The two bullets on slide 40 add the rule: repeat on the means, keep the differences at each step.
Slides 25 to 34 do it as a table that fills in row by row. We follow it exactly. The input is x = [56, 40, 8, 24, 48, 48, 40, 16].
The pairs are (56, 40), (8, 24), (48, 48), (40, 16). Averages: 48, 16, 48, 28. Differences, first minus second then halved: (56 − 40)/2 = 8, (8 − 24)/2 = −8, 0, and (40 − 16)/2 = 12. The row reads [48, 16, 48, 28 | 8, −8, 0, 12]. Slide 26 shows the first of these as a little arrow diagram: (56 + 40)/2 = 48 goes in the left half, 56 − 48 = 8 goes in the right half. The differences are now final. We never touch them again.
Only the four averages are processed. The pairs are (48, 16) and (48, 28). Averages: 32 and 38. Differences: (48 − 16)/2 = 16 and (48 − 28)/2 = 10. The row reads [32, 38 | 16, 10 | 8, −8, 0, 12]. The right half is unchanged.
Now there are two averages: 32 and 38. Their average is 35. Their half-difference is (32 − 38)/2 = −3. The final row is [35 | −3 | 16, 10 | 8, −8, 0, 12]. Slide 34 ends there. We cannot go further, because one number has no neighbour. Eight numbers went in, eight came out.
Pick a signal, then press Next level. Each row halves the purple part and leaves the pink part behind. Press Next level on the last row to start again.
The lecture table is slides 25 to 34. The other signals are toy data, the noisy ramp seeded so it looks the same on every visit. Averages are purple, differences pink, as everywhere in this lesson.
Try the step signal. Its details all vanish except one, the coefficient at the scale of the jump. A signal with structure at one scale shows up at one place in the table. That is the transform doing its job: sorting information by scale.
Read the final row from right to left. The last four numbers, 8, −8, 0, 12, are the finest details: how each neighbouring pair differs. They live at the smallest scale, so they correspond to the highest pitches. The middle two, 16 and 10, compare blocks of two. The single −3 compares the two halves of the whole signal. And the 35 is the average of all eight: (56 + 40 + 8 + 24 + 48 + 48 + 40 + 16)/8 = 280/8 = 35, a number with no detail left at all.
This is the tile picture from Chapter 0, now with numbers. Four coefficients each own a narrow slice of time and a tall band of pitch. Two own a wider slice and a lower band. One owns half the signal. One owns the whole signal at pitch zero. Eight tiles for eight numbers, shaped by scale.
Run the table in reverse. Start from [35 | −3 | 16, 10 | 8, −8, 0, 12]. Rebuild the two averages: 35 + (−3) = 32 and 35 − (−3) = 38. Now there are two averages and two differences, so rebuild four: 32 + 16 = 48 and 32 − 16 = 16, then 38 + 10 = 48 and 38 − 10 = 28. Finally rebuild eight: 48 + 8 = 56, 48 − 8 = 40, and so on back to the original. Each level undoes the one before it exactly.
For a signal of length N the first level handles N/2 pairs, the second N/4, then N/8, down to one. The total number of pairs is N/2 + N/4 + … + 1 = N − 1. Each pair costs a couple of additions. So the whole transform takes a number of operations proportional to N. A fast Fourier transform needs about N log N. The wavelet transform is a bit cheaper still.
One more fact, about energy. In one step, a pair (a, b) with average s and half-difference d has a² + b² = 2s² + 2d². Check level 1: the signal’s sum of squares is 11,840, and 2 × 5,648 (the averages) + 2 × 272 (the differences) is also 11,840. The averages hold 95.4% of the energy after the first step. Level 3 confirms the chain: 2,468 = 2 × 35² + 2 × 3². The pieces add up exactly, as Chapter 4’s Pythagoras promised, once each level is weighted by the 2.
If you scale each step by 1/√2 instead of 1/2 (the version in the slide’s code in Chapter 7), the factor 2 disappears and the energy is preserved with no weights at all. That is the orthonormal Haar transform, and it is what compression in Chapter 8 uses.
Chapter 7
See the average and the difference as a low-pass and a high-pass filter, and chain them into a filter bank
You know the Haar step as arithmetic on pairs. A signal-processing engineer sees it differently. Averaging two neighbours smooths a signal: it keeps the slow part and kills the fast wiggle. Differencing two neighbours does the opposite: it keeps the fast part and kills the slow drift. These two moves are a low-pass filter and a high-pass filter, the oldest tools in the field. The lecture’s slides 35 to 40 show the step in three more costumes: code, a filter tree and a matrix.
A filter replaces each sample by a weighted sum of itself and its neighbours. The weights are the filter’s taps. Slide 35 gives two filters, each with two taps: h = [1, 1]/√2 and g = [1, −1]/√2. Filter with h and each output is (xn + xn−1)/√2, a scaled average. Filter with g and each output is (xn − xn−1)/√2, a scaled difference.
Then comes downsampling: keep every second output and throw the rest away. The kept outputs are exactly the pair averages and pair differences of Chapter 5. We needed only half of them, because each pair was counted twice. The 1/√2 scaling is the orthonormal version from Chapter 6: it keeps the energy. Because g subtracts the earlier sample from the later one, its sign is second minus first. That is why the matrix on slide 24 has second-minus-first rows.
pythonimport numpy as np h = np.array([1, 1]) / np.sqrt(2) # low-pass: a scaled average g = np.array([1, -1]) / np.sqrt(2) # high-pass: a scaled difference (second minus first) def haar_step(x): """x: (N,) with N even. Returns approximation (N/2,) and detail (N/2,).""" a = np.convolve(x, h)[1::2] # filter, then keep every second output d = np.convolve(x, g)[1::2] return a, d def dwt(x, levels): """Layout: [a_L | d_L | ... | d_1], the same length as x.""" parts = [] for _ in range(levels): x, d = haar_step(x) parts.insert(0, d) # finest details go last return np.concatenate([x] + parts) x = np.array([56, 40, 8, 24, 48, 48, 40, 16], dtype=float) c = dwt(x, 3) print(np.round(c, 2)) # [98.99 8.49 -32. -20. -11.31 11.31 0. -16.97] print(np.sum(x**2), np.sum(c**2)) # 11840.0 11840.0: energy is kept
The numbers are the lecture’s table times powers of √2 (the mean 35 becomes 35 × 2√2 = 98.99), and the differences carry the filter’s sign, second minus first. The last line is the check. The sum of squares before and after is the same, 11,840, so no energy is lost or invented. Slides 36 and 37 run the same code on a second signal and plot its approximation and detail, level by level. Chapter 8 does the same kind of thing with a device.
Feed a pure wave of frequency ω (radians per sample) into the filter h. Each output is (1 + e−iω)/√2 times the input wave. The size of that factor is the filter’s gain.
Square and add: |H|² + |G|² = 2cos²(ω/2) + 2sin²(ω/2) = 2. The two filters share the frequency range between them with no gap and no double count, once the factor 2 from downsampling is divided out. Averaging takes the lower half of the band (frequencies from 0 up to half the top). Differencing takes the upper half.
Slide 38 draws the filter bank as a tree. The signal enters and splits into a low-pass branch (LP) and a high-pass branch (HP), each downsampled by 2. The HP branch is finished: it outputs the finest details, covering the top half of the frequency range, a band of width 4B. The LP branch splits again: its HP output covers the next quarter, width 2B, and its LP splits once more into two bands of width B. The spectrum sketches beside it show the bands as boxes: B, B, 2B, 4B. Each band is an octave, a band whose top frequency is twice its bottom.
Try it with a real tone. Slide it from slow to fast and see which output holds its energy.
The curves are the power gain of the four outputs. The bars are the actual share of a 64-sample tone’s energy that each output received. Drag the tone’s frequency, then switch on the ideal brick-wall bands of slide 38.
Frequency is in cycles per sample, from 0 to 0.5. The transform is the orthonormal Haar transform with 3 levels, on 64 samples of cos(2π f n + 0.7). The curves use |Fj|²/2j, which sum to 1 at every frequency. Bars come from the real transform, so they differ slightly from the curves.
Park the tone at 0.18 cycles per sample and most of its energy lands in d2, the octave from 0.125 to 0.25. Slide to 0.06 and it moves to d3 or a3. Now switch on the ideal bands. The real Haar curves are not boxes. They are broad humps that overlap. A tone near a band edge splits its energy between two outputs. Haar is the simplest filter bank, and it is also the leakiest. Better wavelets use longer filters with sharper edges.
Slide 39 writes the whole three-level transform as one 8 × 8 matrix H, in unscaled form. The first four rows are the pair differences. Rows 5 and 6 compare blocks of two. Row 7 compares the two halves. Row 8 sums everything.
Apply H to the lecture’s x and you get [16, −16, 0, 24, 64, 40, −24, 280]. Divide each by its scale factor (2, 2, 2, 2, 4, 4, 8, 8) and you recover the table: 8, −8, 0, 12, 16, 10, −3, 35. The matrix has a useful property: any two different rows multiply to zero, so they are orthogonal. Each row has squared length 2, 2, 2, 2, 4, 4, 8, 8. To go back, give each row its weight and add: x = HT D−1 (Hx), with D the diagonal of those squared lengths. No matrix inversion is needed, only a transpose.
Chapter 8
Keep only the biggest coefficients, and see which signals each basis can squeeze
Back to the thin line of Chapter 5. You may now send only a handful of numbers, not all of them. Which handful? If the numbers are raw samples, any choice drops something real. But if you first move to a basis where most numbers are tiny, you can send the few large ones and drop the rest.
A signal whose energy sits in a few coefficients is sparse in that basis. Slides 36 and 37 show it on a second test signal: a smooth hump with a small bump beside it, then its approximation and its detail at two levels. Over the smooth stretches the detail plots sit near zero. The detail only wakes up near features. That is the picture of sparsity.
Chapter 6 showed that the orthonormal Haar transform keeps energy: the sum of squares before and after is the same. The same holds for any orthonormal basis. Now drop some coefficients and rebuild. The error is the signal minus the rebuild, and that error is itself written in the same basis, with exactly the dropped coefficients and zeros elsewhere. So its energy is the sum of the squares of the dropped coefficients.
To keep m coefficients with the least error, drop the m smallest squares. In other words, keep the m biggest. Here is the worked case from Chapter 6. The orthonormal coefficients of the lecture’s eight numbers are 98.99, 8.49, −32, −20, −11.31, 11.31, 0 and −16.97. Their squares are 9,799, 72, 1,024, 400, 128, 128, 0 and 288, which sum to 11,839 (11,840 with rounding). Keep the biggest four (98.99, −32, −20, −16.97): they hold 11,511, so the dropped four hold 328, or 2.8%. Keep only the biggest one: you rebuild eight copies of the mean, 35, and lose 17.2%.
Choose a signal of 64 numbers and a budget m. The top plot shows the signal (blue) and what each basis rebuilds from its biggest m coefficients. The bottom plot shows how much energy each basis has kept as m grows.
Toy signals of 64 samples (not the lecture’s), each with its average removed so the comparison is about shape. Haar is the orthonormal transform with 6 levels. Fourier is the real orthonormal basis: one constant, a cosine and a sine for each of 31 frequencies, and the alternating wave, 64 numbers in all. Both are ranked by squared size and the top m are kept.
Start with the steps and slide m up from 4. By m = 12 Haar holds 100% of the energy, because a few blocks describe the signal exactly. Fourier is still near 96%, with ripples on both sides of every jump. Now switch to the pure tone. The result flips: Fourier needs just two numbers, a cosine and a sine of the right frequency, while Haar still holds only 75% at m = 12 because its blocks are a poor shape for a smooth wave. The click is the starkest case: Haar describes one spike exactly with about seven numbers, one per level, while Fourier at m = 7 holds only 22%, because it spreads the same spike across all 64 frequencies equally. The two bumps are smooth, so Fourier stays ahead at small budgets: 98.7% against 94.8% at m = 8.
In practice, how do you choose m? Plot the energy kept against m, as the lower plot above does, and look for the knee where the curve flattens. Or set an error budget first, for example “lose at most 1% of the energy”, and keep the smallest m that meets it. The curve also tells you which basis to prefer. The one whose curve rises faster for your kind of signal needs fewer numbers.
Symptom: with too few Fourier coefficients, a sharp edge is surrounded by ripples that overshoot. Measurement: on the steps signal at m = 8 the Fourier rebuild swings visibly past the plateau next to a jump. This is the Gibbs effect: a sum of waves that run forever cannot make a clean corner. Fix: use a basis whose pieces are local, like Haar.
The mirror failure belongs to Haar. Its blocks cannot follow a smooth curve without many small steps. This is the slide 3 rule: match the basis to the signal’s shape. Waves like Fourier, jumps like Haar, smooth bumps like a smoother wavelet. Real signals often hold both a smooth part and an edge, which is why wavelets with a range of smoothness are popular for images, and why Chapter 9 uses them.
After you keep the biggest few, you still have to store them. That is a job for quantization, the subject of Lecture 3 and Lecture 4: round each kept coefficient to a few bits. Coefficients of very different sizes can then get different numbers of bits. A learned alternative to a fixed basis is in dictionary learning.
Chapter 9
Apply the Haar step along rows and then along columns, and read the four pictures that come out
A grey photo is a grid of numbers, one per pixel, with 0 for black and 255 for white. A grid has two directions. A signal had only one. Yet the Haar step needs no new idea. Do it along every row. Then do it along every column. The lecture’s last three slides show this on a comic-strip panel, and the result is a picture you can read at a glance.
Slide 41 shows the first half. Take each column and run the Haar step down it: pair rows 1 and 2, rows 3 and 4, and so on. The top half of the result holds the averages of vertical neighbours. It looks like the original squeezed to half the height. The bottom half holds the half-differences of vertical neighbours. It is nearly black, with thin bright lines wherever the brightness changes from one row to the next, which means along horizontal edges.
Now do the same along the rows. Slide 42 shows both directions done. The picture splits into four quadrants. Here is what each one holds for a small 2 × 2 block of pixels with values a, b on the top row and c, d on the bottom.
Two blocks make it concrete. A smooth gradient block with a = 8, b = 6, c = 4, d = 2 gives LL = 5, HL = (8 − 6 + 4 − 2)/4 = 1, LH = (8 + 6 − 4 − 2)/4 = 2 and HH = (8 − 6 − 4 + 2)/4 = 0. Small details, and no diagonal at all. A checkerboard block with a = d = 9 and b = c = 1 gives LL = 5, HL = 0, LH = 0 and HH = (9 − 1 − 1 + 9)/4 = 4. Only the diagonal quadrant lights up. The two blocks have the same average and completely different texture, and the transform tells them apart.
The data flow keeps the size fixed. A 64 × 64 image has 4,096 numbers. After one level it is still 64 × 64, cut into four 32 × 32 quadrants. Slide 43 then repeats on the top-left quadrant only: the picture of averages is itself a picture, so split it again into four 16 × 16 pieces. Each extra level touches a quarter as many numbers as the one before, so the whole transform costs a constant times the number of pixels.
Left: the transform, with the averages as a small picture in the corner and the details in pink (brighter means bigger). Right: the image rebuilt from the biggest coefficients you keep. Raise the levels, then lower the share kept.
The image is our own toy: a 64 by 64 grey picture with a gradient, a disc, a box, a thin diagonal line and a little noise. The transform is the orthonormal 2D Haar transform. PSNR is 10 log10(255²/MSE), in decibels; higher is closer to the original.
Switch to 1 level and you see the layout of slide 42: a small picture in the corner and three mostly dark quadrants with lines where the disc and box have edges. Raise the levels and the corner splits again, as on slide 43. Now set 3 levels and keep 8%. The rebuild reaches a PSNR of 45.6 dB from 328 of the 4,096 numbers. Switch to 1 level at the same 8% and it drops to 11.4 dB. Why? One level leaves a 32 by 32 corner of 1,024 numbers, 25% of the total, so 8% cannot even hold the small picture. More levels pack the energy into a smaller corner, and the details cluster on edges. The read-out also counts the detail coefficients that are nearly zero: two thirds or more in this toy image, and a larger share in a clean photo.
At 3 levels, push the share down to 2% and then 1%. The PSNR falls from 22.2 dB to 14.7 dB. Symptom: the picture breaks into a mosaic of flat squares. Measurement: the PSNR falls steeply, and each square is 2 to the power of the level wide, because the only pieces left are Haar boxes of that size. Fix: keep more of the finest details near edges, or move to a smoother wavelet. The principle is the same as Chapter 8: the basis must fit the signal.
The next lecture, Lecture 11, takes wavelets into practice. A grid of neighbouring pixels also leads to the distance and classification ideas of Lecture 9, where a compact set of coefficients makes a good feature vector.
Chapter 10
Keep the numbers, the terms, the checklist and the code, and find where to go next
One window cannot serve every pitch, because a window’s time width and frequency width trade off at a fixed product. Wavelets answer by stretching one short wave: long for low pitch, short for high. The continuous transform W(s, τ) scores the match at every scale and place and draws a scalogram. The discrete Haar version uses boxes at every resolution. A signal splits into a coarse average plus details, and each step is just a pair average and a pair difference. Repeat on the averages and N numbers become one mean and N−1 details, sorted by scale. Most details are tiny for smooth signals, so keeping the biggest few compresses.
| Quantity | Value | Where |
|---|---|---|
| Tile area floor | Δt · Δf ≥ 1/(4π) ≈ 0.08 | Chapter 0 |
| Wavelet family | ψs,τ(t) = (1/√s) ψ((t − τ)/s) | Slide 2, Chapter 1 |
| Pitch of a copy | f0/s (large scale, low pitch) | Chapter 1 |
| Energy factor | 1/√s keeps ∫|ψs,τ|² equal for every s | Chapter 1 |
| Lecture signal | 32 Hz burst 0.1 to 0.3 s, 64 Hz from 0.7 s, 1,000 Hz sampling | Slide 6, Chapter 2 |
| Cone of influence | about 1.6/f seconds from each end (our rule) | Chapter 2 |
| Best staircase height | the interval average | Chapter 3 |
| Haar basis | 2j/2 ψ(2jx − k), energy 1 each | Slide 16, Chapter 4 |
| One step | s = (a + b)/2, d = (a − b)/2, so a = s + d, b = s − d | Slides 20 to 22, Chapter 5 |
| Lecture example | [6, 12, 15, 15, 14, 12, 120, 116] → s = [9, 15, 13, 118], d = [−3, 0, 1, 2] | Chapter 5 |
| Lecture table | [56, 40, 8, 24, 48, 48, 40, 16] → [35 | −3 | 16, 10 | 8, −8, 0, 12] | Slides 25 to 34, Chapter 6 |
| Energy per step | a² + b² = 2s² + 2d² (11,840 = 2 · 5,648 + 2 · 272) | Chapter 6 |
| Cost | N − 1 pair steps in all, proportional to N | Chapter 6 |
| Filter gains | |H| = √2|cos(ω/2)|, |G| = √2|sin(ω/2)| | Chapter 7 |
| Haar matrix row norms | squared lengths 2, 2, 2, 2, 4, 4, 8, 8 | Slide 39, Chapter 7 |
| Error after dropping | the sum of the dropped squares (orthonormal basis) | Chapter 8 |
| 2D Haar | rows, then columns; quadrants LL, HL, LH, HH; repeat on LL | Slides 41 to 43, Chapter 9 |
| Term | Plain meaning |
|---|---|
| Mother wavelet | One short wave with zero area and finite energy. Every other wavelet is a stretched, slid copy. |
| Scale and translation | How much we stretch the copy (s) and where we put it (τ). |
| Scalogram | The picture of |W(s, τ)|: time across, pitch up, brightness for match. |
| Scaling function φ | The box that measures averages. It builds the spaces Vj. |
| Detail space Wj | What Vj+1 holds that Vj does not. Orthogonal to Vj. |
| Multiresolution analysis | A signal as a coarse part plus details at every scale. |
| Filter bank | A tree of low-pass and high-pass filters with downsampling: octave bands. |
| Sparse | Most of the energy sits in a few coefficients. |
pythonimport numpy as np def haar_step(x): """x: (N,) with N even. Returns averages (N/2,) and differences (N/2,), slide convention.""" a, b = x[0::2], x[1::2] return (a + b) / 2, (a - b) / 2 # first minus second, halved def haar_unstep(s, d): out = np.empty(2 * len(s)) out[0::2], out[1::2] = s + d, s - d return out def haar(x, levels): """Layout [a_L | d_L | ... | d_1], same length as x.""" parts = [] for _ in range(levels): x, d = haar_step(x) parts.insert(0, d) return np.concatenate([x] + parts) def ihaar(c, levels): n = len(c) >> levels s = c[:n] for _ in range(levels): s = haar_unstep(s, c[n:2 * n]); n *= 2 return s def haar2d(img, levels): """Rows, then columns, then repeat on the top-left corner.""" c = img.astype(float).copy() for l in range(levels): n = c.shape[0] >> l for axis in (1, 0): block = c[:n, :n] moved = np.moveaxis(block, axis, 0) moved_s, moved_d = (moved[0::2] + moved[1::2]) / 2, (moved[0::2] - moved[1::2]) / 2 block[...] = np.moveaxis(np.concatenate([moved_s, moved_d]), 0, axis) return c x = np.array([56, 40, 8, 24, 48, 48, 40, 16], float) c = haar(x, 3) print(c) # [35. -3. 16. 10. 8. -8. 0. 12.], the lecture table print(np.allclose(ihaar(c, 3), x)) im = np.arange(64.).reshape(8, 8) print(haar2d(im, 1)[0, 0], im[:2, :2].mean())
Slides 1 to 7 are Chapters 0 to 2. Slides 8 to 12 are Chapter 3. Slides 13 to 18 are Chapter 4. Slides 19 to 24 are Chapter 5. Slides 25 to 34 are Chapter 6. Slides 35 to 40 are Chapter 7 (the matrix is slide 39), with slides 36 and 37 also feeding Chapter 8. Slides 41 to 43 are Chapter 9. The slide file’s title page numbers this as “Lecture 17” in the 2020 offering and also lists the short-time Fourier transform. The 43 slides themselves cover wavelets only, so our STFT lesson carries that half.
Credit. This lesson re-teaches the wavelets lecture of EE269, Signal Processing and Quantization for Machine Learning, taught at Stanford by Mert Pilanci. The slides are the course’s. All figures, devices, toy signals and toy images here are our own, and the numbers on the lecture’s slides are cited as such. Where the slide’s sign conventions disagree with each other (Chapter 5), we say so.
Now press Present or Teach and explain from memory why one window fails, how a wavelet copy is made, and how eight numbers become 35, −3, 16, 10, 8, −8, 0, 12 and back. Then go back to the signal at the top, switch between the three views, and say why the tiles change shape.