10. Cepstrum, mel and MFCC

Speech recognisers rarely use raw spectra. They warp the frequency axis to follow the ear (the mel scale), take logarithms to turn the source-filter product into a sum, and keep a dozen smooth “cepstral” coefficients that describe the vocal-tract envelope while discarding pitch. This notebook builds that pipeline, mel-frequency cepstral coefficients (MFCCs), from the real cepstrum upwards, and checks each step against the library and against librosa.

Learning outcomes. After working through this notebook you can

  • compute the real cepstrum of a frame and read the pitch period off it;

  • tell the HTK and Slaney mel scales apart, and know which one each library function uses;

  • rebuild the library’s mel spectrogram and MFCCs exactly from its STFT, including what the Python mel_spectrogram returns (the square root of the mel power);

  • convert this library’s MFCCs to librosa’s and explain every scale factor.

import matplotlib.pyplot as plt
import numpy as np
import scipy.signal

import audio_samples as aus

rng = np.random.default_rng(seed=2026)
F64 = np.dtype("float64")
FS = 16_000  # sample rate in Hz used throughout

Concept

Real cepstrum. For an \(N\)-point frame with DFT \(X[k]\),

\[c[q] = \frac{1}{N}\sum_{k=0}^{N-1} \ln|X[k]|\, e^{j2\pi kq/N}\]

where \(q\) is the quefrency in samples (\(q/f_s\) seconds, \(f_s\) the sample rate in Hz). Because \(|X|\) is real and even, \(c[q]\) is real and even. Taking logs turns the source-filter product \(|X| = |E|\cdot|H|\) into a sum, \(\ln|X| = \ln|E| + \ln|H|\): the smooth vocal-tract envelope \(|H|\) appears at low quefrencies, and a periodic source with period \(\tau_0\) samples produces a peak at \(q = \tau_0\), so \(\hat{f}_0 = f_s/q_{peak}\). The library has no cepstrum function; we compute it from its FFT ourselves.

Mel scale. Two conventions are in use, and this library uses both:

  • HTK: \(m = 2595\log_{10}(1 + f/700)\), inverse \(f = 700(10^{m/2595} - 1)\). Used by aus.utils.hz_to_mel, aus.utils.mel_to_hz and aus.utils.mel_frequencies.

  • Slaney (Auditory Toolbox): \(m = 3f/200\) for \(f < 1000\) Hz and \(m = 15 + 27\ln(f/1000)/\ln 6.4\) above. Used by the mel spectrogram and therefore by MFCCs.

Here \(f\) is in Hz and \(m\) in mels; the two scales have very different units (1000 Hz is about 1000 HTK mels but 15 Slaney mels), so never mix them.

Mel filterbank. \(M\) triangular filters with edges equally spaced in mels: \(f_i = m^{-1}(m(f_{min}) + i\,\Delta m)\), \(\Delta m = (m(f_{max}) - m(f_{min}))/(M+1)\), \(i = 0, \dots, M+1\). Filter \(i\) (neighbours \(f_{i-1} < f_i < f_{i+1}\), in Hz) weights FFT bin \(k\) at frequency \(k f_s/N_{fft}\) by

\[H_i(f) = \max\left(0, \min\left(\frac{f - f_{i-1}}{f_i - f_{i-1}}, \frac{f_{i+1} - f}{f_{i+1} - f_i}\right)\right)\]

and the mel power in band \(i\) is \(P_i = \sum_k H_i(kf_s/N_{fft})\,|X[k]|^2\) (squared signal units).

MFCC, as this library computes it. Per frame, with \(M\) mel bands from 0 Hz to \(f_s/2\) (no filter normalisation):

\[L_i = 10\log_{10}\max(P_i, 10^{-8}), \qquad c_k = \sum_{i=0}^{M-1} L_i\cos\left(\frac{\pi k(i + \frac{1}{2})}{M}\right), \qquad \tilde{c}_k = \left(1 + \frac{D}{2}\sin\frac{\pi k}{D}\right)c_k\]

where \(L_i\) is the log mel energy in dB with an absolute floor of \(-80\) dB, \(c_k\) the unnormalised DCT-II (\(k = 0, \dots, K-1\), \(K\) = n_mfcc) and \(\tilde{c}_k\) the liftered coefficient with lifter parameter \(D = 22\). Compared with the orthonormal DCT (\(c_0/\sqrt{M}\) and \(c_k\sqrt{2/M}\)) without a lifter, this library’s values before the lifter are larger by \(\sqrt{M}\) for \(c_0\) and \(\sqrt{M/2}\) for \(k \ge 1\).

