One frame of sound has 257 spectrum bins. A few numbers computed from them, such as brightness, width and disorder, tell a flute from a vowel from a hi-hat.
Learn to treat a spectrum as a probability distribution over frequency, then measure its balance point, width, tails, disorder and change over time.
Pick a sound, then drag Noise added and watch the four numbers move. Then we build every number from zero: the centroid, the spread, the kurtosis, the entropy and the flux.
You need the DFT (the tool that splits a sound into its frequencies, taught in Lecture 6) and the mean and variance of a list of numbers. We build the rest from zero.
Based on Lecture 3 Part II of Stanford EE269: Signal Processing and Quantization for Machine Learning, taught by Mert Pilanci. Lecture slides · All course slides.
Synthesised sounds, sampled at 8,000 Hz, one 512-sample frame with a Hann window. The flute is four harmonics of 440 Hz, the vowel is a 120 Hz buzz shaped by three formants (illustrative values near 730, 1,090 and 2,440 Hz), the hi-hat is high-passed noise. Spectrum bars show magnitude; the four numbers use power, as Chapter 1 explains.
Chapter 0
See why a spectrum is too big to compare, and turn it into a distribution you can measure
Imagine a music app with ten million songs. It must build a playlist called “bright and fast” without a person listening to each song. The computer cannot hear. It can only read numbers. So which numbers should it read?
This lecture answers that question for sound. First we need two small tools. If you know them already, skim the next three sections.
A frame is a short slice of sound. A microphone gives us samples, one air-pressure reading each, many times a second. We take 8,000 per second. A frame of 512 samples then lasts 64 milliseconds.
The DFT (discrete Fourier transform, from Lecture 6) splits that frame into bins. A bin is one frequency bucket. A 512-sample frame gives 257 bins, numbered k = 0 to 256.
Bin k sits at the frequency fk = k × 8,000 / 512 = k × 15.625 Hz. So bin 28 sits at 437.5 Hz, close to a flute’s A at 440 Hz. Each bin holds a complex number X[k]. Its magnitude |X[k]| says how much of that frequency is in the frame. Its power |X[k]|² is the magnitude squared.
Take a list of numbers. Its mean is the balance point: lay the numbers on a see-saw and the mean is where it sits level. Its standard deviation is the typical distance from that point.
A small standard deviation means the numbers huddle together. A large one means they scatter. We will use both ideas on frequencies instead of on data. Hold that thought.
One frame gives 257 numbers. One second of sound, cut into frames that start every 256 samples, gives 31 frames, so about 8,000 numbers. A three-minute song gives about 1.4 million.
That is too much to compare by eye or by rule. Two recordings of the same flute differ in every bin, because of small amounts of noise. We want a few numbers that stay put when the flute stays a flute.
Here is the move. Divide each bin by the total of all bins. The new values are shares. Each share is between 0 and 1, and together they add up to 1.
That is what a probability distribution looks like. The “random variable” is frequency. Drop a pin on the sound’s energy at random, and ask how high in pitch the spot is. The shares tell you the odds for each bin.
Try it on one frame of a vowel. Switch between magnitude and power. Then turn Normalise off and drag the loudness.
Bars show one frame of the vowel “ah”. Choose how loud each bin counts. With Normalise on, the bars are shares of the total. With it off, they are raw values, and loudness moves them.
Illustrative: a synthesised vowel frame (512 samples at 8,000 Hz, Hann window). Raw bars use a fixed scale, so you can see them grow and clip; share bars use a scale fixed to the power version’s biggest share, so magnitude looks flatter than power.
Two things stand out. First, power makes the tall bins taller and the short ones tiny. Magnitude is gentler. Second, with Normalise on, the loudness slider changes nothing. Every bin grows by the same factor, and the division cancels it.
So a whisper and a shout of the same vowel give the same shares. That is what we want from a description of what kind of sound it is. (Chapter 8 shows a case where loudness does matter.)
Now we can ask the spectrum the usual questions of a distribution. Where is its middle? That is the centroid (Chapter 1). How wide is it? That is the spread (Chapter 3). How heavy are its tails? That is the kurtosis (Chapters 4 and 5). How disordered is it? That is the entropy (Chapters 6 and 7).
Across frames we can ask one more question: how fast does the spectrum change? That is the flux (Chapter 8). The lecture’s list also names skewness, flatness, crest and slope. Chapter 9 covers those.
Every formula in the lecture carries the band edges b1 and b2. They mean: use only bins b1 to b2. Telephone speech, for example, lives between about 300 and 3,400 Hz, so a speech feature may ignore the rest.
The lecture lists six uses. Each one is a classifier (a program that sorts inputs into labels) that reads a handful of descriptors per frame.
Chapter 9 builds a tiny classifier of this kind from the numbers in this lesson.
Chapter 1
Compute the balance point of a spectrum, and see why power and magnitude give different answers
Rest a ruler across your finger. Hang a heavy coin at the 10 cm mark and a light one at the 20 cm mark. Slide your finger until the ruler sits level. Your finger is now near the heavy coin, but pulled a little toward the light one.
A spectrum works the same way. The bins are positions along the ruler, in hertz. The shares from Chapter 0 are the weights of the coins. The spot where the ruler balances is the spectral centroid. The lecture calls it the “center of gravity” of the spectrum.
To find a balance point, multiply each position by its weight, add the results, and divide by the total weight. Here is that recipe for a spectrum.
Here fk is the frequency of bin k in hertz, and sk is the spectral value at bin k. The lecture says the magnitude |X[k]| and the power |X[k]|² are both common choices. The band edges b1 and b2 pick the stretch of bins to include.
Use a tiny spectrum. Let N = 8 samples at 8,000 Hz. The bins sit at k × 1,000 Hz, for k = 0 to 4. So they are at 0, 1,000, 2,000, 3,000 and 4,000 Hz.
Say the power is [0, 4, 1, 0, 0]. The total is 5. The shares are [0, 0.8, 0.2, 0, 0]. Now multiply and add.
μ1 = 1,000 × 0.8 + 2,000 × 0.2 = 800 + 400 = 1,200 Hz
The ruler balances at 1,200 Hz. The big bin at 1,000 Hz holds most of the weight. The small bin at 2,000 Hz tugs the balance point upward by 200 Hz.
Now use the magnitude instead. A power of 4 is a magnitude of 2, and a power of 1 is a magnitude of 1. The total is 3. The shares are 2/3 and 1/3.
μ1 = 1,000 × 2/3 + 2,000 × 1/3 = 667 + 667 = 1,333 Hz
Same sound, two answers: 1,200 Hz and 1,333 Hz. Squaring makes the loud bin count for four times the quiet one instead of twice. So power weighting hugs the loudest peak. Magnitude weighting lets quieter bins pull harder.
Now build your own. Drag across the bars to draw a spectrum. The warm triangle is the fulcrum.
Drag across the bars to set their heights (they show magnitude). The filled triangle is the centroid. The hollow one is the other weighting. Move the band edges to ignore bins.
Toy spectra on a grid of 33 bins, 125 Hz apart (so 8,000 Hz sampling). The Worked example preset is the example above: magnitudes 2 and 1 at 1,000 and 2,000 Hz.
Try the Flat preset. Every bin has the same weight, so the ruler balances in the middle: 2,000 Hz. That is a quarter of the sampling rate, and it is where white noise lands. Try Dark and Bright to feel why the lecture says the centroid “indicates brightness”.
As data flow, the centroid is a short pipeline. In: one frame of 512 samples, shape (512,). Multiply by a Hann window, a smooth fade at both ends: still (512,). Take the real DFT, which gives 257 complex numbers, (257,). Square the magnitudes to get power, (257,). Build the frequency axis fk = k × 15.625 Hz, also (257,). Out: one number, in hertz.
The answer is in hertz, so it does not depend on the frame length. It does depend on the band. Flat noise always balances at the middle of the band: 2,000 Hz for a band of 0 to 4,000 Hz, and 4,000 Hz if you record at 16,000 Hz sampling. Compare centroids only between recordings made over the same band.
Here is a failure you will meet. You record a flute and compute its centroid. In a quiet room it reads 520 Hz. Now a fan hums at 50 Hz in the background, as loud as the flute’s main note. The centroid reads 305 Hz. The flute did not change. The hum pulled the ruler down.
This is the symptom. The measurement is the centroid itself. It reads 520 Hz without the hum. With a hum at half the flute’s amplitude it reads 438 Hz. At equal amplitude it reads 305 Hz, and at twice that, 157 Hz. All of these come from the synthetic flute in this lesson.
The fix is the band edge. Set b1 to 100 Hz, so the hum falls outside the band. The centroid returns to 520 Hz, whatever the hum’s loudness. This is why every formula in the lecture carries b1 and b2: they let you say which frequencies you trust.
Chapter 2
Slide a window along a drum loop and watch the centroid jump when the hi-hat hits
A drummer plays a simple loop. The kick drum thumps low. The snare cracks in the middle. The hi-hat ticks high and thin. Your ear hears all three as different brightness. Can one number follow that brightness as the music plays?
The lecture says yes. Its slide shows a drum track and, below it, a centroid curve that jumps at the hi-hat hits. The centroid “indicates brightness”, and the lecture adds that it is commonly used in music analysis and genre classification.
A single spectrum describes one instant. A song lasts minutes. So we cut the signal into short frames, compute one spectrum per frame, and get one centroid per frame. The centroids, in order, form a curve over time.
Two choices define the cut. The frame length is how many samples each frame holds. The hop is how far the window moves between frames. We use 256 samples (32 ms) and a hop of 128 samples (16 ms). So each frame overlaps the last by half.
Two seconds of sound at 8,000 samples per second is 16,000 samples. With these choices that gives 124 frames. The method has a name: the short-time Fourier transform, or STFT. Lecture 8 studies it in depth.
The choice has a cost. A short frame follows quick changes but blurs the frequencies: 256 samples give bins 31.25 Hz apart, twice as coarse as the 512-sample frames of Chapter 0. A long frame does the reverse. There is no free setting.
A spectrogram draws all the frames at once. Time runs left to right. Frequency runs bottom to top. Brightness shows power. Our loop has four kicks, two snares and eight hi-hats in two seconds. They are synthesised from seeded noise and tones, so you hear the same loop every visit.
Top: the spectrogram. Bottom: the centroid of each 32 ms frame. Switch instruments on and off, press Hear it, or drag across the picture to read one frame.
Synthesised loop, 8,000 Hz sampling, 256-sample Hann frames, hop 128, power weights. Kick: a sine that falls from about 140 to 50 Hz. Snare: noise plus a 190 Hz tone. Hi-hat: high-passed noise. A faint noise floor sits under everything, as in a real room. Brightness on the spectrogram is a 60 dB range below the loudest bin.
With only the kick on, the centroid sits near 80 Hz and falls back after each thump. Add the snare: its frames rise to about 1,600 Hz. Add the hi-hat: its frames jump to between 2,400 and 2,950 Hz. Those jumps are the ones on the lecture’s slide.
The centroid does not hear a note. It hears where the weight sits. A hi-hat has no pitch at all, yet its centroid is steady and high. That is why one number can follow brightness through a whole track.
At a drum hit a frame often holds two sounds at once: the tail of a loud kick and the start of a quiet hat. What centroid does that frame report? For independent sounds, power adds when they mix, so the shares add too. The centroid of the mix is then the power-weighted average of the parts.
centroid of the mix = (P1 c1 + P2 c2) / (P1 + P2)
Try it. A 78 Hz thump with nine times the power of a hi-hat whose centroid is 2,776 Hz gives (9 × 78 + 1 × 2,776) / 10 = 348 Hz. We measured 348 Hz on a synthetic mix of those two. The centroid follows the loud sound. A quiet hat over a loud kick lifts it only a little.
Cost matters too. A hop of 128 samples gives 3,750 frames for each minute of sound. A hop of 256 halves that, and blurs the timing of each jump by 16 ms more.
Look at the centroid curve with the hi-hat off and the gate off. Between some kicks the signal falls to the room’s noise floor. The centroid there jumps around, up to about 2,000 Hz, as if a bright sound had started. Nothing is playing.
The measurement explains it. Those frames carry about 49 dB less power than the loudest frame. Only the noise floor is left, and a noise floor is flat, so its balance point is the middle of the band. The centroid of nothing is the centroid of noise.
The fix is a gate. Skip any frame more than 40 dB below the loudest. Press Ignore quiet frames. The invented jumps vanish, and the grey bands show which frames you chose not to describe. Real systems use the same trick: a descriptor of silence is meaningless, so they leave it out.
For a reference, the lecture’s list of readings includes Grey and Gordon (1978), “Perceptual Effects of Spectral Modifications on Musical Timbres”. It studies how changing a spectrum changes the timbre of a note, which is the idea behind using the centroid as a brightness number.
Chapter 3
Measure the width of a spectrum around its centroid, and see why it never quite reaches zero
A flute plays one clean note. A gust of wind blows across a microphone. Both can have a centroid near 2,000 Hz. Yet the flute sounds like a thread, and the wind sounds like a cloud. The centroid says where the sound sits. It does not say how wide it is.
The lecture adds a second number for width: the spectral spread. It is the standard deviation of the spectrum around the centroid, and the lecture says it represents the “instantaneous bandwidth”. Bandwidth means the range of frequencies a sound covers.
Chapter 0 said a standard deviation is the typical distance from the balance point. Here is how to compute that, one step at a time.
Take Chapter 1’s spectrum: shares [0, 0.8, 0.2, 0, 0] at 0, 1,000, 2,000, 3,000 and 4,000 Hz. The centroid was 1,200 Hz. Only two bins have weight.
variance = (1,000 − 1,200)2 × 0.8 + (2,000 − 1,200)2 × 0.2 = 32,000 + 128,000 = 160,000
μ2 = √160,000 = 400 Hz
The little bin at 2,000 Hz carries only 0.2 of the weight, but it sits 800 Hz away. Its squared distance, 640,000, makes it responsible for four fifths of the variance. Far bins matter a lot.
There is a shortcut for two bins. If two frequencies are a distance d apart and the louder one has share p, the spread is d × √(p(1 − p)). Check it: d = 1,000 and p = 0.8 give 1,000 × 0.4 = 400 Hz. The shortcut shows that spread peaks at equal shares: p = 0.5 gives d × 0.5.
There is a second way to compute the same number, and code often uses it. The variance equals the average of f squared minus the centroid squared. Check it: 1,0002 × 0.8 + 2,0002 × 0.2 = 1,600,000, and 1,2002 = 1,440,000. The difference is 160,000, as before. It needs only one pass over the bins. The cost is that it subtracts two large numbers, which can lose digits.
A perfect pure tone puts all its weight in one bin, so its spread is 0. White noise spreads weight evenly from 0 to half the sampling rate. Its spread is (fs/2)/√12, which is fs/(4√3). At 8,000 Hz sampling that is 1,155 Hz. Measured on one noisy frame it comes out near 1,180 Hz.
So every real sound lives between those two. Now play with it. A fixed tone sits at 1,000 Hz. Slide a second tone across it.
Top: the spectrum of two tones, the purple band is one spread either side of the centroid. Bottom: spread against the second tone’s frequency. Drag the frequency, or press Sweep.
Two synthesised sine tones, a 512-sample Hann frame at 8,000 Hz, power weights. Loudness is the second tone’s amplitude as a percentage of the first. The sweep passes through the fixed tone, so the curve dips there. The lecture’s own example (slide 9) shows a spread curve with a V shape against time for a sweeping signal.
Slide the second tone onto the first. The spread falls toward zero, but the curve bottoms out near 9 Hz, not 0. That small floor is not the sound. It is the window.
We multiply each frame by a smooth window before the DFT. A window turns a perfect tone into a tiny hill about four bins wide, because the frame has a start and an end. The hill is the leakage, and its width is about 9 Hz at 512 samples. A 256-sample frame gives 18 Hz, and a 1,024-sample frame gives 4.5 Hz. Longer frames leak less. Every spread you measure includes this floor.
Here is a failure. You measure the flute of Chapter 1. Its spread is 201 Hz. Now a faint whistle at 3,500 Hz joins, only 10% as loud in amplitude, which is 20 dB down. You can barely hear it. The spread jumps to 338 Hz.
The measurement shows why. The whistle holds only 1% of the power, but it sits about 3,000 Hz from the centroid. Squared, that is 9,000,000, and 1% of that is 90,000, more than twice the flute’s own variance of about 40,000.
The fix is a band edge. Set b2 to 3,000 Hz and the spread returns to 200 Hz. The lesson: squared distance makes the spread sensitive to faint, far-away sound. Choose your band before you trust the number.
Chapter 4
Use the fourth moment to ask whether a distribution has more extreme values than a bell curve
Picture two seas. In the first, every wave is about one metre high. In the second, most waves are small, but once a day a freak wave of ten metres rolls in. Both seas can have the same average wave size. A sailor still cares which one she is on.
The kurtosis is the number that tells those seas apart. It measures how often extreme values happen. The lecture puts it this way: kurtosis tells you whether large deviations happen more often or less often than in a Gaussian (a bell curve) with the same variance.
Chapters 1 and 3 used two moments. A moment is an average of a power of the distance from a point. The first power gives the mean (the centroid). The second gives the variance (the spread, squared). The ladder goes on.
The third power gives skewness, which says whether the long tail points left or right. The lecture lists it on its slide of descriptors. The fourth power gives kurtosis. Raising the distance to the fourth power makes a far value count enormously: ten times farther counts ten thousand times more.
Why divide by the spread to the fourth power? Stretch every distance by 2. The top grows by 16 and so does the bottom. The ratio does not move. Kurtosis ignores scale and reads the shape alone.
Slide 11 works kurtosis on plain lists. For a list x with mean zero, divide the average of x to the fourth by the square of the average of x squared. Take the spiky list first.
x = (0, 0, 0, 0, 0, 0, 10, −10)
mean of x² = (100 + 100) / 8 = 25 mean of x⁴ = (10,000 + 10,000) / 8 = 2,500
kurtosis = 2,500 / 25² = 2,500 / 625 = 4
A rare pair of big values lifts the kurtosis above 3. Now the bounded list, where every value has the same size.
x = (−1, −1, −1, −1, 1, 1, 1, 1) mean of x² = 1 mean of x⁴ = 1 kurtosis = 1 / 1² = 1
Nothing here is extreme, so the kurtosis falls below 3. In fact 1 is the lowest value kurtosis can take. A Gaussian sits in between at exactly 3. That is the lecture’s reference point.
Now try your own list. Drag the eight bars. The first two presets are the lecture’s.
Drag the bars up and down to set eight numbers from −10 to 10. The pink line shows 3, the value for a Gaussian. Try the offset slider with Centre first on and off.
The Spiky and Bounded presets are the lecture’s two examples. Bell-like is eight numbers drawn from a seeded Gaussian, so a short list can land far from 3. Bars are clamped to the range −10 to 10.
Skewness uses the cube of the distance, so the sign survives. A long tail on the right gives a positive number. A long tail on the left gives a negative one. The recipe divides by the spread cubed.
(−200)³ × 0.8 + (800)³ × 0.2 = −6.4 × 10⁶ + 1.024 × 10⁸ = 9.6 × 10⁷, and 9.6 × 10⁷ / 400³ = 1.5
The skewness of our usual spectrum is 1.5: the small bin at 2,000 Hz is a long tail pointing right. A symmetric spectrum gives 0. Many programs report excess kurtosis, which is the kurtosis minus 3, so a Gaussian scores 0. The lecture uses the plain version, where a Gaussian scores 3.
For a spectrum the list becomes a distribution over frequency, and the centroid plays the part of the mean. Take our usual example: shares [0, 0.8, 0.2] at 0, 1,000 and 2,000 Hz, centroid 1,200 Hz, spread 400 Hz.
(−200)⁴ × 0.8 + (800)⁴ × 0.2 = 1.28 × 10⁹ + 8.19 × 10¹⁰ = 8.32 × 10¹⁰
kurtosis = 8.32 × 10¹⁰ / 400⁴ = 8.32 × 10¹⁰ / 2.56 × 10¹⁰ = 3.25
In the lesson’s sounds, the flute frame has kurtosis 13.1, because most of the weight sits in a few sharp peaks. White noise comes out at 1.8, the exact value for a flat spectrum. Two equal spikes give 1.
Here is a failure. The slide’s list formula assumes a mean of zero. Take the spiky list and add 10 to every number: (10, 10, 10, 10, 10, 10, 20, 0). Its shape is the same. Applied naively, the slide’s formula gives 27,500 / 125² = 1.76. The true answer is still 4.
The measurement is the offset slider with Centre first off. Moving all the bars together changes the number, which a shape measure must never do. The fix is to subtract the mean first. The spectral formula already does this, because every distance is measured from the centroid μ1.
Chapter 5
Find a hidden signal in noise by asking which frequency channels stop looking Gaussian
A radio telescope listens to a distant galaxy. Almost everything it hears is hiss, the same kind of hiss a warm resistor makes. Somewhere in the recording a satellite, a radar or a phone mast also speaks. The telescope operator must find those intruders and cut them out. How can a computer spot a signal it has never heard before?
It spots them by their shape. Natural noise follows a bell curve. Man-made signals do not. Kurtosis measures exactly how far a signal is from a bell curve. That is why the lecture ends its kurtosis section with two slides of kurtosis curves and one of deep space signals, credited to Gelu Nita.
In Chapter 4 the kurtosis ran along frequency. The spectrum was the distribution, and the number said whether it was peaky. Here the kurtosis runs along time. We watch one frequency channel as the frames go by and ask whether its power behaves like noise.
Astronomers call this version spectral kurtosis, or SK. The two slides stretch the lecture’s word to cover it. Both measure the same thing: how far from Gaussian the numbers are.
Add up many small, independent random pushes, and the total follows a bell curve. This is the central limit theorem. Thermal noise in a receiver is such a total, so it is Gaussian. A Gaussian has kurtosis exactly 3, the lecture’s reference value.
Now change the signal and watch the kurtosis. Rare big spikes make long tails, so the kurtosis rises above 3. A steady sine wave never goes far from its peaks, so its kurtosis falls to 1.5. Mix one into noise and you land between. The reading tells you something is hiding in the noise, and roughly what kind.
Nita and Gary (2010) built a practical estimator from this idea. In each frequency channel, take M power readings P1 to PM, one per frame. Add them up (S1) and add up their squares (S2).
Here is why Gaussian noise gives 1. Noise power in one channel is spread like an exponential: its average square is twice the square of its average. So the ratio is about 2, and 2 − 1 is 1. A steady carrier has the same power every frame, so the ratio is 1 and SK is near 0. A short burst makes the power jump, so SK rises well above 1. The paper says SK is effective for detecting and removing radio interference in real time.
How far from 1 must a channel go before we believe it? Noise itself scatters. Over 20 seeded runs of 31 channels with M = 64 frames, SK for pure noise averaged 1.01 with a standard deviation of 0.24. So a channel must leave 1 by several times 0.24 before we call it interference. More frames give a tighter scatter.
Try it. Hide something in noise and watch two readings: the kurtosis of the samples, and SK for every channel.
Top: a histogram of 4,096 samples against the bell curve with the same variance. Bottom: SK for each frequency channel from 64 frames. The dashed line is 1, the value for noise.
Synthetic data: seeded Gaussian noise with unit variance. Pulses: 1% of samples get a spike of up to ±10. Tone: a sine of up to amplitude 4 with a period of 8 samples, so it lands in channel 8. SK uses 64 frames of 64 samples with a Hann window, channels 1 to 31, and the formula above.
Start with Only noise. The kurtosis hovers near 3 and the SK curve wobbles around 1. Press New noise a few times. It moves by a few tenths, which is the honest scatter of a finite sample. Anything inside that scatter is not evidence of a signal.
Choose Rare pulses at 60%. In the seeded run the kurtosis jumps to about 9, because a few huge values make the tails heavy. The SK curve lifts, since a pulse puts power into every channel at once.
Choose Steady tone at 60%. Now the kurtosis drops, to about 2.2. The SK curve shows a deep notch at channel 8, down to about 0.03, where the tone sits. A tone is too regular to be noise. The overall kurtosis shows only a modest drop, so the per-channel view is what pins the tone to one channel.
This is the failure to guard against. A strong enough mixture of pulses and tones can land the overall kurtosis back near 3, because one pushes it up and the other pulls it down. The signal is not Gaussian, yet the single number says it is.
The measurement is the SK curve. It looks channel by channel, so a tone in channel 8 cannot hide behind a pulse that raises the other channels. The fix is to compute the statistic per channel before you average anything. That is the whole design of SK.
Chapter 6
Count the yes-or-no questions it takes to find the energy, and turn that count into one number
Play a game of twenty questions with a spectrum. I pick one unit of energy at random, using the shares as the odds, and I hide which bin it came from. You ask yes-or-no questions to find the bin. How many questions do you need on average?
If all the energy sits in one bin, you need none. You already know. If the energy is spread evenly over 64 bins, you need 6 questions, because each question can halve the list. The average number of questions is the entropy. The lecture says it represents “the peakiness of the spectrum”, a measure of disorder.
Think of each bin as a possible news item. A bin with a tiny share is rare, so finding the energy there is a big surprise. A bin with a large share is common, so it is a small surprise. Surprise is the logarithm of one over the share, which is −log sk. A logarithm turns “this many times rarer” into “this many questions”.
Why a logarithm and not some other curve? Two independent events multiply their probabilities, but surprises should add. A logarithm turns a product into a sum: −log(p × q) = −log p − log q. Surprise from two coin flips is then the surprise of the first plus the surprise of the second. Only the logarithm has this property, and that is why entropy uses it.
Entropy is the average surprise: each bin’s surprise, weighted by how often it happens. The lecture then divides by the largest value it could have, so the answer runs from 0 to 1.
The shares sk must add up to 1 for this to work, which is why Chapter 0 normalised them. The slide writes the divisor as the log of b2 − b1. In code you use the count of bins in the band.
First take our usual shares, [0, 0.8, 0.2, 0, 0], on a band of 5 bins. Only two terms count. Use natural logarithms.
−(0.8 ln 0.8 + 0.2 ln 0.2) = −(0.8 × (−0.223) + 0.2 × (−1.609)) = 0.179 + 0.322 = 0.500
entropy = 0.500 / ln 5 = 0.500 / 1.609 = 0.311
Second, spread the energy evenly over 4 of 8 bins: each share is 0.25. The sum is ln 4, so the entropy is ln 4 / ln 8 = 2/3, about 0.667.
There is a friendly way to read these numbers. Raise the base of the log to the entropy: the result is the effective number of bins. The second example gives 82/3 = 4, exactly the four bins we used. The first gives about 1.65. So the spectrum [0, 0.8, 0.2, 0, 0] behaves as if its energy were spread evenly over 1.65 bins.
Bars show the shares of 64 bins. Make the peaks wider or add a flat floor. The yellow bracket under the axis shows the effective number of bins, drawn to scale.
Toy spectra: equally tall Gaussian bumps of the width you choose, plus a flat floor that carries the chosen percentage of all the energy, then normalised to shares. Entropy uses natural logs and divides by ln 64, so a flat spectrum scores exactly 1.
Set one peak, width 0.5, floor 0%. The entropy is about 0.16: nearly everything is in a few bins. Widen the peak and it climbs. Add the floor and it climbs faster, because even a faint floor over 64 bins is a lot of small surprises.
Here are the sounds of this lesson, one 512-sample frame each: the flute scores 0.25, the vowel 0.46, the snare 0.84, the hi-hat 0.88 and white noise 0.92. Pure white noise does not reach 1.0. A real frame of noise has random bins, some tall and some short, so it is never perfectly flat.
Back at the top of the page, set the flute and drag the noise slider to 50%. The entropy rises from 0.25 to 0.58. At 100% it reaches 0.80. Entropy is a noise meter: it climbs as a clean tone sinks into hiss.
Here is a failure that bites on the first run. You code the formula and feed it a clean tone. The program prints nan. The cause is in the measurement: a clean tone has bins whose share is exactly 0, and the log of 0 is minus infinity. Zero times minus infinity is not a number.
The fix comes from the maths. As a share shrinks toward 0, s log s also shrinks toward 0. So by agreement, 0 log 0 = 0. In code, drop the zero shares from the sum. A silent frame needs the same care. Its total is 0, so you cannot divide to get shares. Skip the frame, as in Chapter 2.
Chapter 7
Tell a buzzing vowel from a hissing “sss” with one threshold, then break the rule with a hum
Say “ah, sss, ah” slowly, with a hand on your throat. During “ah” your throat buzzes. During “sss” it does not. Air just hisses through a narrow gap between your tongue and teeth.
Speech scientists call the first kind voiced and the second unvoiced. A speech recogniser needs to know which one it is hearing at each moment. The lecture says spectral entropy has been used successfully for this voiced and unvoiced decision.
A voiced sound is a regular buzz. Your vocal folds open and close, say 110 times a second. That regularity puts energy at 110 Hz, 220 Hz, 330 Hz and so on: a comb of harmonics. The energy lives in a few narrow peaks, so the entropy is low.
An unvoiced sound is hiss. Hiss has no rhythm, so its energy spreads over many bins at once. The entropy is high. A quiet room is also hiss, so it also scores high. One threshold on the entropy then splits the frames into two piles.
We built a 1.6 second utterance from synthetic parts. First comes a vowel with its pitch gliding from 110 to 130 Hz (0 to 0.4 s). Then an “sss” of high-passed noise (0.4 to 0.8 s). Then a second vowel gliding from 130 to 100 Hz (0.8 to 1.2 s), and last a quiet room (1.2 to 1.6 s). We cut it into 49 frames of 512 samples, with a hop of 256. We compute the entropy of each frame over a chosen band.
Top: the waveform and the true parts. Middle: the entropy of each frame, and your threshold. Bottom: the truth and the labels your threshold gives. A red box is a wrong label.
Synthetic utterance at 8,000 Hz: harmonic vowels shaped by three formants, high-passed noise for “sss”, white noise for the quiet room. The hum is 50 Hz and its first 11 overtones, falling as 1/h. “Loud” means within 12 dB of the loudest frame. A frame counts as voiced when its entropy is below the threshold. Real speech has harder cases than these.
With the default band and threshold 0.65, the voiced frames sit near 0.53, the “sss” near 0.85 to 0.88 and the quiet room near 0.92. The rule gets 48 of 49 frames right. The one miss straddles the join between “sss” and the second vowel, where a single frame holds both. Slide the threshold down below 0.5 and nothing counts as voiced. Slide it above 0.9 and the quiet room joins the vowels. Anywhere from 0.55 to 0.85 gives 47 or 48 of 49.
Frame length matters too. Over the same utterance, the voiced frames score 0.55 with 256-sample frames, 0.53 with 512 and 0.62 with 1,024, while the “sss” frames stay between 0.83 and 0.88. The long frame loses because the pitch glides during 128 milliseconds, so each harmonic smears across several bins and the comb blurs. Choose a frame short enough that the pitch holds still.
The lecture’s next slide shows a histogram of entropy values for three kinds of recording: speech, music and background. The three piles do not sit in the same place. The lecture says entropy has also been used to tell speech from music.
Here is one reason it can work, offered as our own reading of the slide. Speech flips between voiced and unvoiced sounds many times a second, so its entropy track swings up and down. A sustained musical note holds its harmonic comb, so its entropy stays low and steady. The spread of the entropy over time is then a feature of its own.
Here is the failure. Switch on Mains hum in the quiet room and choose the band 0 to 4,000 Hz. The quiet frames now read about 0.50, while the vowels read 0.52. No threshold can put the vowels on one side and the hum on the other. From 0.55 to 0.85 the best you get is 36 of 49 frames, 73%. The room is silent, yet the rule calls it voiced.
The measurement explains it. A hum is periodic, like a voice. It has its own comb of harmonics at multiples of 50 Hz, so its energy sits in a few peaks and the entropy is low. Entropy measures disorder, and a hum is orderly.
There are two fixes, and you can try both. First, change the band. With 300 to 3,400 Hz the hum falls mostly outside, the quiet frames return to about 0.86, and 48 of 49 frames are right at threshold 0.65. Second, switch on Also require a loud frame. The quiet room is about 21 dB below the loudest frame, so it fails the loudness test whatever its entropy, and the count returns to 48 of 49. A voice activity detector combines several descriptors in exactly this way.
Chapter 8
Compare each frame with the one before it, and find the drum beats as peaks of change
Play spot-the-difference with two photos. You do not need to know what is in either photo. You only count what changed. The more pixels differ, the bigger the change.
Spectral flux does this with two neighbouring spectra. Every other descriptor in this lesson describes one frame. Flux alone compares frames. The lecture says it “represents the variability of the spectrum over time”, and on its slide the beats of a drum track line up with high flux.
Take the spectral value of bin k in the current frame, sk(t), and in the frame before it, sk(t − 1). Their difference says how much that bin changed. We want the size of the change, so we take the absolute value. Then we combine the changes of all bins into one number.
With p = 1 the flux is the plain sum of the changes: every bin’s change counts equally. With p = 2 it is the straight-line distance between the two spectra, so a few big changes count for more than many small ones.
Take the shares from before and let the next frame be different.
s(t − 1) = [0, 0.8, 0.2, 0, 0] s(t) = [0, 0.2, 0.1, 0.3, 0.4]
changes = [0, 0.6, 0.1, 0.3, 0.4]
p = 1: 0.6 + 0.1 + 0.3 + 0.4 = 1.4 p = 2: √(0.36 + 0.01 + 0.09 + 0.16) = √0.62 = 0.787
Notice what p = 2 does. The single big change, 0.6, supplies 58% of the squared total. With p = 1 it supplies only 43% of the sum. A larger p rewards one big jump over many little ones.
Now apply flux to the drum loop of Chapter 2. We compute the magnitude spectrum of each 32 ms frame and the flux between neighbours. A beat is a peak of the flux curve. To find the peaks, we pick local maxima above a threshold. We allow at most one peak every four frames (64 ms), so one hit is not counted twice.
As data flow, 16,000 samples become a matrix of magnitudes of shape (124, 129), frames by bins. The flux turns each pair of neighbouring rows into one number, so the result has 123 entries, and we set a 0 in front to keep one entry per frame. Flux has no unit, so we judge it against the curve’s own highest value.
The green curve is the flux of each frame. Green dots are beats your threshold found. A red ring is a false beat. A red cross marks a real hit that was missed. K, S and H mark kicks, snares and hats.
The same synthetic loop as Chapter 2: 4 kicks, 2 snares, 8 hi-hats, 14 hits in all. Flux uses the magnitude spectrum of 256-sample Hann frames with hop 128, and the threshold is a percentage of the curve’s highest value. A peak counts as a hit if it falls within 3 frames before to 2 frames after the true onset.
At the start, p = 2 and a 10% threshold find all 14 hits with no false ones. Raise the threshold to 40% and p = 2 still finds all 14. Now switch to p = 1. At 10% it is still perfect. At 20% it loses the three later kicks, and at 30% all four.
Why do the kicks vanish? A kick puts its change into a few low bins. A hi-hat spreads a smaller change over a huge number of bins. The p = 1 sum counts the many small changes of the hats as more than the few big ones of the kick. The p = 2 distance weights a few big changes more, so the kick stands out.
In Chapter 0 we divided by the total so that loudness would cancel. For flux that can backfire. A drum hit is mostly a jump in loudness. If we normalise each frame to shares, we throw that jump away, and only the change of shape is left.
Switch on Normalise to shares first. At a low threshold the flux still finds all 14 hits, but it also reports 2 false beats with p = 1 and 5 with p = 2. The false beats sit where a hit dies away into the noise floor. The loudness falls, but the shares jump from the drum’s shape to the floor’s shape, and the flux reads that as a change.
The measurement is the red rings. The fix is to compute the flux on the raw magnitude, as this lesson does by default. Normalising is right for describing what kind of sound it is, and wrong for finding when something happens.
Chapter 9
Meet flatness, crest, slope and rolloff, then pick the descriptors that tell five sounds apart
A detective has a dozen possible clues: a footprint, a fibre, a smell. She cannot chase them all. She must choose the few that best separate the suspects. You face the same choice with descriptors. This chapter finishes the family and then does the choosing.
The lecture’s list on slide 3 names more than the five we have built. Skewness came in Chapter 4. Here are flatness, crest and slope, defined as the MathWorks page that the lecture cites defines them, plus rolloff.
Spectral flatness is the geometric mean of the spectral values divided by their arithmetic mean. The arithmetic mean is the ordinary average. The geometric mean multiplies the values and takes the n-th root, which is the average of their logs. For a perfectly flat spectrum the two means agree, so the flatness is 1. A single empty bin pulls the geometric mean to 0.
Try two spectra with four bins. For shares [0.4, 0.3, 0.2, 0.1] the arithmetic mean is 0.25 and the geometric mean is (0.4 × 0.3 × 0.2 × 0.1)1/4 = 0.221. The flatness is 0.221 / 0.25 = 0.885. For [0.85, 0.05, 0.05, 0.05] the geometric mean is 0.101, so the flatness is 0.406. A peaky spectrum scores low.
Spectral crest is the highest spectral value divided by the arithmetic mean. It asks how far the tallest peak stands above the average. For the same two spectra it is 0.4 / 0.25 = 1.6 and 0.85 / 0.25 = 3.4. Flat is near 1, peaky is large.
Spectral slope is the slope of the least-squares line through the magnitude spectrum, plotted against frequency. It measures tilt. Take magnitudes [4, 3, 2, 1] at 0, 1, 2 and 3 kHz. The mean frequency is 1.5 and the mean magnitude is 2.5. The covariance is −5, the variance of frequency is 5, so the slope is −1 per kHz. Negative means the energy leans toward low frequencies.
Spectral rolloff is the frequency below which a fixed share of the total lies. The MathWorks page says the share is usually 95% or 85%. It is a robust cousin of the centroid: a loud high note moves it, a faint whistle does not. For shares [0.4, 0.3, 0.2, 0.1] at 0, 1, 2 and 3 kHz the running totals are 0.4, 0.7 and 0.9, so the 85% rolloff is the third bin, 2 kHz.
In practice you compute the descriptors for every frame and stack them. Take 30 seconds of sound at 8,000 samples per second: 240,000 samples. With a frame of 512 and a hop of 256 that is 936 frames. With seven descriptors the result is a matrix of shape (936, 7).
A classifier usually wants one short vector per recording or per second. So we summarise each column over time by its mean and its standard deviation. That gives (14,): seven means and seven spreads. Speech then differs from music partly in the swing of the entropy, as Chapter 7 suggested.
Now the detective’s job. We built 40 frames each of five sounds: a flute, a vowel, a snare, a hi-hat and white noise. The pitch, the noise level and the random seed all vary from frame to frame, so the groups overlap a little. Pick any two descriptors for the axes.
Each letter is one frame: F flute, V vowel, S snare, H hi-hat, N noise. Rings mark the class averages. Red letters are frames the nearest-average rule gets wrong. Choose a descriptor for each axis.
Synthetic frames, 512 samples at 8,000 Hz, power weights, whole band. Kurtosis, flatness and crest are drawn on a log scale because they span orders of magnitude. The rule is a nearest class average after rescaling each axis to unit spread: the simplest classifier, chosen to show the features, not the model.
Start with Centroid across and Entropy up. Flute and vowel overlap in the lower left, and snare, hi-hat and noise crowd the upper right. The rule names 162 of 200 frames correctly. Now try Centroid with Crest. The score rises to 179, the best of all 15 pairs, because the crest pulls the peaky flute and vowel far from the flat noise.
Try Spread with Flatness. The score falls to 145. Both measure width in different ways, so they repeat each other and add little. A good pair carries two different clues.
Slide 19 lists the sources. The MathWorks page defines the descriptors, and we used it above. Peeters (2004, IRCAM) is a report on a large set of audio features. Murthy and others (1999) is about speaker identification over telephone channels. Grey and Gordon (1978) is about the perceptual effects of spectral changes on musical timbre. Zhang, Guo and Zhang (2009) designs a voice activity feature from spectral kurtosis. Hansen and Patil is listed under “Speech Under Stress”.
The sources show how the descriptors are used together, as the six uses of Chapter 0: speaker and instrument recognition, scenes, genre, mood and voice activity.
Chapter 10
Keep the numbers, the checklist and the core code, then go on to the lectures that use them
Here is the whole lecture in one paragraph. A spectrum, divided by its total, is a distribution over frequency. Its mean is the centroid, its standard deviation is the spread, its fourth moment is the kurtosis, and its disorder is the entropy. Between frames, the flux says how fast it moves. A few of these numbers replace 257 bins, and they work for sounds of any kind.
This last device uses the five-bin spectrum from our worked examples. Drag the bars and read all seven descriptors at once. The first preset reproduces the numbers you have met: 1,200 Hz, 400 Hz, 3.25, 0.311.
Drag the five bars (power values at 0, 1,000, 2,000, 3,000 and 4,000 Hz). The table under the bars recomputes every descriptor.
| Descriptor | Value | Reads as |
|---|
Toy spectrum: 5 bins, 8 samples at 8,000 Hz, power weights, band 0 to 4,000 Hz, no window. Flatness is 0 whenever one bin is empty. Entropy uses natural logs divided by ln 5.
| Descriptor | What it computes | Low end | High end | Slide |
|---|---|---|---|---|
| Centroid μ1 | Share-weighted mean frequency | Dark sound | Bright sound | 5 to 7 |
| Spread μ2 | Standard deviation around the centroid | 0 for a pure tone (about 9 Hz with a Hann window) | fs / (4√3) for white noise, 1,155 Hz at 8 kHz | 8 and 9 |
| Kurtosis μ4 | Fourth moment divided by the spread to the fourth | 1, two equal spikes | Large for sharp peaks; 3 is a Gaussian, 1.8 a flat spectrum | 10 to 13 |
| Entropy | Average surprise, divided by the log of the bin count | 0, one sharp peak | 1, a perfectly flat spectrum | 14 to 16 |
| Flux | p-norm of the change from the last frame | 0, nothing changed | Peaks at onsets such as drum hits | 17 and 18 |
| Flatness | Geometric mean over arithmetic mean | 0 if any bin is empty | 1, flat | 3 |
| Crest | Highest value over the mean | 1, flat | Large for one tall peak | 3 |
| Slope | Least-squares line through the magnitude spectrum | Negative: energy leans low | Positive: energy leans high | 3 |
And here are the five sounds of this lesson, one 512-sample frame each, so you can calibrate your eye.
| Sound | Centroid | Spread | Kurtosis | Entropy | Flatness | Crest |
|---|---|---|---|---|---|---|
| Flute, A4 | 521 Hz | 201 Hz | 13.1 | 0.25 | under 0.001 | 140 |
| Vowel “ah” | 950 Hz | 475 Hz | 8.5 | 0.46 | 0.001 | 85 |
| Snare | 1,585 Hz | 1,187 Hz | 1.9 | 0.84 | 0.46 | 35 |
| Hi-hat | 2,776 Hz | 815 Hz | 2.5 | 0.88 | 0.29 | 7.4 |
| White noise | 1,983 Hz | 1,177 Hz | 1.8 | 0.92 | 0.59 | 6.1 |
This function does Chapters 0 to 9 for one frame, plus the flux between two frames. We ran it on the flute and on white noise. It returns a centroid of 520 Hz and an entropy of 0.25 for the flute. For the noise it returns 2,064 Hz and 0.93.
pythonimport numpy as np
def spectral_descriptors(frame, fs, b1=0, b2=None, weighting="power"):
"""Descriptors of ONE frame. Returns a dict of floats."""
n = len(frame)
X = np.fft.rfft(frame * np.hanning(n)) # (n//2 + 1,) complex
f = np.arange(len(X)) * fs / n # (n//2 + 1,) Hz
b2 = len(X) - 1 if b2 is None else b2
s = np.abs(X[b1:b2 + 1]) ** (2 if weighting == "power" else 1)
f = f[b1:b2 + 1]
tot = s.sum()
if tot < 1e-12: # silence: nothing to describe
return None
p = s / tot # sums to 1: a distribution over frequency
mu1 = (f * p).sum() # centroid
mu2 = np.sqrt(((f - mu1) ** 2 * p).sum()) # spread
skew = (((f - mu1) ** 3) * p).sum() / mu2 ** 3
kurt = (((f - mu1) ** 4) * p).sum() / mu2 ** 4 # a Gaussian scores 3
ent = -(p[p > 0] * np.log(p[p > 0])).sum() / np.log(len(p)) # 0 = one peak, 1 = flat
flat = np.exp(np.mean(np.log(s + 1e-12))) / s.mean()
crest = s.max() / s.mean()
return dict(centroid=mu1, spread=mu2, skewness=skew, kurtosis=kurt,
entropy=ent, flatness=flat, crest=crest)
def spectral_flux(prev_frame, frame, p=2):
"""Flux between two consecutive frames of the same length."""
w = np.hanning(len(frame))
a = np.abs(np.fft.rfft(prev_frame * w))
b = np.abs(np.fft.rfft(frame * w))
return (np.abs(b - a) ** p).sum() ** (1.0 / p)
def describe_signal(x, fs, n=512, hop=256):
"""Slide a window along x: one row of descriptors per frame, plus flux."""
rows, flux = [], [0.0]
for i in range(0, len(x) - n + 1, hop):
rows.append(spectral_descriptors(x[i:i + n], fs))
if i:
flux.append(spectral_flux(x[i - hop:i - hop + n], x[i:i + n]))
return rows, np.array(flux)
The descriptors sit on top of the DFT of Lecture 6 and the frames of Lecture 8. Their big sibling is the cepstrum and the MFCC features of Lecture 13. To turn features into decisions, continue with distances and classification, whose nearest-average rule is the one our scatter used.
Outside the course, the MathWorks spectral descriptors page defines every formula used here. Nita and Gary’s “The Generalized Spectral Kurtosis Estimator” (2010) is the source of the SK formula in Chapter 5.
Credit: this lesson follows Lecture 3 Part II of Stanford EE269, taught by Mert Pilanci. See the lecture slides and the full set of course slides. The sounds, the devices and the examples here are our own.
Now try it in your own voice: open Present or Teach from the dock at the top, and explain a descriptor aloud. Then go back to the instrument and see which numbers move when you add noise.