Algorithmadvanced
Statistical model voice activity detection
Also called Sohn VAD, likelihood ratio VAD.
Decide speech or noise per frame by a likelihood ratio test of Gaussian models of the spectral bins, smoothed by an HMM hangover.
- Solves
- Voice activity detection
- Time
- O(F N log N) worst
- Space
- O(N) extra
- Where
- F = the number of frames; N = the frame and FFT length
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jongseo Sohn, Nam Soo Kim, Wonyong Sung, 1999
The statistical model VAD of Sohn, Kim and Sung decides for each frame whether it contains speech by a likelihood ratio test between two Gaussian models of its DFT coefficients, noise alone and speech plus noise, and then smooths the decisions with a two-state hidden Markov model. It is one solution of voice activity detection. The older Rabiner-Sambur endpoint detector uses thresholds on energy and zero crossings instead, and finds only the start and end of one word; this method labels every frame and uses the same noise model as the Ephraim-Malah estimator.
In plain words
The method first listens to a short stretch of noise and learns how loud the noise is at each frequency. For every new frame, it asks two questions at each frequency: how likely is this frame if it is only noise, and how likely is it if speech is added. The ratio of the two answers says which story fits better. The ratios of all frequencies are multiplied, so a frame wins the "speech" vote only when many frequencies agree. Speech comes in runs of frames, not in single frames, so a small model of switching between "speech" and "noise" carries the belief from one frame to the next. This stops short gaps inside words from being cut.
The problem
Given a signal cut into frames and a stretch of noise at the start, label each frame 1 for speech and 0 for noise. Each frame has DFT coefficients , . The two hypotheses are
with and independent complex Gaussians of variances and , where is the noise power and the a priori signal-to-noise ratio of bin . The model treats the bins as independent.
The algorithm
Under the model, and . With the a posteriori SNR , the ratio of one bin is
The noise power comes from the first frames, which must be noise. The a priori SNR is unknown and comes from the decision-directed rule , where is the estimated clean power of the previous frame. Two states, 0 for noise and 1 for speech, with the chance of a switch from noise to speech and the reverse, give the smoothed statistic .
SOHN-VAD(x, frames of N samples, init frames, alpha, xi_min, a01, a10, threshold eta)- 1
X(n) <- the DFT of the windowed frame n, for every n - 2
lambda_k <- the mean of |X_k|^2 over the first init frames - 3
for each frame n: gamma_k <- |X_k(n)|^2 / lambda_k - 4
xi_k <- max(alpha A_k^2 / lambda_k + (1 - alpha) max(gamma_k - 1, 0), xi_min) - 5
log Lambda(n) <- sum over k of gamma_k xi_k / (1 + xi_k) - log(1 + xi_k) - 6
log G(n) <- log Lambda(n) + log(a01 + a11 G(n - 1)) - log(a00 + a10 G(n - 1)) - 7
speech(n) <- [log G(n) > log eta] - 8
A_k^2 <- (xi_k / (1 + xi_k))^2 |X_k(n)|^2; if not speech(n), move lambda_k toward |X_k(n)|^2
Line L6 starts from the stationary odds . The code takes from the Wiener gain ; the amplitude of the Ephraim-Malah estimator is a common alternative. The noise power is updated with a factor 0.98 in the frames judged noise. All the sums are in log space, because the product over 129 bins easily overflows.
Example
Take Hz, white Gaussian noise with standard deviation 0.01 for one second, and a 500 Hz tone of amplitude 0.01 from sample 2800 to sample 5200. The tone has half the power of the noise, an SNR of dB over the whole band. Frames of 256 samples with a hop of 128 and the Hamming window give 61 frames and 129 bins. The parameters are , , 10 noise frames at the start, , and (random seed 7).
| frame | start | decision | ||
|---|---|---|---|---|
| 19 | 2432 | 1.92 | 3.84 | 0 |
| 21 | 2688 | 5.34 | 7.28 | 0 |
| 22 | 2816 | 17.82 | 20.02 | 1 |
| 23 | 2944 | 30.33 | 32.53 | 1 |
| 39 | 4992 | 48.72 | 50.92 | 1 |
| 40 | 5120 | 0.41 | 2.61 | 0 |
| 42 | 5376 | -0.42 | 1.77 | 0 |
The decisions are frames 22 to 39. Frames 22 to 38 lie wholly inside the tone, and frame 39 (samples 4992 to 5247) holds it for 208 of its 256 samples. Frames 20, 21 and 40 hold the tone for only part of their length and are labeled noise. The tone lies in a few bins, so it is found even though its total power is below the noise. In frame 42 the frame alone favors noise (), and the memory of the previous speech frames raises to 1.77, still below the threshold. These values are measurements of this run.
Correctness
These are theorems, proved in proofs/correctness.md:
- The bin ratio. Under the two Gaussian models, , and it increases with for . So for known and , the test of line L7 without smoothing is the most powerful test of its size, by the Neyman-Pearson lemma.
- The smoothing is a forward recursion. If the states form a Markov chain with transitions , started from its stationary law, and each frame depends only on its own state, then of line L6 equals the posterior odds . This is the ratio of the two variables of the forward algorithm.
- No smoothing as a special case. With , .
The models are approximations: speech bins are not Gaussian, neighbor bins are correlated by the window, and is an estimate. The decision-directed estimate grows with the current , so even pure noise gives on average: in 5 runs of pure noise with these settings, every frame had between 0.5 and 6.9. This is why the threshold is tuned, not the value 0 that the posterior odds would suggest. That the method is robust at low SNR is a measurement, reported by Sohn, Kim and Sung against the G.729 Annex B VAD.
Proof: Correctness of the statistical model VADfull
We prove the three exact statements of the page: the form of the bin ratio and its optimality for known parameters, the meaning of the smoothed statistic as posterior odds, and the special case without memory.
Lemma 1 (the bin ratio)
Let be complex Gaussian with mean 0 and variance , with density . Under , ; under , with . With ,
Proof. The ratio is . The exponent is . Take the log.
Under the variance is because and are independent complex Gaussians and their variances add.
Monotonicity. For the derivative with respect to is , so increases strictly with . For it is identically 0.
Theorem 1 (the frame test is most powerful for known parameters)
Let and be known, and let the bins be independent under both hypotheses. For every level , the test that decides when , with chosen so that , has the largest among all tests with .
Proof. By independence, the likelihood ratio of the whole frame is , and its log is the sum. Under the sum has a continuous distribution (it is an affine function of the independent exponential variables with positive coefficients, for the bins with ), so a with exactly the level exists. The Neyman-Pearson lemma states that a test that rejects exactly when the likelihood ratio exceeds a constant, at level , is most powerful at that level.
Theorem 2 (the smoothed statistic is the posterior odds)
Let be a Markov chain on with transitions (, , ), started from its stationary law , . Let the frames be independent given the states, with depending only on , and let . Define and
Then for every , .
Proof. Let , the forward variables. They satisfy and . The posterior odds equal , since both posteriors have the same denominator . We show by induction.
For : . The recursion gives , since .
For , divide numerator and denominator by :
using from the hypothesis.
So the decision is the maximum a posteriori decision for frame given the frames up to , and is the Bayes decision when a false alarm costs times as much as a miss. The code uses and computes with a stable log-add, which changes no value.
Corollary (no memory)
If , then for all .
Proof. All four transitions are , so the fraction in the recursion is .
Remarks
The tests check Lemma 1 against the two densities computed directly, Theorem 2 against the sum over all state paths for , and the corollary. The decision-directed depends on the data, so Theorem 1 does not apply exactly to the running detector; the page says how this shifts the threshold.
Complexity
Each frame needs one FFT of points and work for the ratios, the decision-directed rule and the noise update, so the time is for frames. The state is the noise power, the previous clean power and , so the extra memory is , and the method runs online with a delay of one frame.
Properties
- Adapts to the noise. The noise power is updated in frames judged noise, so slowly changing noise is followed.
- Uses the spectrum. A tone or a formant that stands above the noise in a few bins is found even when the total energy barely changes, which energy thresholds miss.
- Calibrated in principle. is a posterior odds under the model, so the threshold has a meaning. In practice the model errors shift it, as above.
- Hang-over by a model. The HMM replaces fixed rules of the form "keep speech for 5 more frames".
Variants and improvements
- Geometric mean. Compare the mean with a threshold, which makes the threshold independent of the number of bins.
- Other distributions. Laplacian or Gamma models of the speech coefficients fit speech better than the Gaussian.
- Better noise tracking. Minimum statistics or MMSE noise trackers update the noise power during speech as well.
- Multiple observations. Use the ratios of several past and future frames in one test, at the cost of delay.
- Learned detectors. Neural VADs, trained on labeled speech, now reach lower error rates in hard noise; this method remains a light, training-free baseline.
When to use it
Use it as a front end of speech coding, of enhancement with spectral subtraction or a Wiener filter, and of recognition, when the noise is stationary or changes slowly and the start of the signal is noise. For clean, isolated words an energy and zero-crossing rule is simpler. For music, babble or other speech-like noise, a trained detector works better.
Pitfalls
- Speech at the start. If the first frames contain speech, the noise power is too high and quiet speech is missed for a long time.
- Noise power absorbing speech. A false "noise" decision during long speech updates the noise power toward the speech and makes later misses more likely.
- Threshold and bin count. The sum over bins grows with the frame length, so the threshold must change with it, or use the geometric mean.
- Floor of the SNR. Without , can be 0, and then for every input: the bin stops voting.
- Overflow. for a loud frame is far beyond the range of floating point. Work with and .
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/likelihood-ratio-vad/. The authors are listed in prov/4HXQ9X.jsonl.
"""Statistical model voice activity detection (Sohn, Kim and Sung).
Each DFT bin X_k of a frame is complex Gaussian with variance lambda_k under H0
(noise only) and lambda_k (1 + xi_k) under H1 (speech plus noise), where
lambda_k is the noise power and xi_k the a priori SNR. With the a posteriori
SNR gamma_k = |X_k|^2 / lambda_k, the likelihood ratio of one bin is
Lambda_k = p(X_k | H1) / p(X_k | H0) = exp(gamma_k xi_k / (1 + xi_k)) / (1 + xi_k).
The bins are independent under the model, so the frame ratio is the product.
The a priori SNR comes from the decision-directed rule, and an HMM of two states
(0 noise, 1 speech) smooths the decisions over time: G(n), the ratio of the two
forward variables, follows
G(n) = Lambda(n) (a01 + a11 G(n - 1)) / (a00 + a10 G(n - 1)),
which is the posterior odds of speech in frame n given frames 1 to n. Everything
is computed in log space.
"""
import math
from typing import List, Sequence, Tuple
from nlsdsp import fft, frames, hamming
from nlslog import log_add
def log_lr_bin(gamma: float, xi: float) -> float:
"""log Lambda_k = gamma xi / (1 + xi) - log(1 + xi)."""
return gamma * xi / (1.0 + xi) - math.log1p(xi)
def decision_directed(prev_amp2: float, noise: float, gamma: float, alpha: float, xi_min: float) -> float:
"""xi = max(alpha A^2 / lambda + (1 - alpha) max(gamma - 1, 0), xi_min), A^2 the previous clean power estimate."""
return max(alpha * prev_amp2 / noise + (1.0 - alpha) * max(gamma - 1.0, 0.0), xi_min)
def hmm_log_odds(log_lambdas: Sequence[float], a01: float, a10: float) -> List[float]:
"""log G(n) for every frame, from the stationary prior odds a01 / a10."""
a00, a11 = 1.0 - a01, 1.0 - a10
la00, la01, la10, la11 = (math.log(v) for v in (a00, a01, a10, a11))
lg = math.log(a01 / a10)
out = []
for ll in log_lambdas:
lg = ll + log_add(la01, la11 + lg) - log_add(la00, la10 + lg) # @line L6
out.append(lg)
return out
def vad(
x: Sequence[float],
frame_len: int = 256,
hop: int = 128,
init_frames: int = 10,
alpha: float = 0.98,
xi_min: float = 10 ** (-2.5),
noise_update: float = 0.98,
a01: float = 0.2,
a10: float = 0.1,
log_eta: float = 10.0,
) -> Tuple[List[int], List[float], List[float]]:
"""Return (decisions, log Lambda per frame, log G per frame). The first init_frames frames must be noise.
frame_len must be a power of 2. The decision is 1 (speech) when log G(n) > log_eta. The
default log_eta = 10 is tuned for frames of 256 samples (129 bins), not derived.
"""
w = hamming(frame_len)
spectra = []
for fr in frames(x, frame_len, hop): # @line L1
spec = fft([v * wi for v, wi in zip(fr, w)])
spectra.append([abs(spec[k]) ** 2 for k in range(frame_len // 2 + 1)])
if len(spectra) < init_frames or init_frames < 1:
raise ValueError("need at least init_frames frames, and init_frames >= 1")
nbins = frame_len // 2 + 1
noise = [sum(s[k] for s in spectra[:init_frames]) / init_frames for k in range(nbins)] # @line L2
noise = [max(v, 1e-12) for v in noise]
prev_amp2 = [0.0] * nbins
a00, a11 = 1.0 - a01, 1.0 - a10
la00, la01, la10, la11 = (math.log(v) for v in (a00, a01, a10, a11))
lg = math.log(a01 / a10)
decisions, log_lambdas, log_odds = [], [], []
for pw in spectra:
total = 0.0
xis = []
for k in range(nbins):
gamma = pw[k] / noise[k] # @line L3
xi = decision_directed(prev_amp2[k], noise[k], gamma, alpha, xi_min) # @line L4
xis.append(xi)
total += log_lr_bin(gamma, xi) # @line L5
lg = total + log_add(la01, la11 + lg) - log_add(la00, la10 + lg) # @line L6
speech = 1 if lg > log_eta else 0 # @line L7
for k in range(nbins): # @line L8
g = xis[k] / (1.0 + xis[k])
prev_amp2[k] = g * g * pw[k]
if not speech:
noise[k] = noise_update * noise[k] + (1.0 - noise_update) * pw[k]
decisions.append(speech)
log_lambdas.append(total)
log_odds.append(lg)
return decisions, log_lambdas, log_odds
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
nlslog.py 152 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/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
test_likelihood_ratio_vad.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/likelihood-ratio-vad/. The authors are listed in prov/4HXQ9X.jsonl.
import itertools
import math
import random
import unittest
from likelihood_ratio_vad import decision_directed, hmm_log_odds, log_lr_bin, vad
from nlsdsp import sine, white_noise
FS = 8000
def tone_in_noise(seed, amp, n=8000):
rng = random.Random(seed)
x = white_noise(rng, n, 0.01)
tone = sine(500, FS, 2400, amp)
for i in range(2400):
x[2800 + i] += tone[i]
return x
class TestBinRatio(unittest.TestCase):
def test_matches_gaussian_densities(self):
# p(X | H) = exp(-|X|^2 / v) / (pi v) for a complex Gaussian of variance v.
rng = random.Random(1)
for _ in range(200):
lam = rng.uniform(0.1, 5.0)
xi = rng.uniform(0.0, 20.0)
x2 = rng.uniform(0.0, 30.0)
p0 = math.exp(-x2 / lam) / (math.pi * lam)
v1 = lam * (1.0 + xi)
p1 = math.exp(-x2 / v1) / (math.pi * v1)
self.assertAlmostEqual(log_lr_bin(x2 / lam, xi), math.log(p1 / p0), places=9)
def test_increasing_in_gamma(self):
for xi in (0.01, 1.0, 10.0):
vals = [log_lr_bin(g, xi) for g in (0.0, 0.5, 1.0, 2.0, 5.0)]
self.assertEqual(vals, sorted(vals))
self.assertEqual(log_lr_bin(3.0, 0.0), 0.0)
def test_decision_directed(self):
self.assertAlmostEqual(decision_directed(2.0, 1.0, 5.0, 0.98, 0.001), 0.98 * 2.0 + 0.02 * 4.0)
self.assertEqual(decision_directed(0.0, 1.0, 0.5, 0.98, 0.001), 0.001)
class TestHmm(unittest.TestCase):
def test_forward_odds_against_enumeration(self):
rng = random.Random(2)
a01, a10 = 0.2, 0.1
trans = [[1 - a01, a01], [a10, 1 - a10]]
prior = [a10 / (a01 + a10), a01 / (a01 + a10)]
for _ in range(20):
lams = [rng.uniform(-3.0, 3.0) for _ in range(6)]
got = hmm_log_odds(lams, a01, a10)
for n in range(1, 7):
mass = [0.0, 0.0]
for path in itertools.product((0, 1), repeat=n):
p = prior[path[0]]
for t in range(1, n):
p *= trans[path[t - 1]][path[t]]
for t in range(n):
if path[t] == 1:
p *= math.exp(lams[t])
mass[path[-1]] += p
self.assertAlmostEqual(got[n - 1], math.log(mass[1] / mass[0]), places=9)
def test_memoryless_chain_gives_frame_ratio(self):
lams = [0.5, -2.0, 7.0, 1.0]
for a, b in zip(hmm_log_odds(lams, 0.5, 0.5), lams):
self.assertAlmostEqual(a, b, places=12)
def test_vad_uses_the_same_recursion(self):
x = tone_in_noise(7, 0.01)
_, ll, lg = vad(x, init_frames=10, log_eta=10.0)
for a, b in zip(hmm_log_odds(ll, 0.2, 0.1), lg):
self.assertAlmostEqual(a, b, places=9)
class TestDetection(unittest.TestCase):
def test_page_example(self):
x = tone_in_noise(7, 0.01)
d, ll, lg = vad(x, init_frames=10, log_eta=10.0)
self.assertEqual(len(d), 61)
self.assertEqual(d, [0] * 22 + [1] * 18 + [0] * 21)
self.assertAlmostEqual(ll[22], 17.82, places=2)
self.assertAlmostEqual(lg[22], 20.02, places=2)
self.assertAlmostEqual(ll[42], -0.42, places=2)
def test_noise_only_has_no_detections(self):
for seed in range(4):
rng = random.Random(100 + seed)
d, _, _ = vad(white_noise(rng, 8000, 0.01), init_frames=10, log_eta=10.0)
self.assertEqual(sum(d), 0)
def test_errors_only_at_edges(self):
for seed in range(3):
d, _, _ = vad(tone_in_noise(seed, 0.02), init_frames=10, log_eta=10.0)
self.assertEqual(sum(d[:20]) + sum(d[42:]), 0)
self.assertEqual(sum(d[22:39]), 17)
def test_short_input(self):
with self.assertRaises(ValueError):
vad([0.0] * 300, init_frames=10)
if __name__ == "__main__":
unittest.main()
History
Before 1999, VADs for speech coding, such as the one of the G.729 Annex B standard, combined thresholds on energy, zero crossings and spectral features. Jongseo Sohn, Nam Soo Kim and Wonyong Sung of Seoul National University proposed in 1999 to treat the decision as a likelihood ratio test of Gaussian models of the DFT coefficients, the models that Ephraim and Malah had used for speech enhancement in 1984, with the decision-directed estimate of the a priori SNR and a hang-over based on a hidden Markov model. The method became a standard baseline; MATLAB's voiceActivityDetector, for example, follows it, with switch probabilities of 0.2 and 0.1 by default.
References
- Jongseo Sohn, Nam Soo Kim and Wonyong Sung, A statistical model-based voice activity detection, IEEE Signal Processing Letters 6(1), 1999, 1 to 3, the Gaussian models of the DFT coefficients, the likelihood ratio of each bin, the decision-directed estimate of the a priori SNR and the HMM-based hang-over scheme
- Philipos C. Loizou, Speech Enhancement, Theory and Practice, second edition, CRC Press, 2013, Section 9.4.3.1 (likelihood ratio approach), p. 406
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 4HXQ9X Edit this page History Report an error Markdown