Classical Audio Classification

Before deep learning, a machine named a sound from a few hand-designed numbers per 25 ms frame and a small statistical model. On the ESC-50 benchmark that stack reached 44%. People reach 81%.

Pick a sound and press Play. Each frame becomes one dot from two features, the ring is their average, and a Gaussian for each class names the clip. Then raise the noise and watch the ring walk away. Then we build every part from zero: frames, features, MFCCs, three classifiers, a sequence model and the honest score.

You need a little Python and the idea that a sound is a list of pressure samples. We build the rest from zero.

Run the 2008 machine

0.00

Illustrative: your browser synthesizes the five sounds (0.4 s at 16 kHz) and 12 training clips per class the same way. The features are real: zero crossings and the centroid of a 512-point FFT of each Hann-windowed 400-sample frame. The 44% and 81% are the ESC-50 baseline and human figures (Piczak, 2015).

Chapter 0

Why Raw Samples Fail

Measure two recordings of one tone and find the tone closer to silence than to itself

A city puts a microphone on a lamppost. Your job is to raise an alarm on a scream and stay quiet for a siren, a bus or a pigeon. It is 2008. You have a laptop, a few hundred labelled clips and no pretrained model.

The first idea is template matching. Store a recorded scream as its list of samples. Call a new clip a scream if its samples are close.

Test it on the simplest sound there is. Take a pure tone sampled 8 times per cycle and call that list x. Record it again, started s samples later, and call it y. The delay is a phase angle φ = 2πs/8. How far apart are x and y?

Say it aloud

The squared distance between x and y equals 8 times one minus cos phi.

‖x − y‖2
the squared distance between x and y subtract sample by sample, square, add.
8
eight twice the energy of one cycle: each copy has energy 4.
cos φ
cos phi the cosine of the delay angle: 1 for no delay, −1 for half a cycle.
In plain words

Each copy has energy 4. Their overlap is 4 cos φ. The squared distance is 4 + 4 minus twice the overlap.

With numbers

A delay of s = 2 samples gives φ = 90° and cos φ = 0. The squared distance is 8, so the distance is 2.828. Silence (all zeros) sits only 2.000 from x.

The same tone, delayed by a quarter of a cycle, is farther from itself than from nothing. At 16 kHz that delay is 0.125 ms. Slide it below. The teal bar is a distance built on two features, numbers computed from the sound: its loudness and how often it crosses zero.

Delay the copy

Blue is the tone, grey is the delayed copy. The bars are the two distances; the dashed line is the distance to silence. Drag the delay until the raw bar crosses the line.

2.00
1.00

One cycle of 8 samples, as in the worked example. The feature distance compares RMS loudness and zero-crossing rate over a whole number of cycles, so delay leaves it at 0.

Delay sφDistanceVerdict
1 sample45°1.531closer than silence
1.33 samples60°2.000tied with silence
2 samples90°2.828worse than silence
4 samples180°4.000as far as it can be

The failure. Symptom: a template matcher misses the same sound recorded twice. Measure: compute the distance between a clip and a copy shifted by one sample. Fix: describe the sound with numbers that ignore phase, length and gain. Halving the gain alone moves the copy to distance 1.000, closer than the shifted one.

Raw samples fail three ways. They change with phase, which the ear ignores. Clips have different lengths, so you cannot subtract their vectors. And 16,000 numbers per second is far too many to learn from 300 clips. The classical pipeline fixes all three in five stages.

The road

  1. Frames: chop the sound into 25 ms pieces that hold still.
  2. Energy and zero crossings: two features with no Fourier transform. The hero’s horizontal axis.
  3. Spectral shape: centroid, rolloff, flux and flatness. The hero’s vertical axis.
  4. MFCCs: 13 numbers that keep the vowel and drop the pitch.
  5. Pooling and k-NN: one vector per clip, and why units matter. The hero’s ring and its Nearest button.
  6. Gaussian mixtures: one EM step by hand. The hero’s Gaussian button and score bars.
  7. SVMs and kernels: the widest margin, and a cheap road to a big space.
  8. HMMs: put time back with the forward pass.
  9. The ceiling: what pooling cannot see, honest folds, and the 44%.
  10. Field guide: terms, numbers, code and links.
