Algorithmcore
Mel filter bank
Also called mel filterbank, log-mel spectrogram, triangular mel filter bank.
Weight the power spectrum of each frame by triangular filters spaced evenly on the mel scale and take logs of the band energies.
- Time
- O(W + N log N + M N) worst
- Space
- O(M N) extra
- Where
- M = the number of filters; N = the FFT length; W = the frame length
- Model
- Real RAM
- Properties
- deterministicexactnot in placeonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Steven Davis, Paul Mermelstein, 1980
A mel filter bank turns the power spectrum of a short frame of audio into a few dozen band energies. Each band is a triangle in frequency, the triangle edges are equally spaced on the mel scale, and the log of each energy is the output. The mel scale page defines the frequency axis only; this page builds the filters on it and applies them. The MFCC of a frame are the discrete cosine transform of these log energies, and a general filter bank of signal processing splits a signal into subband signals that can be put back together, which this analysis does not try to do.
In plain words
The ear hears small changes in pitch at low frequencies but only large changes at high frequencies. A mel filter bank copies this. It puts many narrow bands at the low end of the spectrum and fewer, wider bands at the high end. Each band adds up the energy of the spectrum inside it, with the most weight at its middle and less weight toward its edges. Neighbouring bands overlap by half, so no part of the spectrum between the first and the last band center is lost. Then each sum is replaced by its logarithm, because loudness is heard on a log scale and because a fixed gain then becomes an added constant. The result is a short list of numbers per frame, for example 40, instead of hundreds of spectrum values.
The problem
Given a frame of samples at a sample rate of Hz, a window, an FFT length , a number of filters and a frequency range , compute log band energies. The power spectrum is for , where is the DFT of the windowed frame padded with zeros to points, and bin is at the frequency . The defaults of this page are kHz, samples (25 ms), a hop of 160 samples (10 ms), the symmetric Hamming window, , and . The frames are cut without padding, so a signal of samples gives frames. Common values of are 26 (HTK), 23 (Kaldi) and 40 (the input of many neural networks).
The algorithm
With , the edge frequencies are equally spaced in mel and the filter is a triangle that is linear in Hz, with its foot at and and its top at .
MEL-FILTER-BANK(P, f_s, N, M, f_lo, f_hi) ▷ P[0 .. N/2] is the power spectrum- 1
require M ≥ 1 and 0 ≤ f_lo < f_hi ≤ f_s / 2 - 2
m_lo ← mel(f_lo); m_hi ← mel(f_hi); Δ ← (m_hi - m_lo) / (M + 1) - 3
for i ← 0 to M + 1 do f_i ← mel⁻¹(m_lo + i Δ) - 4
for m ← 1 to M do - 5
for k ← 0 to N/2 do f ← k f_s / N - 6
if f_{m-1} < f ≤ f_m then W[m][k] ← (f - f_{m-1}) / (f_m - f_{m-1}) - 7
else if f_m < f < f_{m+1} then W[m][k] ← (f_{m+1} - f) / (f_{m+1} - f_m) - 8
else W[m][k] ← 0 - 9
for m ← 1 to M do E[m] ← Σ_k W[m][k] P[k] - 10
return ln max(E[m], 10⁻¹⁰) for m ← 1 to M
Lines L1 to L8 depend only on , , and the range, so a program builds the weights once and reuses them for every frame. Lines L9 and L10 run once per frame. The floor in line L10 keeps the log finite on silent frames; toolkits use similar small floors.
This page applies the filters to the power spectrum, as Kaldi and librosa do. HTK applies them to the magnitude , so its band energies are a different quantity. Slaney's Auditory Toolbox and librosa by default also use a different mel scale and scale each triangle to unit area; see the variants below.
Example
Take Hz, (bins every 500 Hz), and the full range 0 to 4000 Hz. Then , the step is mel, and line L3 gives the edges 0, 324.5, 799.3, 1494.3, 2511.4 and 4000 Hz. Lines L4 to L8 give these weights, rounded:
| bin | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| frequency (Hz) | 0 | 500 | 1000 | 1500 | 2000 | 2500 | 3000 | 3500 | 4000 |
| filter 1 | 0 | 0.630 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| filter 2 | 0 | 0.370 | 0.711 | 0 | 0 | 0 | 0 | 0 | 0 |
| filter 3 | 0 | 0 | 0.289 | 0.994 | 0.503 | 0.011 | 0 | 0 | 0 |
| filter 4 | 0 | 0 | 0 | 0.006 | 0.497 | 0.989 | 0.672 | 0.336 | 0 |
| sum | 0 | 1 | 1 | 1 | 1 | 1 | 0.672 | 0.336 | 0 |
Every bin between the first center (324.5 Hz) and the last center (2511.4 Hz) gets a total weight of 1. Filter 1 covers a single bin, because 16 points are too few for its narrow band; with at 16 kHz and , the first filter runs from 0 to 143.7 Hz and covers 4 bins. For the power spectrum , line L9 gives the energies 2.5214, 2.1899, 0.2887 and 0, and line L10 gives the log energies 0.9248, 0.7838, and .
Correctness
The filter bank computes a defined transform, so correctness means that the weights have the shape the definition asks for. The full proofs are below.
- The edges are equally spaced in mel. Since is strictly increasing and line L3 applies its inverse, , so the edges increase and , (theorem).
- Each filter is a triangle. Line L6 gives the rising side and line L7 the falling side, so , the weight is positive only for , and it is 1 exactly when (theorem).
- The filters overlap by half. For every frequency with , the weights of all filters at sum to 1, and at most two of them are positive (theorem). So a flat power spectrum gives band energies that are proportional to the number of bins in each band.
- The log turns gains into offsets. If the spectrum is multiplied by and the energies stay above the floor, every log energy grows by (theorem). A fixed channel gain thus adds a constant to each band, which cepstral mean normalization removes later.
Proof: The mel filter bank has the shape its definition asks forfull
We work in the real RAM, so the arithmetic is exact. The inputs satisfy line L1: and . The function is continuous and strictly increasing on , with the inverse .
Lemma 1 (the edges). Line L3 gives , , , and for .
Proof. By line L3, . For this is , and for it is ; since is one to one, and . Since and is strictly increasing, , so the values strictly increase with , and so do the , because is strictly increasing too. The difference of consecutive mel values is by the formula.
By Lemma 1 the denominators and of lines L6 and L7 are positive, so the weights are well defined. Write for the value that lines L6 to L8 give at the frequency , so that .
Lemma 2 (the triangles). For and every : ; exactly when ; and exactly when .
Proof. The three cases of lines L6 to L8 cover every and do not overlap. If , then , so , with equality to 1 only for . If , then , so . Otherwise .
Lemma 3 (overlap by half). For every with , , and at most two terms are positive. For or , every is 0.
Proof. The last claim follows from Lemma 2, since the support of is inside . For the first claim, if , then by Lemma 2, and every other is 0 because for . Otherwise , and there is exactly one with and , because the edges strictly increase. Then by line L7, and by line L6. Their sum is . Every other filter has (if ) or (if ), so its weight is 0.
Applied to the bin frequencies , Lemma 3 says that every bin between the first and the last center has a total weight of 1, which is what the column sums of the example show and what the tests check on a bank of 26 filters.
Lemma 4 (the band energies and their logs). Line L9 gives , and line L10 gives . If every is multiplied by , and both and are at least , then the output for filter grows by exactly .
Proof. The first part restates the lines. The weights and the power values are nonnegative, so . The sum is linear in , so the new energy is , and under the condition the output changes from to .
Theorem. MEL-FILTER-BANK returns, for each , the log, floored at , of the power spectrum weighted by a triangle whose feet and top are three consecutive edges equally spaced in mel; the triangles sum to 1 between the first and last centers, and a gain on the spectrum adds to each output above the floor.
Proof. Lemmas 1 to 4.
The implementation computes the same quantities in floating point. The tests compare it with a direct DFT and with explicit triangles, check the column sums of Lemma 3 to , the peak of each triangle on a fine grid, and the shift by when the amplitude doubles.
Complexity
In the real RAM, the window costs , the FFT and line L9 with the dense weight table. Because each bin lies in at most two triangles, a sparse table of the nonzero weights makes line L9 cost , so the FFT dominates. Building the table in lines L1 to L8 costs once. The table takes memory, or in sparse form. For one second of 16 kHz audio there are 98 frames, each with one FFT of 512 points.
Properties
- Fixed and linear before the log. The band energies are a fixed linear map of the power spectrum, so they can be computed as one matrix product for all frames.
- Resolution follows the ear. At 16 kHz with 26 filters the bands are about 140 Hz wide at the low end and about 1500 Hz wide at the top.
- Loses the fine structure. The triangles are wider than the spacing of the pitch harmonics for most voices, so the energies follow the spectral envelope and mostly discard the pitch. This is useful for recognizing words and a loss for pitch or speaker work.
- Correlated outputs. Neighbouring log energies overlap and are strongly correlated. The DCT of MFCC mostly removes this for models with diagonal covariances; neural networks take the log energies directly.
Variants and improvements
- Slaney's scale and unit-area filters. The Auditory Toolbox of Slaney, and librosa by default, use a mel scale that is linear below 1 kHz with a step of Hz per mel and logarithmic above with a step of per mel, and scale each triangle to unit area, so the high bands get smaller weights.
- Magnitude in place of power. HTK sums the magnitude . For a band with one strong bin the log energy is then about half the log energy from the power spectrum, and a model trained on one kind does not work on the other.
- Band limits. A low edge of 20 to 133 Hz removes hum and DC, and a high edge below ignores the region where the anti-aliasing filter cuts.
- Other warpings. The Bark scale of perceptual linear prediction uses trapezoid-like masking curves in place of triangles, and gammatone filter banks model the cochlea more closely.
- Learned front ends. Some neural systems learn the filters from raw audio, often starting from mel triangles.
- Data augmentation. SpecAugment masks blocks of bands and frames of the log energies during training.
When to use it
Use a mel filter bank as the front end of a speech recognizer, a keyword spotter or an audio classifier, where the input is a spectrogram and the model is a neural network; 40 to 80 filters are common there. Use it as the first stage of MFCC when the model wants decorrelated features, such as a GMM-HMM. Do not use it when the task needs the harmonics, such as pitch detection, or when the signal must be rebuilt from the bands: the triangles throw information away, and a perfect reconstruction filter bank is the tool for coding.
Pitfalls
- Mixing conventions. The scale (O'Shaughnessy or Slaney), power or magnitude, the normalization of the triangles and the log floor all change the numbers. Features from two toolkits match only when all four match.
- Empty filters. With many filters and a short FFT, the lowest triangles can fall between two bins and get no weight at all, so their energy is always 0 and the log is the floor. Check that each row has a nonzero weight, or lower or raise .
- Log of zero. Digital silence gives a zero energy; without the floor the log is minus infinity and the next layers fail.
- Frame count. Toolkits differ on padding. This page drops the last partial frame; librosa by default pads the signal by half the FFT length on each side, which adds frames.
- Sample rate change. Weights built for 16 kHz are wrong for 8 kHz audio, because the bin frequencies change with .
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-filter-bank/. The authors are listed in prov/3Y1ZJS.jsonl.
"""A bank of triangular filters spaced evenly on the mel scale, and the log mel spectrogram.
The mel scale is m = 2595 log_10(1 + f / 700) (O'Shaughnessy 1987, the HTK form).
The triangles are linear in Hz between their edge frequencies, and the filters
apply to the power spectrum |X[k]|^2, k = 0 to nfft / 2. The log is the natural log,
with a floor before the log.
"""
import math
from typing import List, Optional, Sequence
from nlsdsp import frames, hamming, power_spectrum
def hz_to_mel(f: float) -> float:
"""The mel value of f Hz: 2595 log_10(1 + f / 700)."""
return 2595.0 * math.log10(1.0 + f / 700.0)
def mel_to_hz(m: float) -> float:
"""The inverse of hz_to_mel: 700 (10^(m / 2595) - 1)."""
return 700.0 * (10.0 ** (m / 2595.0) - 1.0)
def edge_frequencies(num_filters: int, fmin: float, fmax: float) -> List[float]:
"""The num_filters + 2 frequencies f_0 < f_1 < ... < f_{M+1}, equally spaced in mel from fmin to fmax."""
lo, hi = hz_to_mel(fmin), hz_to_mel(fmax) # @line L2
step = (hi - lo) / (num_filters + 1)
return [mel_to_hz(lo + i * step) for i in range(num_filters + 2)] # @line L3
def mel_filter_bank(
num_filters: int, nfft: int, fs: float, fmin: float = 0.0, fmax: Optional[float] = None
) -> List[List[float]]:
"""The weights W[m][k] of filter m (0 based) on FFT bin k = 0 to nfft / 2.
Filter m rises linearly from 0 at f_m to 1 at f_{m+1} and falls to 0 at f_{m+2}
(0 based edges), so each filter starts at the center of the one before it.
"""
if fmax is None:
fmax = fs / 2.0
if num_filters < 1 or not 0.0 <= fmin < fmax <= fs / 2.0: # @line L1
raise ValueError("need num_filters >= 1 and 0 <= fmin < fmax <= fs / 2")
edges = edge_frequencies(num_filters, fmin, fmax)
nbins = nfft // 2 + 1
weights = []
for m in range(1, num_filters + 1): # @line L4
left, center, right = edges[m - 1], edges[m], edges[m + 1]
row = []
for k in range(nbins): # @line L5
f = k * fs / nfft
if left < f <= center: # @line L6
row.append((f - left) / (center - left))
elif center < f < right: # @line L7
row.append((right - f) / (right - center))
else:
row.append(0.0) # @line L8
weights.append(row)
return weights
def apply_filter_bank(weights: Sequence[Sequence[float]], spectrum: Sequence[float]) -> List[float]:
"""The band energies e_m = sum_k W[m][k] P[k] of one power spectrum P."""
return [sum(w * p for w, p in zip(row, spectrum)) for row in weights] # @line L9
def log_energies(energies: Sequence[float], floor: float = 1e-10) -> List[float]:
"""ln max(e_m, floor) for each band energy."""
return [math.log(max(e, floor)) for e in energies] # @line L10
def log_mel_spectrogram(
x: Sequence[float],
fs: float = 16000.0,
num_filters: int = 40,
frame_len: int = 400,
hop: int = 160,
nfft: int = 512,
fmin: float = 0.0,
fmax: Optional[float] = None,
floor: float = 1e-10,
) -> List[List[float]]:
"""Frames without padding, the symmetric Hamming window, the power spectrum,
the mel filter bank and the log. One row of num_filters values per frame."""
weights = mel_filter_bank(num_filters, nfft, fs, fmin, fmax)
win = hamming(frame_len)
out = []
for fr in frames(x, frame_len, hop):
spec = power_spectrum([s * w for s, w in zip(fr, win)], nfft)
out.append(log_energies(apply_filter_bank(weights, spec), floor))
return out
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_filter_bank.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mel-filter-bank/. The authors are listed in prov/3Y1ZJS.jsonl.
import cmath
import math
import random
from mel_filter_bank import (
apply_filter_bank,
edge_frequencies,
hz_to_mel,
log_energies,
log_mel_spectrogram,
mel_filter_bank,
mel_to_hz,
)
from nlsdsp import hamming, sine
def test_mel_check_values():
assert round(hz_to_mel(700.0), 2) == 781.17
assert round(hz_to_mel(1000.0), 2) == 999.99
# the area brief gives 2146.07; 2595 log_10(1 + 4000 / 700) = 2146.0645
assert round(hz_to_mel(4000.0), 2) == 2146.06
assert round(hz_to_mel(8000.0), 2) == 2840.02
for f in (0.0, 123.4, 1000.0, 7999.0):
assert abs(mel_to_hz(hz_to_mel(f)) - f) < 1e-9
# the same scale in natural log: 1127 ln(1 + f / 700), to the 4 digits of 1127
for f in (300.0, 3000.0):
assert abs(hz_to_mel(f) - 1127.0 * math.log(1 + f / 700.0)) < 0.05
def test_edges_are_equally_spaced_in_mel():
edges = edge_frequencies(26, 0.0, 8000.0)
assert len(edges) == 28
assert edges[0] == 0.0 and abs(edges[-1] - 8000.0) < 1e-9
mels = [hz_to_mel(f) for f in edges]
steps = [b - a for a, b in zip(mels, mels[1:])]
assert max(steps) - min(steps) < 1e-9
def test_shape_and_triangles():
w = mel_filter_bank(26, 512, 16000.0)
assert len(w) == 26 and all(len(row) == 257 for row in w)
edges = edge_frequencies(26, 0.0, 8000.0)
for m, row in enumerate(w):
assert all(0.0 <= v <= 1.0 for v in row)
nz = [k for k, v in enumerate(row) if v > 0]
assert nz, "every filter of this bank covers a bin"
# the support is inside (f_m, f_{m+2}) in 0 based edges
assert all(edges[m] < k * 16000.0 / 512 < edges[m + 2] for k in nz)
# the largest weight sits on the bin nearest the center, from either side
kmax = max(range(257), key=lambda k: row[k])
assert abs(kmax * 16000.0 / 512 - edges[m + 1]) <= 16000.0 / 512
def test_peak_is_one_at_the_center():
# with a fine grid the bin nearest each center has weight close to 1
nfft = 1 << 14
w = mel_filter_bank(10, nfft, 16000.0)
df = 16000.0 / nfft
edges = edge_frequencies(10, 0.0, 8000.0)
for m, row in enumerate(w):
bound = df / min(edges[m + 1] - edges[m], edges[m + 2] - edges[m + 1])
assert 1.0 - bound <= max(row) <= 1.0
def test_filters_overlap_by_half():
# between the first and the last center, the weights of each bin sum to 1
fs, nfft = 16000.0, 512
w = mel_filter_bank(26, nfft, fs, 100.0, 7000.0)
edges = edge_frequencies(26, 100.0, 7000.0)
for k in range(nfft // 2 + 1):
f = k * fs / nfft
total = sum(row[k] for row in w)
nonzero = sum(1 for row in w if row[k] > 0)
if edges[1] <= f <= edges[26]:
assert abs(total - 1.0) < 1e-12
assert nonzero in (1, 2)
if f <= edges[0] or f >= edges[27]:
assert total == 0.0
def _triangle(f, left, center, right):
if left < f <= center:
return (f - left) / (center - left)
if center < f < right:
return (right - f) / (right - center)
return 0.0
def test_band_energies_against_direct_dft():
rng = random.Random(5)
fs, nfft, n, m_count = 8000.0, 64, 50, 8
frame = [rng.uniform(-1, 1) for _ in range(n)]
padded = frame + [0.0] * (nfft - n)
power = []
for k in range(nfft // 2 + 1):
xk = sum(padded[t] * cmath.exp(-2j * math.pi * k * t / nfft) for t in range(nfft))
power.append(abs(xk) ** 2)
lo, hi = 2595 * math.log10(1 + 0 / 700), 2595 * math.log10(1 + 4000 / 700)
edges = [700 * (10 ** ((lo + i * (hi - lo) / (m_count + 1)) / 2595) - 1) for i in range(m_count + 2)]
ref = [
sum(_triangle(k * fs / nfft, edges[m], edges[m + 1], edges[m + 2]) * power[k] for k in range(nfft // 2 + 1))
for m in range(m_count)
]
from nlsdsp import power_spectrum
got = apply_filter_bank(mel_filter_bank(m_count, nfft, fs), power_spectrum(frame, nfft))
assert all(abs(g - r) < 1e-9 * max(1.0, abs(r)) for g, r in zip(got, ref))
def test_sine_lands_in_the_filter_of_its_frequency():
fs = 16000.0
edges = edge_frequencies(26, 0.0, 8000.0)
win = hamming(400)
for m in (3, 10, 20):
f = edges[m + 1]
x = sine(f, fs, 400)
from nlsdsp import power_spectrum
e = apply_filter_bank(mel_filter_bank(26, 512, fs), power_spectrum([a * b for a, b in zip(x, win)], 512))
assert max(range(26), key=lambda i: e[i]) == m
def test_log_floor_and_spectrogram():
assert log_energies([0.0, 1.0, math.e]) == [math.log(1e-10), 0.0, 1.0]
rows = log_mel_spectrogram([0.0] * 1600)
assert len(rows) == 8 and all(len(r) == 40 for r in rows)
assert all(v == math.log(1e-10) for r in rows for v in r)
# doubling the amplitude adds ln 4 to every log energy
x = sine(440.0, 16000.0, 560)
a = log_mel_spectrogram(x, num_filters=20)
b = log_mel_spectrogram([2 * v for v in x], num_filters=20)
for ra, rb in zip(a, b):
for u, v in zip(ra, rb):
if u > math.log(1e-10) + 30:
assert abs(v - u - math.log(4.0)) < 1e-9
def test_bad_arguments():
for args in ((0, 512, 16000.0), (26, 512, 16000.0, 0.0, 9000.0), (26, 512, 16000.0, 5000.0, 4000.0)):
try:
mel_filter_bank(*args)
except ValueError:
continue
raise AssertionError(args)
History
The mel scale comes from the listening experiments of Stevens, Volkmann and Newman in 1937. Filter banks with bands that widen with frequency were used in speech analysis long before digital computers, in vocoders and in the sound spectrograph. In 1980 Davis and Mermelstein computed 20 triangular filters, linear below 1 kHz and logarithmic above, on a DFT spectrum, took the cosine transform of their log outputs, and found that these mel-frequency cepstral coefficients gave the best recognition among the representations they compared. HTK, and later Kaldi, built the triangles on the formula , Kaldi in the form , which agrees with it to about 4 digits. With deep neural networks in the 2010s, the log filter bank energies themselves, without the cosine transform, became the most common input of speech recognizers.
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): the 20 triangular filters of Fig. 1, Eq. (1), and footnote 1 (linear spacing below 1000 Hz and logarithmic spacing above)
- The HTK Book, version 3.4, Chapter Speech Input/Output, section Filterbank Analysis (triangular filters equally spaced on the mel scale, applied to the magnitude spectrum)
- Xuedong Huang, Alex Acero and Hsiao-Wuen Hon, Spoken Language Processing, Prentice Hall, 2001, Chapter 6 (Speech Signal Representations), section Perceptually Motivated Representations
- S. S. Stevens, J. Volkmann and E. B. Newman, A scale for the measurement of the psychological magnitude pitch, Journal of the Acoustical Society of America 8(3), 1937, 185 to 190, the listener experiments behind the mel scale
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 3Y1ZJS Edit this page History Report an error Markdown