A spectrogram shows which pitches play and when. One knob, the window length, trades the two: a short window pins down the moment, a long one pins down the pitch.
Pick a signal, then drag the window length from short to long. Watch the two tones and the two spikes take turns being sharp. Then we build, piece by piece, the window, the frames, the grid, the trade, the shapes, the beats and the way a neural network uses all of it.
You need what a sine wave is and the idea of a DFT (a list of how much of each pitch a signal holds; Lecture 6 builds it). We rebuild the rest from zero.
Based on Lecture 3 Part II, the STFT deck, of Stanford EE269: Signal Processing and Quantization for Machine Learning, taught by Mert Pilanci. Course slides. Every idea is re-taught here in our own words and devices. It follows Lecture 7, Spectral Descriptors.
The tones and spikes follow the lecture’s example: two sines at 400 and 450 Hz and two single-sample spikes at 0.45 s and 0.50 s, sampled at 4,000 Hz (the deck does not give the spike height; here it is 60 so both kinds show). The chirp is the deck’s sin(400πt²). The voice-like signal is synthetic: a gliding 120 to 170 Hz buzz through two resonances, then a burst of high-pitched hiss. The spectrogram is computed live in your browser with a Hann or rectangular window, hop of a quarter window, 70 dB of range. The teal tile is one window’s time span and frequency spacing. Verdicts count a pair as apart when the dip between the two peaks is at least 3 dB deep.
Chapter 0
Hear why a single DFT of a whole recording cannot tell you when a pitch played
Press a doorbell and you hear two notes: a high one, then a low one. Ding, dong. Now play the recording backwards. Dong, ding. The two notes are the same. Their loudness is the same. Yet your ear hears two different sounds, because the order changed.
Here is the odd part. Take the whole recording and compute its DFT, the list of how much of each pitch the recording holds. The ding-dong and the dong-ding give almost the same list. The tool you already have cannot tell them apart. This lecture fixes that.
A digital recording is a row of numbers called samples, one per tick of the clock. The sampling rate fs is the number of ticks per second. Take N samples. The DFT turns them into N new numbers. Number k says how much of one pure pitch, the one that fits exactly k cycles into your N samples, the recording contains.
The lecture opens with this recap, side by side with its continuous cousin, the Fourier transform of a signal x(t) that lives on a smooth time axis, Xc(f) = ∫ x(t) e−j2πft dt. The discrete version is what a computer can run, so it is the one we use. The shape of the formula matters most: every sample multiplies every pitch.
Look at the spinning arrow again. For pitch k it keeps spinning for the whole block, from the first sample to the last. So pitch k is tested against the entire recording at once. The sum cannot ask “was this pitch present at second 0.3?” It can only ask “was it present, on average, over the block?” We call this a global view.
The timing is not destroyed, to be exact. The DFT can be inverted, so the order of the notes must hide somewhere. It hides in the phases, the angles of the X[k]. A plot of sizes alone drops the phases, and the order goes with them. Reading time out of phases by eye is hopeless, and Chapter 6 shows why.
The lecture states the cost like this: the DFT assumes the signal is roughly stationary over the block, meaning its pitch content does not change as time passes. A steady hum is stationary. Most signals we care about are not. Speech changes sound every tenth of a second. Music changes note. A siren sweeps up and down. A door slam is over in a few milliseconds. These are nonstationary, and for them the question “which pitches, and when?” is the whole point.
The lecture’s idea is simple. Do not take one spectrum of the whole block. Cut out a short stretch, so short that the signal barely changes inside it, and take the spectrum of that stretch. Then slide along and do it again. The cutting tool is a window: a short curve that is large where we look and small where we do not.
Each stretch gives one spectrum. Line the spectra up in time order and you get a grid with time along one side and pitch along the other: X[time, frequency]. This grid is the short-time Fourier transform, the STFT. Its picture is the spectrogram. It is the most common picture in audio work.
Try it on the doorbell. Choose an order below. The left strip is one DFT of the whole second. The right panel is the STFT. The two share the same pitch axis, so you can compare them row by row.
Two notes, 512 Hz and 1,536 Hz, each last half a second. Pick an order, press Hear it, and compare the strip on the left with the panel on the right.
Toy signal: two pure tones, sampled at 8,192 Hz for one second, each tone a whole number of cycles in its half second. The DFT is one 8,192-point transform. The spectrogram uses a 512-sample Hann window and a hop of 128 samples. The difference figure is the size of the gap between the two magnitude spectra divided by the size of the first, computed live; a reversed recording has exactly the same magnitudes, so the gap is rounding error.
With low-then-high chosen, the left strip shows two peaks. Switch to high-then-low and the strip does not move. The right panel moves: the bright band at 512 Hz is on the left in one order and on the right in the other. The third choice, both at once, gives the same two peaks in the strip yet a very different picture on the right.
That is the gain. The STFT keeps the part of the answer the DFT lost. It costs us something in return, and most of this lesson is about that cost: how long to make the window, what shape it takes, what the grid really means, and what a neural network can do with it.
This is Part II of Lecture 3 in Stanford’s EE269, taught by Mert Pilanci. The lecture has 35 slides and a short list of references, mostly on spectral descriptors; we cover those in the previous lesson. The slides are linked at the top of this page and in the last chapter. Everything below is re-taught in our own words, and every picture is made live by the code on this page.
Chapter 1
Build the STFT from the DFT you know, with three numbers: window length, hop and FFT size
Picture a long paper scroll covered in tiny writing. You cannot read it all at once. So you lay a card with a small slot over the scroll and read only what shows through. Then you slide the card along and read the next bit. The card is the whole idea of this chapter.
In signal terms, the scroll is the recording x. The card is a window, a second list of numbers, one per sample, that is large near the slot and small or zero elsewhere. To read one stretch, multiply the recording by the window sample by sample. Everything outside the slot turns into zero. Then take the DFT of what is left. That is one column of the STFT.
The lecture first gives the version for smooth time, with a signal x(τ) and a window w. The new letter t is where the card sits. The letter τ is the running time inside the integral.
Put a window of height 1 for all time and you get the ordinary Fourier transform back. So the STFT is not a new tool. It is the old tool with a card in front of it.
A computer cannot slide a card smoothly. It jumps. The jump size is the hop H, the number of samples between one card position and the next. Each position gives one frame, a window’s worth of samples. The lecture’s frame form, which is also what code does, is the second formula below. Frame m starts at sample mH.
The deck writes the same idea three ways. Slide 4 calls the hop D and writes Xnm = DFT{w[nD − k] x[k]}. Slide 6 calls it H. Slide 23 calls it R. All three are the hop. Slide 6 also gives a sample-shift form, X[τ, k] = ∑ x[n] g[n − τ] e−j2πkn/N, where τ is the window centre in samples; set τ = mH and it matches the frame form.
The slide ends with three bullets, and each one is a separate knob.
Window length L sets time localization: how long a stretch each frame looks at. FFT size N sets the frequency grid: how many pitch bins the DFT reports. If N is bigger than L, the frame is padded with zeros first. Hop H sets redundancy: how much neighbouring frames overlap. A hop of L means no overlap. A hop of L/2 means each sample sits in two frames.
The number of frames follows from the hop. For a recording of Nx samples, slide 24 gives M = ⌊(Nx − L)/H⌋ + 1. The floor brackets mean “round down”. The “+ 1” counts the very first frame.
Take eight samples: x = [1, 2, 3, 4, 5, 6, 7, 8]. Use a rectangular window of length L = 4 (all ones), a hop H = 2, and N = L = 4. The frame count is M = ⌊(8 − 4)/2⌋ + 1 = 3.
Frame 0 is [1, 2, 3, 4]. The four DFT numbers, using the arrow e−j2πkn/4 that turns a quarter turn per step at k = 1:
X[0] = 1 + 2 + 3 + 4 = 10 X[1] = 1 − 2j − 3 + 4j = −2 + 2j X[2] = 1 − 2 + 3 − 4 = −2 X[3] = −2 − 2j
Frame 1 is [3, 4, 5, 6], starting at sample 2. Its DFT is 18, −2 + 2j, −2, −2 − 2j. Frame 2 is [5, 6, 7, 8], and its DFT is 26 and the same three. Only the first number, the DC term (the plain average level, pitch zero), changes from frame to frame: 10, 18, 26. That is right. Each frame is a flat level plus the same small ramp, and a ramp has the same shape wherever you put it.
The output is a table with 3 rows and 4 columns. The recording had 8 numbers. The table holds 12 complex numbers. Overlap and padding have made more numbers than we started with, which is why Chapter 7 can undo the transform.
Here is a failure that bites in practice. The symptom: a clap at the very end of the file never shows in the picture. The measurement: take Nx = 1,000, L = 256, H = 100. Then M = ⌊744/100⌋ + 1 = 8 frames, and the last one ends at sample 7 × 100 + 256 = 956. So 44 samples at the end sit in no frame at all. The fix: pad the end with zeros so that one more frame fits, or centre each frame on its hop as the next chapters do.
Now slide the window yourself. The signal is four notes in a row, the notes of an A major chord played one after another. Move the frame and watch the spectrum answer.
Top: the whole recording with your window in purple. Middle: the frame after the window has scaled it. Bottom: that frame’s spectrum. Drag the frame, then change the window length or the hop.
Toy signal: four sine notes of a quarter second each (440, 554, 659 and 880 Hz) sampled at 8,000 Hz, 8,000 samples in all. Frames follow the lecture’s convention: frame m starts at sample mH and no padding is added. The window is Hann, and the FFT size N equals the window length L. The spectrum shows 0 to 1,500 Hz in decibels, 50 dB of range; the strongest pitch is read off the largest bin, so it is exact only to one bin width, fs / N.
With L = 256 and a hop of L/2 there are 61 frames. Put the frame at the very start, then drag it right. The spectrum jumps from one tall spike to the next, one per note, and stays put while the window lies inside one note. Between two notes the spectrum shows two spikes at once, because the window straddles the change. Set the window to 1,024 and the straddle lasts much longer. That is the first sign of a price we pay for using a window at all.
Chapter 2
Turn a grid of complex numbers into a picture, then read the time and the pitch off any cell
A good map lets you point at a spot and say two things: how far east, how far north. A spectrogram is a map of sound. Along the bottom runs time. Up the side runs pitch. The colour at a spot says how loud that pitch is at that moment. This chapter teaches you to read the map, and to build it from the frames of Chapter 1.
Every cell X[m, k] of the STFT is a complex number. Its size |X| says how strong the pitch is. Its angle says where in its cycle the pitch starts. For the picture we keep only the size. The lecture’s spectrogram is the size squared, the power:
Why decibels? Your ear covers an enormous range, and so does real sound. A loud vowel can hold 100,000 times more power than the hiss after it, and that is 50 dB. On a plain power scale the hiss would be invisible. On a dB scale each factor of ten gets the same step of brightness, so both show.
Here is the failure in numbers. The symptom: a spectrogram that is black except for one thin bright line. The measurement: the faint overtones of a note sit 40 dB below its main pitch, which is 1/10,000 of the power, far too dim to see on a linear scale. The fix: plot in dB and choose a range, often 60 to 80 dB below the brightest cell.
Now the axes. Frame m starts at sample mH, so it starts at tm = mH / fs seconds. Bin k is the pitch that fits k cycles into N samples. One cycle per N samples is fs / N cycles per second, so bin k is at fk = k fs / N hertz. These are slide 7’s two formulas, and they are all you need to read the map.
A worked case, the setup of slide 25: fs = 16,000 Hz, window L = 512, hop H = 128, FFT size N = 512.
window = 512 / 16,000 = 32 ms hop = 128 / 16,000 = 8 ms bin spacing = 16,000 / 512 = 31.25 Hz
Frame m = 50 starts at 50 × 128 / 16,000 = 0.4 s. Bin k = 20 sits at 20 × 31.25 = 625 Hz. A window overlaps its neighbours by 1 − 128/512 = 75%. Many libraries label a frame by its centre, the start plus half a window, which here is 0.4 + 0.016 = 0.416 s. Our pictures use the centre, with zeros padded at both ends, so the first column is centred at time zero.
A real signal has no imaginary part, and that forces a mirror in the DFT: X[N − k] is the complex conjugate of X[k], so the two have the same size. The upper half of the bins repeats the lower half. So code keeps only bins 0 to N/2, which is N/2 + 1 numbers. For N = 512 that is 257. The top bin sits at fs/2 = 8,000 Hz, the Nyquist frequency, the highest pitch a sampled signal can hold. NumPy’s rfft returns exactly these.
Slide 24 gives the recipe. The number of frames is M = ⌊(Nx − L)/H⌋ + 1. For each frame m from 0 to M − 1: take the segment x[n + mH]; multiply it by the window; zero-pad it to length N if N is bigger than L; run the FFT. The cost is M FFTs, so O(M N log N). Stored as a matrix, the STFT has M rows and N/2 + 1 columns for a real signal.
With one second at 16 kHz, the setup above gives M = ⌊(16,000 − 512)/128⌋ + 1 = 122 frames, a matrix of 122 × 257 complex numbers. That is 31,354 complex numbers, or 62,708 real numbers, for 16,000 samples. The picture has roughly four times as many numbers as the sound, which is the price of a 75% overlap.
Tap or click a cell of the spectrogram. The read-out turns the cell number (m, k) into seconds and hertz. Then switch between linear power and decibels.
Toy signals sampled at 4,000 Hz for one second, in the spirit of the lecture’s two example spectrograms (slides 8 and 9, whose exact signals the deck does not give). Up chirp 100 to 900 Hz, down chirp 900 to 100 Hz; or two pitches that swing around 400 Hz twice a second, 200 Hz either way. Window 256 samples, Hann, hop 64, FFT size 512, so frame m is centred at 64m / 4,000 s and bin k sits at 7.8125k Hz.
Tap the crossing point of the two chirps. The read-out gives about 0.5 s and 500 Hz, the moment the rising pitch passes the falling one. Tap on the dark area above the lines and the cell is far below the brightest, often 60 dB or more. Now flip to linear power. The thin ridges stay, but the faint skirt around them disappears. Both pictures are the same numbers, drawn on two scales.
Slide 25 does all of this in a few lines of SciPy. Read it as a recipe with the sizes written next to it.
pythonimport numpy as np from scipy.signal import stft fs = 16000 # samples per second L = 512 # window length: 32 ms H = 128 # hop: 8 ms, so 75% overlap N = 512 # FFT size (N > L would zero-pad each frame) # x: one second of audio, shape (16000,) f, t, Z = stft(x, fs=fs, nperseg=L, noverlap=L-H, nfft=N, window="hann", boundary=None, padded=False) # f: (257,) in Hz = k * 31.25 t: (122,) in seconds Z: (257, 122) complex S = np.abs(Z)**2 # power spectrogram, (257, 122) S_db = 10*np.log10(S + 1e-10) # decibels, with epsilon = 1e-10
Two details trip people up. First, Z has shape (frequency bins, time frames): pitch runs down the rows, the reverse of our M × K table. Second, SciPy divides each value by the sum of the window, so a unit-height sine shows up with size 0.5, not 128. With boundary=None and padded=False SciPy does no padding, so the frame count is exactly the 122 we computed, and t marks frame centres (0.016 s, 0.024 s, and so on).
The slide closes on a rule for what to do with Z. Its size is the energy at that spot. Its angle is the local phase. Most machine learning pipelines keep the log of the power, usually after a mel filter bank, and we reach that in Chapter 8.
Chapter 3
Compute what a window of any length can and cannot separate, and see why no window does both
A drummer taps two beats, 50 milliseconds apart, over a steady hum of two guitar strings that are 50 Hz apart in pitch. To tell the two beats apart, you must listen in very short bursts. A long listen blurs them into one thump. To tell the two strings apart, you must listen for long enough to hear them drift in and out of step. A short listen blurs them into one tone.
You want both at once. The window length decides which one you get. This chapter makes that precise, and shows when you can have both and when you cannot.
The first number is easy. A window of L samples at sampling rate fs looks at L / fs seconds. Slide 10 writes it as time resolution, Δt ≈ L / fs. Two events closer together than this fall in one window and blur.
The second number needs care, because the slide gives the bin spacing, Δf = fs / N: how far apart the rows of the picture sit. Slide 6 says the FFT size N sets the grid, and the window length L sets how sharply the window can tell pitches apart. Resolving two pitches takes a window that is long enough for their difference to show as a slow beat, which is the subject of Chapter 5. As a working rule, a Hann window needs the two pitches to be about two bin spacings of an L-point FFT apart, so
resolution ≈ 2 fs / L (Hann), fs / L (rectangular)
Worked numbers, with fs = 16,000 Hz and L = 512. The window looks at 512 / 16,000 = 32 ms. A Hann window resolves about 2 × 16,000 / 512 = 62.5 Hz. Double the window and the picture changes the other way: 64 ms, and 31 Hz.
Slide 6 says N > L means zero-padding. Pad each frame with zeros before the FFT and the DFT reports more bins, closer together. The curve looks smoother. But the zeros carry no information, so the extra rows only interpolate between what was already there. Try it. Two tones, 60 Hz apart, and a window that cannot separate them.
Two tones, 1,000 Hz and 1,060 Hz, seen through one Hann frame. Pick the window length and the FFT size, and count the peaks.
Toy signal: two unit tones at 1,000 and 1,060 Hz, in step at the middle of the frame, sampled at 4,000 Hz. One Hann frame, zero-padded to N. The teal bar is the rule-of-thumb resolution 2 fs / L. A peak is a bin higher than both neighbours and within 25 dB of the highest bin; two bumps count as two peaks only when the dip between them is 3 dB deep. Counted live.
With L = 64 the resolution is 2 × 4,000 / 64 = 125 Hz, wider than the 60 Hz gap, and no padding helps: the dots multiply, the peak stays single. With L = 256 the resolution is 31 Hz, and two peaks appear even with no padding, because the window finally lasts long enough to see the tones drift apart.
Multiply the two numbers. The time resolution is L / fs. The pitch resolution is about fs / L. The L and fs cancel, and the product is about 1. Draw one window as a rectangle on the time-pitch plane, and that rectangle has a fixed area. A long window is a wide, short tile. A short window is a narrow, tall tile. You can reshape the tile. You cannot shrink it.
This is the spectrogram’s own uncertainty principle, a close cousin of the one in quantum physics. A sharper statement, the Gabor limit, says that the product of a window’s spread in time and its spread in frequency is at least 1/(4π), and that a Gaussian window reaches that floor. The slide puts it in one sentence: the STFT is not a perfect representation; it is a controlled compromise. The teal tile in the hero at the top of the page is exactly this rectangle.
The lecture’s example is x(t) = sin(800πt) + sin(900πt) + δ(t − 0.45) + δ(t − 0.5), sampled at 4,000 Hz. Two tones at 400 and 450 Hz, 50 Hz apart. Two spikes, 50 ms apart. A short window separates the spikes but not the tones. A long one separates the tones but not the spikes.
Let us do the arithmetic. Tones: Hann needs L of about 2 × 4,000 / 50 = 160 samples by the rule, and about 180 on the real picture. Spikes: the window must be shorter than the 50 ms gap, which is 200 samples by the rule. Measured, the spikes stay apart up to about 360 samples, because a Hann window is narrower than its length. So a window of about 180 to 360 samples does both. There is a sweet spot, but only because the product of the gaps, 50 Hz × 0.05 s = 2.5, is big enough. Make the gaps smaller and the sweet spot vanishes. Test it.
The strip under the picture tests 25 window lengths on a logarithmic axis. Green means that pair is separated. Shrink either gap and watch the two green runs stop overlapping.
The tones are at 400 Hz and 400 Hz plus your gap; the spikes are at 0.45 s and 0.45 s plus your gap, height 60, sampled at 4,000 Hz. Each of the 25 tested lengths is a real Hann spectrogram with hop L/4; a pair counts as separated when the dip between its two peaks is 3 dB deep or more. The product of the gaps is a rule of thumb: below 1 nothing worked in our tests, near 1.5 only a sliver, above 2 a comfortable range.
Start at the lecture’s own gaps, 50 Hz and 50 ms. The two green runs overlap between about 180 and 360 samples. Now pull the tone gap down to 25 Hz. The tones need a longer window, 362 samples, while the spikes still need a shorter one, so the runs just touch. At 20 Hz and 50 ms they miss each other: no single window gives you both.
The hop has a small trade of its own. Each frame is centred on a hop position, and the window is tall in the middle and zero at the edges. An event that falls between two frame centres is seen through the sloping sides of the window. Take a click and a Hann window of length L.
With hop = L, the click can land exactly where one window ends and the next begins. Both windows give it weight 0, and the click vanishes. With hop = L/2, the worst place is midway between two centres, L/4 from each, where the window height is 0.5: the click reads 6 dB too weak. With hop = L/4, the worst place is L/8 from a centre, where the height is 0.854: only 1.4 dB too weak. That is why slide 10 asks for 50% to 75% overlap, and why this lesson uses L/4 when it wants features.
The slide gives a heuristic for audio and speech: L about 20 to 40 ms, with 50% to 75% overlap. Here is why. A deep male voice buzzes at about 100 Hz, so its harmonics sit 100 Hz apart. A Hann window needs about 2 / 100 = 20 ms to see them as separate stripes. Speech sounds change every 50 to 100 ms, so a window much beyond 40 ms smears one sound into the next. The two limits bracket 20 to 40 ms.
When one window cannot do both, there are two ways out. Compute several STFTs with different windows and use them together, which Chapter 9 does for training losses. Or use a transform whose tiles change shape with pitch, which is what the wavelets lecture builds.
Here is the failure in numbers. The symptom: two piano notes a semitone apart, A at 440 Hz and B-flat at 466 Hz, look like one smeared band. The measurement: they are 26 Hz apart. With L = 512 at 16,000 Hz the resolution is 2 × 16,000 / 512 = 62.5 Hz, more than twice the gap. The fix: L of at least 2 × 16,000 / 26 = 1,230 samples, so take L = 2,048, a window of 128 ms with a resolution of 15.6 Hz. The price is timing: any change faster than 128 ms now blurs.
Chapter 4
Compare five windows by the spectrum each one smears, and pick one for the job
Take a steady note from a flute and cut a piece out with scissors, in the middle of a wave. The piece starts and stops with a jump. Play it and you hear a click at each end. The flute never clicked. The click is the cut. Audio editors hide it with a short fade in and fade out. That fade is a window.
The window you choose decides how much of this false click-noise your spectrogram invents. This chapter shows why, and compares the five windows that the lecture and the field use.
The simplest window is the rectangular window: all ones inside the frame, zero outside. It is the card from Chapter 1 with nothing done to its edges. A tone that does not fit a whole number of cycles into the frame ends on a jump. The DFT sees the jump and reports energy at pitches the signal does not contain. That wrong energy is spectral leakage.
Slide 11 compares three windows side by side: rectangular, triangular and Hann. Each row shows the window in time and its spectrum next to it. The rectangular row has the most ragged spectrum. The Hann row has the smoothest.
Slide 22 holds the key fact in its last bullet: windowing is smoothing in frequency. Multiplying two signals in time is the same as convolving their spectra. Convolving means sliding one curve across the other and adding up the overlap, which blurs the result.
Now put in a pure tone. Its true spectrum is one spike. Smoothing one spike with G gives a copy of G, centred on the tone. So a pure tone shows up as the window’s own spectrum. The tall middle of G, the main lobe, sets the width of every peak, and so sets the resolution of Chapter 3. The little bumps beside it, the sidelobes, are the leakage. A good window has a narrow main lobe and low sidelobes. You will see that you cannot get both.
Slide 11 gives the Hann window as g[n] = ½(1 − cos(2πn / (N − 1))). Take a frame of five samples, so N = 5 and the denominator is 4. The cosine takes the angles 0, π/2, π, 3π/2 and 2π, and the cosines are 1, 0, −1, 0, 1.
g = ½(1 − [1, 0, −1, 0, 1]) = [0, 0.5, 1, 0.5, 0]
Apply it to the frame [2, 4, 6, 4, 2]. The result is [0, 2, 6, 2, 0]. The ends are gone and the middle is untouched, so the frame now rises smoothly from zero and falls smoothly back. No jump, no click. One caution: this slide formula divides by N − 1, the symmetric form. SciPy’s stft divides by N, the periodic form, which is the one that adds up exactly in Chapter 7. The two differ in the last digits and not in the lesson.
Slide 11 shows three windows. Two more complete the usual set. The Hamming window is 0.54 − 0.46 cos(2πn/N), a Hann window lifted so its ends sit at 0.08 instead of zero. The Blackman window adds a second cosine term, 0.42 − 0.5 cos(2πn/N) + 0.08 cos(4πn/N), and falls to zero even more gently. (The sidelobe levels below are the standard textbook values from Harris, 1978; the device measures them for you.)
Top: the window shape. Bottom: the spectrum of a 64-sample frame holding one tone. The curve is the true shape, a copy of the window’s spectrum. The dots are what the DFT actually reports, one per bin. Slide the tone halfway between two bins.
Toy frame: a unit sine at bin 16 plus your offset of a 64-sample frame (periodic windows, as SciPy uses). The curve is the same frame zero-padded to 1,024 points. Main lobe width is measured from the first dip on one side to the first dip on the other, in bins of the 64-point DFT; the highest sidelobe is the highest bump beyond those dips. Leakage is read at 8 bins from the tone. All are measured live, in decibels below the tone’s true peak.
Start with the rectangular window and the tone exactly on a bin (offset 0). The dots show one tall spike and nothing else. The tone fits the frame perfectly, so there is no jump and no leakage. Now slide the offset to 0.5. The spike drops, and every dot on both sides lights up, falling slowly: leakage everywhere. Switch to Hann and the same offset gives a wider peak but far lower tails. Switch to Blackman and the tails nearly vanish, while the peak grows wider still.
A real signal is almost never exactly on a bin, so the offset-0.5 view is the honest one. This is also the dots’ second flaw, called scalloping: a tone between bins reads a few decibels weaker than the same tone on a bin. The read-out gives you that number for each window.
Use the numbers as a menu. Rectangular has the narrowest main lobe, so it gives the best resolution, and the worst leakage, with the highest sidelobe only about 13 dB down. Use it when you know the signal fits the frame. Hann is the safe default for audio, with main lobe twice as wide and sidelobes about 31 dB down. Hamming pushes the nearest sidelobes to about 43 dB down by keeping a small edge, a classic for speech. Blackman goes to about 58 dB down, with the widest main lobe: use it when a faint tone sits close to a strong one.
Here is the failure in numbers. The symptom: a faint tone, 40 dB below a loud neighbour, is missing from the picture. The measurement: seen through a rectangular window, the loud tone leaks about −26 dB at 8 bins away, which buries a tone that is 40 dB down. The fix: switch to Blackman, whose leakage at that distance is far below −40 dB, and accept the wider peak.
Chapter 5
Add two close tones, hear them throb, and find the same ripple in the picture
A piano tuner strikes two strings that should sound the same note. If one is a hair off, the sound throbs: wah, wah, wah. The more out of tune, the faster the throb. The tuner turns the peg until the throb slows and stops. The throb is a clue that two tones sit close in pitch. This chapter shows where it comes from, and why the same throb shows up as ripples in a spectrogram.
Slides 14 to 16 build it. Tone one is x1(t) = sin(2π 440 t). Tone two is x2(t) = sin(2π 442 t). Add them. Zoomed in, the sum looks like an ordinary wave of about 441 Hz. Zoomed out, its height swells and fades, slowly. To see why, we need one identity from trigonometry, slide 17.
Why is it true? Write a = u + v and b = u − v. The angle-addition rule gives sin(u + v) = sin u cos v + cos u sin v, and sin(u − v) = sin u cos v − cos u sin v. Add them. The cos u sin v terms cancel and the sin u cos v terms double: sin(u + v) + sin(u − v) = 2 sin u cos v. Now u = (a + b)/2 and v = (a − b)/2, which is the identity.
Put a = 2π 440 t and b = 2π 442 t. The carrier is sin(2π 441 t), the average pitch, 441 Hz. The envelope is 2 cos(2π 1 t), a wave of 1 Hz, half the 2 Hz difference. That is slide 18’s statement: a fast carrier modulated by a slowly varying envelope.
Now count the throbs. The envelope runs from +2 down to −2 and back once per second, so its size peaks twice per second: at 0 s, at 0.5 s, at 1 s. The sign does not matter. A wave multiplied by −1 is the same wave shifted by half a cycle, and the ear cannot tell. The slide says so: two tones with the same frequency and different phase sound identical. So the loudness swells |f1 − f2| times per second, here 2, once every 0.5 s. We call each swell a beat, and the steady pitch you hear is the average, 441 Hz.
Count to see how the rate scales. Over three seconds, tones at 440 and 442 Hz give 6 swells, slow enough to follow with your hand. Tones at 440 and 450 Hz give 30, a flutter. The beat rate is just the gap, so tuning two strings closer together slows the throb until it stops at zero gap.
The ear does not hear 440 and 442 as two pitches. It hears one pitch between them, with a throb. Press Hear it below. Then drag the second tone away and the throb speeds up.
Now the link to the STFT. A window that is short compared with the beat period 1/Δf sees only a sliver of the envelope, so inside it the sum looks like one steady tone near 441 Hz. The spectrogram draws one ridge, and the ridge is bright at each swell and dark in between. That brightness pulse is the ripple of slide 18: the origin of audible beating and visual ripple artifacts in time-frequency representations. A window long enough to resolve the two tones, about 2/Δf by the rule of Chapter 3, sees both, and draws two steady ridges with no ripple.
Top: the sum of a 440 Hz tone and a second tone, with its envelope dashed. Bottom: its spectrogram near 440 Hz. Change the gap, then change the window.
Toy signal: two unit sines, 440 Hz and 440 Hz plus your gap, sampled at 2,048 Hz for three seconds. The spectrogram uses a Hann window, hop of a quarter window, 60 dB of range, and shows 400 to 480 Hz. Beat rate is the gap in hertz. Ridge swing is the ratio of the brightest to the dimmest band power over the middle of the clip, measured live. A pair counts as two ridges when the dip between peaks is 3 dB deep.
Start at a gap of 4 Hz and a window of 60 ms. You see one ridge that flashes four times a second, matching the waveform’s swells above it. Pull the window up to about 500 ms and the ridge splits in two and stops flashing. Set the gap to 10 Hz and the split comes at about 300 ms. Set it to 2 Hz and even 1,000 ms is not enough. The beat period is the time you must wait to see the tones part.
Slide 12 shows a chirp, a tone whose pitch slides: x(t) = sin(400πt²) sampled at 4,000 Hz. Its pitch is 400t Hz, so it climbs from 0 to 400 Hz in one second. With a Hann window the spectrogram is one clean diagonal. With a rectangular window (slide 13) faint diagonal stripes appear on both sides of it, parallel to the ridge. These are sidelobes, Chapter 4’s leakage, following the chirp. They are a different ripple from beating, with a different cure: change the window, not its length.
The same chirp, drawn twice. Hann on top, rectangular below. Raise the dynamic range to dig out the faint stripes.
The deck’s chirp, sin(400πt²) at 4,000 Hz. Window 256 samples, hop 64, FFT size 512. Stray energy is the highest power found 6 or more bins away from the chirp’s own ridge, in any frame between 0.2 s and 0.9 s, in decibels below the ridge’s peak; the ridge position is the known 400t Hz.
At 50 dB the rectangular panel shows clear stripes, and the Hann panel shows far fewer. The read-out puts a number on it. Raise the range to 90 dB and even Hann shows a faint haze. Nothing in the chirp changed. Only the window did.
Here is the failure in numbers. The symptom: a picture full of stripes that look like real signal. The measurement: stripes that run parallel to the ridge and fade with distance are sidelobes, and stripes that make the ridge pulse in time are beats. The fix: for sidelobes, a smoother window; for beats, a longer window, or accept that two tones this close read as one.
Chapter 6
Read each coefficient as a match with a small windowed wave, and use that to predict how shifts move the picture
Imagine a hardware shop with a drawer of tiny tuning forks. You hold the recording near each fork in turn. A fork buzzes loudly if the recording holds its pitch right where you hold it, and stays silent if not. The strength of the buzz is the STFT coefficient for that fork. This chapter says it exactly, and then uses it to predict what happens to the picture when you delay, raise or flip a signal.
Take two lists of numbers of the same length. Multiply them entry by entry and add up. This is the inner product. It is large when the two lists rise and fall together, near zero when one does not care about the other, and it flips sign when one list is the mirror of the other. It is a match score.
Slide 23 says the STFT is a set of such scores. Define the time-frequency atom gm,k[n] = w[n − mR] e+j2πkn/N. It is the spinning arrow for pitch k, cut down to a short stretch around frame m by the window w. (The slide calls the hop R here. It is the same hop as H.) A small wave that lives in one place and one pitch, as the lecture says, a localized sinusoid: a windowed complex exponential.
A tiny check by hand. Take N = 4 and x = [0, 1, 0, −1], a sine at one quarter of the sampling rate. The atom for k = 1 has e+j2πn/4 = [1, j, −1, −j], and its conjugate is [1, −j, −1, j]. Multiply and add: 0·1 + 1·(−j) + 0·(−1) + (−1)·j = −2j. The size is 2. The DFT bin gives the same −2j, because the DFT is this inner product, with a window of all ones.
The set of all atoms, shifted in time by multiples of the hop and in pitch by multiples of the bin spacing, is a Gabor system. The STFT asks, for every atom in turn, “how much of you is in the signal?” Try it by hand below. The third panel adds up the products as you go: a straight climb means the atom and the signal agree, and a wander near zero means they do not.
The signal is the chirp from slide 12, climbing 400 Hz in one second. Slide the atom to a time and a pitch. Top: where the atom sits. Middle: the signal and the atom, zoomed in. Bottom: the running total of the products.
The chirp is sin(400πt²) at 4,000 Hz, so its pitch at time t is 400t Hz. The atom has a 256-sample Hann window (64 ms) and the pitch you chose. The score is the size of the inner product divided by L/4 = 64, the score a unit-height tone that exactly fills the window would earn, so 1.00 means a perfect match. The middle panel draws the real part of the atom.
At the start (0.50 s and 200 Hz) the atom sits exactly on the chirp: the running total climbs steadily and ends near 0.98 of a perfect match. Move the pitch to 300 Hz and the total wanders and ends near zero. Move the time to 0.75 s and the pitch to 300 Hz and it climbs again. The bright ridge of the spectrogram is the set of atoms that match.
Slide 22 lists properties of the sample-shift form Xx[τ, k] = ∑ x[n] g[n − τ] e−j2πkn/N. Each one answers a practical question.
Linearity. The STFT of αx + βy is α times the STFT of x plus β times that of y. Two sounds played together give the sum of their pictures, as far as the complex numbers go. This is why masking in Chapter 9 can pull a voice out of noise.
Time shift. Delay the signal by n0 samples, y[n] = x[n − n0]. Substitute m = n − n0 in the sum. The window moves to τ − n0, and one factor e−j2πkn0/N falls out. So Xy[τ, k] = e−j2πkn0/N Xx[τ − n0, k]. The picture slides right by n0. Each cell keeps its size. Only the angle turns.
Modulation. Multiply the signal by e+j2πk0n/N. That exponential joins the one inside the sum and gives e−j2π(k − k0)n/N. So Xy[τ, k] = Xx[τ, (k − k0) mod N]. The picture slides up by k0 bins, and the “mod N” says it wraps around the top. The DFT is circular.
Real symmetry. For a real signal and a real window, X[τ, N − k] = X[τ, k]*. The sizes mirror, and half of the rows are redundant, which is why Chapter 2 stored N/2 + 1 of them.
Windowing is smoothing. Chapter 4’s fact, and the cause of leakage.
A worked phase factor. Take N = 512 and a delay of n0 = 64 samples. For bin k = 20 the factor is e−j2π·20·64/512 = e−j5π = −1, so that cell flips sign. For k = 16 the factor is e−j4π = 1, so the cell is unchanged. For k = 2 it is e−jπ/2 = −j, a quarter turn. A pitch that completes a whole number of cycles during the delay comes back to where it was; the others turn by the fraction they miss.
One more fact about the atoms. With hop H and N bins there are about Nx/H frames and N bins, so Nx N / H coefficients for Nx samples, a redundancy of N/H. For the setup of Chapter 2 that is 4. The atoms overlap in time and in pitch, so they are not independent: the coefficients carry the same information several times over. That is why Chapter 7 can rebuild the signal, and why an edited table can contradict itself.
Two tone bursts. The dashed boxes mark where they started. Delay the signal, or multiply it by a spinning arrow to lift its pitch. The picture shows all N bins, so you can see the wrap.
Toy signal at 4,000 Hz: a Hann-shaped burst of 250 Hz from 0.1 to 0.3 s and one of 625 Hz from 0.5 to 0.8 s, each a whole bin (bins are 7.8125 Hz). Window 256 samples, hop 64, FFT size 512, so a delay in steps of 64 samples (16 ms) lands on a whole frame. The checks are computed live: sizes are compared cell by cell against the original picture moved by your amounts.
Delay the signal by 320 ms and both bursts slide right by exactly that, with the same brightness. Lift the pitch by 128 bins (1,000 Hz) and both rise, and their mirror images move too. Push the shift past 432 bins and you can watch the higher burst leave the top and re-enter at the bottom. The read-out reports the largest difference between the moved picture and the new one, and it is rounding error: the rules are exact.
One subtlety. The slide measures time from the start of the recording (“absolute” time), so its delayed picture picks up a phase factor. A library measures each frame from its own start. In that convention the delayed picture is a pure copy, with no phase change at all. The sizes, which are all a spectrogram shows, agree in both.
Chapter 7
Invert each frame, add the overlaps, and learn why an edited spectrogram never comes back exactly
You have filmed a long street scene as overlapping snapshots, one every few frames, and each snapshot was faded at its edges, like a vignette. Now you want the film back. If you simply stack the snapshots, the faded edges leave dark seams. You must add the overlaps back so that the fades cancel exactly. This is the inverse STFT, and the trick is called overlap-add.
Every frame was made by a DFT, so every frame can be undone by an inverse DFT. Slide 26 writes it for frame m.
The output of this step is not the original signal. It is the original times the window. The faded snapshot, one per frame, each L numbers long (the FFT size N may be longer, with zeros after L).
Put each rebuilt frame back where it came from, at sample mH, and add the overlaps. The slide’s recipe also multiplies each frame by the window a second time, and divides by the sum of the squared windows.
Here is why it works, in one line. Each frame gives back g[n−mH] · g[n−mH] · x[n]. Add over the frames: x[n] · ∑m g2. Divide by ∑m g2 and x[n] is left alone. So as long as the squared windows add to something above zero, the original comes back, for any hop. Slide 26 states the condition more loosely: a consistency condition, often a constant-sum property for the pair of analysis and synthesis windows. If ∑m g (no square) is a constant, the window is called COLA, for constant overlap-add, and plain adding is enough.
A worked case with a periodic Hann window of L = 8: g = [0, 0.146, 0.5, 0.854, 1, 0.854, 0.5, 0.146]. Use hop H = 4. At the four phases of the hop, g plus the window shifted by 4 gives 0 + 1, 0.146 + 0.854, 0.5 + 0.5 and 0.854 + 0.146. Each is exactly 1, so ∑ g is constant: Hann at 50% overlap is COLA. The squares add to 1, 0.751, 0.5 and 0.751, so ∑ g2 is not constant, and the division in the formula is what keeps the answer exact.
Rebuilding an untouched STFT is easy. The trouble starts when a model edits it. Suppose you zero a band of pitches in every frame. Each frame now claims a slightly different story about the samples it shares with its neighbours. No single signal has exactly that edited STFT: the picture is inconsistent. Overlap-add resolves the quarrel by averaging, and this average is the signal whose STFT is the closest, in the least-squares sense, to the edited one (Griffin and Lim, 1984). Analyse that signal again and the zeroed band is no longer empty.
Run the experiment. The signal is the chirp. The edit cuts the band 150 to 250 Hz in every frame. The panel shows the analysis of what comes back.
Top: shifted windows (purple) and their sums, scaled so that a flat line at 1 means constant. Bottom: the spectrogram of the rebuilt signal. The dashed box is the band that was cut.
The chirp is sin(400πt²) at 4,000 Hz. Window L = 256 (periodic), FFT size 512, centred frames, rebuilt with the slide’s formula and ε = 10−8. Error is the energy of the difference between the original and the rebuilt signal, relative to the original, with no edit. Hole depth is the energy left between 150 and 250 Hz, from 0.4 s to 0.6 s, in the analysis of the rebuilt signal, relative to the original’s.
With the edit off and a hop of L/2, the error is about −157 dB, the rounding error of a computer. The signal comes back exactly. Turn the edit on. The chirp now has a gap where it crosses the band, but the gap is filled in faintly, and the hole depth is only about −20 dB: the rebuilt signal keeps about 1% of the band’s energy. The edit survived only in part. Change the hop and the depth moves by a few decibels, never to minus infinity.
Now set the hop to L. The error jumps to about −19 to −21 dB. With no overlap and a Hann window, a few samples at the window’s edges get weight near zero and cannot be recovered. At the very end, one stretch is never inside any frame. The fix for both is the overlap that the slide’s 50 to 75% heuristic gives.
This is also why a network that edits spectrograms does better when it works through the inverse in training, as Chapter 9 shows. If the loss looks at the final waveform, the network learns to make edits that survive the round trip.
Chapter 8
Follow one second of sound through magnitude, log and mel into the picture a network reads
A radiologist reads an X-ray by eye. Dark patches, bright lines, edges: patterns in a picture. Image networks learned to read such pictures years ago. So when a team wants a network to recognise a spoken word, a bird call or a failing motor, they use a trick. They turn the sound into a picture, and hand the picture to an image network. The STFT is the camera.
Slide 27 writes the chain in one line: x[n] → X[m, k] → |X[m, k]| → log(|X| + ε). Walk it with the setup from slide 25: one second at 16,000 Hz, L = 512, hop 128, N = 512.
waveform (16000,) → STFT (257, 122) complex → magnitude (257, 122) → log (257, 122) → add a channel (1, 257, 122)
Step by step. The STFT turns 16,000 numbers into a 257 by 122 table of complex numbers. The magnitude drops the angles and leaves 31,354 real numbers. The log squeezes the range, as Chapter 2 showed. Then one dummy axis, the channel (a grey picture has one, a colour picture three), makes the table look like a one-channel image. A convolutional network, or a vision transformer that cuts the picture into patches, can now read it.
Why drop the angles? For recognising what a sound is, the sizes carry most of what matters, and the angles are hard for a network to learn. For rebuilding sound they are needed, which is why Chapter 9 keeps them when it edits. Why does an image network suit this picture? A harmonic stripe, a click, a rising chirp: each is a local pattern that means the same wherever it sits. A convolution kernel finds a pattern wherever it sits. Chapter 6 showed the other half of the reason: delay a sound and the picture slides, with its sizes unchanged.
Most pipelines add one more step. Ears do not hear all pitches with equal sharpness. A 50 Hz gap between 100 and 150 Hz is a big musical step. The same 50 Hz gap between 5,000 and 5,050 Hz is nearly inaudible. The mel scale stretches low pitches and squeezes high ones to match. A common form is mel = 2,595 log10(1 + f / 700).
Worked numbers. At 1,000 Hz: 1 + 1,000/700 = 2.4286, log10(2.4286) = 0.3853, and 2,595 × 0.3853 = 1,000 mel. The formula is built to give 1,000 mel at 1,000 Hz. At 4,000 Hz: 1 + 5.714 = 6.714, log10 = 0.8270, so 2,146 mel. At 8,000 Hz: 12.43, log10 = 1.0945, so 2,840 mel. The upper half of a 16 kHz recording, 4,000 to 8,000 Hz, takes only 694 of the 2,840 mel.
A mel filter bank lays triangles evenly in mel, so they are narrow at low pitch and wide at high pitch. Each triangle averages the power of the bins under it. Written as a matrix, the bank has one row per triangle and one column per STFT bin. With 40 triangles, a (40 × 257) matrix times the (257 × 122) power table gives a (40 × 122) table. That is the slide’s chain: |X|² → mel filter bank → M[m, ℓ] → log(M + ε).
The slide gives three reasons. The filters average energy across bands, roughly as the ear does. They cut 257 rows to 40, which saves memory and compute. And they de-emphasise the very fine harmonic structure, the thin stripes of a voice, so a model keys on the broad shape that tells one vowel from another. The slide defers the theory of these filters to the linear-systems lecture; that lesson and the cepstrum and MFCC lesson carry it on. Its own summary is the best one: a linear filter bank, a downsample in frequency, and log compression.
Pick a stage of the pipeline. The picture is what a network would receive. For the log stages, drag the floor ε and watch the faint detail appear and vanish.
The voice-like sound is synthetic: a buzz gliding from 120 to 170 Hz through two resonances for 0.7 s, then a burst of hiss from 0.8 to 1.15 s, at 8,000 Hz. Window 256 samples (32 ms), Hann, hop 80 (10 ms), FFT size 256. The mel bank has 32 triangles from 0 to 4,000 Hz with the formula above; each band is drawn at its own pitch range, so you can see the warp. The floor ε is added to the power relative to the brightest cell before the logarithm.
Set the stage to Magnitude. You see the vowel’s bright bands near its two resonances and only a faint smudge of hiss. Switch to Power and the vowel gets brighter while the hiss fades almost to nothing: squaring widens the gap between loud and quiet. Switch to Log power and the hiss lights up, and the harmonic stripes of the buzz show clearly. Now pull ε up to 10−2. The hiss disappears under the floor and the dark valleys between the stripes turn flat. At 10−1 only the strongest stripes of the vowel remain. The floor decides how deep the picture looks.
Switch to Log-mel. The 129 rows of the STFT have become 32. The bands are thin at the bottom, fat at the top, and the stripes of the buzz blur into the vowel’s broad shape. That is the slide’s “de-emphasise fine structure” made visible.
Slide 34 makes the point that nothing here is about speech. Any signal that is locally sinusoidal can go through the same camera. The slide lists vibration and machinery fault detection (bearing faults, motor monitoring), ECG and EEG patterns, radar and sonar micro-Doppler signatures, and seismic events. Once the map exists, the whole vision toolbox opens: CNNs, ViTs, U-Nets.
The only new decision is the window. Take a motor sampled at 10,000 Hz (illustrative). A window of 1,024 samples looks at 102 ms and resolves about 2 × 10,000 / 1,024 = 20 Hz. That resolves the motor’s running harmonics if they are 50 Hz apart. A bearing fault that taps twice per revolution shows as vertical streaks, the way a click does, and needs a shorter window to place each tap. Chapter 3’s trade shows up in every field.
Chapter 9
Treat the STFT as a matrix a gradient can pass through, then mask it, hide parts of it and clean a noisy voice
A sound engineer cleans a noisy recording at a mixing desk. She does not push and pull the raw wave. She looks at the spectrogram, sees the hiss as a haze in the high rows, and turns those rows down. A neural network can do the same job. It looks at the STFT, decides how much to turn down each cell, and the result goes back through the inverse of Chapter 7. For that to be trainable, the whole path has to let a gradient through.
Slide 29 makes the plain point: the STFT is linear, so X = A x for a suitable matrix A. Each row of A is one atom from Chapter 6, a windowed spinning arrow, so row (m, k) multiplied by the signal gives cell X[m, k]. For the slide-25 setup, A has 31,354 complex rows and 16,000 columns, a matrix of half a billion entries. Nobody builds it. The FFT applies it quickly.
A matrix is the friendliest thing a training loop can meet. If a loss depends on X, its gradient with respect to the signal is the conjugate transpose of A applied to the gradient with respect to X. That transpose is, up to the window, the overlap-add of Chapter 7. So “backpropagate through the STFT” costs one inverse STFT. Deep learning frameworks, such as PyTorch and JAX, have this built in, which is what the slide means by you can backpropagate through the feature extractor. It is used, as the slide says, in speech enhancement, audio generation and self-supervised learning.
To train a model that makes audio, you must score how close its output x̂ is to a target x. The obvious score compares the waves sample by sample. It has a flaw. Delay a 500 Hz tone by one millisecond, half a cycle, and the new wave is the opposite of the old. The sample-by-sample error is as large as it can be. The ear hears the same tone. Chapter 6 told us what the STFT does with a delay: it moves the picture and keeps the sizes. So compare the sizes instead. Slide 30 gives two such losses.
The slide adds one more idea: a multi-resolution STFT loss, the sum of such losses over several settings of N and the hop. By Chapter 3, a long window judges pitch and a short one judges timing. Summing several keeps the model honest at every scale. (Parallel WaveGAN, a speech-synthesis model, uses this form of loss.) Try the scores below. A delay should hurt the waveform score much more than the spectrogram score. Noise should hurt the log score most.
In practice, at 16,000 Hz, a typical set is windows of 64, 256 and 1,024 samples, which look at 4 ms, 16 ms and 64 ms, each with a hop of a quarter window. The 4 ms view catches clicks and the exact moment of an onset. The 64 ms view checks that the pitch and the harmonics are right. The 16 ms view sits between them. A model that satisfies all three has the right timing and the right pitch.
The copy is the original after an error you choose. The bars show three scores, and shorter is better. Switch the error, the window used by the spectrogram scores, and the amount.
The original is the synthetic voice-like sound from the last chapter, 1.2 s at 8,000 Hz. Waveform error is the rms of the difference as a share of the rms of the original (100% means the error is as big as the signal). Size error is the sum of gaps between STFT sizes as a share of the sum of the original’s sizes (Lmag as a share). Log error is the mean gap between 20 log10(size + 10−4) values, in dB, against a full scale of 30 dB. Hann window, hop L/4. The noise is white and seeded, set relative to the whole original.
With a delay of 0.5 ms and the middle window, the waveform error is already 173% of the signal, bigger than the signal itself, while the size error is about 1%. Raise the delay to 3 ms and the waveform error stays above 100%. The spectrogram scores barely move at L = 256 and L = 1,024. At L = 64 they jump, because an 8 ms window is short enough for a 3 ms delay to matter, which is Chapter 3 again. Now switch to noise. At −30 dB the waveform error is only 3% and the size error about 5%, but the log score shows a gap of about 9 dB, because the silent stretches now hold noise. One loss is not enough for every job.
Slide 31 turns the spectrogram into a place to train more robustly. Augmentation means making the training set bigger by changing each example in ways that should not change its answer. For spectrograms the lecture gives two cheap moves. A frequency mask zeroes (or fills with the mean) a random band of rows. A time mask zeroes a random span of frames. The intuition is invariance: a model that has seen words with a band or a moment missing cannot lean on any one stripe, so it learns to use the rest. This is SpecAugment (Park et al., 2019).
Set how wide each mask is, choose how it is filled, and press Draw new masks for fresh random positions.
The picture is the log power of the synthetic voice-like sound, 129 rows by 121 frames (window 256, hop 80, FFT size 256, 70 dB of range). Mask positions are random each time you press the button. Zero means the lowest brightness, which is how a log picture shows silence; mean means the average brightness of the whole picture.
At 14 rows and 18 frames, the two masks hide about a quarter of the cells between them, yet the vowel is still easy to read from the cells that remain. That is the point of the augmentation. A network that must recognise the vowel from this picture has to use more than one place for it.
Slide 32 shows the last and most popular use. Take a mixture y = x + v, a clean voice x plus noise v. Compute Y = STFT(y). A network predicts a mask M[m, k], one number per cell, and the cleaned STFT is the product cell by cell, X̂ = M ⊙ Y. The inverse STFT turns it back into a waveform, x̂ = iSTFT(X̂).
The slide separates two kinds of mask. A magnitude mask, with M between 0 and 1, can only turn cells down. It keeps the noisy phase of the mixture, so it ignores phase updates. A complex mask can change both size and angle, so it can correct the phase too. A real network predicts M. To see what the best possible mask could do, we use an oracle: a mask computed from the true voice and noise, which a real network can only approximate.
Top: the noisy mixture. Bottom: the signal after the mask and the inverse STFT. Choose the noise level and the kind of oracle mask.
Voice-like sound plus seeded white noise, 8,000 Hz, 1.2 s. STFT window 256, hop 64, FFT size 256, Hann; the inverse is Chapter 7’s overlap-add. The masks are oracles built from the true voice S and noise V: magnitude |S| / (|S| + |V|); binary 1 where |S| > |V| and 0 elsewhere; complex S / Y. A trained network only approximates them. Signal-to-noise is 10 log10 of the voice energy over the energy of the error.
Start at 5 dB with no mask: the output is the mixture, and the signal-to-noise stays at 5 dB. Choose the magnitude mask. The haze between the stripes fades and the number climbs by about 8 dB, to 12.9. The binary mask, all or nothing, does slightly better here, 14 dB, because it removes the noise completely wherever the voice is weaker. Now choose the complex mask. The result is the clean voice to rounding error, because the mask corrects the phase as well. The gap between the magnitude row and the complex row is the value of the phase that Chapter 8 dropped. (The oracle knows the true voice. A trained network can only come close.)
Chapter 10
Keep the numbers, the checklist and the core code, and see where to go next
The DFT answers “which pitches?” but not “when?”. The STFT answers both by taking a short window of the signal, multiplying, taking a DFT, and sliding on by a hop. The result is a table of complex numbers, one per frame and pitch bin, drawn as a spectrogram. A window of L samples gives about L/fs seconds of time resolution and about 2 fs/L hertz of pitch resolution with a Hann window, so no window is sharp in both. The window’s shape decides how much energy leaks. Overlap-add rebuilds the signal from an untouched table, and gives only the closest consistent signal from an edited one. Because the STFT is linear and differentiable, networks read its log magnitude as an image, train through it with spectral losses, hide parts of it, and cut noise with masks.
| Quantity | Rule | Worked value |
|---|---|---|
| Window time span | Δt ≈ L / fs | L = 512 at 16,000 Hz: 32 ms |
| Bin spacing | Δf = fs / N | N = 512 at 16,000 Hz: 31.25 Hz |
| Pitch resolution | about 2 fs / L (Hann), fs / L (rectangular) | L = 512: about 62.5 Hz with Hann |
| Frames | M = ⌊(Nx − L) / H⌋ + 1 | 1 s, L = 512, H = 128: 122 |
| Bins kept for a real signal | N / 2 + 1 | N = 512: 257 |
| Cell to seconds and hertz | tm = mH / fs, fk = k fs / N | m = 50, k = 20: 0.4 s, 625 Hz |
| Overlap | 1 − H / L | H = L/4: 75% |
| Cost | M FFTs, O(M N log N) | 122 FFTs of 512 points per second of audio |
| Decibels | 10 log10(S + ε) | 10 times the power: +10 dB |
| Window: rectangular | main lobe 2 bins wide | highest sidelobe about 13 dB down |
| Window: Hann | main lobe 4 bins wide | about 31 dB down |
| Window: Hamming | main lobe 4 bins wide | about 43 dB down |
| Window: Blackman | main lobe 6 bins wide | about 58 dB down |
| Beat rate | |f1 − f2| per second | 440 and 442 Hz: 2 per second |
| Speech heuristic | L about 20 to 40 ms, overlap 50% to 75% | L = 512 at 16 kHz is 32 ms |
| Mel scale | 2,595 log10(1 + f / 700) | 1,000 Hz is 1,000 mel |
Everything the devices on this page do fits in three short functions. The first two are slides 24 and 26. The third is slide 28.
pythonimport numpy as np def stft(x, L=512, H=128, N=512, window=None): window = np.hanning(L + 1)[:-1] if window is None else window # periodic Hann M = 1 + -(-len(x) // H) # frames, each centred on m*H pad = np.pad(x, (L // 2, L // 2 + H)) X = np.empty((N // 2 + 1, M), complex) # (N/2+1, M) for m in range(M): X[:, m] = np.fft.rfft(pad[m*H : m*H + L] * window, n=N) # cut, window, pad, FFT return X def istft(X, L=512, H=128, N=512, window=None, length=None): window = np.hanning(L + 1)[:-1] if window is None else window M = X.shape[1] out = np.zeros(L + H * (M - 1)); den = np.zeros_like(out) for m in range(M): out[m*H : m*H + L] += window * np.fft.irfft(X[:, m], n=N)[:L] # window again, add den[m*H : m*H + L] += window ** 2 out /= den + 1e-8 # divide by the summed g^2 return out[L // 2 : L // 2 + length] def log_mel(S_pow, fs, N=512, n_mels=40, eps=1e-10): mel = lambda f: 2595 * np.log10(1 + f / 700) imel = lambda m: 700 * (10 ** (m / 2595) - 1) edges = imel(np.linspace(0, mel(fs / 2), n_mels + 2)) f = np.arange(N // 2 + 1) * fs / N fb = np.zeros((n_mels, len(f))) # (40, 257) triangles for i in range(n_mels): a, b, c = edges[i:i + 3] fb[i] = np.clip(np.minimum((f - a) / (b - a), (c - f) / (c - b)), 0, None) return np.log(fb @ S_pow + eps) # (40, M) x = np.random.randn(16000) # one second at 16 kHz X = stft(x) # (257, 126), complex y = istft(X, length=len(x)) # back to (16000,), error about 1e-8 F = log_mel(np.abs(X) ** 2, 16000) # (40, 126), what a CNN reads
This version pads so that frame m is centred on sample mH, which gives 126 frames for one second (library defaults differ by a frame or two, as Chapter 2 noted). The error after the round trip is about 10−8, the ε in the denominator, so the rebuild is exact to that size.
Slide 33 lists the places the STFT shows up whenever a signal is locally sinusoidal. Audio classification (keyword spotting, acoustic scenes, music tagging) runs a log-mel spectrogram through a CNN or a transformer. Speech recognition adds SpecAugment and a sequence model. Enhancement and separation predict a mask and invert, as in Chapter 9. Audio generation, vocoders and diffusion models, often work on mel features and train with STFT losses. Multi-microphone audio uses phase differences between channels, which Chapter 6’s time-shift rule explains: a delay τ between two microphones turns the phase of bin k by 2π fk τ. With the microphones 10 cm apart and sound travelling at 343 m/s, the largest delay is 0.1 / 343 = 0.29 ms, so a 1,000 Hz bin turns by up to 2π × 1,000 × 0.00029 = 1.83 radians. Compare phases across bins and you can steer a beam. Slide 34 carries the idea past sound, to machinery vibration, ECG and EEG, radar and sonar, and seismic events.
This lesson follows Lecture 3 Part II of Stanford EE269, Signal Processing and Quantization for Machine Learning, taught by Mert Pilanci. The course site and the slides page hold the original. The window comparison on slide 11 credits Meinard Müller and Frank Zalkow (audiolabs-erlangen.de); our version is drawn live from the formulas. The slide’s reference list (spectral descriptors, speech and music features) belongs to Lecture 7. Other facts used here: sidelobe and main-lobe values from F. J. Harris, “On the use of windows for harmonic analysis with the discrete Fourier transform”, Proceedings of the IEEE, 1978; the least-squares inverse from D. W. Griffin and J. S. Lim, “Signal estimation from modified short-time Fourier transform”, IEEE Transactions on Acoustics, Speech, and Signal Processing, 1984; SpecAugment from D. S. Park et al., 2019 (arXiv:1904.08779); the multi-resolution STFT loss in Parallel WaveGAN, R. Yamamoto et al., 2020 (arXiv:1910.11480). Every toy signal on this page is labelled as ours in its fine print.
Now press Present or Teach and explain, from memory, why a window of 64 ms resolves two tones 50 Hz apart that a window of 16 ms cannot, and what the 16 ms window gives you instead. Then go back to the window at the top, set it to 200 samples on the tones and spikes, and explain why both pairs show.