A tone delayed by 2 samples is 2.828 from the original, while silence is 2.000 away. What does this show?

Chapter 1

Framing: Chop Sound Into Stillness

Cut the signal into short overlapping windows and count the frames, the frame rate and the frequency resolution

Average the brightness of a whole four-second clip and you mix a word, a siren sweep and a passing bus into one number. One sample alone has no brightness at all. The answer lies between, for a physical reason.

A vocal tract, a string or an engine changes shape slowly, over tens of milliseconds. So over 20 to 40 ms the spectrum of a sound stays roughly fixed. This is quasi-stationarity. We cut the signal into overlapping frames, treat each as a still photograph, and describe each one. Framing is filming: the frame length is the shutter time and the hop is the time between photographs.

SettingSpeech valueWhat it controls
Frame length L25 ms = 400 samples at 16 kHztime against frequency detail
Hop h10 ms = 160 samplesframes per second (here 100)
WindowHanntapers the edges to stop leakage

How many frames does a clip give? Call the clip length in samples N, the frame length L and the hop h. The last frame must end inside the clip.

Say it aloud

n-frames equals one plus the floor of N minus L, over h.

nframes
n-frames the number of whole frames that fit.
⌊ ⌋
the floor of round down to a whole number.
N
N samples in the clip.
L
L samples in one frame.
h
h samples between frame starts.
In plain words

The first frame takes L samples. Each later frame starts h samples on. Count how many hops fit in the N minus L samples left, round down, and add the first frame.

With numbers

A 4 s clip at 16 kHz: N = 64,000, L = 400, h = 160. (64,000 − 400) / 160 = 397.5, round down to 397, add 1: 398 frames. The array is (398, 400).

The frame length also fixes the frequency resolution: FFT bins sit sr/L apart, where sr is the sample rate. At 16,000 / 400 that is 40 Hz. Zero-padding to 512 points draws the same 40 Hz detail more smoothly. It adds no information.

Set the shutter and the frame rate

The signal changes character at 0.5 s. Each purple hump is one Hann-windowed frame. Lengthen the frames and find where one frame swallows the change.

25
40%

Illustrative signal at 16 kHz: a low tone, then a brighter buzz. Counts use the formula above.

The failure. Symptom: your frame count for a 4 s clip is 401, not 398. Measure: check the library call; librosa.stft pads the clip by half a frame at each end by default (center=True). Fix: pick one convention and use it for training and test.

A 3 s clip at 16 kHz is framed with L = 400 and h = 160. How many frames, and what bin spacing?

Chapter 2

Energy and Zero Crossings

Describe a frame with a sum and a sign test, and see how a constant offset breaks one of them

Two features need no Fourier transform at all. They answer the two coarsest questions about a frame: is anything here, and is it smooth or hissy? Phone voice detectors still run them because they cost one operation per sample.

Short-time energy E is the sum of the squared samples. The RMS is the square root of E over L, and engineers report it in decibels, 10 log10(E/L). The log turns a gain change into a fixed offset: halve the gain and every frame drops 6.02 dB.

The second feature counts sign changes. Call the samples of one frame xn, for n from 0 to L − 1.

Say it aloud

ZCR equals the count of n where the sign of x-n differs from the sign of x-n-minus-one, over L minus one.

ZCR
Z C R the zero-crossing rate: the share of neighbouring pairs that change sign, from 0 to 1.
#{ … }
the count of n where how many sample pairs have opposite signs.
L − 1
L minus one the number of neighbouring pairs in a frame of L samples.
In plain words

Walk the frame one pair at a time. Count the pairs where the signal changes sign. Divide by the L minus 1 pairs. A fast wiggle gives a high ZCR.

With numbers

The frame 0.1, 0.6, −0.4, −0.8, 0.2, 0.9, −0.1, −0.5 has signs + + − − + + − −: 3 changes in 7 pairs, so ZCR = 0.429. Over 7 / 16,000 s that is 6,857 crossings a second, like a 3.4 kHz tone.

The same frame has E = 2.28, RMS = √(2.28 / 8) = 0.534 and −5.45 dB. Libraries differ on ZCR: librosa divides by L and returns 0.375 for this frame. Check the convention before you compare papers.

Mix tone into noise

