Vocal Intelligence Mathematics with Python

Vocal Intelligence Mathematics with Python AI

Vocal Intelligence here means an AI system’s ability to hear a voice, find its features, recognise words and tone, and respond quickly. This guide explains the mathematics step by step, with Python code that needs only NumPy.

Pipeline: Voice → Frames → MFCC + Prosody → AI Model → Words and Emotion → Score

Note: This is an educational demo. It uses computer-generated signals, not real human speech. Attention and CTC are shown as separate examples and are not trained into a full speech recogniser.

1. The Voice Signal

A computer stores sound as a list of numbers. We sample it 16,000 times per second. To keep this tutorial self-contained, we create a synthetic voice-like signal made of a base pitch and its harmonics. Copy the code blocks in order into one file named vi.py.

x[n] = A · Σk=1..5 (1/k) · sin(k·Ï†[n]) + noise[n]
φ[n] = (2Ï€ / fs) · Σi≤n f0 · (1 + drift[i])
import numpy as np

SR = 16000                      # sampling rate (Hz)
rng = np.random.default_rng(42)

def synth_voice(f0, amp, wobble, noise, dur=1.0):
    t = np.arange(int(SR * dur)) / SR
    drift = np.cumsum(rng.normal(0, wobble, t.size)) / np.sqrt(SR)
    phase = 2 * np.pi * np.cumsum(f0 * (1 + drift)) / SR
    x = sum(np.sin(k * phase) / k for k in range(1, 6))
    return amp * x + rng.normal(0, noise, t.size)

A = loudness, f0 = pitch in Hz, fs = sampling rate.

2. Pre-emphasis, Framing and Windowing

Pre-emphasis boosts high frequencies. Speech changes over time, so we cut it into short overlapping frames (40 ms long, every 10 ms). A Hamming window smooths the edges of each frame.

y[n] = x[n] − α·x[n−1],  α = 0.97
w[n] = 0.54 − 0.46·cos( 2Ï€n / (N−1) )
def frames_of(x, size=640, hop=160, alpha=0.97):
    y = np.append(x[0], x[1:] - alpha * x[:-1])
    n = 1 + (len(x) - size) // hop
    idx = np.arange(size) + hop * np.arange(n)[:, None]
    return x[idx], y[idx] * np.hamming(size)

3. MFCC: How AI “Hears” Sound

Mel-Frequency Cepstral Coefficients (MFCCs) are compact numbers describing the shape of the sound spectrum. The Mel scale imitates human hearing, which separates low pitches better than high ones.

Power: P[k] = |X[k]|² / NFFT
Mel scale: m = 2595 · log10(1 + f/700)
Log-Mel energy: S[m] = ln( Σk Hm[k]·P[k] + ε )
MFCC: c[j] = Σm=0..M−1 S[m] · cos( Ï€j(m + ½) / M )
def hz_to_mel(f): return 2595 * np.log10(1 + f / 700)
def mel_to_hz(m): return 700 * (10 ** (m / 2595) - 1)