With the library

A 0.25 s, 440 Hz tone; 32 ms frames every 10 ms, the usual speech setting. mel_spectrogram(SpectrogramParams, MelParams, LogParams=None) and mfcc(StftParams, n_mels, MfccParams) take different parameter objects.

audio = aus.sine_wave(440.0, 0.25, sample_rate=FS, amplitude=0.5, dtype=F64)
stft = aus.StftParams(n_fft=512, hop_size=160, window=aus.WindowType.hanning, centre=True)
sp = aus.SpectrogramParams(stft, FS)
mel_params = aus.MelParams(40, 0.0, FS / 2)

mel = np.asarray(audio.mel_spectrogram(sp, mel_params))
mfcc = np.asarray(audio.mfcc(stft, 40, aus.MfccParams(13)))
# 4000 samples, hop 160, centred frames: 1 + 4000/160 = 26 frames.
assert mel.shape == (40, 26)
assert mfcc.shape == (13, 26)  # 13 coefficients, c0 included, lifter 22

# The tone falls in the band whose centre is nearest 440 Hz. Below 1 kHz the Slaney
# scale is linear, so band i (0-based) is centred at (i + 1) * 73.57 Hz.
loudest = int(np.argmax(mel[:, 13]))
centre = (loudest + 1) * (200 / 3) * (15 + 27 * np.log(8) / np.log(6.4)) / 41
print(f"loudest mel band: {loudest}, centred at {centre:.1f} Hz")
assert loudest == 5 and abs(centre - 441.4) < 0.05

fig, axs = plt.subplots(1, 2, figsize=(8, 3))
axs[0].imshow(20 * np.log10(np.maximum(mel, 1e-6)), origin="lower", aspect="auto")
axs[0].set(xlabel="Frame (10 ms)", ylabel="Mel band", title="Mel spectrogram (dB)")
axs[1].imshow(mfcc, origin="lower", aspect="auto", cmap="coolwarm")
axs[1].set(xlabel="Frame (10 ms)", ylabel="Coefficient k", title="MFCC")
plt.tight_layout()
plt.show()
loudest mel band: 5, centred at 441.4 Hz
../_images/47223dc4b6a1688f2ed98b0e6a95b8518ab192e1fc99d30a44bdb6e35a8c78f4.png

How it works

The real cepstrum and cepstral pitch. A vowel-like frame (the formant filter of notebook 08 excited every 100 samples, \(f_0 = 160\) Hz), Hann-windowed, 1024 samples. The library’s fft returns the one-sided spectrum (bins \(0 \dots N/2\), like numpy.fft.rfft); because \(\ln|X|\) is even, numpy.fft.irfft gives the full inverse DFT from those bins.

def vowel(period, n=2600):
    a = np.array([1.0])
    for f, b in [(700.0, 80.0), (1220.0, 90.0), (2600.0, 120.0)]:
        r, th = np.exp(-np.pi * b / FS), 2 * np.pi * f / FS
        a = np.convolve(a, [1.0, -2 * r * np.cos(th), r * r])
    e = np.zeros(n)
    e[::period] = 1.0
    return scipy.signal.lfilter([1.0], a, e)


def cepstrum(frame):
    # Real cepstrum of a frame from the library's one-sided FFT.
    n = len(frame)
    X = np.asarray(aus.AudioSamples.new_mono(frame, sample_rate=FS).fft(n))[0]  # bins 0..n/2
    return np.fft.irfft(np.log(np.maximum(np.abs(X), 1e-12)), n)


N = 1024
frame = np.hanning(N) * vowel(100)[1500 : 1500 + N]  # np.hanning is the symmetric Hann
ceps = cepstrum(frame)

# Check against the definition with the full two-sided numpy FFT.
direct = np.fft.ifft(np.log(np.maximum(np.abs(np.fft.fft(frame)), 1e-12))).real
assert np.allclose(ceps, direct, atol=1e-12)

q_lo, q_hi = int(FS / 400), int(FS / 60)  # search f0 between 60 and 400 Hz: q = 40 ... 266
q_peak = q_lo + int(np.argmax(ceps[q_lo : q_hi + 1]))
print(f"cepstral peak at q = {q_peak} samples -> f0 = {FS / q_peak} Hz")
assert q_peak == 100 and FS / q_peak == 160.0