Teal ticks mark each zero crossing. The teal dot is this frame in the (ZCR, dB) plane. Push toward noise, then lower the level, then add a DC offset.

0.15
0.70
0.00

Illustrative 400-sample frame: a 300 Hz tone mixed with white noise. Regions are rough guides, not a trained model. The ZCR here does not remove the mean, so you can see the failure.

The failure. Symptom: ZCR reads 0 on a frame that sounds normal. Measure: print the frame mean; a badly coupled preamp adds a constant offset. Fix: subtract the frame mean before counting. Add 0.9 to the worked frame and every sample is positive, so ZCR falls from 0.429 to 0.

A frame of quiet room tone usually has:

Chapter 3

Spectral Shape: Centroid, Rolloff, Flux, Flatness

Summarise one magnitude spectrum with numbers that match the words bright, thin, changing and noisy

Energy and ZCR cannot tell a violin from a flute. Both are loud and periodic. We need to know which frequencies carry the energy. So take the FFT of the windowed frame and keep only the magnitudes, dropping phase for the reason in Chapter 0. A 400-sample frame gives 201 magnitudes, one per bin, 40 Hz apart.

The most useful summary is the balance point. Call the frequency of bin k fk and its magnitude mk.

Say it aloud

The centroid equals the sum over k of f-k times m-k, over the sum over k of m-k.

centroid
the spectral centroid the centre of mass of the spectrum, in Hz. It tracks brightness.
Σk
the sum over k add one term per frequency bin.
fk
f-k the frequency of bin k, in Hz.
mk
m-k the magnitude in bin k.
In plain words

Treat each magnitude m-k as a weight placed at its frequency f-k. Multiply, add, and divide by the total weight. The result is where the spectrum balances.

With numbers

With a made-up five-bin spectrum: magnitudes 1, 3, 4, 1.5, 0.5 at 0, 2, 4, 6, 8 kHz. The top sum is 0 + 6,000 + 16,000 + 9,000 + 4,000 = 35,000. Divide by the total 10: centroid = 3,500 Hz.

Three more numbers finish the set. Each one comes from the same five bins.

FeatureQuestionRecipeToy value
Rolloffwhere is the top?first bin where the running total reaches 85%6,000 Hz
Fluxhow fast is it changing?distance to the previous frame’s magnitudes2.550
Flatnesstone or noise?geometric mean over arithmetic mean, 0 to 10.776

The running total is 1, 4, 8, 9.5, 10, so the total first reaches 85% of 10 at bin 3, 6 kHz. Flux uses a next frame of 1, 2, 3, 3, 2: the differences 0, −1, −1, 1.5, 1.5 give √6.5 = 2.550. Keep only the increases (3.0) and flux fires on onsets but not on decays.

Shape the spectrum

Blue bars are this frame; grey outlines are the last one. The teal line is the centroid and the dashed line is the rolloff. Move brightness fast and watch flux jump.

0.30
0.20

Illustrative 24-bin spectrum from 0 to 8 kHz. The features use the recipes in the table.

The failure. Symptom: NaN in the clip’s mean centroid. Measure: find frames whose magnitudes sum to about 0; the centroid divides by that sum. Fix: skip frames below an energy threshold and add a small constant to every divisor.

Add a flat noise floor of 0.3 to every bin of the toy spectrum (centroid 3,500 Hz). What happens to the centroid?

Chapter 4

MFCCs: Keep the Envelope, Drop the Pitch

Warp frequency, take a log, then a cosine transform, and keep 13 numbers that describe the vowel

Centroid and rolloff cannot tell “ah” from “eh”. The vowels differ in where the spectrum’s bumps sit. Davis and Mermelstein (1980) gave the answer that ran speech recognition for thirty years: mel-frequency cepstral coefficients (MFCCs).

The vocal folds make a buzz, the source, which sets the pitch. The throat and mouth shape it, the filter, which sets the vowel. The spectrum is their product, and a log turns it into a sum. The pitch part wiggles fast across frequency and the vowel part moves slowly, so a second transform separates them.

  1. Power spectrum of the windowed frame: 201 bins.
  2. Mel filterbank: 40 triangles, narrow at low frequency, wide at high.
  3. Log of each band energy.
  4. DCT: 40 correlated numbers become 40 coefficients.
  5. Keep the first 13. They hold the envelope.

The mel scale spaces the triangles the way the ear hears pitch. Call the frequency f and its mel value m.

Say it aloud

m equals 2595 times log base ten of one plus f over 700.

m
m the pitch distance in mels.
2595
twenty-five ninety-five a constant chosen so that 1,000 Hz maps to 1,000 mel.
log10
log base ten grows by 1 each time its input grows ten times.
f
f frequency in hertz.
In plain words

Below 700 Hz, m grows almost in step with f. Above it, m grows with the log of f.

With numbers

f = 1,000 gives m = 1,000. f = 4,000 gives 2,146 and f = 8,000 gives 2,840. The top 4 kHz span only 694 mel, so the triangles there are wide.

After the log, a discrete cosine transform (DCT) measures each cosine ripple in the log-mel shape. Call the log band energies sn, for N bands, and coefficient k ck.

Say it aloud

c-k equals the sum over n of s-n times cos of pi k times n plus one half, over N.

ck
c-k coefficient k: c-0 is overall level, c-1 is tilt, c-2 is a middle bump.
Σn
the sum over n add one term per mel band, n from 0 to N − 1.
sn
s-n the log energy of mel band n.
cos(…)
cos of pi k, n plus one half, over N a cosine with k half cycles across the bands.
In plain words

For each k, lay a cosine with k half cycles across the bands. Multiply it by the log energies s-n and add.

With numbers

With made-up band energies 2, 8, 4, 1, the logs are 0.693, 2.079, 1.386, 0. Then c-0 = 4.159, c-1 = 0.906 (tilted low), c-2 = −1.961 (a middle bump), c-3 = −0.375.

Why the DCT? Neighbouring mel bands move together, and the DCT nearly decorrelates them. Then a Gaussian needs one variance per dimension: 39 numbers, not the 780 of a full covariance (Chapter 6). Add the first and second time differences of the 13 to get the classic 39 per frame.

Move the vowel, then the pitch

Left: 40 log-mel bands. Right: their 40 DCT coefficients, the kept ones in teal. Move the formant, then the pitch, and see which coefficients react.

0.35
3.0
13

Illustrative: a smooth envelope (warm curve) times a comb whose spacing stands for pitch. The DCT is the formula above with N = 40.

The failure. Symptom: your MFCCs differ from a colleague’s. Measure: check the DCT scaling (scipy with no norm doubles every value) and the mel formula (librosa defaults to the Slaney mel; this formula is htk=True). Fix: pin both.

Why does the MFCC pipeline apply a DCT after the log-mel step?

Chapter 5

Pool, Standardize, Then Find Neighbours

Turn a clip into one fixed vector, put every feature on the same scale, and let the nearest clips vote

A clip is now an array of shape (T, 39), and T depends on the clip’s length. A classifier wants one fixed vector. Statistics pooling takes the mean and the standard deviation of each feature over time: (78,) for any length. Four frames with ZCR 0.42, 0.30, 0.55, 0.33 pool to mean 0.400 and standard deviation 0.097.

The simplest classifier stores every labelled clip. To label a new one, it finds the k closest stored clips and lets them vote. This is k-nearest neighbours (k-NN). It has no training step, so it is the fastest test of whether your features separate the classes at all.

ClipZCRCentroid (kHz)LabelRaw distance to Q
A0.101.5speech1.300
B0.142.0speech0.802
C0.053.0music0.204
D0.073.6music0.800
Q0.092.8? 

Look inside one distance. To A, the ZCR difference squared is 0.0001 and the centroid difference squared is 1.69. The centroid is about 17,000 times louder in the sum. The distance ignores ZCR. The fix gives each feature the same scale. Call a feature’s value v, its training mean μ and its training standard deviation σ.

Say it aloud

z equals v minus mu, over sigma.

z
z the standardized value: how many standard deviations from the mean.
v
v the raw feature value, in its own unit.
μ
mu the feature’s mean over the training clips.
σ
sigma the feature’s standard deviation over the training clips.
In plain words

Subtract the training mean mu from the value v. Divide by the training spread sigma. Every feature now has mean 0 and spread 1, whatever its unit.

With numbers

ZCR has μ = 0.090 and σ = 0.0339, so A’s 0.10 becomes +0.295. Centroid has μ = 2.525 and σ = 0.823, so A’s 1.5 becomes −1.246. In z units the nearest clip to Q changes from C (1.204) to D (1.137).

Drag the query, then drop the scaling

Drag the ink ring or tap the plane. Lines join it to its k nearest clips. Turn standardizing off and watch the neighbours line up along the centroid axis.

3

Illustrative clips: speech (purple), music (pink) and rain (teal), 14 each, drawn from fixed Gaussians.

The failure. Symptom: test accuracy drops several points when a colleague reruns your split. Measure: check where μ and σ came from. Fix: fit them on the training clips only and reuse them on test clips; make_pipeline(StandardScaler(), ...) does this for you.

Why did z-scoring change which clip was nearest to Q?

Chapter 6

Gaussian Mixtures and One EM Step

Describe each class as a few weighted bells, and fit them by guessing soft memberships and refitting

k-NN memorises. A better plan describes each class as a probability density over feature space, then labels a new clip by asking which density scores it highest. From about 1990 to 2012, every speech recognizer did this with Gaussian mixtures (GMMs).

One Gaussian is one bell with a mean and a variance. A class like “dog” holds yaps and woofs, two lumps, and one bell would put its peak in the empty valley. So use K bells, each with a weight πk, a mean μk and a variance σk2. The catch: nobody tells us which bell made which point. The EM algorithm guesses that softly, then refits.

The guess is Bayes’ rule. Call data point n xn and the bell-shaped density N(x | μ, σ2).

Say it aloud

r-n-k equals pi-k times N of x-n given mu-k and sigma-k squared, over the sum over j of the same thing for bell j.

rnk
r-n-k the responsibility: the chance that bell k made point n, from 0 to 1.
πk
pi-k bell k’s weight: its share of all points.
N(xn | μk, σk2)
N of x-n given mu-k, sigma-k squared the height of bell k at the point: the bell function exp(−(x − μ)2 / 2σ2) / √(2πσ2).
Σj …
the sum over j the same product for every bell, so the responsibilities add to 1.
In plain words

For point x-n, multiply each bell’s weight pi-k by its height at the point. Divide each product by their total. That is the E-step. The M-step refits each mean, variance and weight with every point counted r-n-k times.

With numbers

With made-up points 2, 3, 8, 9, start with μ = 4 and 7, σ2 = 4, π = 0.5. At x = 2 the heights are in the ratio e−0.5 : e−3.125 = 0.607 : 0.044. So r = 0.9325 and 0.0675.

Finish the step by hand. The responsibilities for bell 1 are 0.9325, 0.8670, 0.1330, 0.0675. They sum to 2.000.

μ1 = (0.9325·2 + 0.8670·3 + 0.1330·8 + 0.0675·9) / 2.000 = 6.1376 / 2 = 3.069, and μ2 = 7.931
σ2 = 6.6789 / 2 = 3.339 for both  ·  log-likelihood −10.046 → −9.139

The means moved out toward the clusters. Run to the end and they reach 2.5 and 8.5 with variance 0.25. EM never lowers the log-likelihood, the log of how probable the data is under the model. It can stop on a poor peak, so real systems start from k-means.

Step EM by hand

Each point blends purple and pink by its responsibilities. Press E-step, then M-step. Then set the start gap to 0 and press Run.

3.0

The toy set is the worked example; gap 3 starts the means at 4 and 7. The 40-point set is illustrative. A variance floor of 0.05 stops collapse.

The failure. Symptom: training reports an absurdly good likelihood. Measure: print the smallest variance; one bell has shrunk onto a single point, and its height runs to infinity. Fix: a variance floor (reg_covar in scikit-learn) and restarts.

What does a GMM give that k-NN does not?

Chapter 7

Support Vector Machines and the Kernel Trick

Choose the boundary with the widest empty corridor, and reach a large feature space without building it

A GMM models what each class looks like. If you only need the answer, model the boundary. Many straight lines split two separable classes with zero training error. The support vector machine (SVM) picks the one with the widest empty corridor, the margin, because features are noisy and a wide corridor tolerates noise.

The classifier is f(x) = w · x + b, where w is a weight vector and b an offset; it says +1 when f(x) > 0. Real classes overlap, so the SVM lets points violate the corridor at a price. Call the label of clip i yi, +1 or −1, and the price per unit of violation C.