def mel_bank(n_mels=26, n_fft=1024):
    pts = mel_to_hz(np.linspace(0, hz_to_mel(SR / 2), n_mels + 2))
    freqs = np.arange(n_fft // 2 + 1) * SR / n_fft
    H = np.zeros((n_mels, freqs.size))
    for m in range(n_mels):
        lo, mid, hi = pts[m:m + 3]
        H[m] = np.maximum(0, np.minimum((freqs - lo) / (mid - lo),
                                        (hi - freqs) / (hi - mid)))
    return H

def mfcc(windowed, n_mfcc=13, n_fft=1024):
    power = np.abs(np.fft.rfft(windowed, n_fft)) ** 2 / n_fft
    logmel = np.log(power @ mel_bank(n_fft=n_fft).T + 1e-10)
    M = logmel.shape[1]
    k = np.arange(n_mfcc)[:, None]
    basis = np.cos(np.pi * k * (np.arange(M) + 0.5) / M)
    return logmel @ basis.T

Hm is the m-th triangular filter and M = 26 is the number of filters. We keep the first 13 coefficients (an unnormalised DCT-II).

4. Prosody: Pitch, Energy and Voice Variation

Prosody is how something is said. Pitch comes from autocorrelation: we find the delay at which the wave best matches itself.

Autocorrelation: R(Ï„) = Σn x[n]·x[n+Ï„]
Pitch: f0 = fs / Ï„*,  Ï„* = argmax R(Ï„)
Energy: RMS = √( (1/N) Σ x[n]² )
Zero-crossing rate: ZCR = sign changes / (N−1)
Jitter proxy = mean|f0[t] − f0[t−1]| / mean(f0)
Shimmer proxy = mean|RMS[t] − RMS[t−1]| / mean(RMS)
def pitch(frame, fmin=60, fmax=400):
    f = frame - frame.mean()
    r = np.correlate(f, f, "full")[len(f) - 1:]
    lo, hi = SR // fmax, SR // fmin
    lag = lo + np.argmax(r[lo:hi + 1])
    if 0 < lag < len(r) - 1:               # parabolic refinement
        a, b, c = r[lag - 1:lag + 2]
        d = a - 2 * b + c
        if d != 0:
            return SR / (lag + 0.5 * (a - c) / d)
    return SR / lag

def prosody(raw):
    f0 = np.array([pitch(f) for f in raw])
    rms = np.sqrt(np.mean(raw ** 2, axis=1))
    zcr = np.mean(np.signbit(raw[:, 1:]) != np.signbit(raw[:, :-1]), axis=1)
    # Frame-level proxies; clinical jitter/shimmer use single pitch cycles
    jitter = np.mean(np.abs(np.diff(f0))) / f0.mean()
    shimmer = np.mean(np.abs(np.diff(rms))) / rms.mean()
    return np.array([f0.mean(), f0.std(), rms.mean(), zcr.mean(), jitter, shimmer])

def features(x):
    raw, win = frames_of(x)
    return np.concatenate([mfcc(win).mean(axis=0), prosody(raw)])

These jitter and shimmer values compare frames and are teaching proxies. Clinical measures compare individual pitch cycles, so do not use these for health assessment. The final feature vector has 13 MFCCs + 6 prosody values = 19 numbers.

5. Classification: Calm or Excited?

A softmax classifier turns features into probabilities. It learns by gradient descent, reducing the cross-entropy loss. Features are standardised first using the training data’s mean and standard deviation.

Standardise: z = (v − μ) / σ
Softmax: pc = esc / Σj esj,  s = zW + b
Loss: L = −(1/N) Σi ln pi,yáµ¢ + (λ/2)‖W‖²
Update: W ← W − η · ( Záµ€(P − Y)/N + λW )
Bias: b ← b − η · mean(P − Y)
def softmax(z):
    e = np.exp(z - z.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)

def make_dataset(n):
    X, y = [], []
    for i in range(n):
        label = i % 2
        if label == 0:   # calm
            x = synth_voice(rng.uniform(100, 180), rng.uniform(.1, .35), .02, .01)
        else:            # excited
            x = synth_voice(rng.uniform(160, 280), rng.uniform(.25, .6), .08, .01)
        X.append(features(x)); y.append(label)
    return np.array(X), np.array(y)

def train(X, y, lr=0.1, epochs=300, lam=1e-3):
    W, b = np.zeros((X.shape[1], 2)), np.zeros(2)
    Y = np.eye(2)[y]
    for _ in range(epochs):
        P = softmax(X @ W + b)
        W -= lr * (X.T @ (P - Y) / len(X) + lam * W)
        b -= lr * (P - Y).mean(axis=0)
    return W, b

6. Self-Attention: Understanding Context

Transformer-based speech models use attention so that each frame can look at other frames. This simple version has no learned weights (Q = K = V = H). Real models learn separate projections for Q, K and V.

Attention(Q, K, V) = softmax( QKáµ€ / √d ) · V
def self_attention(H):
    A = softmax(H @ H.T / np.sqrt(H.shape[1]))   # Q = K = V = H (no learned weights)
    return A @ H, A

7. CTC: Matching Audio to Text

Audio has many more frames than the text has letters. Connectionist Temporal Classification (CTC), used in many speech recognisers, adds up the probability of every valid alignment.

P(text | audio) = Σπ ∈ B⁻¹(text) Πt pt(Ï€t)
Loss = −ln P(text | audio)
Forward: αt(s) = [αt−1(s) + αt−1(s−1) + αt−1(s−2)*] · pt(zs)
def ctc_prob(P, target, blank=0):
    ext = [blank]
    for c in target:
        ext += [c, blank]
    T, S = len(P), len(ext)
    a = np.zeros((T, S))
    a[0, 0] = P[0, ext[0]]
    if S > 1:
        a[0, 1] = P[0, ext[1]]
    for t in range(1, T):
        for s in range(S):
            v = a[t - 1, s]
            if s >= 1:
                v += a[t - 1, s - 1]
            if s >= 2 and ext[s] != blank and ext[s] != ext[s - 2]:
                v += a[t - 1, s - 2]
            a[t, s] = v * P[t, ext[s]]
    return a[-1, -1] + (a[-1, -2] if S > 1 else 0)

* The s−2 term applies only when zs is not blank and differs from zs−2. Worked example: two frames, each with P(blank)=0.6 and P(a)=0.4. The paths “aa”, “a_” and “_a” all give “a”: 0.16 + 0.24 + 0.24 = 0.64. This multiplies raw probabilities, so long audio needs a log-space version.

8. Word Error Rate (Accuracy of Speech-to-Text)

WER counts the word mistakes. S = substitutions, D = deletions, I = insertions, N = words in the correct sentence. Lower is better, and it can exceed 100%.

WER = (S + D + I) / N
def wer(ref, hyp):
    r, h = ref.lower().split(), hyp.lower().split()
    D = np.zeros((len(r) + 1, len(h) + 1), int)
    D[:, 0] = np.arange(len(r) + 1)
    D[0, :] = np.arange(len(h) + 1)
    for i in range(1, len(r) + 1):
        for j in range(1, len(h) + 1):
            D[i, j] = min(D[i-1, j] + 1, D[i, j-1] + 1,
                          D[i-1, j-1] + (r[i-1] != h[j-1]))
    return D[-1, -1] / len(r)

Example: “the” is heard as “a” in a 5-word sentence, so WER = 1/5 = 20%.

9. Vocal Intelligence Score (Illustrative)

There is no universally accepted formula for “vocal intelligence”. The score below is an example framework proposed for this article that combines four qualities of a voice AI. Choose and validate your own weights for a real product.

VIS = 100 × (0.4·A + 0.3·E + 0.2·R + 0.1·e−t/Ï„)
A = max(0, 1 − WER)  (speech accuracy)
E = mean probability given to the correct emotion class
R = prosody quality, 0 to 1 (from listener ratings or your own test)
t = response delay in ms, Ï„ = 1000 ms
def vi_score(asr, emotion, prosody_s, latency_ms,
             w=(0.4, 0.3, 0.2, 0.1), tau=1000):
    parts = np.array([asr, emotion, prosody_s, np.exp(-latency_ms / tau)])
    return 100 * float(np.dot(w, np.clip(parts, 0, 1)))

Hand calculation: with A = 0.80, E close to 1, R = 0.85 and t = 300 ms, VIS = 100 × (0.32 + 0.3·E + 0.17 + 0.0741) = 56.41 + 30·E. The program calculates E and prints the final score below. R and t are sample inputs, not measurements.

10. Run the Complete Program

Add this last block to vi.py, then run:

pip install numpy
python vi.py
if __name__ == "__main__":
    X_train, y_train = make_dataset(80)
    X_test, y_test = make_dataset(40)
    mu, sd = X_train.mean(0), X_train.std(0) + 1e-8
    W, b = train((X_train - mu) / sd, y_train)
    P = softmax(((X_test - mu) / sd) @ W + b)
    acc = np.mean(P.argmax(1) == y_test)
    print(f"Feature vector size : {X_train.shape[1]}")
    print(f"Pitch check (200 Hz): {features(synth_voice(200, .3, 0, 0))[13]:.1f} Hz")
    print(f"Test accuracy       : {acc:.2%}")

    H = mfcc(frames_of(synth_voice(150, .3, .02, .01))[1])
    H = (H - H.mean(0)) / (H.std(0) + 1e-8)
    context, A = self_attention(H)
    print(f"Attention output    : {context.shape}")

    probs = np.array([[0.6, 0.4], [0.6, 0.4]])   # columns: blank, 'a'
    p = ctc_prob(probs, [1])
    print(f"CTC P('a'), loss    : {p:.2f}, {-np.log(p):.4f}")

    err = wer("turn on the kitchen light", "turn on a kitchen light")
    print(f"Word Error Rate     : {err:.2%}")

    emo_conf = P[np.arange(len(y_test)), y_test].mean()
    # prosody score (0.85) and latency (300 ms) are example inputs
    print(f"VI Score (example)  : {vi_score(1 - err, emo_conf, 0.85, 300):.2f} / 100")

11. Output

Output from a test run with NumPy 2.5.3:

Feature vector size : 19
Pitch check (200 Hz): 200.0 Hz
Test accuracy       : 100.00%
Attention output    : (97, 13)
CTC P('a'), loss    : 0.64, 0.4463
Word Error Rate     : 20.00%
VI Score (example)  : 86.22 / 100

About the 100% accuracy: the synthetic calm and excited signals are designed to differ in pitch, loudness and variation, so they are very easy to separate. It does not show real-world performance. For real use, train and test on labelled human recordings, keep test speakers separate from training speakers, and check results across languages and accents.

12. Summary

StageMain formula or methodPurpose
Signal processingPre-emphasis, windowPrepare audio
FeaturesMFCC, f0, RMS, ZCRDescribe the voice
LearningSoftmax, cross-entropyClassify tone
ContextSelf-attentionLink frames
Speech-to-textCTC, WERTrain and evaluate
OverallVIS (illustrative)Compare systems under the same tests

Conclusion

Voice AI is built from signal processing, probability, linear algebra and optimisation. Understanding these formulas helps you see what happens between speaking a sentence and getting an AI response. A natural next step is to replace the synthetic signals with real, consented voice recordings. Voice data is personal, so collect and store it responsibly.

Post a Comment

0 Comments