Algorithmcore
Mel-frequency cepstral coefficients
Also called MFCC, mel cepstrum.
Speech features from the discrete cosine transform of the log mel filter bank energies of each frame, keeping the first dozen or so.
- Time
- O(T (N log N + M N + K M)) worst
- Space
- O(M N + T K) extra
- Where
- K = the number of coefficients kept; M = the number of filters; N = the FFT length; T = the number of frames
- Model
- Real RAM
- Properties
- deterministicexactnot in placeonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Steven Davis, Paul Mermelstein, 1980
Mel-frequency cepstral coefficients, or MFCC, are a short vector of numbers per frame of speech, usually 13, that describe the shape of the spectral envelope. They are computed by pre-emphasis, a mel filter bank with a log, and a discrete cosine transform of the log energies, of which only the first coefficients are kept. They differ from the log mel energies of the mel filter bank only by that last transform, which decorrelates them and drops the fine detail, and from PLP cepstra, which smooth a Bark-scale spectrum with an all-pole model in place of the cosine transform. Delta features and cepstral mean normalization are usually applied to MFCC afterwards.
In plain words
A speech sound is shaped mostly by the mouth and throat, and that shape shows as a smooth outline of the spectrum, with peaks at the resonances. MFCC describe that outline with a few numbers. First, the high frequencies are boosted a little. Then the signal is cut into short overlapping pieces, and for each piece the energy in about 26 bands is measured, with narrow bands at low pitch and wide bands at high pitch, as the ear does. The logs of these energies are then described as a sum of cosine waves across the bands. The first cosine gives the overall loudness, the next ones give the broad tilt and the large bumps, and the later ones give finer detail. Keeping only the first 13 keeps the outline and drops the ripples that come from the pitch of the voice.
The problem
Given a signal with samples in at Hz, compute one vector per frame. The defaults of this page are those of HTK where it has one: kHz, pre-emphasis with , frames of samples with a hop of 160 and no padding, so frames, the symmetric Hamming window, an FFT of points, triangular filters from 0 Hz to on the scale , the natural log with a floor of , coefficients to , and a sine lifter with . Kaldi uses 23 filters by default. This page applies the filters to the power spectrum; HTK applies them to the magnitude, and its numbers differ.
The algorithm
The orthonormal DCT-II of the log energies is
and the sine lifter multiplies by .
MFCC(x, f_s, M, K, Q)- 1
y[0] ← x[0]; y[n] ← x[n] - 0.97 x[n - 1] for n ≥ 1 ▷ pre-emphasis - 2
W ← the M triangular mel weights for N = 512 and f_s ▷ MEL-FILTER-BANK lines L1 to L8 - 3
for each frame v of y (400 samples, hop 160, no padding) do - 4
u[i] ← v[i] · (0.54 - 0.46 cos(2π i / 399)) for i ← 0 to 399 - 5
P[k] ← |Σ_i u[i] e^{-2π j k i / 512}|² for k ← 0 to 256 ▷ by the FFT - 6
E[m] ← Σ_k W[m][k] P[k] for m ← 1 to M - 7
ℓ[m] ← ln max(E[m], 10⁻¹⁰) - 8
c ← the first K values of the orthonormal DCT-II of ℓ - 9
output c'[n] ← (1 + (Q/2) sin(π n / Q)) c[n] for n ← 0 to K - 1
Line L1 runs over the whole signal; HTK applies it inside each frame, which changes only the first sample of each frame. Line L4 uses the symmetric Hamming window, which is 0.08 at both ends. Lines L6 and L7 are lines L9 and L10 of the mel filter bank. Line L8 is the discrete cosine transform of type II. Davis and Mermelstein wrote it without the factors , as ; HTK uses for every , including . The orthonormal form of this page makes the transform an orthogonal matrix. Many systems replace by the log energy of the frame.
Example
A frame of digital silence gives for all , so line L7 gives in every band. The DCT of a constant vector is zero except for , which for is , and the lifter leaves unchanged. So silence is the vector .
If a frame is multiplied by 3, every power value is multiplied by 9 and every log energy grows by . Again only changes, by . All of to stay the same, so they do not depend on the loudness.
The lifter weights for are, for to 12: 1, 2.565, 4.099, 5.570, 6.947, 8.203, 9.313, 10.254, 11.006, 11.554, 11.888, 12 and 11.888. They raise the higher coefficients, which are small, to a size like the lower ones.
For a sine of 440 Hz and amplitude 1 at 16 kHz, the first frame gives, rounded, . One second of this signal gives 98 such vectors.
Correctness
MFCC are a defined transform, so correctness means that each line computes its part. The full proofs are below.
- The DCT is orthogonal. With the factors , the full DCT-II matrix has (theorem). So with and no lifter, , and no information is lost before the truncation to coefficients.
- Loudness goes into only. A gain on the frame adds to every above the floor. The DCT of a constant vector is zero in every coefficient but , so only changes, by (theorem).
- A fixed channel becomes an additive constant, approximately. A linear filter with frequency response multiplies by about . If is nearly constant inside each band, every grows by a fixed amount , and every frame's by one fixed vector (heuristic: exact only for a flat response in each band and a filter much shorter than the frame). Cepstral mean normalization uses this.
- Truncation smooths. Keeping the first of coefficients and inverting gives the least squares fit of by the first cosines, a smoothed version of the log spectrum (theorem, from the orthogonality).
Proof: What each step of MFCC computes, and why the gain only moves c_0full
We work in the real RAM. The frames, the window and the FFT are those of the shared helper, and the FFT returns the DFT exactly. Lines L6 and L7 are the mel filter bank, whose weights are proved there to be triangles that sum to 1 between the first and last centers. What is left to prove is the part that is new on this page: the DCT of line L8, the effect of a gain, the meaning of the truncation, and the lifter. Let and .
Lemma 1 (a cosine sum). For every integer with , .
Proof. Let , so and . The sum is the real part of , a geometric sum with ratio . Here . If is even, . If is odd, , which is purely imaginary. In both cases the real part is 0.
Lemma 2 (the DCT is orthogonal). Let be the matrix with entries for and , where and for . Then .
Proof. Write and , and use . Summed over , the two terms are the sums of Lemma 1 with and , or the constant when . If , both are nonzero and , so the sum is 0. If , the sum of is , and . If , then gives and , with , gives 0, so the sum is and .
So line L8 computes , where is the first rows of . With and no lifter, , because a square matrix with also has .
Lemma 3 (constant vectors). If for every , then and for .
Proof. . For , by Lemma 1 with .
Lemma 4 (a gain moves only ). Let the frame give the log energies , and let the frame with give . If all energies of both frames are at least , then and for , before and after the lifter.
Proof. Line L1 is linear, and lines L4 and L5 give a power spectrum that scales by . Line L6 is linear, so , and line L7 gives by the condition. Line L8 is linear, so , and Lemma 3 gives the claim. The lifter of line L9 multiplies by a factor that depends only on , and its factor at is , so the claim holds after it too.
Lemma 5 (truncation is a least squares fit). For , the vector , built from the kept coefficients, is the vector closest to in the Euclidean norm among all combinations of the first rows of .
Proof. The rows of are orthonormal by Lemma 2, so the first rows are an orthonormal basis of their span. The closest point of a subspace with an orthonormal basis is , and .
Theorem. For every frame, MFCC returns for , where is the first coefficients of an orthogonal transform of the floored log mel energies of the pre-emphasized, Hamming-windowed frame. A gain on the signal changes only , by , as long as no energy is at the floor, and the kept coefficients give the best fit of the log energies by cosines.
Proof. Lines L1 to L7 compute the floored log energies by their definitions and by the mel filter bank proof. Lemma 2 gives the orthogonality, Lemma 4 the gain, and Lemma 5 the fit. Line L9 is the definition of the lifter.
The tests check Lemma 2 on an matrix, the Parseval identity with 26 coefficients, Lemma 3 on silence, Lemma 4 with , and the whole chain against a slow direct computation with explicit DFT sums, triangles and cosine sums.
Complexity
In the real RAM, each frame costs for lines L4 and line L1's share, for the FFT, for line L6 with dense weights (or with sparse weights), and for the DCT done directly, so frames cost . The weights take memory and the output . With the defaults, one second of audio is 98 FFTs of 512 points, which is small work for any processor.
Properties
- Compact. 13 numbers per 10 ms describe the envelope; with the delta features the usual vector has 39.
- Nearly decorrelated. The DCT is close to the principal components of log filter bank energies of speech (a measurement, not a theorem), so the coefficients are nearly uncorrelated, and a Gaussian mixture with diagonal covariances fits them well.
- Gain invariant except . By the second claim above.
- Sensitive to additive noise. Noise adds to the power, not to the log, so it changes the coefficients in a nonlinear way; low energy bands are hit hardest.
- Not invertible. The pitch harmonics and the phase are gone, so speech cannot be rebuilt well from MFCC alone.
Variants and improvements
- Energy in place of . HTK and many systems append the log energy of the frame and drop , or keep both.
- Number of filters and coefficients. 20 filters (Davis and Mermelstein), 23 (Kaldi), 26 (HTK) or 40; 12 or 13 coefficients for recognition, more for speaker work.
- Liftering. The sine lifter with is HTK's; others use no lifter, because a diagonal-covariance model removes the scale anyway.
- Normalization. Cepstral mean normalization and variance normalization over the utterance or a sliding window, and vocal tract length normalization, which warps the filter frequencies per speaker.
- Relatives. PLP cepstra replace the filter bank and DCT by a Bark spectrum and an all-pole fit; RASTA filtering filters the log bands over time before the transform; LPC cepstra come from linear predictive coding.
- No DCT. Neural network recognizers mostly take the log mel energies directly, because they do not need decorrelated inputs.
When to use it
Use MFCC for classical speech recognition with GMM-HMM models, for template matching with dynamic time warping, and for speaker features such as i-vectors, where decorrelated low-dimensional inputs matter. They are also a cheap and robust feature for audio classification with small data. For neural networks trained on large data, log mel filter bank energies usually work as well or better. For tasks that need pitch, such as intonation or tone languages, add a pitch feature, because MFCC remove most of it.
Pitfalls
- Comparing toolkits. Power or magnitude, the mel formula, the filter count, the DCT scaling, the lifter, the log floor and per-frame or whole-signal pre-emphasis all differ between HTK, Kaldi and librosa, and change the numbers.
- Too many filters for the FFT. With 40 or more filters and a short FFT, the lowest filters can be empty. Check that every filter has a nonzero weight.
- Silence and the floor. Digital silence gives at the floor and the other coefficients 0; frames near silence give large, noisy values. Many systems add a tiny dither noise before the analysis.
- Mismatched sample rates. Features of 8 kHz audio and 16 kHz audio are not comparable, because the filter range changes.
- Expecting noise robustness. MFCC are not robust to additive noise; use noise reduction, such as spectral subtraction, or train on noisy data.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mel-frequency-cepstral-coefficients/. The authors are listed in prov/85RNE7.jsonl.
"""Mel-frequency cepstral coefficients (MFCC) of a speech signal.
The steps, with the defaults of the page (HTK values where HTK has one):
pre-emphasis with alpha = 0.97 over the whole signal, frames of 400 samples with a
hop of 160 and no padding, the symmetric Hamming window, the power spectrum with
an FFT of 512 points, 26 triangular filters equally spaced on the mel scale
m = 2595 log_10(1 + f / 700) from 0 Hz to fs / 2, the natural log with a floor of
1e-10, the orthonormal DCT-II, coefficients c_0 to c_12, and the sine lifter with
L = 22.
The framing, the window, the FFT and the DCT come from the shared helper nlsdsp.
"""
import math
from typing import List, Optional, Sequence
from nlsdsp import dct2, frames, hamming, power_spectrum
def hz_to_mel(f: float) -> float:
return 2595.0 * math.log10(1.0 + f / 700.0)
def mel_to_hz(m: float) -> float:
return 700.0 * (10.0 ** (m / 2595.0) - 1.0)
def pre_emphasis(x: Sequence[float], alpha: float = 0.97) -> List[float]:
"""y[0] = x[0] and y[n] = x[n] - alpha x[n - 1] for n >= 1."""
return [x[0]] + [x[n] - alpha * x[n - 1] for n in range(1, len(x))] if x else []
def mel_weights(num_filters: int, nfft: int, fs: float, fmin: float = 0.0, fmax: Optional[float] = None):
"""Triangular weights W[m][k], linear in Hz, with edges equally spaced in mel."""
if fmax is None:
fmax = fs / 2.0
if num_filters < 1 or not 0.0 <= fmin < fmax <= fs / 2.0:
raise ValueError("need num_filters >= 1 and 0 <= fmin < fmax <= fs / 2")
lo, hi = hz_to_mel(fmin), hz_to_mel(fmax)
step = (hi - lo) / (num_filters + 1)
edges = [mel_to_hz(lo + i * step) for i in range(num_filters + 2)]
weights = []
for m in range(1, num_filters + 1):
left, center, right = edges[m - 1], edges[m], edges[m + 1]
row = []
for k in range(nfft // 2 + 1):
f = k * fs / nfft
if left < f <= center:
row.append((f - left) / (center - left))
elif center < f < right:
row.append((right - f) / (right - center))
else:
row.append(0.0)
weights.append(row)
return weights
def lifter(c: Sequence[float], q: int) -> List[float]:
"""The sine lifter c'_n = (1 + (q / 2) sin(pi n / q)) c_n. q = 0 leaves c unchanged."""
if q <= 0:
return list(c)
return [(1.0 + 0.5 * q * math.sin(math.pi * n / q)) * v for n, v in enumerate(c)]
def mfcc_of_frame(
frame: Sequence[float],
weights: Sequence[Sequence[float]],
window: Sequence[float],
nfft: int = 512,
num_ceps: int = 13,
cep_lifter: int = 22,
floor: float = 1e-10,
) -> List[float]:
"""The MFCC vector c_0 to c_{num_ceps - 1} of one frame (already pre-emphasized)."""
u = [s * w for s, w in zip(frame, window)] # @line L4
p = power_spectrum(u, nfft) # @line L5
e = [sum(w * v for w, v in zip(row, p)) for row in weights] # @line L6
log_e = [math.log(max(v, floor)) for v in e] # @line L7
c = dct2(log_e, num_ceps) # @line L8
return lifter(c, cep_lifter) # @line L9
def mfcc(
x: Sequence[float],
fs: float = 16000.0,
num_filters: int = 26,
num_ceps: int = 13,
frame_len: int = 400,
hop: int = 160,
nfft: int = 512,
alpha: float = 0.97,
cep_lifter: int = 22,
fmin: float = 0.0,
fmax: Optional[float] = None,
floor: float = 1e-10,
) -> List[List[float]]:
"""One row of num_ceps coefficients per frame. A signal of L >= frame_len samples
gives 1 + (L - frame_len) // hop rows; a shorter signal gives none."""
if num_ceps > num_filters:
raise ValueError("num_ceps must be at most num_filters")
y = pre_emphasis(x, alpha) # @line L1
weights = mel_weights(num_filters, nfft, fs, fmin, fmax) # @line L2
window = hamming(frame_len)
return [
mfcc_of_frame(fr, weights, window, nfft, num_ceps, cep_lifter, floor)
for fr in frames(y, frame_len, hop) # @line L3
]
nlsdsp.py 191 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small signal processing tools for the natural-language-and-speech pages.
A signal is a list of floats x[0], ..., x[L - 1], usually in [-1, 1]. A frame is
a list of floats. A spectrum is a list of floats or complex numbers.
The defaults of the area are fs = 16000 Hz, frames of 400 samples (25 ms), a hop
of 160 samples (10 ms), the symmetric Hamming window and an FFT length of 512.
The LPC sign convention is A(z) = 1 - sum_{k=1}^{p} a_k z^-k, so the prediction
of x[n] is sum_{k=1}^{p} a_k x[n - k].
This module holds no algorithm of any page of the area: no mel scale, no mel
filter bank, no feature extractor, no pre-emphasis and no zero-crossing rate.
The pages build those on top of it.
"""
import cmath
import math
from typing import List, Sequence, Tuple
def frames(x: Sequence[float], frame_len: int, hop: int) -> List[List[float]]:
"""Cut x into frames of frame_len samples, one every hop samples, with no padding.
A signal of L >= frame_len samples gives 1 + (L - frame_len) // hop frames.
A signal shorter than one frame gives no frame. The last samples that do not
fill a frame are dropped.
"""
if frame_len <= 0 or hop <= 0:
raise ValueError("frame_len and hop must be positive")
n = len(x)
if n < frame_len:
return []
count = 1 + (n - frame_len) // hop
return [list(x[i * hop : i * hop + frame_len]) for i in range(count)]
def hamming(n: int) -> List[float]:
"""The symmetric Hamming window w[i] = 0.54 - 0.46 cos(2 pi i / (n - 1)), i = 0 to n - 1."""
if n <= 0:
raise ValueError("the window length must be positive")
if n == 1:
return [1.0]
return [0.54 - 0.46 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]
def hann(n: int) -> List[float]:
"""The symmetric Hann window w[i] = 0.5 - 0.5 cos(2 pi i / (n - 1)), i = 0 to n - 1."""
if n <= 0:
raise ValueError("the window length must be positive")
if n == 1:
return [1.0]
return [0.5 - 0.5 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]
def fft(x: Sequence[complex]) -> List[complex]:
"""The DFT X[k] = sum_n x[n] exp(-2 pi i k n / N) by the iterative radix 2 FFT.
The length N must be a power of 2. The cost is O(N log N) operations.
"""
n = len(x)
if n == 0 or n & (n - 1):
raise ValueError("the FFT length must be a power of 2")
a = [complex(v) for v in x]
# bit reversal permutation
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
w_step = cmath.exp(-2j * math.pi / size)
for start in range(0, n, size):
w = 1.0 + 0.0j
for k in range(start, start + half):
u = a[k]
v = a[k + half] * w
a[k] = u + v
a[k + half] = u - v
w *= w_step
size *= 2
return a
def power_spectrum(frame: Sequence[float], nfft: int) -> List[float]:
"""|X[k]|^2 for k = 0 to nfft / 2, where X is the DFT of the frame zero padded to nfft."""
if len(frame) > nfft:
raise ValueError("the frame is longer than the FFT length")
spec = fft(list(frame) + [0.0] * (nfft - len(frame)))
return [abs(spec[k]) ** 2 for k in range(nfft // 2 + 1)]
def dct2(x: Sequence[float], k: int) -> List[float]:
"""The first k coefficients of the orthonormal DCT-II of x.
c[j] = s_j sum_{n=0}^{N-1} x[n] cos(pi j (2 n + 1) / (2 N)), with s_0 = sqrt(1 / N)
and s_j = sqrt(2 / N) for j >= 1. The full transform (k = N) is an orthogonal matrix.
"""
n = len(x)
if n == 0:
raise ValueError("empty input")
if k < 0 or k > n:
raise ValueError("k must be between 0 and len(x)")
out = []
for j in range(k):
s = math.sqrt((1.0 if j == 0 else 2.0) / n)
out.append(s * sum(x[i] * math.cos(math.pi * j * (2 * i + 1) / (2 * n)) for i in range(n)))
return out
def autocorr(x: Sequence[float], max_lag: int) -> List[float]:
"""r[k] = sum_{n=0}^{L-1-k} x[n] x[n + k] for k = 0 to max_lag (no normalization)."""
n = len(x)
return [sum(x[i] * x[i + k] for i in range(n - k)) if k < n else 0.0 for k in range(max_lag + 1)]
def levinson(r: Sequence[float], p: int) -> Tuple[List[float], float]:
"""Solve the normal equations of linear prediction of order p by the Levinson-Durbin recursion.
Returns (a, e): a = [a_1, ..., a_p] with A(z) = 1 - sum a_k z^-k, and e the
prediction error of order p. Needs r[0] > 0 and len(r) > p. If the error
reaches 0 before order p (a perfectly predictable signal), the remaining
coefficients are 0.
"""
if len(r) <= p:
raise ValueError("need r[0] to r[p]")
if r[0] <= 0:
raise ValueError("r[0] must be positive")
a = [0.0] * (p + 1) # a[0] is unused
e = float(r[0])
for i in range(1, p + 1):
if e <= 0.0:
break
acc = r[i] - sum(a[j] * r[i - j] for j in range(1, i))
k = acc / e
new = a[:]
new[i] = k
for j in range(1, i):
new[j] = a[j] - k * a[i - j]
a = new
e *= 1.0 - k * k
return a[1:], e
def sine(f: float, fs: float, n: int, amp: float = 1.0, phase: float = 0.0) -> List[float]:
"""x[i] = amp sin(2 pi f i / fs + phase) for i = 0 to n - 1."""
return [amp * math.sin(2.0 * math.pi * f * i / fs + phase) for i in range(n)]
def pulse_train(f0: float, fs: float, n: int) -> List[float]:
"""Unit pulses at the samples round(j fs / f0), j = 0, 1, 2, ..., and 0 elsewhere, n samples."""
if f0 <= 0:
raise ValueError("f0 must be positive")
x = [0.0] * n
period = fs / f0
j = 0
while True:
pos = int(math.floor(j * period + 0.5))
if pos >= n:
break
x[pos] = 1.0
j += 1
return x
def white_noise(rng, n: int, sigma: float) -> List[float]:
"""n samples of Gaussian noise with mean 0 and standard deviation sigma, from rng (a random.Random)."""
return [rng.gauss(0.0, sigma) for _ in range(n)]
def all_pole(x: Sequence[float], a: Sequence[float]) -> List[float]:
"""Filter x through 1 / A(z): y[n] = x[n] + sum_{k=1}^{p} a_k y[n - k], with zero initial state."""
p = len(a)
y: List[float] = []
for i, v in enumerate(x):
acc = float(v)
for k in range(1, p + 1):
if i - k < 0:
break
acc += a[k - 1] * y[i - k]
y.append(acc)
return y
test_mel_frequency_cepstral_coefficients.py 262 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mel-frequency-cepstral-coefficients/. The authors are listed in prov/85RNE7.jsonl.
import cmath
import math
import random
import nlsdsp
from mel_frequency_cepstral_coefficients import (
hz_to_mel,
lifter,
mel_to_hz,
mel_weights,
mfcc,
mfcc_of_frame,
pre_emphasis,
)
from nlsdsp import (
all_pole,
autocorr,
dct2,
fft,
frames,
hamming,
hann,
levinson,
power_spectrum,
pulse_train,
sine,
white_noise,
)
# ---------------------------------------------------------------- the shared helper nlsdsp.py
def test_helper_header():
with open(nlsdsp.__file__, encoding="utf-8") as f:
lines = f.read().splitlines()
assert lines[1] == (
"# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/."
" The authors are listed in prov/."
)
def test_frames_check_value():
x = [0.0] * 16000
fr = frames(x, 400, 160)
assert len(fr) == 98
assert all(len(f) == 400 for f in fr)
assert len(frames(x[:399], 400, 160)) == 0
assert len(frames(x[:400], 400, 160)) == 1
assert len(frames(x[:559], 400, 160)) == 1
assert len(frames(x[:560], 400, 160)) == 2
y = list(range(10))
assert frames(y, 4, 3) == [[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9]]
def test_windows():
w = hamming(400)
assert abs(w[0] - 0.08) < 1e-12 and abs(w[-1] - 0.08) < 1e-12
assert all(abs(w[i] - w[399 - i]) < 1e-12 for i in range(400))
assert abs(max(w) - 1.0) < 1e-4
h = hann(5)
assert [round(v, 12) for v in h] == [0.0, 0.5, 1.0, 0.5, 0.0]
assert hamming(1) == [1.0] and hann(1) == [1.0]
def _dft(x):
n = len(x)
return [sum(x[t] * cmath.exp(-2j * math.pi * k * t / n) for t in range(n)) for k in range(n)]
def test_fft_against_dft():
rng = random.Random(1)
for n in (1, 2, 4, 8, 32, 64):
x = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
got, ref = fft(x), _dft(x)
assert all(abs(g - r) < 1e-9 for g, r in zip(got, ref))
x = sine(1000.0, 16000.0, 64)
got, ref = fft(x), _dft(x)
assert all(abs(g - r) < 1e-9 for g, r in zip(got, ref))
# 1000 Hz at 16 kHz with 64 points falls on bin 4: |X[4]| = 64 / 2
assert abs(abs(got[4]) - 32.0) < 1e-9
try:
fft([0.0] * 6)
except ValueError:
pass
else:
raise AssertionError("length 6 must fail")
def test_power_spectrum():
x = sine(500.0, 8000.0, 16)
ps = power_spectrum(x, 32)
assert len(ps) == 17
ref = _dft(x + [0.0] * 16)
assert all(abs(ps[k] - abs(ref[k]) ** 2) < 1e-9 for k in range(17))
# Parseval: sum |x|^2 = (1 / N) sum over all N bins of |X|^2
full = [abs(v) ** 2 for v in ref]
assert abs(sum(v * v for v in x) - sum(full) / 32) < 1e-9
def test_dct2_orthonormal():
n = 8
rows = [dct2([1.0 if i == j else 0.0 for i in range(n)], n) for j in range(n)]
# rows[j][k] is entry (k, j) of the DCT matrix; check orthogonality of the matrix
for a in range(n):
for b in range(n):
dot = sum(rows[j][a] * rows[j][b] for j in range(n))
assert abs(dot - (1.0 if a == b else 0.0)) < 1e-12
c = dct2([2.0] * 5, 5)
assert abs(c[0] - 2.0 * math.sqrt(5)) < 1e-12
assert all(abs(v) < 1e-12 for v in c[1:])
def test_autocorr():
assert autocorr([1.0, 2.0, 3.0], 3) == [14.0, 8.0, 3.0, 0.0]
def test_levinson_order_two():
a_true = [1.3, -0.81] # poles at radius 0.9, angle about 43.8 degrees
h = all_pole([1.0] + [0.0] * 599, a_true)
r = autocorr(h, 2)
a, e = levinson(r, 2)
assert abs(a[0] - 1.3) < 1e-9 and abs(a[1] + 0.81) < 1e-9
# the impulse response has prediction error exactly the first sample: e = 1
assert abs(e - 1.0) < 1e-9
# a higher order fit gives zeros beyond order 2
a4, _ = levinson(autocorr(h, 4), 4)
assert abs(a4[2]) < 1e-9 and abs(a4[3]) < 1e-9
# noise through the same filter gives the coefficients up to sampling error
rng = random.Random(7)
y = all_pole(white_noise(rng, 8000, 1.0), a_true)
a_est, _ = levinson(autocorr(y, 2), 2)
assert abs(a_est[0] - 1.3) < 0.03 and abs(a_est[1] + 0.81) < 0.03
def test_levinson_matches_direct_solve():
r = [4.0, 2.0, 1.0]
a, e = levinson(r, 2)
# normal equations [[4, 2], [2, 4]] a = [2, 1]
assert abs(a[0] - 0.5) < 1e-12 and abs(a[1]) < 1e-12
assert abs(e - (4.0 - 0.5 * 2.0)) < 1e-12
def test_pulse_train_and_noise():
x = pulse_train(100.0, 16000.0, 500)
assert [i for i, v in enumerate(x) if v] == [0, 160, 320, 480]
x = pulse_train(120.0, 8000.0, 300)
assert [i for i, v in enumerate(x) if v] == [0, 67, 133, 200, 267]
n1 = white_noise(random.Random(3), 5, 0.1)
n2 = white_noise(random.Random(3), 5, 0.1)
assert n1 == n2 and len(n1) == 5
def test_all_pole_first_order():
y = all_pole([1.0, 0.0, 0.0, 0.0], [0.5])
assert y == [1.0, 0.5, 0.25, 0.125]
# ---------------------------------------------------------------- MFCC
def test_frame_count_and_shape():
x = sine(440.0, 16000.0, 16000)
c = mfcc(x)
assert len(c) == 98 and all(len(row) == 13 for row in c)
assert mfcc(x[:399]) == []
def test_pre_emphasis_and_lifter():
y = pre_emphasis([1.0, 1.0, 1.0, 0.0])
assert y[0] == 1.0 and abs(y[1] - 0.03) < 1e-15 and abs(y[2] - 0.03) < 1e-15 and y[3] == -0.97
w = lifter([1.0] * 23, 22)
assert w[0] == 1.0 and abs(w[11] - 12.0) < 1e-12 and abs(w[22] - 1.0) < 1e-12
assert lifter([3.0, 4.0], 0) == [3.0, 4.0]
def test_silence_gives_only_c0():
c = mfcc([0.0] * 800)
assert len(c) == 3
for row in c:
assert abs(row[0] - math.sqrt(26) * math.log(1e-10)) < 1e-9
assert all(abs(v) < 1e-9 for v in row[1:])
def test_gain_changes_only_c0():
rng = random.Random(11)
x = white_noise(rng, 1200, 0.1)
a = mfcc(x)
b = mfcc([3.0 * v for v in x])
for ra, rb in zip(a, b):
assert abs(rb[0] - ra[0] - math.sqrt(26) * 2 * math.log(3.0)) < 1e-9
assert all(abs(u - v) < 1e-9 for u, v in zip(ra[1:], rb[1:]))
def test_parseval_of_the_orthonormal_dct():
rng = random.Random(2)
x = white_noise(rng, 400, 0.1)
w = mel_weights(26, 512, 16000.0)
win = hamming(400)
c = mfcc_of_frame(pre_emphasis(x), w, win, num_ceps=26, cep_lifter=0)
p = power_spectrum([s * v for s, v in zip(pre_emphasis(x), win)], 512)
log_e = [math.log(max(sum(a * b for a, b in zip(row, p)), 1e-10)) for row in w]
assert abs(sum(v * v for v in c) - sum(v * v for v in log_e)) < 1e-8
def test_against_a_direct_computation():
# a second, slow path: direct DFT, explicit triangles in mel edges, explicit DCT-II sums
rng = random.Random(4)
fs, n_len, hop, nfft, m_count, k_count, q = 8000.0, 200, 80, 256, 20, 12, 22
x = white_noise(rng, 360, 0.2)
got = mfcc(x, fs, m_count, k_count, n_len, hop, nfft)
y = [x[0]] + [x[i] - 0.97 * x[i - 1] for i in range(1, len(x))]
hi = 2595 * math.log10(1 + 4000 / 700)
edges = [700 * (10 ** (i * hi / (m_count + 1) / 2595) - 1) for i in range(m_count + 2)]
ref = []
for t in range(1 + (len(y) - n_len) // hop):
fr = [y[t * hop + i] * (0.54 - 0.46 * math.cos(2 * math.pi * i / (n_len - 1))) for i in range(n_len)]
power = [abs(sum(fr[i] * cmath.exp(-2j * math.pi * k * i / nfft) for i in range(n_len))) ** 2 for k in range(nfft // 2 + 1)]
log_e = []
for m in range(m_count):
lo, ce, hi_e = edges[m], edges[m + 1], edges[m + 2]
e = 0.0
for k, pk in enumerate(power):
f = k * fs / nfft
if lo < f <= ce:
e += pk * (f - lo) / (ce - lo)
elif ce < f < hi_e:
e += pk * (hi_e - f) / (hi_e - ce)
log_e.append(math.log(max(e, 1e-10)))
row = []
for j in range(k_count):
s = math.sqrt((1 if j == 0 else 2) / m_count)
cj = s * sum(log_e[i] * math.cos(math.pi * j * (i + 0.5) / m_count) for i in range(m_count))
row.append((1 + q / 2 * math.sin(math.pi * j / q)) * cj)
ref.append(row)
assert len(got) == len(ref) == 3
for g, r in zip(got, ref):
assert all(abs(u - v) < 1e-7 for u, v in zip(g, r))
def test_tone_moves_energy_to_its_filter():
# the log mel energies of a pure tone peak in the filter whose center is the tone
w = mel_weights(26, 512, 16000.0)
lo, hi = 0.0, hz_to_mel(8000.0)
center = mel_to_hz(lo + 8 * (hi - lo) / 27)
x = sine(center, 16000.0, 400)
win = hamming(400)
p = power_spectrum([s * v for s, v in zip(x, win)], 512)
e = [sum(a * b for a, b in zip(row, p)) for row in w]
assert max(range(26), key=lambda i: e[i]) == 7
def test_bad_arguments():
try:
mfcc([0.0] * 400, num_filters=10, num_ceps=13)
except ValueError:
pass
else:
raise AssertionError("num_ceps > num_filters must fail")
History
The cepstrum of Bogert, Healy and Tukey (1963) and Noll's use of it for pitch led to cepstral features for speech, and in 1974 Atal found the LPC cepstrum the best of the linear prediction parameters for speaker recognition. In 1980 Davis and Mermelstein put the cepstrum on the mel scale: they took the cosine transform of the log outputs of 20 triangular filters, linear below 1 kHz and logarithmic above, and found these mel-frequency cepstral coefficients the best of the representations they compared for recognizing monosyllabic words in sentences. HTK made 26 filters, 12 or 13 coefficients, the lifter with 22 and the 39-dimensional vector with delta features a standard in the 1990s. MFCC were the main feature of speech recognition until the move to neural networks in the 2010s, and they remain common in speaker recognition and audio classification.
References
- S. B. Davis and P. Mermelstein, Comparison of parametric representations for monosyllabic word recognition in continuously spoken sentences, IEEE Transactions on Acoustics, Speech, and Signal Processing 28(4), 1980, 357 to 366, Section II.C (Parametric Representations): Eq. (1), the cosine transform of the log energies of the 20 filters of Fig. 1
- The HTK Book, version 3.4, Chapter Speech Input/Output, sections Filterbank Analysis and Cepstral Features (the DCT of the log filter bank amplitudes and the sine lifter with CEPLIFTER)
- Xuedong Huang, Alex Acero and Hsiao-Wuen Hon, Spoken Language Processing, Prentice Hall, 2001, Chapter 6 (Speech Signal Representations), sections Cepstral Processing and Perceptually Motivated Representations
- Lawrence R. Rabiner and Ronald W. Schafer, Theory and Applications of Digital Speech Processing, Pearson, 2010, Chapter 8 (the cepstrum and homomorphic speech processing)
- B. S. Atal, Effectiveness of linear prediction characteristics of the speech wave for automatic speaker identification and verification, Journal of the Acoustical Society of America 55(6), 1974, 1304 to 1312, the comparison of parameters derived from linear prediction, in which the cepstrum did best
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 85RNE7 Edit this page History Report an error Markdown