Say it aloud

Minimize one half the squared length of w, plus C times the sum over i of the max of zero and one minus y-i times f of x-i.

minimize
minimize find the w and b that make the total smallest.
½‖w‖2
one half the squared length of w small w means a wide margin, since the margin is 2 / ‖w‖.
C
C the exchange rate between margin width and violations.
Σi
the sum over i one term per training clip.
max(0, 1 − yi f(xi))
the hinge loss zero when clip i sits at least 1 unit inside its side; grows by 1 for each unit short.
In plain words

Charge for a narrow corridor through the length of w. Charge C for every unit a clip falls short of its side. Pick the w and b with the smallest total charge.

With numbers

With made-up points (3, 3) labelled +1 and (1, 1) labelled −1, take w = (0.5, 0.5) and b = −2. Then f = +1 and −1, so both hinges are 0. ‖w‖ = 0.707 and the margin is 2.828, the whole gap. A clip with f = 0.4 pays 0.6; one with f = −0.3 pays 1.3.

Only clips on or inside the corridor change w. They are the support vectors. The solution touches the data only through dot products. So you can swap in a kernel K(u, v) that equals a dot product in a bigger space.

u = (1, 2), v = (3, 1): (u · v)2 = 52 = 25
φ(x) = (x12, √2 x1x2, x22): φ(u) · φ(v) = 9 + 12 + 4 = 25

The cheap side never builds φ. The RBF kernel exp(−γ‖u − v‖2) goes further: for these vectors and γ = 0.5 it gives e−2.5 = 0.082. Its knob γ sets how far one support vector reaches.

Train an SVM, then overfit it

The pale band is the corridor. Ringed points are support vectors. Switch to RBF and push γ up until the regions break into islands.

0.8
3.0
0.35

Illustrative standardized 2-D data, 14 clips per class, trained in your browser by simplified SMO on the dual problem.

The failure. Symptom: training accuracy 100%, test near chance. Measure: count support vectors; near every clip means memorising. Fix: grid-search C and γ under cross-validation, and standardize first, because the RBF distance is the unit bug of Chapter 5 again.

(u · v)2 = 25 and φ(u) · φ(v) = 25. What does that show?

Chapter 8

Hidden Markov Models and the Forward Pass

Add a prior that sounds continue, and score a whole sequence by sharing work across paths

Classify each 10 ms frame alone and the labels flicker: speech, speech, music, speech. No real sound switches 100 times a second. A hidden Markov model (HMM) fixes this. A hidden state moves from frame to frame by a transition probability, and each state emits what we observe. In speech, each emission model was a GMM from Chapter 6.

StateStartTo STo MEmits HEmits L
S (speech)0.60.70.30.80.2
M (music)0.40.40.60.30.7

H means high ZCR and L means low. We observe H, L, L. How likely is that under the model? Any of 23 = 8 state paths could make it, and for 100 frames with 3 states there are 3100, about 5 × 1047.

The forward pass shares work. Call αt(j) the chance of the first t observations with state j at time t. Call aij the chance of moving from i to j. Call bj(ot) the chance that j emits observation ot.

Say it aloud

Alpha-t of j equals the sum over i of alpha-t-minus-one of i times a-i-j, all times b-j of o-t.

αt(j)
alpha-t of j the chance of seeing o-1 to o-t and ending in state j.
Σi
the sum over i add over every state you could have come from.
αt−1(i)
alpha-t-minus-one of i last frame’s value for state i.
aij
a-i-j the chance of moving from state i to state j.
bj(ot)
b-j of o-t the chance that state j emits what we saw at time t.
In plain words

To be in state j now, you came from some state i. Multiply each old alpha by its move chance a-i-j and add them. Then multiply by the chance b-j that j shows what you observed. Repeat for each frame. The sum of the last alphas is the sequence chance.

With numbers

Start: α1(S) = 0.6 × 0.8 = 0.48 and α1(M) = 0.4 × 0.3 = 0.12. Next, after L: α2(S) = (0.48 × 0.7 + 0.12 × 0.4) × 0.2 = 0.0768, and α2(M) = (0.48 × 0.3 + 0.12 × 0.6) × 0.7 = 0.1512. One L flipped the belief to music.

