Algorithm Search⌘K

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
Properties
deterministicexactnot in placeonline
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 WW samples at a sample rate of fsf_s Hz, a window, an FFT length N≥WN \ge W, a number of filters MM and a frequency range 0≤flo<fhi≤fs/20 \le f_{lo} < f_{hi} \le f_s / 2, compute MM log band energies. The power spectrum is P[k]=∣X[k]∣2P[k] = |X[k]|^2 for k=0,…,N/2k = 0, \ldots, N/2, where XX is the DFT of the windowed frame padded with zeros to NN points, and bin kk is at the frequency kfs/Nk f_s / N. The defaults of this page are fs=16f_s = 16 kHz, W=400W = 400 samples (25 ms), a hop of 160 samples (10 ms), the symmetric Hamming window, N=512N = 512, flo=0f_{lo} = 0 and fhi=fs/2f_{hi} = f_s / 2. The frames are cut without padding, so a signal of L≥400L \ge 400 samples gives 1+⌊(L−400)/160⌋1 + \lfloor (L - 400) / 160 \rfloor frames. Common values of MM are 26 (HTK), 23 (Kaldi) and 40 (the input of many neural networks).

The algorithm

With mel⁡(f)=2595log⁡10(1+f/700)\operatorname{mel}(f) = 2595 \log_{10}(1 + f / 700), the edge frequencies are equally spaced in mel and the filter mm is a triangle that is linear in Hz, with its foot at fm−1f_{m-1} and fm+1f_{m+1} and its top at fmf_m.

  1. MEL-FILTER-BANK(P, f_s, N, M, f_lo, f_hi) ▷ P[0 .. N/2] is the power spectrum
  2. 1require M ≥ 1 and 0 ≤ f_lo < f_hi ≤ f_s / 2
  3. 2m_lo ← mel(f_lo); m_hi ← mel(f_hi); Δ ← (m_hi - m_lo) / (M + 1)
  4. 3for i ← 0 to M + 1 do f_i ← mel⁻¹(m_lo + i Δ)
  5. 4for m ← 1 to M do
  6. 5for k ← 0 to N/2 do f ← k f_s / N
  7. 6if f_{m-1} < f ≤ f_m then W[m][k] ← (f - f_{m-1}) / (f_m - f_{m-1})
  8. 7else if f_m < f < f_{m+1} then W[m][k] ← (f_{m+1} - f) / (f_{m+1} - f_m)
  9. 8else W[m][k] ← 0
  10. 9for m ← 1 to M do E[m] ← Σ_k W[m][k] P[k]
  11. 10return ln max(E[m], 10⁻¹⁰) for m ← 1 to M