fig, ax = plt.subplots(figsize=(8, 3))
q = np.arange(N // 2)
ax.plot(1000 * q / FS, ceps[: N // 2])
ax.axvline(1000 * q_peak / FS, color="C3", ls=":", label="pitch peak (6.25 ms)")
ax.set(xlabel="Quefrency (ms)", ylabel="c[q]", title="Real cepstrum of a 160 Hz vowel", ylim=(-0.5, 1.8))
ax.legend()
plt.show()
assert 1000 * q_peak / FS == 6.25
cepstral peak at q = 100 samples -> f0 = 160.0 Hz
../_images/17c1d66c972927cfd6bd095b2e10bbdc3924cef73c98c7e3d448ba33aec4ef1a.png

The two mel scales, side by side. aus.utils.hz_to_mel is HTK; the Slaney scale is written out below and checked against librosa.hz_to_mel. hz_to_mel and mel_to_hz round-trip. aus.utils.mel_frequencies is also HTK, so it does not give the centre frequencies of the library’s mel spectrogram bands.

import librosa

slaney = lambda f: np.where(f < 1000, 3 * f / 200, 15 + 27 * np.log(np.maximum(f, 1e-9) / 1000) / np.log(6.4))
for f in [0.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0]:
    htk = aus.utils.hz_to_mel(f)
    print(f"{f:6.0f} Hz: HTK {htk:8.2f} mel, Slaney {float(slaney(f)):6.3f} mel")
    assert abs(htk - 2595 * np.log10(1 + f / 700)) < 1e-9
    assert abs(aus.utils.mel_to_hz(htk) - f) < 1e-9  # HTK round trip
    assert abs(librosa.hz_to_mel(f) - slaney(f)) < 1e-9  # Slaney reference
assert abs(aus.utils.hz_to_mel(1000.0) - 999.99) < 0.005
assert abs(aus.utils.hz_to_mel(4000.0) - 2146.06) < 0.005
assert slaney(1000.0) == 15.0 and abs(slaney(4000.0) - 35.164) < 5e-4
# mel_frequencies follows the HTK scale, not the Slaney filterbank.
assert np.allclose(aus.utils.mel_frequencies(5, 0.0, 8000.0), librosa.mel_frequencies(5, fmin=0, fmax=8000, htk=True))
assert not np.allclose(aus.utils.mel_frequencies(5, 0.0, 8000.0), librosa.mel_frequencies(5, fmin=0, fmax=8000))
     0 Hz: HTK     0.00 mel, Slaney  0.000 mel
   500 Hz: HTK   607.45 mel, Slaney  7.500 mel
  1000 Hz: HTK   999.99 mel, Slaney 15.000 mel
  2000 Hz: HTK  1521.36 mel, Slaney 25.082 mel
  4000 Hz: HTK  2146.06 mel, Slaney 35.164 mel
  8000 Hz: HTK  2840.02 mel, Slaney 45.246 mel

The filterbank, and what mel_spectrogram returns. We rebuild the 40 triangles on the Slaney scale and apply them to the power \(|X|^2\) of the library’s own STFT. The STFT itself is re-derived first: symmetric Hann window, frames centred by padding \(N/2\) zeros at both ends.

The result is the mel power \(P_i\). The Python mel_spectrogram without LogParams returns \(\sqrt{P_i}\) (a “magnitude” mel spectrogram; it is not the filterbank applied to \(|X|\)), and with LogParams it returns \(20\log_{10}\sqrt{P_i} = 10\log_{10} P_i\), floored at floor_db.

X = np.asarray(audio.stft(stft).data)  # complex, (n_fft/2 + 1, frames)
x = audio.to_numpy()
padded = np.pad(x, 256)  # centre=True: zero padding of n_fft/2
frames = np.stack([padded[t * 160 : t * 160 + 512] for t in range(X.shape[1])], axis=1)
X_ours = np.fft.rfft(np.hanning(512)[:, None] * frames, axis=0)
assert np.allclose(X_ours, X, atol=1e-12)  # same products, f64: rounding level

# Slaney triangles with peak 1 (no normalisation).
slaney_inv = lambda m: np.where(m < 15, 200 * m / 3, 1000 * np.exp(np.log(6.4) * (m - 15) / 27))
M = 40
edges = slaney_inv(np.arange(M + 2) * slaney(FS / 2) / (M + 1))
f_bins = np.arange(257) * FS / 512
fb = np.array([np.clip(np.minimum((f_bins - edges[i]) / (edges[i + 1] - edges[i]),
                                  (edges[i + 2] - f_bins) / (edges[i + 2] - edges[i + 1])), 0, None)
               for i in range(M)])
assert np.allclose(fb, librosa.filters.mel(sr=FS, n_fft=512, n_mels=40, norm=None, dtype=np.float64), atol=1e-12)

P = fb @ np.abs(X) ** 2  # mel power
assert np.allclose(np.sqrt(P), mel, rtol=1e-10)  # Python mel_spectrogram = sqrt(mel power)
assert not np.allclose(fb @ np.abs(X), mel, rtol=1e-3)  # ... not the filterbank applied to |X|
mel_db = np.asarray(audio.mel_spectrogram(sp, mel_params, aus.LogParams(-80.0)))
assert np.allclose(mel_db, 10 * np.log10(np.maximum(P, 1e-8)), atol=1e-9)
print("mel_spectrogram = sqrt(fb @ |X|^2); with LogParams(-80): 10 log10(max(P, 1e-8))")
mel_spectrogram = sqrt(fb @ |X|^2); with LogParams(-80): 10 log10(max(P, 1e-8))

MFCC, re-derived from the library’s log-mel spectrogram: the unnormalised DCT-II and the lifter must give mfcc exactly. Then librosa, with every convention matched: the same symmetric Hann window, zero padding, no filter normalisation (norm=None), no top_db clipping. librosa’s orthonormal DCT then differs from ours by exactly \(\sqrt{M}\) for \(c_0\) and \(\sqrt{M/2}\) for \(k \ge 1\), times our lifter weights.

vowel_audio = aus.AudioSamples.new_mono(0.5 * vowel(133, 8000) / np.abs(vowel(133, 8000)).max(), sample_rate=FS)
L_db = np.asarray(vowel_audio.mel_spectrogram(sp, mel_params, aus.LogParams(-80.0)))
lib = np.asarray(vowel_audio.mfcc(stft, 40, aus.MfccParams(13)))

k = np.arange(13)
dct = np.cos(np.pi * k[:, None] * (np.arange(M)[None, :] + 0.5) / M)  # unnormalised DCT-II
lifter = 1 + 11 * np.sin(np.pi * k / 22)
ours = lifter[:, None] * (dct @ L_db)
# MFCC values reach about 1600 here; 1e-9 absolute is rounding level.
assert np.allclose(ours, lib, atol=1e-9)

S = librosa.feature.melspectrogram(y=vowel_audio.to_numpy(), sr=FS, n_fft=512, hop_length=160,
                                   window=np.hanning(512), center=True, pad_mode="constant",
                                   n_mels=40, fmin=0.0, fmax=FS / 2, norm=None, dtype=np.float64)
ref = librosa.feature.mfcc(S=librosa.power_to_db(S, top_db=None), n_mfcc=13)  # ortho DCT, no lifter
scale = np.r_[np.sqrt(M), np.full(12, np.sqrt(M / 2))]
assert np.allclose(lib, (scale * lifter)[:, None] * ref, atol=1e-8)
ratio = lib[:, 25] / ref[:, 25]
print("aus / librosa for c0, c1, c3:", np.round(ratio[[0, 1, 3]], 3))
assert abs(ratio[0] - np.sqrt(40)) < 1e-9  # 6.325
assert abs(ratio[1] - np.sqrt(20) * (1 + 11 * np.sin(np.pi / 22))) < 1e-9  # 11.473
aus / librosa for c0, c1, c3: [ 6.325 11.473 24.908]

So with 40 bands this library’s \(c_0\) is \(\sqrt{40} = 6.32\) times librosa’s and \(c_1\) is \(\sqrt{20}\,(1 + 11\sin(\pi/22)) = 11.47\) times. With librosa’s own default settings the numbers differ further, and not by a constant factor, so features computed with one library cannot be fed to a model trained with the other.

default = librosa.feature.mfcc(y=vowel_audio.to_numpy(), sr=FS, n_mfcc=13, n_fft=512, hop_length=160, n_mels=40)
r_default = lib[:, 25] / default[:, 25]
print("aus / librosa-default ratios, c0..c3:", np.round(r_default[:4], 2))
assert not np.allclose(r_default[1:], (scale * lifter)[1:], rtol=0.01)
aus / librosa-default ratios, c0..c3: [ 1.75 10.77 19.56  8.31]

Ask the library to explain

aus.explain.explain(MelParams, sample_rate=..., n_fft=...) tabulates the band edges and counts filters that contain no FFT bin. With 128 bands and n_fft = 256 at 16 kHz the bins are 62.5 Hz apart but the lowest triangles are only 46.8 Hz wide. We check the prediction against a real spectrogram.

mel128 = aus.MelParams(128, 0.0, 8000.0)
doc = aus.explain.explain(mel128, sample_rate=16_000.0, n_fft=256)
empty = int(doc.quantity("Empty filters"))
assert empty == 13
assert doc.has_warning_containing("contain no FFT bin")
assert abs(doc.quantity("Narrowest band width") - 46.77) < 0.01

# The computed spectrogram of white noise has exactly that many all-zero bands.
noise = aus.white_noise(0.25, sample_rate=16_000, amplitude=0.5, dtype=F64, seed=7)
sp256 = aus.SpectrogramParams(aus.StftParams(256, 128, aus.WindowType.hanning, True), 16_000.0)
s = np.asarray(noise.mel_spectrogram(sp256, mel128))
assert int(np.sum(np.all(s == 0.0, axis=1))) == empty
doc

Mel filterbank

128 triangular filters spaced evenly on the Slaney mel scale between 0 Hz and 8000 Hz; bands are 46.7655 Hz wide at the bottom and 376.669 Hz wide at the top. Normalisation: None.

Formulas

Slaney mel scale, as implemented (linear below 1 kHz, logarithmic above). The HTK form 2595 log10(1 + f/700) is not used:

$$ m(f) = \begin{cases} \frac{3f}{200} & f < 1000 \ 15 + \frac{27 \ln(f/1000)}{\ln 6.4} & f \geq 1000 \end{cases} $$

Band edges: M + 2 points equally spaced on the mel scale:

$$ f_i = m^{-1}\left(m(f_{min}) + i , \frac{m(f_{max}) - m(f_{min})}{M + 1}\right), \quad i = 0, \dots, M+1 $$

Triangular filter i evaluated at each FFT bin frequency (peak 1):

$$ H_i(f) = \max\left(0, \min\left(\frac{f - f_{i-1}}{f_i - f_{i-1}}, \frac{f_{i+1} - f}{f_{i+1} - f_i}\right)\right) $$

Symbols

| Symbol | Meaning | Value | |—|—|—| | $M$ | number of mel bands | 128 | | $f_{min}$ | lowest edge | 0 Hz | | $f_{max}$ | highest edge | 8000 Hz | | $norm$ | filter normalisation | None: triangles keep peak 1, so wide high-frequency bands collect more energy |

Derived quantities

| Quantity | Value | Formula | |—|—|—| | Mel range | $m(f_{max}) - m(f_{min})$ = 45.2456 mel | $m(f_{max}) - m(f_{min})$ | | Mel spacing | $\Delta m$ = 0.350741 mel | $(m(f_{max}) - m(f_{min}))/(M+1)$ | | Lowest band centre | $f_1$ = 23.3828 Hz | $m^{-1}(m(f_{min}) + \Delta m)$ | | Highest band centre | $f_M$ = 7809.39 Hz | $m^{-1}(m(f_{max}) - \Delta m)$ | | Narrowest band width | $f_2 - f_0$ = 46.7655 Hz | $f_{i+1} - f_{i-1}$ | | Widest band width | $f_{M+1} - f_{M-1}$ = 376.669 Hz | $f_{i+1} - f_{i-1}$ | | FFT bin spacing | $\Delta f$ = 62.5 Hz | $f_s / N$ | | Empty filters | $M_{empty}$ = 13 | $#{i : H_i(k f_s/N) = 0 \ \forall k}$ |

Band edges (lowest and highest bands)

| Band | Lower (Hz) | Centre (Hz) | Upper (Hz) | Width (Hz) | |—|—|—|—|—| | 1 | 0 | 23.3828 | 46.7655 | 46.7655 | | 2 | 23.3828 | 46.7655 | 70.1483 | 46.7655 | | 3 | 46.7655 | 70.1483 | 93.531 | 46.7655 | | 126 | 7264.4 | 7441.7 | 7623.33 | 358.934 | | 127 | 7441.7 | 7623.33 | 7809.39 | 367.695 | | 128 | 7623.33 | 7809.39 | 8000 | 376.669 |

Trade-offs

  • More mel bands give finer spectral detail but narrower low-frequency bands, which may contain no FFT bin.

  • Mel spacing approximates the frequency resolution of the ear: roughly linear below 1 kHz and logarithmic above.

Warnings

  • Caution: 13 of 128 mel filters contain no FFT bin (bin spacing 62.5 Hz, narrowest band 46.7655 Hz); those bands are always zero. Hint: Use fewer mel bands, raise f_min, or a larger n_fft.

See also

  • Mel spectrogram: audio_samples::AudioTransforms::mel_power_spectrogram

  • Python: audio_samples.explain.explain(MelParams)

# MFCC: the lifter weights 1 + 11 sin(pi k / 22) peak at k = 11.
mdoc = aus.explain.explain(aus.MfccParams(13), n_mels=40)
assert mdoc.quantity("Largest lifter weight") == 12.0
# Cepstrum: the longest quefrency of a 1024-point frame is 512 samples, so f0 > 31.25 Hz.
cdoc = aus.explain.cepstrum(1024, 16_000.0)
assert cdoc.quantity("Lowest detectable f0") == 31.25
assert cdoc.has_warning_containing("no stand-alone cepstrum")
mdoc

Mel-frequency cepstral coefficients (MFCC)

Each frame’s mel power spectrum is converted to dB, decorrelated with a DCT-II, and the first 13 coefficients are kept, liftered with L = 22.

Formulas

Log mel energies in dB with an absolute floor of -80 dB (mel filterbank 0 Hz to f_s/2, no normalisation):

$$ L_i = 10 \log_{10} \max\left(P_i, 10^{-8}\right) $$

Unnormalised DCT-II, as implemented. An orthonormal DCT-II would return c_0/sqrt(M) and c_k·sqrt(2/M) instead:

$$ c_k = \sum_{i=0}^{M-1} L_i \cos\left(\frac{\pi k (i + \frac{1}{2})}{M}\right) $$

Sinusoidal liftering with k counted from 0, so c_0 keeps weight 1:

$$ \tilde{c}_k = \left(1 + \frac{L}{2} \sin\left(\frac{\pi k}{L}\right)\right) c_k $$

Symbols

| Symbol | Meaning | Value | |—|—|—| | $K$ | coefficients computed | 13 | | $L$ | lifter parameter (0 = off) | 22 | | $P_i$ | power in mel band i | | | $M$ | number of mel bands | 40 |

Derived quantities

| Quantity | Value | Formula | |—|—|—| | Output coefficients per frame | $K_{out}$ = 13 | $K - [\text{c}_0 \text{ dropped}]$ | | Largest lifter weight | $\max_k w_k$ = 12 | $1 + (L/2)\sin(\pi k/L)$ |

Lifter weights

| k | weight | |—|—| | 0 | 1 | | 1 | 2.56546 | | 2 | 4.09906 | | 3 | 5.56957 | | 4 | 6.94705 | | 5 | 8.20347 | | 6 | 9.31325 | | 7 | 10.2538 | | 8 | 11.006 | | 9 | 11.5544 | | 10 | 11.888 | | 11 | 12 | | 12 | 11.888 |

Trade-offs

  • Low-order coefficients describe the smooth spectral envelope (vocal-tract shape); higher ones capture finer detail and pitch harmonics.

  • Dropping c0 makes features insensitive to overall loudness.

See also

  • Compute: audio_samples::AudioTransforms::mfcc

  • Compute (Python): audio_samples.AudioSamples.mfcc

  • From log-mel: spectrograms::mfcc_from_log_mel

  • Python: audio_samples.explain.explain(MfccParams)

Exercises

Exercise 1 (quefrency). A 250 Hz voice is analysed with 1024-point frames at 16 kHz. At which quefrency (in samples) do you expect the cepstral peak? Check with a synthetic vowel and store the measured peak in answer.

answer = None  # TODO
# Solution
c = cepstrum(np.hanning(1024) * vowel(64)[1500:2524])  # one pulse every 64 samples = 250 Hz
answer = 40 + int(np.argmax(c[40:267]))
assert answer == 64 and 1000 * answer / FS == 4.0  # 64 samples, 4 ms

Exercise 2 (units). Predict aus.utils.hz_to_mel(700.0) and the Slaney mel value of 700 Hz. Store the pair in answer.

answer = None  # TODO
# Solution
answer = (aus.utils.hz_to_mel(700.0), 3 * 700.0 / 200)
assert abs(answer[0] - 781.17) < 0.005  # 2595 log10(2)
assert answer[1] == 10.5 and abs(librosa.hz_to_mel(700.0) - 10.5) < 1e-12

Exercise 3 (empty bands). For 128 mel bands at 16 kHz, what is the smallest power-of-two n_fft with no empty filter? Store it in answer.

answer = None  # TODO
# Solution
empty_for = lambda n_fft: aus.explain.explain(mel128, sample_rate=16_000.0, n_fft=n_fft).quantity("Empty filters")
assert empty_for(128) > empty_for(256) > 0  # coarser bins, more empty bands
answer = 512  # bins 31.25 Hz apart, narrower than the 46.8 Hz lowest triangle
assert empty_for(answer) == 0

Exercise 4 (comparing with librosa). With 40 mel bands and the default lifter, by what total factor does this library’s \(c_3\) exceed librosa’s (same log-mel input, orthonormal DCT)? Predict, then check against the ratio computed above. Store the factor in answer.

answer = None  # TODO
# Solution
answer = np.sqrt(40 / 2) * (1 + 11 * np.sin(3 * np.pi / 22))
assert abs(answer - 24.91) < 0.005
assert abs(ratio[3] - answer) < 1e-9

Common pitfalls

  • Two mel scales. aus.utils.hz_to_mel, mel_to_hz and mel_frequencies are HTK; the mel spectrogram and MFCCs are Slaney. Do not label mel spectrogram bands with mel_frequencies.

  • mel_spectrogram returns \(\sqrt{\text{mel power}}\), not mel power and not the filterbank applied to \(|X|\); square it to compare with librosa.feature.melspectrogram (power 2). With LogParams it returns \(10\log_{10}\) of the power with an absolute floor (not one relative to the peak).

  • No filter normalisation by default. MelParams(..., norm=None) keeps triangles of peak 1; norm='slaney' gives equal-area triangles.

  • Unnormalised DCT and lifter 22 (with \(k\) counted from 0): MFCC values are much larger than those of an orthonormal DCT without a lifter. From Python, MfccParams exposes only n_mfcc; the lifter and the choice to drop \(c_0\) cannot be changed, so divide by the lifter weights yourself.

  • Absolute log floor. The dB step clamps at \(10^{-8}\) (\(-80\) dB re 1), so a quiet signal’s MFCCs depend on its level.

  • Symmetric Hann. WindowType.hanning is the symmetric window; spectra computed with the periodic one (scipy.signal.get_window("hann", N)) differ slightly.

  • AudioSamples.fft(n) is one-sided (\(n/2 + 1\) bins), like numpy.fft.rfft.

See also

  • Rust guide chapter: Cepstrum, mel and MFCC (available from the next release; until then build the docs locally with cargo doc --features educational,full_no_plotting --open).

  • Python API: AudioSamples.mel_spectrogram, AudioSamples.mfcc, AudioSamples.stft, AudioSamples.fft, MelParams, MfccParams, LogParams, aus.utils.hz_to_mel, aus.explain.explain, aus.explain.cepstrum (API reference).

  • Previous: 09. Pitch. Next: 11. Energy and voice activity.

References

  • Davis, S. B. and Mermelstein, P. (1980). Comparison of parametric representations for monosyllabic word recognition in continuously spoken sentences. IEEE Transactions on Acoustics, Speech, and Signal Processing, 28(4), 357-366.

  • Slaney, M. (1998). Auditory Toolbox, version 2. Technical Report 1998-010, Interval Research Corporation. (The Slaney mel scale and filterbank.)

  • Juang, B.-H., Rabiner, L. R. and Wilpon, J. G. (1987). On the use of bandpass liftering in speech recognition. IEEE Transactions on Acoustics, Speech, and Signal Processing, 35(7), 947-954. (The sinusoidal lifter.)

  • Oppenheim, A. V. and Schafer, R. W. (2010). Discrete-Time Signal Processing, 3rd ed. Pearson. Chapter 13 (cepstrum analysis and homomorphic deconvolution).