Wavelets in Practice

A Fourier transform tells you which frequencies a signal holds, but not when. A wavelet lens finds a 20 ms burst and a steady tone in one picture.

Learn how to pick a wavelet, why wavelets and short windows see differently, and how that powers activity recognition, heartbeat analysis, chirp tracking and noise removal.

Press each lens in turn, then drag the burst through time. The Fourier lens never notices it move. Then we build every lens from zero and put it to work on phone sensors, heartbeats, chirps and noisy signals.

You need the idea of a frequency (how many times a wave repeats each second) and a little algebra. We build the rest from zero.

Based on Lecture 11, Wavelets Part II, of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci (October 5, 2021). Find the slides on the course slides page. Every idea is re-taught here in our own words and devices; it follows Lecture 10, Wavelets.

One signal, four lenses

0.55 s

Toy signal, 512 samples at 512 Hz: a 40 Hz sine of amplitude 1 plus a 150 Hz burst (Gaussian envelope, 10 ms spread) of amplitude 1.2. Map colour is amplitude. The Fourier map is one spectrum repeated at every time. The window lenses use a Hann window of 256 or 32 samples; the wavelet lens uses a Morlet wavelet of 6 cycles. The teal ring marks where the burst really is.

Chapter 0

Why One Signal Needs Several Lenses

See why no single transform answers both “which frequencies?” and “when?”, and meet the three lenses this lecture compares

Strap a phone to your wrist and walk across a room. For 2.56 seconds the phone reads its accelerometer 50 times a second. That gives 128 numbers per axis, and they wiggle. Your job is to say whether you were walking, climbing stairs or sitting still.

A list of 128 numbers is a signal: a quantity measured at evenly spaced moments. Each number is a sample. The measurements per second are the sampling rate, here 50 Hz (hertz, meaning “per second”). Staring at the raw list tells you almost nothing. You need a better point of view.

Two points of view

The first point of view is the one you started with: the time domain. It answers “what was the value at this moment?” The second is the frequency domain. It answers “how much of the signal repeats slowly, and how much repeats fast?” Walking has a steady beat near 2 repeats per second. Sitting has almost none.

A transform is a way to move between the two views without losing any information. The classic one is the Fourier transform. It writes the signal as a sum of sine waves, and it tells you how tall each sine wave is. Lectures 6 to 8 built it; the DFT lesson shows the details.

Here is the catch. A sine wave never starts and never stops. It fills all of time. So when the Fourier transform builds a short click out of sine waves, it needs a great many of them, all cancelling each other everywhere except at the click. The heights survive. The timing hides in how the sine waves line up, and a plain spectrum chart throws that away.

Resolution: telling two things apart

Every lens has a resolution: the smallest gap between two events that it can still show as two events. A lens can have a time resolution (how close two clicks can be) and a frequency resolution (how close two tones can be). Here is the sad rule of this whole subject. You cannot make both as sharp as you like at the same time. Squeeze one and the other blurs.

Three lenses come out of that rule, and this lecture compares them. The Fourier lens has perfect frequency detail and no timing at all. The short-time Fourier transform (STFT) cuts the signal into slices with a fixed-length window and takes the Fourier transform of each slice. It gives some timing and some frequency detail, the same everywhere. The wavelet lens uses short wiggles of many sizes: small ones to pin down fast events, big ones to measure slow waves.

The lecture’s opening claim. Pilanci puts it in one line: what makes a good wavelet is application specific. You choose by three questions. Is it short in time or narrow in frequency? Is it smooth? Is it orthogonal, meaning its shifted copies carry no overlapping information? Chapter 1 answers each, and the later chapters use the answers.

Try the choice yourself

Five jobs follow. Each one has a lens that fits best. Look at the waveform, pick a lens, and read why. Do not worry if you guess: the rest of the lesson builds the reasons.

Pick the lens for the job

The waveform is the signal. The line under it names the job. Press the lens you would use, then read the reason.

The waveforms are drawn from simple formulas, so they are illustrative. The advice follows the lecture: Fourier suits stationary signals and filtering, wavelets suit fast transients, and the STFT suits slowly changing tones.

Notice how the answers depend on the shape of the signal, not on any ranking of lenses. A steady hum is perfect for Fourier. A single slam is a disaster for it. That is the pattern of the whole lecture: match the lens to the signal.

What this lecture covers

The lecture has two halves. The first half builds understanding: what makes a wavelet good, how the wavelet transform differs from the STFT, and why the difference shows up as a picture of tiles. The second half applies the lenses: recognising activity from phone sensors, detecting an irregular heartbeat, tracking chirps, and removing noise. The housekeeping takes one sentence: this is the second of two lectures on wavelets, and its slides are on the course page linked above.

  1. A good wavelet: short, smooth, orthogonal, and the families that trade these off.
  2. wavedec: the real call, its output, and the filter tree behind it.
  3. Fourier versus wavelet: uniform tiles against adaptive tiles, and the 100 Hz puzzle.
  4. The STFT: slide a window, take a spectrum, repeat.
  5. Tiles and glitches: how the two lenses cut the time-frequency plane and why locality matters.
  6. Reading human activity: phone sensors, nearest neighbours, features and a deep net.
  7. Reading a heartbeat: an 8-level decomposition feeding a classifier.
  8. Chirps: signals whose frequency moves, and the window trade-off.
  9. Denoising: threshold the coefficients, hard or soft, in 1D and in images.
  10. The field guide: numbers, code and where to go next.
A recording holds a steady hum plus one click. Which fact does a plain Fourier magnitude spectrum fail to tell you?

Chapter 1

What Makes a Good Wavelet

Judge a wavelet by its support, its smoothness and its orthogonality, then meet the families that trade them off

Try to draw a smooth hill using only flat steps. You can do it, but you need many thin steps, and the staircase still shows. Now try to draw a sharp cliff using only smooth bumps. Again you can, but the cliff needs many bumps, and they ring on both sides.

A wavelet is the brick, and the signal is the thing you build. A brick that matches the shape of the signal needs few pieces. A brick that does not match needs thousands. That is the whole reason the lecture says a good wavelet is application specific.

The brick, in one paragraph

Lecture 10 introduced the mother wavelet ψ(t): a short wave that starts at zero, wiggles up and down and returns to zero, with an average of exactly zero. You make the other bricks by scaling it (stretching or squeezing it in time) and shifting it (sliding it along). The wavelet coefficient for one brick says how much of the signal that brick explains. A signal of N samples becomes N coefficients.

The slide lists three questions to ask about the mother wavelet. We take them one at a time.

Question 1: where does it live, in time and in frequency?

A wavelet has compact time support when it is exactly zero outside a short stretch of time. Short support means each coefficient looks at only a few samples. If a spike sits at sample 100, only the few bricks that cover sample 100 notice it.

Frequency has the same question. A wavelet with compact frequency support uses only a narrow band of frequencies, so each scale separates one band cleanly. Here lies the trade-off from Chapter 0. A wavelet cannot be very short in time and very narrow in frequency at once. The product of the two spreads has a floor. Choose the corner you need.

Question 2: how smooth is it?

Smoothness has an exact meaning here. The k-th moment of ψ is the integral of tkψ(t). The wavelet has N vanishing moments if the moments for k = 0, 1, up to N − 1 are all zero. Moment 0 is the average, and every wavelet has it vanish. More vanishing moments mean a smoother wavelet.

