{ "cells": [ { "cell_type": "markdown", "id": "c000", "metadata": {}, "source": [ "# 10. Cepstrum, mel and MFCC\n", "\n", "Speech recognisers rarely use raw spectra. They warp the frequency axis to follow the ear (the mel\n", "scale), take logarithms to turn the source-filter product into a sum, and keep a dozen smooth\n", "\"cepstral\" coefficients that describe the vocal-tract envelope while discarding pitch. This\n", "notebook builds that pipeline, mel-frequency cepstral coefficients (MFCCs), from the real cepstrum\n", "upwards, and checks each step against the library and against librosa.\n", "\n", "**Learning outcomes.** After working through this notebook you can\n", "\n", "* compute the real cepstrum of a frame and read the pitch period off it;\n", "* tell the HTK and Slaney mel scales apart, and know which one each library function uses;\n", "* rebuild the library's mel spectrogram and MFCCs exactly from its STFT, including what the Python\n", " `mel_spectrogram` returns (the square root of the mel power);\n", "* convert this library's MFCCs to librosa's and explain every scale factor." ] }, { "cell_type": "code", "execution_count": null, "id": "c001", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import scipy.signal\n", "\n", "import audio_samples as aus\n", "\n", "rng = np.random.default_rng(seed=2026)\n", "F64 = np.dtype(\"float64\")\n", "FS = 16_000 # sample rate in Hz used throughout" ] }, { "cell_type": "markdown", "id": "c002", "metadata": {}, "source": [ "## Concept\n", "\n", "**Real cepstrum.** For an $N$-point frame with DFT $X[k]$,\n", "\n", "$$c[q] = \\frac{1}{N}\\sum_{k=0}^{N-1} \\ln|X[k]|\\, e^{j2\\pi kq/N}$$\n", "\n", "where $q$ is the *quefrency* in samples ($q/f_s$ seconds, $f_s$ the sample rate in Hz). Because\n", "$|X|$ is real and even, $c[q]$ is real and even. Taking logs turns the source-filter product\n", "$|X| = |E|\\cdot|H|$ into a sum, $\\ln|X| = \\ln|E| + \\ln|H|$: the smooth vocal-tract envelope $|H|$\n", "appears at low quefrencies, and a periodic source with period $\\tau_0$ samples produces a peak at\n", "$q = \\tau_0$, so $\\hat{f}_0 = f_s/q_{peak}$. The library has **no cepstrum function**; we compute it\n", "from its FFT ourselves.\n", "\n", "**Mel scale.** Two conventions are in use, and this library uses both:\n", "\n", "- HTK: $m = 2595\\log_{10}(1 + f/700)$, inverse $f = 700(10^{m/2595} - 1)$. Used by\n", " `aus.utils.hz_to_mel`, `aus.utils.mel_to_hz` and `aus.utils.mel_frequencies`.\n", "- Slaney (Auditory Toolbox): $m = 3f/200$ for $f < 1000$ Hz and\n", " $m = 15 + 27\\ln(f/1000)/\\ln 6.4$ above. Used by the mel spectrogram and therefore by MFCCs.\n", "\n", "Here $f$ is in Hz and $m$ in mels; the two scales have very different units (1000 Hz is about\n", "1000 HTK mels but 15 Slaney mels), so never mix them.\n", "\n", "**Mel filterbank.** $M$ triangular filters with edges equally spaced in mels:\n", "$f_i = m^{-1}(m(f_{min}) + i\\,\\Delta m)$, $\\Delta m = (m(f_{max}) - m(f_{min}))/(M+1)$,\n", "$i = 0, \\dots, M+1$. Filter $i$ (neighbours $f_{i-1} < f_i < f_{i+1}$, in Hz) weights FFT bin $k$ at\n", "frequency $k f_s/N_{fft}$ by\n", "\n", "$$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)$$\n", "\n", "and the mel power in band $i$ is $P_i = \\sum_k H_i(kf_s/N_{fft})\\,|X[k]|^2$ (squared signal units).\n", "\n", "**MFCC, as this library computes it.** Per frame, with $M$ mel bands from 0 Hz to $f_s/2$ (no\n", "filter normalisation):\n", "\n", "$$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$$\n", "\n", "where $L_i$ is the log mel energy in dB with an absolute floor of $-80$ dB, $c_k$ the\n", "**unnormalised** DCT-II ($k = 0, \\dots, K-1$, $K$ = `n_mfcc`) and $\\tilde{c}_k$ the liftered\n", "coefficient with lifter parameter $D = 22$. Compared with the orthonormal DCT\n", "($c_0/\\sqrt{M}$ and $c_k\\sqrt{2/M}$) without a lifter, this library's values before the lifter\n", "are larger by $\\sqrt{M}$ for $c_0$ and $\\sqrt{M/2}$ for $k \\ge 1$." ] }, { "cell_type": "markdown", "id": "c003", "metadata": {}, "source": [ "## With the library\n", "\n", "A 0.25 s, 440 Hz tone; 32 ms frames every 10 ms, the usual speech setting.\n", "`mel_spectrogram(SpectrogramParams, MelParams, LogParams=None)` and\n", "`mfcc(StftParams, n_mels, MfccParams)` take different parameter objects." ] }, { "cell_type": "code", "execution_count": null, "id": "c004", "metadata": {}, "outputs": [], "source": [ "audio = aus.sine_wave(440.0, 0.25, sample_rate=FS, amplitude=0.5, dtype=F64)\n", "stft = aus.StftParams(n_fft=512, hop_size=160, window=aus.WindowType.hanning, centre=True)\n", "sp = aus.SpectrogramParams(stft, FS)\n", "mel_params = aus.MelParams(40, 0.0, FS / 2)\n", "\n", "mel = np.asarray(audio.mel_spectrogram(sp, mel_params))\n", "mfcc = np.asarray(audio.mfcc(stft, 40, aus.MfccParams(13)))\n", "# 4000 samples, hop 160, centred frames: 1 + 4000/160 = 26 frames.\n", "assert mel.shape == (40, 26)\n", "assert mfcc.shape == (13, 26) # 13 coefficients, c0 included, lifter 22\n", "\n", "# The tone falls in the band whose centre is nearest 440 Hz. Below 1 kHz the Slaney\n", "# scale is linear, so band i (0-based) is centred at (i + 1) * 73.57 Hz.\n", "loudest = int(np.argmax(mel[:, 13]))\n", "centre = (loudest + 1) * (200 / 3) * (15 + 27 * np.log(8) / np.log(6.4)) / 41\n", "print(f\"loudest mel band: {loudest}, centred at {centre:.1f} Hz\")\n", "assert loudest == 5 and abs(centre - 441.4) < 0.05\n", "\n", "fig, axs = plt.subplots(1, 2, figsize=(8, 3))\n", "axs[0].imshow(20 * np.log10(np.maximum(mel, 1e-6)), origin=\"lower\", aspect=\"auto\")\n", "axs[0].set(xlabel=\"Frame (10 ms)\", ylabel=\"Mel band\", title=\"Mel spectrogram (dB)\")\n", "axs[1].imshow(mfcc, origin=\"lower\", aspect=\"auto\", cmap=\"coolwarm\")\n", "axs[1].set(xlabel=\"Frame (10 ms)\", ylabel=\"Coefficient k\", title=\"MFCC\")\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "c005", "metadata": {}, "source": [ "## How it works\n", "\n", "**The real cepstrum and cepstral pitch.** A vowel-like frame (the formant filter of notebook 08\n", "excited every 100 samples, $f_0 = 160$ Hz), Hann-windowed, 1024 samples. The library's `fft`\n", "returns the one-sided spectrum (bins $0 \\dots N/2$, like `numpy.fft.rfft`); because $\\ln|X|$ is\n", "even, `numpy.fft.irfft` gives the full inverse DFT from those bins." ] }, { "cell_type": "code", "execution_count": null, "id": "c006", "metadata": {}, "outputs": [], "source": [ "def vowel(period, n=2600):\n", " a = np.array([1.0])\n", " for f, b in [(700.0, 80.0), (1220.0, 90.0), (2600.0, 120.0)]:\n", " r, th = np.exp(-np.pi * b / FS), 2 * np.pi * f / FS\n", " a = np.convolve(a, [1.0, -2 * r * np.cos(th), r * r])\n", " e = np.zeros(n)\n", " e[::period] = 1.0\n", " return scipy.signal.lfilter([1.0], a, e)\n", "\n", "\n", "def cepstrum(frame):\n", " # Real cepstrum of a frame from the library's one-sided FFT.\n", " n = len(frame)\n", " X = np.asarray(aus.AudioSamples.new_mono(frame, sample_rate=FS).fft(n))[0] # bins 0..n/2\n", " return np.fft.irfft(np.log(np.maximum(np.abs(X), 1e-12)), n)\n", "\n", "\n", "N = 1024\n", "frame = np.hanning(N) * vowel(100)[1500 : 1500 + N] # np.hanning is the symmetric Hann\n", "ceps = cepstrum(frame)\n", "\n", "# Check against the definition with the full two-sided numpy FFT.\n", "direct = np.fft.ifft(np.log(np.maximum(np.abs(np.fft.fft(frame)), 1e-12))).real\n", "assert np.allclose(ceps, direct, atol=1e-12)\n", "\n", "q_lo, q_hi = int(FS / 400), int(FS / 60) # search f0 between 60 and 400 Hz: q = 40 ... 266\n", "q_peak = q_lo + int(np.argmax(ceps[q_lo : q_hi + 1]))\n", "print(f\"cepstral peak at q = {q_peak} samples -> f0 = {FS / q_peak} Hz\")\n", "assert q_peak == 100 and FS / q_peak == 160.0\n", "\n", "fig, ax = plt.subplots(figsize=(8, 3))\n", "q = np.arange(N // 2)\n", "ax.plot(1000 * q / FS, ceps[: N // 2])\n", "ax.axvline(1000 * q_peak / FS, color=\"C3\", ls=\":\", label=\"pitch peak (6.25 ms)\")\n", "ax.set(xlabel=\"Quefrency (ms)\", ylabel=\"c[q]\", title=\"Real cepstrum of a 160 Hz vowel\", ylim=(-0.5, 1.8))\n", "ax.legend()\n", "plt.show()\n", "assert 1000 * q_peak / FS == 6.25" ] }, { "cell_type": "markdown", "id": "c007", "metadata": {}, "source": [ "**The two mel scales**, side by side. `aus.utils.hz_to_mel` is HTK; the Slaney scale is written\n", "out below and checked against `librosa.hz_to_mel`. `hz_to_mel` and `mel_to_hz` round-trip.\n", "`aus.utils.mel_frequencies` is also HTK, so it\n", "does **not** give the centre frequencies of the library's mel spectrogram bands." ] }, { "cell_type": "code", "execution_count": null, "id": "c008", "metadata": {}, "outputs": [], "source": [ "import librosa\n", "\n", "slaney = lambda f: np.where(f < 1000, 3 * f / 200, 15 + 27 * np.log(np.maximum(f, 1e-9) / 1000) / np.log(6.4))\n", "for f in [0.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0]:\n", " htk = aus.utils.hz_to_mel(f)\n", " print(f\"{f:6.0f} Hz: HTK {htk:8.2f} mel, Slaney {float(slaney(f)):6.3f} mel\")\n", " assert abs(htk - 2595 * np.log10(1 + f / 700)) < 1e-9\n", " assert abs(aus.utils.mel_to_hz(htk) - f) < 1e-9 # HTK round trip\n", " assert abs(librosa.hz_to_mel(f) - slaney(f)) < 1e-9 # Slaney reference\n", "assert abs(aus.utils.hz_to_mel(1000.0) - 999.99) < 0.005\n", "assert abs(aus.utils.hz_to_mel(4000.0) - 2146.06) < 0.005\n", "assert slaney(1000.0) == 15.0 and abs(slaney(4000.0) - 35.164) < 5e-4\n", "# mel_frequencies follows the HTK scale, not the Slaney filterbank.\n", "assert np.allclose(aus.utils.mel_frequencies(5, 0.0, 8000.0), librosa.mel_frequencies(5, fmin=0, fmax=8000, htk=True))\n", "assert not np.allclose(aus.utils.mel_frequencies(5, 0.0, 8000.0), librosa.mel_frequencies(5, fmin=0, fmax=8000))" ] }, { "cell_type": "markdown", "id": "c009", "metadata": {}, "source": [ "**The filterbank, and what `mel_spectrogram` returns.** We rebuild the 40 triangles on the Slaney\n", "scale and apply them to the power $|X|^2$ of the library's own STFT. The STFT itself is\n", "re-derived first: symmetric Hann window, frames centred by padding $N/2$ zeros at both ends.\n", "\n", "The result is the mel **power** $P_i$. The Python `mel_spectrogram` without `LogParams` returns\n", "$\\sqrt{P_i}$ (a \"magnitude\" mel spectrogram; it is *not* the filterbank applied to $|X|$), and with\n", "`LogParams` it returns $20\\log_{10}\\sqrt{P_i} = 10\\log_{10} P_i$, floored at `floor_db`." ] }, { "cell_type": "code", "execution_count": null, "id": "c010", "metadata": {}, "outputs": [], "source": [ "X = np.asarray(audio.stft(stft).data) # complex, (n_fft/2 + 1, frames)\n", "x = audio.to_numpy()\n", "padded = np.pad(x, 256) # centre=True: zero padding of n_fft/2\n", "frames = np.stack([padded[t * 160 : t * 160 + 512] for t in range(X.shape[1])], axis=1)\n", "X_ours = np.fft.rfft(np.hanning(512)[:, None] * frames, axis=0)\n", "assert np.allclose(X_ours, X, atol=1e-12) # same products, f64: rounding level\n", "\n", "# Slaney triangles with peak 1 (no normalisation).\n", "slaney_inv = lambda m: np.where(m < 15, 200 * m / 3, 1000 * np.exp(np.log(6.4) * (m - 15) / 27))\n", "M = 40\n", "edges = slaney_inv(np.arange(M + 2) * slaney(FS / 2) / (M + 1))\n", "f_bins = np.arange(257) * FS / 512\n", "fb = np.array([np.clip(np.minimum((f_bins - edges[i]) / (edges[i + 1] - edges[i]),\n", " (edges[i + 2] - f_bins) / (edges[i + 2] - edges[i + 1])), 0, None)\n", " for i in range(M)])\n", "assert np.allclose(fb, librosa.filters.mel(sr=FS, n_fft=512, n_mels=40, norm=None, dtype=np.float64), atol=1e-12)\n", "\n", "P = fb @ np.abs(X) ** 2 # mel power\n", "assert np.allclose(np.sqrt(P), mel, rtol=1e-10) # Python mel_spectrogram = sqrt(mel power)\n", "assert not np.allclose(fb @ np.abs(X), mel, rtol=1e-3) # ... not the filterbank applied to |X|\n", "mel_db = np.asarray(audio.mel_spectrogram(sp, mel_params, aus.LogParams(-80.0)))\n", "assert np.allclose(mel_db, 10 * np.log10(np.maximum(P, 1e-8)), atol=1e-9)\n", "print(\"mel_spectrogram = sqrt(fb @ |X|^2); with LogParams(-80): 10 log10(max(P, 1e-8))\")" ] }, { "cell_type": "markdown", "id": "c011", "metadata": {}, "source": [ "**MFCC, re-derived** from the library's log-mel spectrogram: the unnormalised DCT-II and the lifter\n", "must give `mfcc` exactly. Then **librosa**, with every convention matched: the same symmetric Hann\n", "window, zero padding, no filter normalisation (`norm=None`), no\n", "`top_db` clipping. librosa's orthonormal DCT then differs from ours by exactly $\\sqrt{M}$ for\n", "$c_0$ and $\\sqrt{M/2}$ for $k \\ge 1$, times our lifter weights." ] }, { "cell_type": "code", "execution_count": null, "id": "c012", "metadata": {}, "outputs": [], "source": [ "vowel_audio = aus.AudioSamples.new_mono(0.5 * vowel(133, 8000) / np.abs(vowel(133, 8000)).max(), sample_rate=FS)\n", "L_db = np.asarray(vowel_audio.mel_spectrogram(sp, mel_params, aus.LogParams(-80.0)))\n", "lib = np.asarray(vowel_audio.mfcc(stft, 40, aus.MfccParams(13)))\n", "\n", "k = np.arange(13)\n", "dct = np.cos(np.pi * k[:, None] * (np.arange(M)[None, :] + 0.5) / M) # unnormalised DCT-II\n", "lifter = 1 + 11 * np.sin(np.pi * k / 22)\n", "ours = lifter[:, None] * (dct @ L_db)\n", "# MFCC values reach about 1600 here; 1e-9 absolute is rounding level.\n", "assert np.allclose(ours, lib, atol=1e-9)\n", "\n", "S = librosa.feature.melspectrogram(y=vowel_audio.to_numpy(), sr=FS, n_fft=512, hop_length=160,\n", " window=np.hanning(512), center=True, pad_mode=\"constant\",\n", " n_mels=40, fmin=0.0, fmax=FS / 2, norm=None, dtype=np.float64)\n", "ref = librosa.feature.mfcc(S=librosa.power_to_db(S, top_db=None), n_mfcc=13) # ortho DCT, no lifter\n", "scale = np.r_[np.sqrt(M), np.full(12, np.sqrt(M / 2))]\n", "assert np.allclose(lib, (scale * lifter)[:, None] * ref, atol=1e-8)\n", "ratio = lib[:, 25] / ref[:, 25]\n", "print(\"aus / librosa for c0, c1, c3:\", np.round(ratio[[0, 1, 3]], 3))\n", "assert abs(ratio[0] - np.sqrt(40)) < 1e-9 # 6.325\n", "assert abs(ratio[1] - np.sqrt(20) * (1 + 11 * np.sin(np.pi / 22))) < 1e-9 # 11.473" ] }, { "cell_type": "markdown", "id": "c013", "metadata": {}, "source": [ "So with 40 bands this library's $c_0$ is $\\sqrt{40} = 6.32$ times librosa's and $c_1$ is\n", "$\\sqrt{20}\\,(1 + 11\\sin(\\pi/22)) = 11.47$ times. With librosa's own default settings the numbers\n", "differ further, and not by a constant factor, so features computed with one library cannot be fed\n", "to a model trained with the other." ] }, { "cell_type": "code", "execution_count": null, "id": "c014", "metadata": {}, "outputs": [], "source": [ "default = librosa.feature.mfcc(y=vowel_audio.to_numpy(), sr=FS, n_mfcc=13, n_fft=512, hop_length=160, n_mels=40)\n", "r_default = lib[:, 25] / default[:, 25]\n", "print(\"aus / librosa-default ratios, c0..c3:\", np.round(r_default[:4], 2))\n", "assert not np.allclose(r_default[1:], (scale * lifter)[1:], rtol=0.01)" ] }, { "cell_type": "markdown", "id": "c015", "metadata": {}, "source": [ "## Ask the library to explain\n", "\n", "`aus.explain.explain(MelParams, sample_rate=..., n_fft=...)` tabulates the band edges and counts\n", "filters that contain no FFT bin. With 128 bands and `n_fft = 256` at 16 kHz the bins are 62.5 Hz\n", "apart but the lowest triangles are only 46.8 Hz wide. We check the prediction against a real\n", "spectrogram." ] }, { "cell_type": "code", "execution_count": null, "id": "c016", "metadata": {}, "outputs": [], "source": [ "mel128 = aus.MelParams(128, 0.0, 8000.0)\n", "doc = aus.explain.explain(mel128, sample_rate=16_000.0, n_fft=256)\n", "empty = int(doc.quantity(\"Empty filters\"))\n", "assert empty == 13\n", "assert doc.has_warning_containing(\"contain no FFT bin\")\n", "assert abs(doc.quantity(\"Narrowest band width\") - 46.77) < 0.01\n", "\n", "# The computed spectrogram of white noise has exactly that many all-zero bands.\n", "noise = aus.white_noise(0.25, sample_rate=16_000, amplitude=0.5, dtype=F64, seed=7)\n", "sp256 = aus.SpectrogramParams(aus.StftParams(256, 128, aus.WindowType.hanning, True), 16_000.0)\n", "s = np.asarray(noise.mel_spectrogram(sp256, mel128))\n", "assert int(np.sum(np.all(s == 0.0, axis=1))) == empty\n", "doc" ] }, { "cell_type": "code", "execution_count": null, "id": "c017", "metadata": {}, "outputs": [], "source": [ "# MFCC: the lifter weights 1 + 11 sin(pi k / 22) peak at k = 11.\n", "mdoc = aus.explain.explain(aus.MfccParams(13), n_mels=40)\n", "assert mdoc.quantity(\"Largest lifter weight\") == 12.0\n", "# Cepstrum: the longest quefrency of a 1024-point frame is 512 samples, so f0 > 31.25 Hz.\n", "cdoc = aus.explain.cepstrum(1024, 16_000.0)\n", "assert cdoc.quantity(\"Lowest detectable f0\") == 31.25\n", "assert cdoc.has_warning_containing(\"no stand-alone cepstrum\")\n", "mdoc" ] }, { "cell_type": "markdown", "id": "c018", "metadata": {}, "source": [ "## Exercises\n", "\n", "**Exercise 1 (quefrency).** A 250 Hz voice is analysed with 1024-point frames at 16 kHz. At which\n", "quefrency (in samples) do you expect the cepstral peak? Check with a synthetic vowel and store the\n", "measured peak in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c019", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c020", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "c = cepstrum(np.hanning(1024) * vowel(64)[1500:2524]) # one pulse every 64 samples = 250 Hz\n", "answer = 40 + int(np.argmax(c[40:267]))\n", "assert answer == 64 and 1000 * answer / FS == 4.0 # 64 samples, 4 ms" ] }, { "cell_type": "markdown", "id": "c021", "metadata": {}, "source": [ "**Exercise 2 (units).** Predict `aus.utils.hz_to_mel(700.0)` and the Slaney mel value of 700 Hz.\n", "Store the pair in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c022", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c023", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "answer = (aus.utils.hz_to_mel(700.0), 3 * 700.0 / 200)\n", "assert abs(answer[0] - 781.17) < 0.005 # 2595 log10(2)\n", "assert answer[1] == 10.5 and abs(librosa.hz_to_mel(700.0) - 10.5) < 1e-12" ] }, { "cell_type": "markdown", "id": "c024", "metadata": {}, "source": [ "**Exercise 3 (empty bands).** For 128 mel bands at 16 kHz, what is the smallest power-of-two\n", "`n_fft` with no empty filter? Store it in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c025", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c026", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "empty_for = lambda n_fft: aus.explain.explain(mel128, sample_rate=16_000.0, n_fft=n_fft).quantity(\"Empty filters\")\n", "assert empty_for(128) > empty_for(256) > 0 # coarser bins, more empty bands\n", "answer = 512 # bins 31.25 Hz apart, narrower than the 46.8 Hz lowest triangle\n", "assert empty_for(answer) == 0" ] }, { "cell_type": "markdown", "id": "c027", "metadata": {}, "source": [ "**Exercise 4 (comparing with librosa).** With 40 mel bands and the default lifter, by what total\n", "factor does this library's $c_3$ exceed librosa's (same log-mel input, orthonormal DCT)? Predict,\n", "then check against the `ratio` computed above. Store the factor in `answer`." ] }, { "cell_type": "code", "execution_count": null, "id": "c028", "metadata": {}, "outputs": [], "source": [ "answer = None # TODO" ] }, { "cell_type": "code", "execution_count": null, "id": "c029", "metadata": { "tags": [ "solution" ] }, "outputs": [], "source": [ "# Solution\n", "answer = np.sqrt(40 / 2) * (1 + 11 * np.sin(3 * np.pi / 22))\n", "assert abs(answer - 24.91) < 0.005\n", "assert abs(ratio[3] - answer) < 1e-9" ] }, { "cell_type": "markdown", "id": "c030", "metadata": {}, "source": [ "## Common pitfalls\n", "\n", "- **Two mel scales.** `aus.utils.hz_to_mel`, `mel_to_hz` and `mel_frequencies` are HTK; the mel\n", " spectrogram and MFCCs are Slaney. Do not label mel spectrogram bands with `mel_frequencies`.\n", "- **`mel_spectrogram` returns $\\sqrt{\\text{mel power}}$**, not mel power and not the filterbank\n", " applied to $|X|$; square it to compare with `librosa.feature.melspectrogram` (power 2). With\n", " `LogParams` it returns $10\\log_{10}$ of the power with an absolute floor (not one relative to\n", " the peak).\n", "- **No filter normalisation by default.** `MelParams(..., norm=None)` keeps triangles of peak 1;\n", " `norm='slaney'` gives equal-area triangles.\n", "- **Unnormalised DCT and lifter 22** (with $k$ counted from 0): MFCC values are much larger than\n", " those of an orthonormal DCT without a lifter. From Python, `MfccParams` exposes only `n_mfcc`;\n", " the lifter and the choice to drop $c_0$ cannot be changed, so divide by the lifter weights\n", " yourself.\n", "- **Absolute log floor.** The dB step clamps at $10^{-8}$ ($-80$ dB re 1), so a quiet signal's\n", " MFCCs depend on its level.\n", "- **Symmetric Hann.** `WindowType.hanning` is the symmetric window; spectra computed with the\n", " periodic one (`scipy.signal.get_window(\"hann\", N)`) differ slightly.\n", "- **`AudioSamples.fft(n)` is one-sided** ($n/2 + 1$ bins), like `numpy.fft.rfft`.\n", "\n", "## See also\n", "\n", "- Rust guide chapter: [Cepstrum, mel and MFCC](https://docs.rs/audio_samples/latest/audio_samples/guide/c10_cepstrum_mel_mfcc/index.html) (available from the next release; until then build the docs locally with `cargo doc --features educational,full_no_plotting --open`).\n", "- Python API: `AudioSamples.mel_spectrogram`, `AudioSamples.mfcc`, `AudioSamples.stft`,\n", " `AudioSamples.fft`, `MelParams`, `MfccParams`, `LogParams`, `aus.utils.hz_to_mel`,\n", " `aus.explain.explain`, `aus.explain.cepstrum` ([API reference](../api/audio_samples.rst)).\n", "- Previous: [09. Pitch](09_pitch.ipynb). Next: [11. Energy and voice activity](11_energy_vad.ipynb)." ] }, { "cell_type": "markdown", "id": "references", "metadata": {}, "source": [ "## References\n", "\n", "* 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.\n", "* Slaney, M. (1998). *Auditory Toolbox*, version 2. Technical Report 1998-010, Interval Research Corporation. (The Slaney mel scale and filterbank.)\n", "* 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.)\n", "* Oppenheim, A. V. and Schafer, R. W. (2010). *Discrete-Time Signal Processing*, 3rd ed. Pearson. Chapter 13 (cepstrum analysis and homomorphic deconvolution)." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }