Algorithmadvanced
Perceptual linear prediction
Also called PLP, PLP analysis.
Hermansky's features: a Bark-scale critical band spectrum with equal loudness and cube-root compression, modeled by an all-pole fit.
- Time
- O(N log N + M N + M p + p^2) worst
- Space
- O(M N) extra
- Where
- M = the number of critical band samples; N = the FFT length; p = the model order
- Model
- Real RAM
- Properties
- deterministicexactnot in placeonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Hynek Hermansky, 1990
Perceptual linear prediction, or PLP, is the feature extractor of Hermansky (1990): it warps the power spectrum of a frame to the Bark scale, smooths it with a critical band curve, weights it by an equal loudness curve and takes its cube root, and then fits an all-pole model to the result. Plain linear predictive coding fits the all-pole model to the spectrum as it is, with the same resolution at all frequencies; PLP fits it to a spectrum that has first been reshaped to match hearing, so a low model order such as 5 is enough. MFCC shape the spectrum with a mel filter bank and a log and then use a cosine transform, where PLP uses the cube root and the all-pole fit. RASTA filtering is often added to PLP to remove slow channel effects.
In plain words
PLP first changes the spectrum of a short frame of speech the way the ear would. It spreads the frequencies on a scale where equal steps sound like equal steps, and it sums the energy in bands about as wide as the ear's own filters. It then lowers the very low and very high frequencies, which the ear hears less, and compresses loud and soft parts with a cube root, as loudness grows with the cube root of power. On this reshaped spectrum it fits a smooth curve with only a few peaks, using the same method that linear prediction uses on the raw spectrum. The curve's few numbers, usually turned into cepstral coefficients, are the features. Because the reshaping hides details that differ between speakers, a curve with just two peaks describes the vowel well.
The problem
Given a frame of speech at a sample rate of Hz and a model order , compute the cepstrum of an all-pole model of the auditory spectrum of the frame. Hermansky's analysis has these steps. The frame is windowed (Hamming) and its power spectrum is computed by the FFT. The frequency in Hz goes to the Bark value
The critical band curve, with in Bark, is
the equal loudness curve, with in rad/s, is
and the intensity-to-loudness law is . The all-pole model is with .
The algorithm
The band centers are points evenly spaced from 0 to , a little under 1 Bark apart. Bin of the FFT is at .
PLP(frame, f_s, p, K)- 1
P[k] ← |FFT_N(Hamming · frame)[k]|² for k ← 0 to N/2 - 2
W[i][k] ← ψ(Ω_i - Ω(f_k)) for i ← 0 to M - 1 and k ← 0 to N/2 - 3
θ[i] ← Σ_k W[i][k] P[k] ▷ critical band integration - 4
ξ[i] ← E(2π · Ω⁻¹(Ω_i)) · θ[i] ▷ equal loudness - 5
φ[i] ← ξ[i]^0.33 ▷ cube root law - 6
φ[0] ← φ[1]; φ[M - 1] ← φ[M - 2] - 7
r[τ] ← (φ[0] + 2 Σ_{i=1}^{M-2} φ[i] cos(π τ i / (M - 1)) + φ[M - 1] cos(π τ)) / (2(M - 1)) for τ ← 0 to p - 8
(a_1 … a_p, g) ← LEVINSON-DURBIN(r, p) - 9
c_0 ← ln g; c_m ← a_m + Σ_{k=1}^{m-1} (k/m) c_k a_{m-k} for m ← 1 to K ▷ a_j = 0 for j > p
Line L2 sums over the FFT bins with the weight ; a bin contributes to band when it lies between 2.5 Bark below and 1.3 Bark above the center, the same reach as the integration of the paper, which resamples the warped spectrum instead. Line L6 copies the end values, because the two end bands have no data beyond the band edges; the paper does the same. Line L7 is the inverse DFT of the even extension of over points, so is the autocorrelation of a signal whose power spectrum on the Bark axis is . Line L8 is the Levinson-Durbin recursion, as in linear predictive coding, and is its final prediction error. Line L9 turns the model into its cepstrum, the usual output. The model lives on the Bark axis: in means , and in general.
Example
Take Hz, so Bark, bands 0.973 Bark apart, centered at 0, 98, 198, 304, 417, 542, 681, 838, 1017, 1222, 1460, 1737, 2059, 2436, 2877, 3394 and 4000 Hz. The equal loudness weight is dB at 100 Hz, dB at 500 Hz, dB at 1 kHz, dB at 2 kHz and dB at 4 kHz, relative to its limit at high frequencies.
A pulse train of 100 Hz through one resonance at 1000 Hz with a bandwidth of 80 Hz gives, for a frame of 200 samples (25 ms), the auditory spectrum = 0.194, 0.194, 0.468, 0.750, 1.066, 1.473, 2.073, 4.153, 6.955, 5.356, 3.201, 1.973, 1.583, 1.388, 1.280, 1.240, 1.240, with its peak in the band at 1017 Hz. A 5th order model gives , , and the cepstrum to = 0.3869, , , , 0.1325, . The peak of the model spectrum, mapped back from the Bark axis, is at 1104 Hz. For resonances at 500, 1500 and 2000 Hz the peaks are at 531, 1577 and 2059 Hz, all within 0.6 Bark of the resonance.
Correctness
PLP computes a defined feature, so correctness means that lines L7 to L9 do what they claim for the auditory spectrum built in lines L1 to L6. The full proofs are below.
- Line L7 gives a valid autocorrelation. If every , the Toeplitz matrix of is positive definite (theorem), so the Levinson-Durbin recursion runs without division by zero, every reflection coefficient has , and has all its zeros inside the unit circle.
- Line L9 is the cepstrum of the model. With minimum phase, the numbers of line L9 are the Fourier coefficients of : (theorem).
- Loudness moves only . A gain on the frame multiplies and by , and by , leaves unchanged and multiplies by , so only changes, by (theorem).
- The model peak follows a formant. A 5th order model has room for two resonances, and on vowel-like inputs its peaks sit near the formants on the Bark axis, as in the example (measurement). Hermansky's experiments that favour order 5 for speaker-independent features are measurements too.
Proof: The all-pole fit and the cepstrum of PLP are well defined and correctfull
We work in the real RAM. Lines L1 to L6 compute the auditory spectrum by direct formulas, so there is nothing to prove about them beyond the definitions on the page. We prove that lines L7 to L9 are well defined and compute the cepstrum of an all-pole model of , and that a gain on the frame changes only . Let and assume , and for every .
Let be the even extension of to points: for and for . Let .
Lemma 1 (line L7 is an inverse DFT). For , , and this number is real.
Proof. Pair the term with the term for . They have the same and conjugate exponentials, so together they give . The term gives , and the term gives . Dividing by gives line L7.
Lemma 2 (positive definite). The Toeplitz matrix with is positive definite.
Proof. Since by Lemma 1 (the sum is real and even in ), . For a real vector ,
Equality would need the polynomial , of degree at most and not zero, to vanish at the distinct points , because every . A nonzero polynomial of degree at most has fewer than roots, so the sum is positive.
Lemma 3 (line L8). On a positive definite Toeplitz matrix, the Levinson-Durbin recursion never divides by zero, every reflection coefficient satisfies , every prediction error is positive, and the result solves the normal equations for , with . The polynomial then has all its zeros strictly inside the unit circle.
Proof. These are the standard facts about the recursion, proved on the Levinson-Durbin recursion page: the error after step is , a ratio of leading principal minors, so it is positive, and forces . A polynomial built by the recursion from reflection coefficients of modulus below 1 has its zeros inside the unit circle, which is the stability result of the lattice form (the Schur-Cohn test read backwards).
Lemma 4 (line L9 is the cepstrum). Let have all its zeros inside the unit circle and . Define and for by line L9. Then for every real ,
Proof. Write with . For each factor has the convergent series , so converges for , with real because the are real. Differentiate , or equivalently , and multiply by :
The coefficient of gives , with for . Dividing by gives the recursion of line L9, so for by induction on . Finally .
Lemma 5 (a gain moves only ). If the frame is multiplied by and every , then is unchanged, is multiplied by , grows by , and for is unchanged.
Proof. scales by in line L1. Lines L3 and L4 are linear, so and scale by , and line L5 gives scaled by . Line L6 copies values, and line L7 is linear, so scales by the same factor . The normal equations of Lemma 3 are unchanged when is scaled, so is the same, and scales by . In line L9, grows by , and the for depend only on .
Theorem. If the auditory spectrum is positive and , PLP returns the first cepstral coefficients of a stable all-pole model whose predictor solves the normal equations of the autocorrelation of , and a gain on the frame changes only .
Proof. Lemmas 1 to 5.
The tests check Lemma 1 against a complex inverse DFT, Lemma 3 against a direct solve of the normal equations, Lemma 4 against the inverse DFT of the log model spectrum on 1024 points, and Lemma 5 with a gain of 4.
Complexity
In the real RAM, line L1 costs , line L2 but only once per sample rate, line L3 with the dense weights or with only the nonzero ones, lines L4 to L6 , line L7 , line L8 and line L9 . With about 17 to 21 and to 12, the FFT dominates. The weight table takes memory.
Properties
- Low order. The reshaped spectrum is smooth enough that a 5th order model describes the first two formants, against 10 to 14 for plain LPC at 8 to 10 kHz.
- Gain separated. The predictor does not depend on the loudness, and all of it goes to and .
- Less speaker dependent. By smoothing over critical bands, PLP hides details such as the exact higher formants, which vary between speakers more than between vowels (measurement in the paper).
- Not robust to the channel by itself. A fixed filter still changes the spectrum; RASTA filtering or cepstral mean normalization is needed for that.
Variants and improvements
- RASTA-PLP. Filter the log critical band trajectories over time with the RASTA filter between lines L3 and L4, then exponentiate; this removes slow channel effects and is the common form in noisy and telephone speech.
- PLP on mel filters. HTK computes PLP from its mel filter bank, with the equal loudness curve and the cube root applied to the filter outputs, and allows higher orders such as 12 for recognition.
- Order and number of cepstra. Order 5 for speaker independence, orders 8 to 14 when more detail is wanted; usually 13 cepstra with delta features.
- Other loudness laws. Some front ends use a log or a smaller power in place of the cube root; the all-pole fit then models a more compressed spectrum.
When to use it
Use PLP in place of or beside MFCC for GMM-HMM speech recognition, especially in the RASTA-PLP form for telephone or noisy speech, and when features should depend little on the speaker. Systems that combine several front ends often include it. For neural network recognizers trained on large data the log mel energies of a mel filter bank are simpler and usual. Do not use a 5th order PLP model when speaker identity matters: the point of the low order is to hide it.
Pitfalls
- Forgetting the Bark axis. The model spectrum is a function of the warped frequency. Its peaks must be mapped back through before they are compared with formants in Hz.
- Zero bands. A band with , from digital silence, makes the Toeplitz matrix singular. Add a tiny dither or a floor before line L5.
- The cube root of negative values. Numerical noise can make a filtered (RASTA) band slightly negative; clamp before the power.
- Mixing implementations. The paper's resampling, the HTK mel version and the rastamat code give different numbers; the end band handling and the equal loudness form differ too.
- The sign of . With , as in some code, the recursion of line L9 changes sign. This page uses .
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
# 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
perceptual_linear_prediction.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/perceptual-linear-prediction/. The authors are listed in prov/H7TRFV.jsonl.
"""Perceptual linear prediction (PLP) of one frame, after Hermansky (1990).
Steps: the power spectrum of the windowed frame; critical band integration with
the masking curve psi on the Bark scale Omega(f) = 6 asinh(f / 600); the equal
loudness weight E(omega) of the paper (the form for a band up to about 5 kHz);
the cube root law Phi = Xi^0.33; an all-pole model of order p fitted to Phi
through its autocorrelation (the inverse DFT of Phi) and the Levinson-Durbin
recursion; and the cepstrum of the all-pole model.
The integration sums over the FFT bins with the weight psi(Omega_i - Omega(f_k)),
in place of the paper's resampling of the warped spectrum. The band centers are
M = ceil(Omega(fs / 2)) + 1 points equally spaced from 0 to Omega(fs / 2), a little
under 1 Bark apart. The LPC sign convention is A(z) = 1 - sum a_k z^-k.
"""
import math
from typing import List, Optional, Sequence, Tuple
from nlsdsp import hamming, levinson, power_spectrum
def hz_to_bark(f: float) -> float:
"""Omega(f) = 6 ln(f / 600 + sqrt((f / 600)^2 + 1)) = 6 asinh(f / 600), f in Hz."""
return 6.0 * math.asinh(f / 600.0)
def bark_to_hz(b: float) -> float:
return 600.0 * math.sinh(b / 6.0)
def masking_curve(z: float) -> float:
"""The critical band curve psi of Hermansky (1990), z in Bark (target minus masker)."""
if z < -1.3 or z > 2.5:
return 0.0
if z < -0.5:
return 10.0 ** (2.5 * (z + 0.5))
if z <= 0.5:
return 1.0
return 10.0 ** (-1.0 * (z - 0.5))
def equal_loudness(f: float) -> float:
"""E(omega) = (omega^2 + 56.8e6) omega^4 / ((omega^2 + 6.3e6)^2 (omega^2 + 0.38e9)), omega = 2 pi f."""
w2 = (2.0 * math.pi * f) ** 2
return (w2 + 56.8e6) * w2 * w2 / ((w2 + 6.3e6) ** 2 * (w2 + 0.38e9))
def band_centers(fs: float) -> List[float]:
top = hz_to_bark(fs / 2.0)
m = int(math.ceil(top)) + 1
return [i * top / (m - 1) for i in range(m)]
def critical_band_weights(nfft: int, fs: float) -> Tuple[List[float], List[List[float]]]:
"""The band centers in Bark and the weights W[i][k] = psi(Omega_i - Omega(f_k))."""
centers = band_centers(fs)
barks = [hz_to_bark(k * fs / nfft) for k in range(nfft // 2 + 1)]
return centers, [[masking_curve(c - b) for b in barks] for c in centers]
def autocorrelation_of_spectrum(phi: Sequence[float], max_lag: int) -> List[float]:
"""The inverse DFT of the even extension of phi_0 .. phi_{M-1} (a spectrum on 0 to pi):
r[k] = phi_0 + 2 sum_{i=1}^{M-2} phi_i cos(pi k i / (M - 1)) + phi_{M-1} cos(pi k), over 2 (M - 1)."""
m = len(phi)
n = 2 * (m - 1)
out = []
for k in range(max_lag + 1):
s = phi[0] + phi[-1] * math.cos(math.pi * k)
s += 2.0 * sum(phi[i] * math.cos(math.pi * k * i / (m - 1)) for i in range(1, m - 1))
out.append(s / n)
return out
def lpc_to_cepstrum(a: Sequence[float], gain: float, n: int) -> List[float]:
"""The cepstrum c_0 .. c_{n-1} of the model spectrum gain / |A(e^{jw})|^2.
c_0 = ln gain, and for m >= 1, c_m = a_m + sum_{k=1}^{m-1} (k / m) c_k a_{m-k},
with a_m = 0 for m > p. This is the Fourier series of the log model spectrum."""
p = len(a)
c = [math.log(gain)] + [0.0] * (n - 1)
for m in range(1, n):
acc = a[m - 1] if m <= p else 0.0
for k in range(max(1, m - p), m):
acc += (k / m) * c[k] * a[m - k - 1]
c[m] = acc
return c
def plp_frame(
frame: Sequence[float],
fs: float = 8000.0,
order: int = 5,
num_ceps: Optional[int] = None,
nfft: Optional[int] = None,
weights=None,
) -> Tuple[List[float], List[float], float, List[float]]:
"""PLP of one frame. Returns (cepstrum, a, gain, phi): the cepstrum c_0 .. c_{num_ceps-1}
of the all-pole model, the predictor a_1 .. a_p, the model gain and the auditory spectrum phi."""
if nfft is None:
nfft = 1 << max(1, (len(frame) - 1).bit_length())
if num_ceps is None:
num_ceps = order + 1
win = hamming(len(frame))
p = power_spectrum([s * w for s, w in zip(frame, win)], nfft) # @line L1
centers, w = weights if weights is not None else critical_band_weights(nfft, fs) # @line L2
theta = [sum(wi * pk for wi, pk in zip(row, p)) for row in w] # @line L3
xi = [equal_loudness(bark_to_hz(c)) * t for c, t in zip(centers, theta)] # @line L4
phi = [v ** 0.33 for v in xi] # @line L5
phi[0], phi[-1] = phi[1], phi[-2] # @line L6
r = autocorrelation_of_spectrum(phi, order) # @line L7
a, gain = levinson(r, order) # @line L8
return lpc_to_cepstrum(a, gain, num_ceps), a, gain, phi # @line L9
def model_spectrum(a: Sequence[float], gain: float, omega: float) -> float:
"""gain / |A(e^{j omega})|^2 with A(z) = 1 - sum a_k z^-k."""
re = 1.0 - sum(ak * math.cos(omega * (k + 1)) for k, ak in enumerate(a))
im = sum(ak * math.sin(omega * (k + 1)) for k, ak in enumerate(a))
return gain / (re * re + im * im)
test_perceptual_linear_prediction.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/perceptual-linear-prediction/. The authors are listed in prov/H7TRFV.jsonl.
import cmath
import math
import random
from nlsdsp import all_pole, levinson, pulse_train, white_noise
from perceptual_linear_prediction import (
autocorrelation_of_spectrum,
band_centers,
bark_to_hz,
critical_band_weights,
equal_loudness,
hz_to_bark,
lpc_to_cepstrum,
masking_curve,
model_spectrum,
plp_frame,
)
def test_bark_scale():
assert round(hz_to_bark(5000.0), 1) == 16.9
assert abs(hz_to_bark(600.0) - 6.0 * math.log(1.0 + math.sqrt(2.0))) < 1e-12
for f in (0.0, 100.0, 1000.0, 3999.0):
assert abs(bark_to_hz(hz_to_bark(f)) - f) < 1e-9
def test_masking_curve():
assert masking_curve(0.0) == 1.0
assert masking_curve(-0.5) == 1.0 and masking_curve(0.5) == 1.0
assert abs(masking_curve(-1.3) - 0.01) < 1e-12
assert abs(masking_curve(1.5) - 0.1) < 1e-12
assert abs(masking_curve(2.5) - 0.01) < 1e-12
assert masking_curve(-1.31) == 0.0 and masking_curve(2.51) == 0.0
def test_equal_loudness_rises_to_one():
vals = [equal_loudness(f) for f in (50.0, 100.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0)]
assert all(a < b for a, b in zip(vals, vals[1:]))
assert all(0.0 < v < 1.0 for v in vals)
assert equal_loudness(0.0) == 0.0
assert abs(equal_loudness(1e7) - 1.0) < 1e-3
def test_band_centers_and_weights():
c = band_centers(8000.0)
assert len(c) == 17 and c[0] == 0.0 and abs(c[-1] - hz_to_bark(4000.0)) < 1e-12
assert all(0.9 < b - a < 1.0 for a, b in zip(c, c[1:]))
centers, w = critical_band_weights(256, 8000.0)
assert len(w) == 17 and all(len(row) == 129 for row in w)
# each band reaches 2.5 Bark below its center and 1.3 Bark above
for ci, row in zip(centers, w):
for k, v in enumerate(row):
z = hz_to_bark(k * 8000.0 / 256)
if v > 0:
assert ci - 2.5 <= z <= ci + 1.3
def test_autocorrelation_of_spectrum_is_an_inverse_dft():
rng = random.Random(3)
phi = [rng.uniform(0.1, 2.0) for _ in range(9)]
full = phi + phi[-2:0:-1] # the even extension, 16 points
n = len(full)
ref = [(sum(full[i] * cmath.exp(2j * math.pi * k * i / n) for i in range(n)) / n).real for k in range(6)]
got = autocorrelation_of_spectrum(phi, 5)
assert all(abs(g - r) < 1e-12 for g, r in zip(got, ref))
# a flat spectrum is white: r = [phi, 0, 0, ...]
flat = autocorrelation_of_spectrum([2.0] * 9, 4)
assert abs(flat[0] - 2.0) < 1e-12 and all(abs(v) < 1e-12 for v in flat[1:])
def _solve(m, b):
# Gauss elimination with partial pivoting, for the Toeplitz check
n = len(b)
a = [row[:] + [b[i]] for i, row in enumerate(m)]
for col in range(n):
piv = max(range(col, n), key=lambda r: abs(a[r][col]))
a[col], a[piv] = a[piv], a[col]
for r in range(n):
if r != col:
f = a[r][col] / a[col][col]
a[r] = [x - f * y for x, y in zip(a[r], a[col])]
return [a[i][n] / a[i][i] for i in range(n)]
def test_levinson_on_an_auditory_spectrum_matches_a_direct_solve():
rng = random.Random(8)
x = white_noise(rng, 200, 0.3)
_, a, gain, phi = plp_frame(x, 8000.0, order=5)
r = autocorrelation_of_spectrum(phi, 5)
toeplitz = [[r[abs(i - j)] for j in range(5)] for i in range(5)]
direct = _solve(toeplitz, r[1:6])
assert all(abs(u - v) < 1e-9 for u, v in zip(a, direct))
assert abs(gain - (r[0] - sum(ak * rk for ak, rk in zip(a, r[1:6])))) < 1e-9
def test_lpc_to_cepstrum_matches_the_log_spectrum():
a, gain, n = [1.2, -0.7, 0.2], 0.5, 1024
c = lpc_to_cepstrum(a, gain, 12)
log_s = [math.log(model_spectrum(a, gain, 2 * math.pi * i / n)) for i in range(n)]
for m in range(12):
# c is the inverse DFT of the log model spectrum: ln S(w) = sum over all m of c_|m| e^{-j w m}
ref = sum(log_s[i] * math.cos(2 * math.pi * m * i / n) for i in range(n)) / n
assert abs(c[m] - ref) < 1e-9
def test_end_samples_copy_their_neighbors():
rng = random.Random(1)
_, _, _, phi = plp_frame(white_noise(rng, 200, 0.2), 8000.0)
assert phi[0] == phi[1] and phi[-1] == phi[-2]
def test_gain_changes_only_c0():
rng = random.Random(5)
x = white_noise(rng, 200, 0.2)
c1, a1, _, _ = plp_frame(x, 8000.0)
c2, a2, _, _ = plp_frame([4.0 * v for v in x], 8000.0)
# power scales by 16, the cube root law by 16^0.33, the gain by the same
assert abs(c2[0] - c1[0] - 0.33 * math.log(16.0)) < 1e-9
assert all(abs(u - v) < 1e-9 for u, v in zip(c1[1:], c2[1:]))
assert all(abs(u - v) < 1e-9 for u, v in zip(a1, a2))
def test_model_peak_near_a_formant():
fs = 8000.0
top = hz_to_bark(fs / 2.0)
for formant in (500.0, 1000.0, 1500.0, 2000.0):
r = math.exp(-math.pi * 80.0 / fs)
th = 2.0 * math.pi * formant / fs
x = all_pole(pulse_train(100.0, fs, 600), [2.0 * r * math.cos(th), -r * r])
_, a, gain, _ = plp_frame(x[200:400], fs, order=5)
best = max(range(401), key=lambda i: model_spectrum(a, gain, math.pi * i / 400))
# the model lives on the Bark axis: omega = pi means fs / 2
assert abs(best / 400.0 * top - hz_to_bark(formant)) < 1.0
History
Linear prediction came to speech in the late 1960s and early 1970s with the work of Itakura and Saito and of Atal and Hanauer, and its all-pole fit follows the spectrum with the same accuracy at all frequencies, unlike the ear. Hynek Hermansky published PLP in the Journal of the Acoustical Society of America in 1990. The paper joined three approximations from psychoacoustics with an all-pole model and, from its experiments, recommended a 5th order model for features that should not depend on the speaker. In 1994 Hermansky and Morgan added RASTA filtering, and RASTA-PLP became a standard front end of the 1990s, used next to MFCC in many recognizers.
References
- Hynek Hermansky, Perceptual linear predictive (PLP) analysis of speech, Journal of the Acoustical Society of America 87(4), 1990, 1738 to 1752, the steps of the analysis (the Bark warping, the critical band curve, the equal loudness curve, the cube root law and the all-pole model fitted through the inverse DFT) and the experiments that recommend a 5th order model
- The HTK Book, version 3.4, Chapter Speech Input/Output, section Perceptual Linear Prediction (PLP computed on a mel filter bank)
- Xuedong Huang, Alex Acero and Hsiao-Wuen Hon, Spoken Language Processing, Prentice Hall, 2001, Chapter 6 (Speech Signal Representations), sections Linear Predictive Coding and Perceptually Motivated Representations
- 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, Eq. (3): the cepstrum computed directly from the linear prediction coefficients
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 H7TRFV Edit this page History Report an error Markdown