Why does that help? Suppose the signal, over the short stretch a brick covers, looks like a polynomial of degree less than N. A polynomial is a sum of terms cktk. The coefficient is the integral of the signal times ψ, so it becomes a sum of ck times the k-th moment. Every moment is zero, so the coefficient is zero.

Check it with numbers. Haar has one vanishing moment, so it kills flat stretches only. Feed it the ramp 0, 1, 2, 3 and its detail filter (1, −1)/√2 gives −0.707 for each pair. The next wavelet, db2, has two vanishing moments. Its detail filter is (−0.1294, −0.2241, 0.8365, −0.4830). Apply it to 0, 1, 2, 3.

−0.1294×0 − 0.2241×1 + 0.8365×2 − 0.4830×3 = 0.0000

The ramp vanishes. A smooth signal made of gentle polynomial pieces then produces coefficients that are almost all zero, with a few large ones near its kinks. Few large numbers is called sparsity, and Chapters 6 and 9 live on it. Play with the next device to see the pattern.

Test the vanishing moments

Top left: the wavelet you pick. Top right: a polynomial signal with one jump. Bottom: the size of every finest-scale detail coefficient, on a log scale. Raise the degree until the wavelet stops coping.

1

Illustrative signal: 128 samples of (n/32)degree plus a step of 2 after sample 88. A coefficient counts as lit if it exceeds 0.000001. Coefficients are computed exactly from the standard Daubechies filters, with no padding at the edges.

Read the counts. Haar, with one vanishing moment, goes quiet only for a flat signal. Each step up in vanishing moments buys one more degree of polynomial for free. The price shows at the jump: the wavelet gets longer, so the jump lights up more neighbouring coefficients (1, 2, 3 and 4 of them). Smoothness and short support pull against each other.

Question 3: is it orthogonal?

Two bricks are orthogonal if their overlap integral is zero, like perpendicular arrows. An orthogonal wavelet basis has every scaled and shifted copy perpendicular to every other. Three gifts follow. There is no redundancy, so N samples give exactly N coefficients. Energy is preserved: the sum of squared coefficients equals the sum of squared samples (Parseval’s identity). And rebuilding the signal is easy: you apply the transpose of the analysis, with no matrix inverse.

Orthogonality has a price too. It pushes against symmetry and smoothness. Some famous wavelets give it up on purpose, as the next section shows.

The families, and which question each answers

Haar (db1) is the oldest: +1 then −1. Its support is shortest possible and it is orthogonal and symmetric, but it is a step, so it is not smooth. It suits edges and blocky data.

Daubechies wavelets (dbN) are orthogonal with N vanishing moments and the shortest support that allows it: a filter of 2N taps. db4 has 8 taps. They are asymmetric, which bends the phase. They are the default workhorse.

Symlets redesign the Daubechies filters to be close to symmetric, and coiflets add vanishing moments to the scaling function as well. Biorthogonal wavelets use two filter sets, one to analyse and one to rebuild. That lets them be exactly symmetric and still reconstruct perfectly, which is why the lecture’s image example in Chapter 9 uses one. The continuous wavelets Morlet (a Gaussian-windowed sine) and Mexican hat are not orthogonal and are not compactly supported, but they are smooth and good for pictures of scale against time.

Rule of thumb. Sharp edges and spikes: a short wavelet such as Haar or db2. Smooth curves: more vanishing moments, db4 and up. Images: symmetric ones, symlets or biorthogonal. A picture of time against frequency: Morlet.

Failure looks like this. You use db4 on a staircase of constant steps. The symptom: each jump lights up four coefficients instead of one, and the denoised result rings. The measurement: the device above counts them. The fix: use Haar, whose support matches the steps.

A signal is locally a cubic polynomial (degree 3). Which wavelet gives zero coefficients there?

Chapter 2

wavedec: Split a Signal Into Octave Bands

Follow one call from a long signal to a packed vector of coefficients, and see what each piece of the tree holds

You record 256 samples of a vibration sensor and call one line of MATLAB: [c, l] = wavedec(x, 4, 'db4'). Back come two vectors. A long one, c, holds every coefficient end to end. A short one, l, holds a handful of lengths. The slide shows a tree diagram and says little else. This chapter opens the box.

One level: a smooth half and a rough half

A single step uses two small filters. The lowpass filter h averages neighbouring samples, so it keeps the slow part of the signal. The highpass filter g takes differences, so it keeps the fast part. After filtering, you keep every second output and discard the rest. That step is downsampling by 2.

The slow half is the approximation (a). The fast half is the detail (d). Each has half as many numbers as the input. Nothing is lost, because the two halves together still hold N numbers. Work one by hand with Haar, where h = (1, 1)/√2 and g = (1, −1)/√2. Take eight samples.

x = [4, 6, 10, 12, 8, 6, 5, 5]
a = [7.07, 15.56, 9.90, 7.07]   d = [−1.41, −1.41, 1.41, 0]

The first approximation value is (4 + 6)/√2 = 7.07. The first detail is (4 − 6)/√2 = −1.41. Check the energy. The samples hold 16 + 36 + 100 + 144 + 64 + 36 + 25 + 25 = 446. The approximation holds 440 and the detail holds 6. They sum to 446. The transform kept all the energy and moved almost all of it into the smooth half.

The tree: repeat on the smooth half

Now split the approximation again, and again. Each split halves the length. Level n means n splits. After n levels you hold one final approximation an and n details dn, …, d1. The tree in the slide draws exactly this: the signal on top, a1 and d1 below it, then a1 splits into a2 and d2, and so on.

The output packs the pieces from coarse to fine. The coefficient vector is c = [a_n | d_n | d_(n-1) | … | d_1]. The bookkeeping vector is l = [len(a_n), len(d_n), …, len(d_1), len(x)]. You need l because c is one flat list and has no marks between the pieces. For 256 samples at level 4 with the periodic version we use here, l = [16, 16, 32, 64, 128, 256].

MATLAB’s default does not wrap the signal around. It extends the ends, so its pieces run slightly longer: each length is about (N + F − 1)/2, rounded down, where F is the filter length. The lengths in l tell you the truth. Never assume N/2j.

What frequency does each detail hold?

Each split halves the sampling rate of the smooth half, so it halves the top frequency too. If the signal has sampling rate fs, its content runs up to fs/2. Detail d1 holds the upper half of that range, from fs/4 to fs/2. Detail d2 holds the next half down, and so on. Every band is one octave (a factor of 2 in frequency) wide. In general dj spans fs/2j+1 to fs/2j.

This is the adaptive resolution Chapter 3 is about. The top band is wide, 64 Hz at fs = 256, and the coefficients there sit only two samples apart, so timing is sharp. The bottom band at level 5 is narrow, 4 Hz, and the coefficients sit 32 samples apart, so timing is coarse but frequency is precise.

Open the wavedec tree

Top: the signal (grey) and its rebuild from the bands you keep (warm). Below: one row of coefficients per band. Choose the level, then press a band to drop it from the rebuild.

4

Illustrative signal sampled at 256 Hz for one second: a 3 Hz wave, a 28 Hz tone, a click at sample 170 and a little noise. The transform is the db4 wavelet with wrap-around ends, so pieces have exactly N/2j numbers. Energy shares use Parseval’s identity.

Drop d1 first. The click loses its sharp edge and the rebuild looks smoother, but you lose little energy: the top octave held mostly noise. Now drop the approximation. The slow 3 Hz wave vanishes and the rebuild collapses toward zero. Dropping a band is filtering, done by deleting coefficients.