One more step gives α3 = 0.022848 and 0.079632, so P(H, L, L) = 0.10248. Adding all 8 paths gives the same number. Swap the sum for a max and keep pointers, and you get the Viterbi path: S, M, M, with chance 0.042336, only 41% of the total.

Step the trellis

Each column is a frame; each node holds α. Press Step to send α along the edges, then apply the emission. Raise the stay-chance and see one odd frame stop flipping the belief.

0.70

The model in the table. The stay chance sets S to S; M to M is 0.6 shifted by the same amount. At 0.70 the numbers match the worked example.

The failure. Symptom: the forward pass returns exactly 0 on a long clip. Measure: 1,000 frames at about 0.1 each gives 10−1000, below the smallest double (about 10−308). Fix: work in logs with log-sum-exp, or rescale α every frame and add up the log scale factors.

The forward pass finds P(O) = 0.10248 in a few multiply-adds. What makes the shortcut exact?

Chapter 9

The Pipeline, the Benchmarks, the Ceiling

Trace one clip from 64,000 numbers to 78, score it honestly, and see what pooling throws away

StageShapeWhat it throws away
Waveform, 4 s at 16 kHz(64000,)nothing yet
Frames, 25 ms / 10 ms(398, 400)nothing; overlap adds copies
Magnitude spectrum(398, 201)phase
Mel bands, log, DCT, keep 13(398, 13)fine detail and pitch
Plus deltas(398, 39)nothing; adds motion
Mean and std pooling(78,)time order, all of it

Mean and standard deviation do not care about order. Shuffle a clip’s frames and the pooled vector stays bit for bit the same. So a siren rising and the same siren falling are one input. This is the bag of frames assumption. HMMs were the classical way around it.

Reverse the siren

Top: the centroid of each frame over time. Below: the pooled mean and standard deviation, and the response of one small diagonal filter that a CNN could learn. Switch the order.

Illustrative 32-frame siren from 0.8 to 2.4 kHz. The filter is a slope detector: the mean sign of each frame-to-frame change.

Honest scoring matters as much as the model. ESC-50 (Piczak, 2015) has 2,000 five-second clips in 50 classes, 40 each, in 5 fixed folds. UrbanSound8K (Salamon et al., 2014) has 8,732 slices of up to 4 s in 10 classes and 10 fixed folds. Both cut several clips from one recording, so a random split lets the model learn a recording’s background hum. Use the fixed folds.

Accuracy can also lie. A detector tested on 80 background, 15 alarm and 5 glass-break clips gets 72, 3 and 0 right: 75% accuracy. The per-class recalls are 0.90, 0.20 and 0. Their mean, the balanced accuracy, is 36.7%. On a balanced set like ESC-50, plain accuracy is fair.

System on ESC-50Accuracy
k-NN on pooled MFCC and ZCR32.2%
SVM, same features39.6%
Random forest, same features44.3%
Human listeners81.3%
CNN on log-mel (Piczak, 2015)64.5%
PANNs CNN14, fine-tuned (2020)94.7%
Audio Spectrogram Transformer (2021)95.6%

The best hand-feature system reached 44% where people reach 81%. In music the gap was smaller: Tzanetakis and Cook (2002) classified ten genres at 61% with timbre, rhythm and pitch features. Where hand features match the task, the classical stack competes.

Four things stopped it. Only the classifier learned; every feature was fixed in advance. MFCCs drop pitch and high detail, which non-speech sounds need. No stage could see a 2-D time-frequency shape such as a chirp. And it had no way to use more data, such as AudioSet’s two million clips (2017).

The failure. Symptom: 60% on ESC-50 with MFCCs and an SVM. Measure: check the split; clips from one source file sit in train and test. Fix: GroupKFold on the official folds. Expect the high 30s to mid 40s.

Why does ESC-50 ship five fixed folds instead of letting you shuffle?

Chapter 10

Field Guide

Keep the terms, numbers, checks and the whole pipeline in one place

A classical audio classifier frames the sound at 25 ms and 10 ms. It describes each frame with energy, ZCR, spectral shape and 13 MFCCs. It pools mean and spread over time, standardizes, and hands one vector to k-NN, a GMM or an SVM. An HMM puts order back when order matters.