Lines L1 to L8 depend only on fsf_s, NN, MM 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 10−1010^{-10} 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 ∣X[k]∣|X[k]|, 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 fs=8000f_s = 8000 Hz, N=16N = 16 (bins every 500 Hz), M=4M = 4 and the full range 0 to 4000 Hz. Then mel⁡(4000)=2146.06\operatorname{mel}(4000) = 2146.06, the step is Δ=429.21\Delta = 429.21 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 kk 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 N=512N = 512 at 16 kHz and M=26M = 26, the first filter runs from 0 to 143.7 Hz and covers 4 bins. For the power spectrum P=(0,4,1,0,0,0,0,0,0)P = (0, 4, 1, 0, 0, 0, 0, 0, 0), line L9 gives the energies 2.5214, 2.1899, 0.2887 and 0, and line L10 gives the log energies 0.9248, 0.7838, −1.2422-1.2422 and ln⁡10−10=−23.0259\ln 10^{-10} = -23.0259.

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 mel⁡\operatorname{mel} is strictly increasing and line L3 applies its inverse, mel⁡(fi)=mlo+iΔ\operatorname{mel}(f_i) = m_{lo} + i \Delta, so the edges increase and f0=flof_0 = f_{lo}, fM+1=fhif_{M+1} = f_{hi} (theorem).
  • Each filter is a triangle. Line L6 gives the rising side and line L7 the falling side, so 0≤W[m][k]≤10 \le W[m][k] \le 1, the weight is positive only for fm−1<f<fm+1f_{m-1} < f < f_{m+1}, and it is 1 exactly when f=fmf = f_m (theorem).
  • The filters overlap by half. For every frequency ff with f1≤f≤fMf_1 \le f \le f_M, the weights of all filters at ff 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 c>0c > 0 and the energies stay above the floor, every log energy grows by ln⁡c\ln c (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: M≥1M \ge 1 and 0≤flo<fhi≤fs/20 \le f_{lo} < f_{hi} \le f_s / 2. The function mel⁡(f)=2595log⁡10(1+f/700)\operatorname{mel}(f) = 2595 \log_{10}(1 + f / 700) is continuous and strictly increasing on f≥0f \ge 0, with the inverse mel⁡−1(m)=700(10m/2595−1)\operatorname{mel}^{-1}(m) = 700 (10^{m / 2595} - 1).

Lemma 1 (the edges). Line L3 gives f0=flof_0 = f_{lo}, fM+1=fhif_{M+1} = f_{hi}, f0<f1<⋯<fM+1f_0 < f_1 < \cdots < f_{M+1}, and mel⁡(fi+1)−mel⁡(fi)=Δ\operatorname{mel}(f_{i+1}) - \operatorname{mel}(f_i) = \Delta for 0≤i≤M0 \le i \le M.

Proof. By line L3, mel⁡(fi)=mlo+iΔ\operatorname{mel}(f_i) = m_{lo} + i \Delta. For i=0i = 0 this is mel⁡(flo)\operatorname{mel}(f_{lo}), and for i=M+1i = M + 1 it is mlo+(mhi−mlo)=mel⁡(fhi)m_{lo} + (m_{hi} - m_{lo}) = \operatorname{mel}(f_{hi}); since mel⁡\operatorname{mel} is one to one, f0=flof_0 = f_{lo} and fM+1=fhif_{M+1} = f_{hi}. Since flo<fhif_{lo} < f_{hi} and mel⁡\operatorname{mel} is strictly increasing, Δ>0\Delta > 0, so the values mel⁡(fi)\operatorname{mel}(f_i) strictly increase with ii, and so do the fif_i, because mel⁡−1\operatorname{mel}^{-1} is strictly increasing too. The difference of consecutive mel values is Δ\Delta by the formula. □\square

By Lemma 1 the denominators fm−fm−1f_m - f_{m-1} and fm+1−fmf_{m+1} - f_m of lines L6 and L7 are positive, so the weights are well defined. Write Tm(f)T_m(f) for the value that lines L6 to L8 give at the frequency ff, so that W[m][k]=Tm(kfs/N)W[m][k] = T_m(k f_s / N).

Lemma 2 (the triangles). For 1≤m≤M1 \le m \le M and every f≥0f \ge 0: 0≤Tm(f)≤10 \le T_m(f) \le 1; Tm(f)>0T_m(f) > 0 exactly when fm−1<f<fm+1f_{m-1} < f < f_{m+1}; and Tm(f)=1T_m(f) = 1 exactly when f=fmf = f_m.

Proof. The three cases of lines L6 to L8 cover every ff and do not overlap. If fm−1<f≤fmf_{m-1} < f \le f_m, then 0<f−fm−1≤fm−fm−10 < f - f_{m-1} \le f_m - f_{m-1}, so 0<Tm(f)≤10 < T_m(f) \le 1, with equality to 1 only for f=fmf = f_m. If fm<f<fm+1f_m < f < f_{m+1}, then 0<fm+1−f<fm+1−fm0 < f_{m+1} - f < f_{m+1} - f_m, so 0<Tm(f)<10 < T_m(f) < 1. Otherwise Tm(f)=0T_m(f) = 0. □\square

Lemma 3 (overlap by half). For every ff with f1≤f≤fMf_1 \le f \le f_M, ∑m=1MTm(f)=1\sum_{m=1}^{M} T_m(f) = 1, and at most two terms are positive. For f≤f0f \le f_0 or f≥fM+1f \ge f_{M+1}, every Tm(f)T_m(f) is 0.

Proof. The last claim follows from Lemma 2, since the support of TmT_m is inside (fm−1,fm+1)⊆(f0,fM+1)(f_{m-1}, f_{m+1}) \subseteq (f_0, f_{M+1}). For the first claim, if f=f1f = f_1, then T1(f)=1T_1(f) = 1 by Lemma 2, and every other Tm(f)T_m(f) is 0 because f1≤fm−1f_1 \le f_{m-1} for m≥2m \ge 2. Otherwise f1<f≤fMf_1 < f \le f_M, and there is exactly one jj with 1≤j≤M−11 \le j \le M - 1 and fj<f≤fj+1f_j < f \le f_{j+1}, because the edges strictly increase. Then Tj(f)=(fj+1−f)/(fj+1−fj)T_j(f) = (f_{j+1} - f)/(f_{j+1} - f_j) by line L7, and Tj+1(f)=(f−fj)/(fj+1−fj)T_{j+1}(f) = (f - f_j)/(f_{j+1} - f_j) by line L6. Their sum is (fj+1−fj)/(fj+1−fj)=1(f_{j+1} - f_j)/(f_{j+1} - f_j) = 1. Every other filter mm has f≤fm−1f \le f_{m-1} (if m≥j+2m \ge j + 2) or f≥fm+1f \ge f_{m+1} (if m≤j−1m \le j - 1), so its weight is 0. □\square

Applied to the bin frequencies f=kfs/Nf = k f_s / N, 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 E[m]=∑kTm(kfs/N)P[k]≥0E[m] = \sum_k T_m(k f_s / N) P[k] \ge 0, and line L10 gives ln⁡max⁡(E[m],10−10)\ln \max(E[m], 10^{-10}). If every P[k]P[k] is multiplied by c>0c > 0, and both E[m]E[m] and cE[m]c E[m] are at least 10−1010^{-10}, then the output for filter mm grows by exactly ln⁡c\ln c.

Proof. The first part restates the lines. The weights and the power values are nonnegative, so E[m]≥0E[m] \ge 0. The sum is linear in PP, so the new energy is cE[m]c E[m], and under the condition the output changes from ln⁡E[m]\ln E[m] to ln⁡(cE[m])=ln⁡c+ln⁡E[m]\ln(c E[m]) = \ln c + \ln E[m]. □\square

Theorem. MEL-FILTER-BANK returns, for each mm, the log, floored at 10−1010^{-10}, 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 cc on the spectrum adds ln⁡c\ln c to each output above the floor.

Proof. Lemmas 1 to 4. □\square

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 10−1210^{-12}, the peak of each triangle on a fine grid, and the shift by ln⁡4\ln 4 when the amplitude doubles.

Complexity

In the real RAM, the window costs O(W)O(W), the FFT O(Nlog⁡N)O(N \log N) and line L9 O(MN)O(M N) 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 O(N)O(N), so the FFT dominates. Building the table in lines L1 to L8 costs O(MN)O(M N) once. The table takes O(MN)O(M N) memory, or O(N)O(N) 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 200/3200/3 Hz per mel and logarithmic above with a step of ln⁡(6.4)/27\ln(6.4)/27 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 ∣X[k]∣|X[k]|. 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 fs/2f_s / 2 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 MM or raise NN.
  • 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 fsf_s.

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.

mel_filter_bank.pyI0RawGitHub
# 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 2595log⁡10(1+f/700)2595 \log_{10}(1 + f / 700), Kaldi in the form 1127ln⁡(1+f/700)1127 \ln(1 + f/700), 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

  1. 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)
  2. 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)
  3. Xuedong Huang, Alex Acero and Hsiao-Wuen Hon, Spoken Language Processing, Prentice Hall, 2001, Chapter 6 (Speech Signal Representations), section Perceptually Motivated Representations
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example