Getting the pieces back out

Real code gives you named access. In MATLAB, appcoef(c, l, 'db4', 4) returns a4 and detcoef(c, l, 3) returns d3. The call waverec(c, l, 'db4') rebuilds the signal. In Python, PyWavelets does the same job and returns a list instead of one packed vector: coeffs = pywt.wavedec(x, 'db4', level=4) gives [a4, d4, d3, d2, d1].

The slide’s example code (slide 5) does exactly this. It computes a level-4 decomposition, plots the approximation coefficients, then plots the details of levels 3, 2 and 1 as separate panels. The approximation looks like a smoothed copy of the signal. The finest detail looks like fast jitter. That stack of plots is the same picture as our device.

Data flow to remember. Input: N numbers. Output: N numbers, packed coarse to fine, plus a short length vector. The map is orthogonal for the orthogonal wavelets, so the energy is the same before and after.

Failure first shows as a symptom: the rebuilt signal has a bump at the edges that was never in the original. The measurement: the first and last few coefficients of each detail are unusually large. The cause: the transform has to extend the signal past its ends, and a wrap-around joins the last sample to the first. The fix is a gentler extension mode, such as a mirror (the symmetric mode that MATLAB and PyWavelets use by default).

A signal is sampled at 1,000 Hz. Which frequencies does the level 2 detail d2 hold?

Chapter 3

Fourier Versus Wavelet: Uniform or Adaptive Resolution

Compare what each transform does well, and see why 100 Hz of detail means different things at 400 Hz and at 4,000 Hz

Two pianists each strike two keys at once. The first pair of notes sits at 400 Hz and 500 Hz. The second sits at 4,000 Hz and 4,100 Hz. In both pairs the gap is 100 Hz. Your ear hears the first pair as a wide musical gap, almost four semitones. It hears the second as a gap of less than half a semitone, close to out of tune.

Same gap in hertz, very different gap to a listener. That one fact is the heart of slide 6, and it separates the Fourier transform from the wavelet transform.

What Fourier does best

The lecture lists two strengths. The first is the convolution theorem. Convolution is the operation behind every filter: slide a short pattern (the filter) along the signal, and at each position add up the products. Done directly, it costs one multiply for every pair of positions.

The theorem says that the Fourier transform of a convolution is the product of the Fourier transforms: DFT(x ∗ h) = DFT(x) · DFT(h), multiplied bin by bin. The reason is that a sine wave passes through any filter as a sine wave of the same frequency, only scaled and shifted. So in the frequency domain a filter just multiplies each bin by a number.

The saving is large. Filter 1,024 samples with a 1,024-tap filter. Directly, that is 1,024 × 1,024 = 1,048,576 multiply-adds. With the fast Fourier transform you zero-pad to 2,048, run three transforms of about 11,000 multiplies each, and multiply the bins. That is roughly 36,000 operations, about 30 times fewer. Wavelets have no closed form relation like this. The wavelet transform of a convolution is not a simple product of anything.

The second strength is uniform spectral resolution. The DFT of N samples has bins spaced fs/N apart, at every frequency. A bin at 50 Hz is exactly as wide as a bin at 5,000 Hz. This is ideal when the interesting things are evenly spaced, such as the harmonics of a mains hum at 50, 100, 150 and 200 Hz.

What wavelets do best

Wavelets give adaptive resolution. In Chapter 2 each band was one octave wide: the band at 4 Hz is about 4 Hz wide, and the band at 100 Hz is about 100 Hz wide. The width grows in step with the frequency. We say the ratio of centre frequency to width is constant, and call that ratio the quality factor, Q. A wavelet lens has the same Q at every scale. A Fourier lens has the same width at every frequency, so its Q grows with frequency.

The lecture drives this home with one sentence: 100 Hz resolution at 400 Hz and at 4,000 Hz are not the same. Do the arithmetic. At 400 Hz a 100 Hz bin is 100/400 = 25% of the frequency. At 4,000 Hz it is 100/4,000 = 2.5%. Measured in semitones (a semitone is a frequency ratio of 21/12, about 1.0595), the first bin spans 12·log2(500/400) = 3.9 semitones. The second spans 12·log2(4100/4000) = 0.4 semitones.

So a Fourier bin is too coarse for the low notes and needlessly fine for the high ones. The wavelet band always spans one octave, 12 semitones, and can be split finer where you need it. Hearing is built the same way: we judge pitch by ratios. Many natural signals share this feature, which is why wavelet lenses pair so well with speech, music and vibration.

Try it. Slide the centre frequency, and compare the two tile widths at that spot on a logarithmic frequency axis.

Compare the two rulers

The axis is logarithmic: each equal step to the right is a doubling of frequency. Top ruler: Fourier bins of 100 Hz. Bottom ruler: wavelet octave bands. The teal marks show the tile around your frequency.

400 Hz

Exact arithmetic: the Fourier bin is k×100 to (k+1)×100 Hz around your frequency; the wavelet band is the octave from 62.5×2m to 62.5×2m+1 Hz that contains it. The 100 Hz and the pair 400 Hz and 4,000 Hz come from the lecture; the octave edges are our illustrative choice.

Drag from 400 to 4,000 Hz. The Fourier bin keeps its width in hertz, so on the log axis it shrinks to a hairline. The octave band keeps its width on the log axis, so it grows from 250 Hz wide to 4,000 Hz wide. One is uniform in hertz. The other is uniform in ratio.

Choosing between them

Use Fourier when the signal is steady, when you want to filter by convolution, or when the harmonics are evenly spaced and you need to count them. Use wavelets when events are short, when the frequency range is wide, and when the exact timing of a fast event matters. The wavelet decomposition is cheap too: its cost grows in proportion to N, while the fast Fourier transform costs in proportion to N log N.

Mirror image. Fourier gives exact frequency and no time. Wavelets give exact time at high frequency and exact frequency at low frequency. The next chapters make that statement precise.

Failure looks like this. You analyse a voice recorded at 16,000 Hz with a wavelet decomposition, and want to count its harmonics (pitch 200 Hz gives harmonics every 200 Hz). The symptom: harmonics 6, 7, 8 and 9 all land in one coefficient group. The measurement: that octave band spans 1,000 to 2,000 Hz, so it holds the harmonics at 1,200, 1,400, 1,600 and 1,800 Hz together. The fix: use a Fourier or STFT view for harmonic counting.

Why is “100 Hz resolution” a very different promise at 400 Hz and at 4,000 Hz?

Chapter 4

The Short-Time Fourier Transform

Cut a signal into short windowed chunks, take a spectrum of each, and read how window length sets what you can see

Read a long page through a card with a small window cut in it. You see a few words at a time. Slide the card along and you can read the whole page, and you always know where on the page you are. The short-time Fourier transform does the same with a signal. The card is the window. What you read through it is one spectrum.

The reason to do this is the problem from Chapter 0. One spectrum of the whole signal loses timing. A spectrum of a short chunk only describes that chunk, so the chunk’s position in time is the timing information you kept.

The window

A window signal w[m] is a list of weights that is zero outside a short stretch. The slide’s example is the rectangular window: w[m] = 1 for m from 0 to L − 1, and 0 elsewhere. Multiply a signal by it and everything outside L samples disappears. Multiply by a window that tapers smoothly to zero at both ends, such as the Hann window, and the chunk fades in and out instead of being chopped.