TermWhat it isNumber on this page
Frame count1 + ⌊(N − L) / h⌋398 for 4 s at 16 kHz
Bin spacingsr / L40 Hz
ZCRsign changes / (L − 1)3/7 = 0.429
CentroidΣ f m / Σ m3,500 Hz on the toy
Mel2595 log10(1 + f / 700)8 kHz = 2,840 mel
MFCCDCT of log mel energies, keep 134.159, 0.906, −1.961, −0.375
z-score(v − μ) / σ, fit on trainnearest changes C to D
EM stepresponsibilities, then weighted refitmeans 4, 7 → 3.069, 7.931
SVM margin2 / ‖w‖2.828
Forward passαt(j) = [Σ αt−1(i) aij] bj(ot)P(H, L, L) = 0.10248

Checklist

  1. Pin the frame length, hop, window, padding (center), mel variant and DCT scaling.
  2. Subtract the frame mean before ZCR; add a small constant before every log and divide.
  3. Fit the scaler on training clips only.
  4. Evaluate on the dataset’s fixed folds, grouped by source recording.
  5. Report per-class recall, and balanced accuracy when classes are unequal.
  6. Floor GMM variances; grid-search SVM C and γ; seed every split.

The core in code

pythonimport numpy as np, librosa, glob, os
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.model_selection import GroupKFold, cross_val_score

SR, N_FFT, HOP = 16000, 400, 160                         # ch 1: 25 ms frames, 10 ms hop

def clip_features(path):
    x, _ = librosa.load(path, sr=SR)                          # (n_samples,)
    mf  = librosa.feature.mfcc(y=x, sr=SR, n_mfcc=13, n_fft=N_FFT, hop_length=HOP)  # ch 4: (13, T)
    d1, d2 = librosa.feature.delta(mf), librosa.feature.delta(mf, order=2)
    zcr = librosa.feature.zero_crossing_rate(x, frame_length=N_FFT, hop_length=HOP)  # ch 2
    cen = librosa.feature.spectral_centroid(y=x, sr=SR, n_fft=N_FFT, hop_length=HOP)   # ch 3
    F = np.vstack([mf, d1, d2, zcr, cen / SR])                   # (41, T)
    return np.concatenate([F.mean(1), F.std(1)])              # ch 5: (82,)

files = sorted(glob.glob('ESC-50/audio/*.wav'))               # names: fold-source-take-class.wav
X = np.stack([clip_features(f) for f in files])
y = np.array([int(os.path.basename(f)[:-4].split('-')[3]) for f in files])
folds = np.array([int(os.path.basename(f).split('-')[0]) for f in files])
clf = make_pipeline(StandardScaler(), SVC(kernel='rbf', C=10))        # ch 5, ch 7
print(cross_val_score(clf, X, y, groups=folds, cv=GroupKFold(5)).mean())   # ch 9: official folds

Where it sits

The front end in full is in Audio Representations. EE269: Cepstrum and MFCC derives the cepstrum, and EE269: The DFT the DFT. HMMs get their own lesson in Hidden Markov Models; the same recursion runs in the Bayes filter. EM gets a full treatment in EM and GMMs, SVMs in EE269: SVM. The moment a network replaced the GMM is in DNN-GMM-HMM Hybrids.

Keep going

Acoustic Scene Classification · PANNs · AST · Self-Supervised Speech · BEATs · CLAP · Whisper

Sources: Piczak, “ESC: Dataset for Environmental Sound Classification” (ACM MM 2015) and the ESC-50 repository; Salamon, Jacoby and Bello, UrbanSound8K (ACM MM 2014); Kong et al., PANNs; Gong et al., AST; Davis and Mermelstein (1980); Tzanetakis and Cook (2002). All toy numbers are illustrative and checked by script.

The takeaway. The classical pipeline is a chain of chosen forgettings: phase, pitch, fine detail, order. Each bought tractability on 2008 hardware. A hand feature is a prior, priors win when data is scarce, and data stopped being scarce.

Now press Present or Teach and explain from memory: why raw samples fail, what the 13 MFCCs keep, how one EM step moves the means, and why pooling cannot hear a siren reversed. Then go back to the hero, pick Speech, and find the noise level where the verdict flips.

Classical Audio Classification
Next: Acoustic Scene Classification · Back to Gleams