The formula, one symbol at a time

Put the window at sample n. Take the L samples under it, weight them, and compute their DFT. The slide writes that as one equation.

X[n, k]
The answer: how much of frequency bin k sits in the chunk that starts at sample n. It depends on two numbers, so it is a table, not a list.
∑m=0L−1
Add up over the L positions inside the window. The variable m counts positions from the window’s left edge.
x[n + m]
The signal sample that lies under window position m when the window starts at sample n. Moving n slides the card along the page.
w[m]
The window’s weight at position m. It is 1 for a rectangle and fades toward 0 for a Hann window.
e−j(2π/N)km
A spinning arrow (a complex sine wave) that completes k turns over N steps. Multiplying by it and adding asks: how much of this frequency is in the chunk? Here j is the square root of −1.

Check it on a chunk small enough to do by hand. Take L = 4, a rectangular window, N = 4, and the samples x = [1, 0, −1, 0], which is a cosine that repeats once every 4 samples. For k = 1 the arrows at m = 0 and m = 2 are 1 and e−jπ = −1, so X = 1 + (−1)(−1) = 2. For k = 0 the sum is 1 + (−1) = 0. The full result is |X| = [0, 2, 0, 2]. The energy sits in bin 1 and its mirror, bin 3, exactly where a cosine of one cycle per four samples belongs.

From bins to a smooth frequency axis

The slide then lets frequency be any real number λ instead of the grid 2πk/N. This is the continuous-frequency STFT: X[n, λ] equals the same sum with e−jλm. Nothing new happens; you simply read the spectrum between the grid points. In hertz, λ corresponds to f = λfs/(2π). Our devices use this form, so each map is smooth.

If N is larger than L you zero-pad the chunk. That interpolates the spectrum and makes it look smoother, but it adds no real detail. The detail comes from the window length L alone: two tones closer than about fs/L hertz blur into one bump.

Slide the window, read the spectrum

The signal is a tone rising from 20 Hz to 180 Hz over one second. The teal box is the window. Middle: the chunk after weighting. Bottom: its spectrum, with the true frequency marked. Move the window and change its length and shape.

200

Toy signal: 512 samples at 512 Hz, f(t) = 20 + 160t hertz. The spectrum is the continuous-frequency STFT, computed directly at every hertz from 0 to 255. The true frequency is read at the window centre.

Slide the window along and the peak climbs with the chirp: the STFT tracks a moving tone. Now try the lengths. At 256 samples the peak is narrow in the picture of bins but the tone moves 80 Hz during the window, so the bump spreads. At 32 samples the window sees almost no motion, but its bins are 16 Hz apart and the bump is wide anyway. Somewhere between is best.

That is the time-frequency trade-off in numbers. A window of L samples lasts L/fs seconds and resolves fs/L hertz. Multiply: the product is exactly 1. Halve the window and you double the bin width.

The STFT has one fixed window. The same L serves every frequency and every moment. That sameness is what Chapter 5 compares with the wavelet lens.

The rectangular window has a failure of its own. Its sharp edges leak: a pure tone spreads small bumps (sidelobes) across the whole spectrum. The symptom is a faint ripple around a strong peak. You can see it by switching the device from Hann to Rectangular. The fix is a tapered window, at the cost of a main bump about twice as wide.

You halve the STFT window from 128 to 64 samples at a sampling rate of 512 Hz. What happens?

Chapter 5

Two Ways to Tile Time and Frequency

Cut the time-frequency plane into tiles with a fixed window or with adaptive wavelets, and see how locality finds a glitch Fourier cannot

Picture a floor you want to cover with tiles. Time runs left to right and frequency runs bottom to top. Each tile is one number the transform reports: how much signal lives in that patch. Your choice is the shape of the tiles.

The STFT of Chapter 4 uses one shape everywhere: identical rectangles. A wavelet transform uses tall thin tiles at the top of the floor and short wide tiles at the bottom. The next device lets you see both.

Same ingredients, different atoms

Slide 10 states the shared recipe in one line: a windowed signal is the signal compared with a windowed complex exponential. Each STFT value X[n, λ] is an inner product (multiply two lists sample by sample and add) between the signal and one atom: a short piece of sine wave of frequency λ sitting at position n. All atoms have the same length L.

A wavelet coefficient is the same kind of inner product, but its atoms are stretched copies of one mother wavelet. A scale s is the stretch factor. The centre frequency of the atom is about fc/s, where fc is a constant set by the wavelet. Small scale means a squeezed, short atom that listens to high frequency. Large scale means a stretched, long atom that listens to low frequency. That is the slide’s rule: short windows for high frequencies, long windows for low frequencies.

Why the tiles can change shape and not size

A tile that lasts Δt seconds can resolve a frequency band Δf wide, and the product Δt · Δf cannot go below a fixed floor. This is the uncertainty principle you met in Chapter 1. In units where one sample is one step, every tile has the same area, so shrinking the tile in time stretches it in frequency.

Take a one-second signal sampled at 512 Hz. A STFT window of 64 samples gives tiles 125 ms long and 8 Hz tall. Every tile on the floor looks like that. Count them: 8 tiles across times 32 tiles up gives 256. The wavelet floor also has 256 tiles, but they are shaped differently. The top band spans 128 to 256 Hz, so its tiles are 128 Hz tall and 1/128 s = 7.8 ms long, and there are 128 of them. The next band down has half as many, each twice as long. The bottom bands, 4 Hz tall, hold tiles 250 ms long.

Tile the plane

Time runs across, frequency runs up. Choose a lens, pick a window length for the STFT, then press an event or tap the plane. The teal tile is the one number that holds your event.

64

Bookkeeping convention for one second at 512 Hz: each tile has area 1 (time in seconds times width in hertz), so both floors hold 256 tiles. Each tile stands for one complex value; a real signal gives two real numbers per tile. The wavelet bands are the seven octaves from 0 to 4 Hz up to 128 to 256 Hz. The band edges are the standard octaves of Chapter 2.

Choose the burst at 150 Hz. With a 64-sample window its tile is 125 ms wide, so the burst could be anywhere in a span of an eighth of a second. With the wavelet floor its tile is 7.8 ms wide. Now choose the 40 Hz tone. The STFT tile is 8 Hz tall. The wavelet tile spans 32 to 64 Hz, a 32 Hz band, which is coarser in frequency but 31 ms long. Neither floor is better everywhere. The wavelet floor spends its precision where each kind of event needs it.

Slide 11 in one sentence. The wavelet transform has good time resolution and relatively poor frequency resolution at high frequencies, and good frequency resolution and relatively poor time resolution at low frequencies. It suits non-periodic signals with fast transient features, meaning high-frequency content that lasts a short time.

Locality: finding a glitch

Slides 13 to 15 test that claim on one example. Take a big, slow sine wave and add a tiny glitch at sample 180, small enough to see only in a close-up. Now ask each lens where the glitch is.

The Fourier transform answers badly. The glitch is a very short event, and a short event has a flat, wide spectrum: its energy is spread thinly over every frequency bin. The spectrum of the sine plus glitch is almost the same as that of the sine alone, and nothing in it says “sample 180”. The wavelet transform answers well, because a short, high-frequency wavelet slid over the signal only responds when it lands on the glitch.

The slide labels both behaviours. The stretched, low-frequency wavelet matches the long sinusoid and finds its peaks and valleys. The short, high-frequency wavelet matches the discontinuity and finds its location at 180. Try it on a glitch you place yourself.

Find the glitch

Top: a slow sine with a small glitch. Middle: the Fourier spectrum on a log scale, with and without the glitch. Bottom: the wavelet map, with fast wavelets at the top. Drag the glitch and change its size.

180
10%

Toy signal: 300 samples at 300 Hz, a 2 Hz sine of amplitude 1 plus a narrow bump (Gaussian, 1.2 samples wide) of the size you choose. The wavelet map is a Morlet transform of 6 cycles at 24 log-spaced frequencies from 2 to 100 Hz; brightness is on a log scale. The glitch estimate is the brightest column in the upper half of the map.

Slide the glitch around: the streak follows it exactly, while the Fourier spectrum barely changes shape. Shrink it to 2% and the streak dims but stays at the right place. The Fourier floor tells you only that something short happened. Locality, the ability to say where, is the wavelet’s gift.

Failure looks like this. A bearing in a machine develops a tiny crack that clicks once per turn. The symptom: the FFT of the vibration looks healthy, because the clicks are short and faint. The measurement: the clicks show up as streaks in a wavelet map. The fix: add a time-localised view, wavelet or STFT with a short window, to your monitoring.

Why does a wavelet map show a short glitch at the right sample while the Fourier spectrum does not?

Chapter 6

Reading Human Activity From a Phone

Turn raw accelerometer windows into features, and watch accuracy climb from 77% to 95% as the lens improves

Your phone knows when you walk. A tiny sensor, the accelerometer, reports how fast the phone speeds up along three axes. A second sensor, the gyroscope, reports how fast it turns. Cut the stream into windows of 128 readings, and each window should say one thing: walking, climbing stairs, descending stairs, sitting, standing or lying down.

Slide 16 shows two such windows, one walking and one lying. The walking window wobbles on all six channels (three for acceleration, three for turning). The lying window is almost flat. The data set is the Human Activity Recognition set from Reyes-Ortiz and colleagues (2012). The lecture splits it into 7,724 training windows and 2,575 test windows.

The simplest classifier, and why raw samples fail

The lecture starts with k-nearest neighbours. To classify a new window, compare it with every training window, find the k closest, and let them vote. With k = 3, the three nearest windows decide. “Closest” uses the ℓ2 distance: subtract the two windows sample by sample, square, add up and take the square root. The distance lesson builds this from zero.

Run it on the raw samples x[n] and slide 18 reports an accuracy of 0.77. It works, but it is fragile. Two people walk with the same rhythm, yet their steps begin at different moments inside the 2.56-second window. Sample by sample, the two windows look like different signals, as one waveform peaks while the other dips.

The fix: keep the size, drop the timing

The DFT magnitude solves exactly this. Shift a signal later by s samples and its DFT value at bin k picks up a factor of e−j2πks/N. That factor is a spinning arrow of length 1, so it changes the phase of each bin and leaves the magnitude alone. Check with the cosine from Chapter 4: x = [1, 0, −1, 0] has |X| = [0, 2, 0, 2]. Shift it by one sample to [0, 1, 0, −1]: the magnitudes are still [0, 2, 0, 2].

The lecture computes |X1[k]|, |X2[k]|, and so on for all training windows and runs the same 3-NN on them. Accuracy rises to 0.85. Feel why in the first device.

Shift the walker

A is a reference walking window. B is another walker with the same gait, starting later by the shift you choose. C is someone climbing stairs. A fair classifier should say A is closer to B. Drag the shift and watch which measure keeps its head.

12 samples

Illustrative synthetic gaits at 50 Hz, 128 samples each: walking is a 2.0 Hz wave with two overtones, climbing stairs is a 1.5 Hz wave with different overtones, and every window has its own small random noise. Distances are ℓ2 norms. Real accuracies on the true data set (0.77 and 0.85) are the lecture’s, from slide 18.

Try a shift near 12 samples, half a step. Raw distance now calls the climber closer than the other walker, so 1-nearest-neighbour votes wrongly. The DFT-magnitude distance barely moves, and the right answer wins at every shift. The price is that you threw away the phase, and phase held the timing.

Wavelet features: size and timing together

Wavelets keep both. Slides 19, 20, 37 and 38 show the continuous wavelet transform of these windows as a scalogram: an image with time across and scale (frequency) down, coloured by how strongly each wavelet matches. Slide 19 changes the number of scales, 32, 64 and 128, which is just how finely the frequency axis is cut. The six activities give six visibly different pictures: walking shows regular diagonal stripes, lying shows almost none.

You could hand these pictures to a classifier directly, and slide 39 does: a deep convolutional network reaches 94.91% test accuracy. But slide 21 shows a cheaper road (credited to A. Taspinar). Take the discrete wavelet decomposition of each window, and for each band compute a few plain numbers:

Stack the numbers from every band into one feature vector. For five bands and six numbers each, that is 30 numbers per channel. Feed them to a plain linear classifier. Open the second device to see the vector for each activity.

Read the scalogram and features

Pick an activity. Top: one body-acceleration channel. Middle: its scalogram, low frequencies at the bottom. Below: six features for each wavelet band. Change the number of scales to cut the frequency axis finer.

Illustrative synthetic signals at 50 Hz, 128 samples, standing in for the real recordings. Features are computed from a 4-level db4 decomposition. The scalogram is a Morlet transform with the chosen number of scales between 0.5 and 24 Hz. Static postures look alike in body acceleration alone; the real data set also uses gravity to tell them apart.

Look at the table for walking and for sitting. The moving activities pour variance into the middle bands (the ones around the step rate), and their entropy is low because the energy is organised. The still activities have tiny variance everywhere. A linear rule can separate them by thresholding a few columns.

The scoreboard

Slide 22 lines up four methods on one test set. Raw 3-NN scores 77%. DFT-magnitude 3-NN scores 85%. A 1D convolutional net, which learns its own filters along time, scores 91%. The wavelet features with a linear classifier score 95%. The third device lets you inspect each pipeline.

Climb the ladder

Each bar is a test accuracy from the lecture. Press a method to see what goes in and what comes out.

All five accuracies are read from the lecture’s slides 18, 22 and 39 (77%, 85%, 91%, 94.91%, 95%), one train and test split of the Human Activity Recognition set. The description of each pipeline is ours.

Two lessons hide in the ladder. First, the feature route beat the deep network, because the wavelet features already encode the physics (how much energy sits in which band, how spiky it is), so a plain linear model has little left to learn. Second, the deep network on scalograms nearly matches it, because scalograms hand a convolutional network a picture with clear structure. The deep learning lesson shows how such a network learns.

Concept and realization. Input: a window of 128 samples per channel. Features: per-band statistics of a wavelet decomposition. Model: a linear classifier over about 30 numbers per channel. Output: one of six labels. The lecture scores each method on 2,575 test windows that it did not train on.

Failure looks like this. Your classifier labels half of the sitting windows as standing. The symptom: a confusion table with a block between those two rows. The measurement: both classes have near-zero variance in every band, so the features cannot separate them. The fix: add a feature that differs, such as the direction of gravity from the raw accelerometer.

Why does 3-NN on DFT magnitudes beat 3-NN on raw samples when people start their steps at different moments?

Chapter 7

Reading a Heartbeat With Wavelets

Split an ECG into octave bands, squeeze the bands into a few numbers with PCA, and feed them to a classifier

Stick two electrodes on a chest and record the heart’s electrical activity. The trace is an electrocardiogram, or ECG. Each beat draws the same little picture: a small bump (the P wave), a sharp spike (the R peak, inside the QRS complex) and a broad hill (the T wave). The time from one R peak to the next is the RR interval.

Slide 23 puts a normal rhythm beside an irregular one. In the normal rhythm the spikes march at an even pace. In the irregular rhythm they come at uneven gaps, some beats look wider and some are missing their P wave. A doctor reads such a trace by eye. Can a program?

Why a heartbeat suits wavelets

An ECG mixes four things that live at different speeds. The QRS spike is fast: a few tens of milliseconds, with content roughly between 10 and 40 Hz (typical values, not from the slides). The P and T waves are slow, around 1 to 10 Hz. The baseline drifts as the patient breathes, below 1 Hz. Muscle twitches add hiss at high frequency.

That is a signal with short fast events on top of slow structure, exactly the case from Chapter 5. A wavelet decomposition separates the four. Each octave band of Chapter 2 holds a different part of the heartbeat, and each coefficient stays tied to a moment in time, so you can still say when the spike happened.

A cardiologist reads two things from this trace: how regular the beats are, and how wide each QRS spike is. Regularity is a question of when, the gaps between spikes. Width is a question of how fast, the frequency content of one spike. A single Fourier spectrum mixes both answers together. Bands that stay tied to time keep them apart. Wide, early beats put their energy in slower bands. Narrow, healthy ones put it in faster bands.

The pipeline on the slides

Slide 24 shows the method from a paper by Q. Qin and colleagues in Scientific Reports. It has two figures worth reading. Figure 3 is an 8-level wavelet multiresolution analysis: the ECG passes through a tree like Chapter 2’s, but eight levels deep, giving the bands cD1 to cD8 and the final approximation cA8. Each band has its own frequency range. At a sampling rate fs of 360 Hz, a common ECG rate, level j spans fs/2j+1 to fs/2j: cD1 covers 90 to 180 Hz, cD4 covers 11 to 22 Hz, and cA8 covers 0 to 0.7 Hz.

Figure 4 turns the many coefficients into a short vector using PCA, principal component analysis. This is the one idea you need. A beat gives hundreds of wavelet coefficients, but they move together: when the QRS gets wider, many numbers change at once. PCA finds the directions along which the coefficients vary the most, ranked by their contributory ratio (the share of total variance each direction explains). Keep the top few directions and drop the rest. A beat is now described by a handful of numbers, and those go to a classifier such as the support vector machine of Lecture 17. Slide 25 reproduces the paper’s table comparing its approach against earlier published methods.

Data flow. ECG segment of N samples, then 8-level DWT giving N coefficients in 9 groups, then PCA giving about 10 numbers, then a classifier giving a rhythm label. Each step makes the representation smaller and the next step cheaper.

See the band energies move

Our device builds a toy version. It makes a 5.7-second ECG for three kinds of rhythm, runs the 8-level decomposition with db4, and reports the share of energy in each of the 9 bands. That vector of nine shares is a feature vector. Compare it with the average vectors of the three rhythms and the nearest one wins.

Fingerprint a rhythm

Top: a toy ECG with the R peaks marked. Bottom: the share of energy in each wavelet band; the thin ticks mark the average for a normal rhythm. Choose a rhythm, then press New recording to try another random one.

Toy ECG, illustrative: 2,048 samples at 360 Hz, built from Gaussian P, Q, R, S and T bumps plus slow baseline drift and noise. Irregular beats have random RR gaps, no P wave and a small fast ripple. Early beats are wide, come 0.32 s early and are followed by a pause. Class templates are the average band shares of eight toy recordings each, and the nearest template is found in log space. This is a teaching toy, not a diagnostic.

Look at the early beats. Their wide QRS complexes push energy toward the middle bands, around d5 and d6, away from d4. The irregular rhythm differs less in this toy, and the classifier is sometimes wrong, so press New recording a few times. In 90 test recordings of this toy (30 of each rhythm) the nearest-template rule was right 84 times, and every miss was an irregular recording.

Failure looks like this. The classifier calls a normal trace irregular. The symptom: a beat with a large baseline wander. The measurement: a big share of energy in the lowest bands, which swamps the others. The fix: drop cA8 and cD8 (below 1.4 Hz) before computing features, since they hold drift, not rhythm.

Why does the pipeline run PCA after the wavelet decomposition?

Chapter 8

Chirps: When Frequency Moves

Track signals whose pitch changes, and derive the window length that balances smear against blur

A siren rises. A bird’s call sweeps from low to high in a tenth of a second. A bat’s echo-location cry slides down. In each case the frequency is not a number. It is a function of time. We call such a signal a chirp.

The limit of a single spectrum

Slide 26 sets two signals side by side. The first is a steady sine: its Fourier spectrum is one clean spike. The second is the same sine with a short burst of faster wiggles in the middle: its spectrum keeps the spike and adds a block of extra frequencies, and nothing in the block says when the burst came. A signal whose frequency content changes over time is non-stationary. A steady one is stationary. Fourier assumes the stationary case, and it fails quietly on the other.

What a chirp looks like in numbers

The lecture writes the linear chirp as x(t) = sin(2π(ct2 + f0t)). The instantaneous frequency is the rate at which the angle inside the sine is turning, measured in turns per second. Take the angle 2π(ct2 + f0t), differentiate with respect to t, and divide by 2π.

f(t) = 2ct + f0

Frequency climbs in a straight line. With c = 200 and f0 = 20, the frequency at t = 0.5 s is 2·200·0.5 + 20 = 220 Hz. Slide 29’s quadratic chirp adds a cubic term, sin(2π(ct3 + dt2 + f0t)), so its frequency is 3ct2 + 2dt + f0: a curve that bends upward.

Slide 30 uses two hyperbolic chirps added together, sampled at 2,048 Hz. Their frequencies are 7.5/(0.80 − t)2 and 2.5/(0.80 − t)2. Both climb slowly at first, then shoot up as t nears 0.80 s, and one stays three times above the other. The matching angle is 2πa/(0.80 − t), whose derivative divided by 2π gives a/(0.80 − t)2 for a = 7.5 or 2.5. At t = 0.6 their frequencies are 187.5 Hz and 62.5 Hz.

One spectrum, then two windows

Slide 31 takes the DFT of the whole two-chirp signal. You get one decaying spread of energy, with no hint of two rising ridges. Slides 32 and 33 apply the STFT with two window lengths. The 200 ms window has fine frequency detail but the fast late part smears across a wide band. The 50 ms window follows the fast part, but its coarse 20 Hz bins blur the slow early part, where the two ridges lie close together.

You can predict this. A window of length T seconds resolves frequency to about 1/T hertz. During that same window, a chirp with rate β (hertz per second) sweeps βT hertz. The picture stays sharp when these are about equal, so βT = 1/T and the best window is

Tbest = 1/√β

For the linear chirp above, β = 2c = 400 Hz per second, so Tbest = 1/20 = 50 ms. In that window the chirp sweeps 20 Hz and the resolution is also 20 Hz. For the hyperbolic chirp the rate is not constant. The rate is the derivative of 7.5/(0.80 − t)2, which is 15/(0.80 − t)3. At t = 0.1 that is 44 Hz per second, so Tbest is 150 ms. At t = 0.6 it is 1,875 Hz per second, so Tbest is 23 ms. No single window is best everywhere. A middle choice such as 50 ms is a compromise.

The wavelet answer

Slide 34 shows the continuous wavelet transform of the same signal, and both ridges appear sharp from start to finish. The wavelet lens has an adaptive window. A Morlet wavelet of 6 cycles has a Gaussian envelope whose spread is 6/(2πf) seconds: about 24 ms at 40 Hz and 6 ms at 150 Hz. Where the chirp is slow and low, the window is long and the frequency is precise. Where the chirp is fast and high, the window is short and follows it. Slide 35 draws the same map as a three-dimensional surface, with the two ridges as mountain crests.

Try it yourself. The lab below computes every map live from the signal.

Chirp lab

Pick a signal and a lens. The dashed line is the true instantaneous frequency. For the STFT, change the window length and watch the ridge thicken or merge.

200 ms

Signals sampled at 2,048 Hz for one second. Linear: 20 + 400t Hz. Quadratic: 10 + 40t + 450t2 Hz (illustrative constants). Hyperbolic: the lecture’s 7.5/(0.80 − t)2 and 2.5/(0.80 − t)2, cut off where they pass 900 Hz. STFT uses a Hann window; the wavelet is Morlet with 6 cycles.

Choose the hyperbolic pair with the 200 ms window. The fast ridges smear and read too low, 288 Hz instead of 333. Drop to 20 ms and the slow ridges merge into one. Near 50 ms both parts are readable, but the wavelet reads them without any tuning. Now select the linear chirp: a 50 ms window is near ideal, because β is constant and Tbest = 50 ms.

Rule. A window of T seconds resolves 1/T hertz and sees a chirp sweep βT hertz. Pick T = 1/√β when the rate is steady. When the rate changes by a large factor, use a lens whose window changes too.

Failure first shows as a symptom: two ridges look like one fat band. The measurement is the gap between them, 41 Hz at t = 0.45 s here, against the window’s blur 1/T and sweep βT. The fix: shorten the window until the sweep fits, or switch to wavelets.

A linear chirp sweeps at β = 400 Hz per second. Which window length balances smear against blur?

Chapter 9

Wavelet Denoising: Shrink the Small, Keep the Big

Transform a noisy signal, shrink its small coefficients, transform back, and derive why hard and soft thresholds do what they do

You record a sensor trace with three clear peaks and one flat block. The sensor adds hiss, so the trace is fuzzy everywhere. You want the peaks and the block back, with the fuzz gone. If you low-pass filter the trace, the fuzz fades, but the sharp edges of the peaks and the block soften with it.

Wavelets offer a cleverer plan, and it fits in four lines. Slide 40 lists them: take the input x; compute the wavelet transform y = Wx; shrink the coefficients; reconstruct x̂ = W−1S(y), where S is the shrinking rule.

Why shrinking the small ones works

The reason has two halves. First, a clean signal that is smooth with a few edges has a sparse wavelet representation: most coefficients are close to zero, and a few are large. You met this in Chapter 1. The energy of the signal piles up in a handful of numbers.

Second, the noise does the opposite. The wavelet transform is orthogonal, which means it acts like a rotation of the data. A rotation does not change the spread of white Gaussian noise. If each noise sample has standard deviation σ, each noise coefficient also has standard deviation σ. The noise stays evenly spread. So after the transform, big coefficients are almost all signal, and small coefficients are almost all noise. Delete the small ones and the noise goes with them.

Slide 43 writes this as a model. You observe y = y* + σw, where y* is the clean sparse signal, and w is standard Gaussian noise, independent for every entry. The task: recover y* from y.

Two shrinking rules

Slide 42 defines both rules with a threshold λ, a cut-off size. Hard thresholding keeps a coefficient unchanged if it is bigger than λ in size and sets it to zero otherwise: Hλ(y) = y·1[|y| > λ]. Soft thresholding also zeros the small ones but pulls every survivor toward zero by λ: Sλ(y) = sign(y)·(|y| − λ)+, where (u)+ means “u, or 0 if u is negative”.

Try four coefficients with λ = 1: y = [−3, −0.7, 0.4, 1.5]. Hard thresholding gives [−3, 0, 0, 1.5]. Soft thresholding gives [−2, 0, 0, 0.5]. Both kill the two small values. Hard keeps the big ones exactly. Soft shaves 1 off each.

Where the rules come from

Slide 43 states that each rule solves an optimisation problem. Hard thresholding solves minz ‖y − z‖22 + λ‖z‖0, where ‖z‖0 counts nonzero entries. Soft thresholding solves the same with λ‖z‖1, the sum of absolute values. The two terms fight: stay close to the data, but keep z cheap.

The problem splits into one tiny problem per coefficient. For the ℓ0 case there are only two candidates. Keep z = y, cost λ. Set z = 0, cost y2. Keep the coefficient when λ < y2, that is when |y| exceeds √λ. That is hard thresholding at √λ.

For the ℓ1 case minimise (y − z)2 + λ|z|. For z > 0 the slope is 2(z − y) + λ, which is zero at z = y − λ/2. This is a valid answer only when y > λ/2. Otherwise the minimum sits at z = 0. The result is soft thresholding with threshold λ/2. (The slide writes the threshold as λ; that matches a penalty of 2λ|z|.) Play with this in the first device.

Find the minimiser

Left: the cost (y − z)² plus the penalty, as a curve over z. The ring is the lowest point. Right: the rule you get by sweeping y, with your y marked.

1.50
1.00

Exact: the cost is evaluated on a grid of z from −4 to 4 and the lowest point is marked. The count penalty adds λ for every z not equal to 0, so the curve has an isolated point at z = 0 with height y². The thresholds √λ and λ/2 follow from the derivation above.

Set the size penalty with y = 1.5 and λ = 1. The lowest point is at z = 1.0, which is y − λ/2. Drop y below 0.5 and it snaps to 0. Switch to the count penalty: the answer is either y itself or 0, and it jumps at |y| = 1.

Denoise a real trace

Now apply it to the trace. The wavelet is Haar or db4, the transform has five levels, and the threshold touches the detail coefficients only. Leave the approximation alone: it holds the slow shape.

How big should λ be? Donoho and Johnstone gave a rule. First estimate the noise level from the finest detail band, where almost all of the coefficients are noise: σ̂ = median(|d1|)/0.6745. The 0.6745 is the median of |w| for a standard Gaussian. Then set the universal threshold λ = σ̂√(2 ln N). The reason: the biggest of N noise samples is about σ√(2 ln N), so this threshold sits just above all the noise. For N = 512, √(2 ln 512) = 3.53, so λ = 3.53σ̂.

Denoise the trace

Top: the noisy trace (yellow), the clean trace (dashed) and your denoised result (purple). Bottom: all 512 coefficients as stems; purple stems survive the threshold. Set the noise, pick a rule, and drag λ or press Universal.

0.12
0.40

Toy trace: 512 samples, three Gaussian peaks and a flat block, plus Gaussian noise of the chosen level (the same noise draw at every setting, only its size changes). Error is the root mean square difference from the clean trace. Five-level orthogonal decomposition; only the detail bands are thresholded.

Press Universal with soft thresholding and db4 at σ = 0.12. The threshold lands near 0.48 and the error falls from 0.125 to 0.088: the three peaks and the block stay, and the fuzz is gone. Now switch to hard. The error drops further, to 0.061, because the peaks keep their full height instead of losing λ off the top. But hard thresholding can leave small spurious spikes where a noise coefficient just clears the threshold, and the curve looks rougher. This is the slide 47 contrast: hard keeps the right size and risks jumps, soft gives continuity and risks bias. Try Haar: the block edges stay crisp but the smooth peaks come out as steps, the wrong brick for a smooth hill.

Slides 44 to 46 show the same trace denoised with two different wavelets, a symlet and a Daubechies, and the results differ in smoothness. The choice of wavelet from Chapter 1 matters here.

The same trick on a picture

Slide 48 denoises an image of a leaping cat with a 2D biorthogonal wavelet. A 2D wavelet transform applies the 1D transform to every row, and then to every column of the result. One level splits the image into four blocks: a smooth, quarter-size copy (LL), and three blocks of details: horizontal edges, vertical edges and diagonal ones. You repeat on the smooth copy. Edges in a picture are sparse, so most detail coefficients are noise. Threshold them, rebuild, and the grain fades while the edges stay.

Denoise the picture

Left: the clean picture. Middle: with noise. Right: after thresholding the wavelet details. Raise the noise, then press Universal or drag λ yourself.

0.20
0.50

Toy 64 by 64 picture (a disc, a rectangle, a thin line and a gradient), three-level 2D db2 transform, details thresholded, the smooth block untouched. The lecture’s own example is a photograph with a 2D biorthogonal wavelet. PSNR is 20 log10(1/error) in decibels, with pixel values from 0 to 1.

Failure looks like this: you push λ too high. The symptom is a cartoon-like result where thin lines vanish and edges look waxy. The measurement: PSNR rises and then falls as you drag λ past the best value. The fix: stay near the universal threshold, or tune λ on a held-out noisy copy.

Why can a threshold on wavelet coefficients remove noise while keeping a sharp edge?

Chapter 10

The Field Guide: Match the Lens to the Signal

Keep the numbers, the checklist and the core code, and see where wavelets sit among the other tools of the course

The lecture asked one question in many costumes: which lens fits this signal? A good wavelet is short, smooth and orthogonal in the amounts your job needs. Fourier gives exact frequency, the convolution theorem and no timing. The STFT gives timing and frequency at one fixed trade-off. The wavelet lens adapts its window to the frequency, which makes it the tool for transients, chirps and sparse structure. Applications follow from that: phone-sensor activity recognition, heartbeat classification, chirp tracking, and denoising by thresholding.

The numbers and terms to keep

ItemValue or ruleWhere it came from
Vanishing momentsN moments kill polynomials of degree below N. dbN has 2N taps.Chapter 1, slide 2
Detail band djfs/2j+1 to fs/2j, one octave wideChapter 2, slides 4 and 5
100 Hz at 400 Hz versus 4,000 Hz25% against 2.5% of the frequency; 3.9 against 0.4 semitonesChapter 3, slide 6
STFT window of L samplesTime blur L/fs, bin spacing fs/L, product 1Chapters 4 and 5, slides 7 to 12
Best window for a chirpT = 1/√β, with β the rate in Hz per secondChapter 8 (derived here)
Activity accuracyRaw 3-NN 77%, DFT 3-NN 85%, 1D CNN 91%, CNN 94.91%, wavelet features 95%Chapter 6, slides 18, 22 and 39
Activity data split7,724 training windows, 2,575 test windowsSlide 18
Hard and soft rulesy·1[|y| > λ] and sign(y)(|y| − λ)+Chapter 9, slide 42
Cut-offs from the penaltiesℓ0 gives √λ; ℓ1 gives λ/2Chapter 9, slide 43 (derived here)
Universal thresholdλ = σ̂√(2 ln N), σ̂ = median(|d1|)/0.6745Chapter 9 (Donoho and Johnstone)

A checklist before you choose

  1. Is the signal stationary? If its frequencies do not change, use Fourier.
  2. Do you need to filter? Convolution through the DFT is the fast road.
  3. Are there short transients? Use a wavelet lens or a short STFT window.
  4. Does the frequency move? Estimate its rate β and try T = 1/√β. If β changes a lot, use wavelets.
  5. Do you want sparsity? Match the wavelet to the signal: short for edges, more vanishing moments for smooth curves.
  6. Do you want features for a classifier? Take per-band statistics and try a linear model first.
  7. Do you want to denoise? Estimate σ from d1, try the universal threshold, then tune hard against soft.

The core as code

python
import numpy as np
import pywt
from scipy.signal import stft

def denoise(x, wavelet="db4", level=5, mode="soft"):
    coeffs = pywt.wavedec(x, wavelet, level=level)       # [a_n, d_n, ..., d_1]
    sigma = np.median(np.abs(coeffs[-1])) / 0.6745         # noise level from the finest band
    lam = sigma * np.sqrt(2 * np.log(len(x)))             # universal threshold
    out = [coeffs[0]] + [pywt.threshold(d, lam, mode=mode) for d in coeffs[1:]]
    return pywt.waverec(out, wavelet)[: len(x)]

def band_features(c):                               # six numbers per wavelet band
    p = c ** 2 / (c ** 2).sum()
    entropy = -(p[p > 0] * np.log2(p[p > 0])).sum()
    zcr = np.mean(np.diff(np.sign(c)) != 0)
    mcr = np.mean(np.diff(np.sign(c - c.mean())) != 0)
    return [c.mean(), np.median(c), c.var(), zcr, mcr, entropy]

def window_features(x, wavelet="db4", level=4):       # x: (128,) one channel -> (30,)
    return np.concatenate([band_features(c) for c in pywt.wavedec(x, wavelet, level=level)])

# time-frequency maps of one signal x sampled at fs
f, t, Z = stft(x, fs=fs, nperseg=128, window="hann")             # fixed window
coefs, freqs = pywt.cwt(x, np.arange(1, 65), "morl", sampling_period=1 / fs)  # scalogram

# best STFT window for a chirp with rate beta (Hz per second)
T_best = 1 / np.sqrt(beta)

Shapes: window_features turns a 128-sample window into 5 bands times 6 numbers = 30 values. Feed those to a linear classifier such as sklearn.linear_model.LogisticRegression.

Where this sits in the field

The STFT and the wavelet lens are two answers to one trade-off, and the choice recurs everywhere. Speech systems take a short-window spectrum and compress it, as in cepstra and MFCCs. Sparse recovery by an ℓ1 penalty, the soft-threshold rule, is the seed of dictionary learning, where the dictionary is learned instead of fixed. Convolutional networks learn their own filter banks, a data-driven cousin of the wavelet tree (see Lecture 24).

Keep going

The takeaway. No lens is best. Fourier says what, the STFT says roughly what and when at one fixed trade-off, and wavelets say when at high frequency and what at low frequency. Pick the one whose weaknesses your signal does not mind.

Credit: these are Lecture 11 (Wavelets Part II, October 5, 2021) of Stanford EE269, Signal Processing for Machine Learning, taught by Mert Pilanci. The slides are on the course slides page and the course home is web.stanford.edu/class/ee269. The activity data set is from Reyes-Ortiz and colleagues (2012), the wavelet feature slide is credited to A. Taspinar, and the arrhythmia pipeline is from Q. Qin and colleagues in Scientific Reports. Next, press Teach to draw the ideas on a whiteboard, or Present to explain them aloud, or go back to the four lenses at the top.

EE269 Lecture 11: Wavelets in Practice
Lecture by Mert Pilanci, Stanford EE269 · Back to Lecture 10, Wavelets · Back to Gleams