Audio and Speech Data Science with MFCC and wav2vec
Audio modelling starts with a question that tabular and vision teams never have to ask: what should the input representation even be. Raw waveforms carry phase information that matters little for speech but a great deal for music, while spectrograms trade phase for a picture a convolutional network can read, and hand-crafted cepstral coefficients compress decades of speech science into a compact vector. Choosing badly costs accuracy before training begins, and switching later means rebuilding the entire pipeline. This lesson walks the representation choices, then applies them to transcription and sound classification.
Framing, windows, and the twenty-five millisecond assumption
Speech is quasi-stationary only over very short intervals, meaning its statistical properties hold constant for tens of milliseconds and then shift as the articulators move. Every classical feature pipeline exploits this by cutting the signal into frames of roughly twenty-five milliseconds with a ten-millisecond hop, so consecutive frames overlap and no phoneme boundary falls between two windows unnoticed. Apply a window function such as Hamming to each frame to taper the edges, because an abrupt cut in the time domain spreads energy across the whole frequency spectrum and corrupts the estimate.
Sample rate sets the ceiling on what you can represent. Anything above sixteen kilohertz adds little for speech, since the useful energy for intelligibility sits well below eight kilohertz, and doubling the sample rate doubles both storage and compute for no gain. Resample everything to one rate at ingestion and make it a constant of the pipeline; models silently degrade when a recording arrives at eight kilohertz and is upsampled to pretend otherwise.
MFCCs, mel spectrograms, and what each discards
A mel spectrogram maps the power spectrum onto the mel scale, which approximates how human pitch perception compresses high frequencies, then keeps a few dozen filterbank energies. MFCCs go one step further and take a discrete cosine transform of the log mel energies, decorrelating them so that a diagonal covariance assumption becomes reasonable. The trade-off is interpretability: mel spectrograms retain the fine structure that convolutional networks exploit, while MFCCs throw away phase and fine spectral detail in exchange for compactness.
| Representation | Dimensions per frame | Best for | Notable weakness |
|---|---|---|---|
| Raw waveform | Sample rate per second | Very large end-to-end models | Expensive, needs far more data |
| Mel spectrogram | 64 to 128 | CNNs, general audio classification | Still carries some phase loss |
| MFCC plus deltas | 39 to 60 | Small models, classical pipelines | Loses detail modern networks can use |
| Learned features (wav2vec) | 768 to 1024 | Transcription, low-resource ASR | Heavy inference, GPU preferred |
import numpy as np
import librosa
def extract_features(path: str, sr_target: int = 16000):
"""Load, normalise, and derive the standard feature set."""
y, sr = librosa.load(path, sr=sr_target, mono=True)
y = np.append(y[0], y[1:] - 0.97 * y[:-1]) # pre-emphasis
y = y / (np.max(np.abs(y)) + 1e-8) # peak normalise
mel = librosa.feature.melspectrogram(
y=y, sr=sr, n_fft=512, hop_length=160, n_mels=80
)
mel_db = librosa.power_to_db(mel, ref=np.max)
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13, n_fft=512, hop_length=160)
deltas = librosa.feature.delta(mfcc)
delta2 = librosa.feature.delta(mfcc, order=2)
return {
"mel_db": mel_db,
"mfcc_stack": np.vstack([mfcc, deltas, delta2]),
"centroid": librosa.feature.spectral_centroid(y=y, sr=sr).mean(),
"zcr": librosa.feature.zero_crossing_rate(y).mean(),
"rms": librosa.feature.rms(y=y).mean(),
"duration": len(y) / sr,
}
signal = np.random.randn(16000).astype(np.float32) * 0.1
import soundfile as sf
sf.write("_tmp_audio.wav", signal, 16000)
features = extract_features("_tmp_audio.wav")
print({k: (np.shape(v) if hasattr(v, "shape") else round(float(v), 4))
for k, v in features.items()})
Always plot the mel spectrogram once per new dataset. Domain shifts such as telephone bandwidth, background music, or heavy compression are visible in a spectrogram long before they show up as a two-point accuracy drop.
Transcription with wav2vec-style pretraining
Self-supervised speech models learn a representation from unlabelled audio and then map it to characters with a small labelled dataset. The practical consequence is dramatic data efficiency: a model pre-trained on tens of thousands of hours can be adapted with a few minutes of domain-specific audio, provided the fine-tuning schedule uses a low learning rate and freezes the feature encoder for the first epochs.
Two inference details are worth checking in review. First, every pipeline must resample to sixteen kilohertz, because feeding eight kilohertz audio to a model expecting sixteen produces confident nonsense. Second, extremely long recordings should be split on silence at roughly ten to thirty seconds, since attention over a single very long sequence degrades and memory grows quickly.
For production transcription services, consider batching requests and using a streaming API where latency matters. Many speech-to-text providers offer streaming endpoints that return partial hypotheses as the speaker talks, enabling real-time captions or voice assistants. When self-hosting, ONNX or TensorRT export of the fine-tuned model can reduce inference latency significantly, especially on GPU hardware.
import torch
import librosa
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
class Transcriber:
def __init__(self, model_name: str = "facebook/wav2vec2-base-960h"):
self.processor = Wav2Vec2Processor.from_pretrained(model_name)
self.model = Wav2Vec2ForCTC.from_pretrained(model_name)
self.model.eval()
@torch.no_grad()
def transcribe(self, path: str) -> str:
audio, _ = librosa.load(path, sr=16000)
inputs = self.processor(
audio, sampling_rate=16000, return_tensors="pt", padding=True
)
logits = self.model(inputs.input_values).logits
token_ids = logits.argmax(dim=-1)
return self.processor.batch_decode(token_ids)[0]
@torch.no_grad()
def confidence(self, path: str) -> dict:
audio, _ = librosa.load(path, sr=16000)
inputs = self.processor(
audio, sampling_rate=16000, return_tensors="pt", padding=True
)
logits = self.model(inputs.input_values).logits
probs = torch.softmax(logits, dim=-1)
best = probs.max(dim=-1).values
return {
"mean_confidence": float(best.mean()),
"low_confidence_frames": int((best < 0.5).sum()),
}
# transcriber = Transcriber()
# print(transcriber.transcribe("sample.wav"))
Classifying sounds with a convolutional recurrent hybrid
Sound classification differs from transcription because the label describes the whole clip rather than a timeline. A convolutional front end extracts local patterns from the mel spectrogram, a bidirectional recurrent layer models how those patterns evolve, and attention pooling selects the frames that matter instead of averaging them all equally.
import torch
import torch.nn as nn
class AudioClassifier(nn.Module):
def __init__(self, num_classes: int, n_mels: int = 80, hidden: int = 128):
super().__init__()
self.cnn = nn.Sequential(
nn.Conv2d(1, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(),
nn.AdaptiveAvgPool2d((None, None)),
)
self.rnn = nn.LSTM(
input_size=128 * (n_mels // 4), hidden_size=hidden,
num_layers=2, batch_first=True, bidirectional=True, dropout=0.3,
)
self.score = nn.Linear(hidden * 2, 1)
self.head = nn.Sequential(
nn.Linear(hidden * 2, 64), nn.ReLU(), nn.Dropout(0.3),
nn.Linear(64, num_classes),
)
def forward(self, mel: torch.Tensor) -> torch.Tensor:
feats = self.cnn(mel)
batch, channels, freq, time = feats.size()
feats = feats.permute(0, 3, 1, 2).reshape(batch, time, channels * freq)
packed, _ = self.rnn(feats)
weights = torch.softmax(self.score(packed), dim=1)
context = (weights * packed).sum(dim=1)
return self.head(context)
model = AudioClassifier(num_classes=12)
print(model(torch.randn(2, 1, 80, 128)).shape)
If the recurrent layer feels heavy, replace it with a couple of temporal convolution layers. On short clips the difference is usually small, and the convolutional version trains faster and batches more cleanly.
Augmentation that reflects real recording conditions
Audio augmentation works because it imitates the channel rather than adding arbitrary noise. Time stretching changes speaking rate without shifting pitch, pitch shifting covers speaker variation, background noise taken from an actual room recording teaches the model to ignore it, and SpecAugment masks contiguous time and frequency bands inside the spectrogram so the model cannot rely on one narrow cue.
import numpy as np
import librosa
class AudioAugmenter:
def __init__(self, sr: int = 16000, seed: int = 0):
self.sr = sr
self.rng = np.random.default_rng(seed)
def __call__(self, y: np.ndarray) -> np.ndarray:
if self.rng.random() < 0.5:
y = librosa.effects.time_stretch(y, rate=float(self.rng.uniform(0.85, 1.15)))
if self.rng.random() < 0.3:
y = librosa.effects.pitch_shift(
y, sr=self.sr, n_steps=float(self.rng.uniform(-2, 2))
)
if self.rng.random() < 0.5:
noise_level = float(self.rng.uniform(0.001, 0.01))
y = y + self.rng.standard_normal(y.shape) * noise_level
return y
def spec_augment(self, spec: np.ndarray, freq_masks: int = 2,
time_masks: int = 2, max_width: int = 16) -> np.ndarray:
out = spec.copy()
rows, cols = out.shape
for _ in range(freq_masks):
width = int(self.rng.integers(1, max_width))
start = int(self.rng.integers(0, max(1, rows - width)))
out[start:start + width, :] = 0
for _ in range(time_masks):
width = int(self.rng.integers(1, max_width))
start = int(self.rng.integers(0, max(1, cols - width)))
out[:, start:start + width] = 0
return out
augmenter = AudioAugmenter()
clean = np.random.randn(16000).astype(np.float32) * 0.05
augmented = augmenter(clean)
print(augmented.shape, round(float(np.abs(augmented).max()), 4))
Apply augmentation on the fly inside the training loop so the model sees a different corruption every epoch, and leave validation completely untouched. Augmenting validation data does not make it more realistic, it makes it noisier, and noisy validation hides real regressions.
Evaluation: word error rate and honest error analysis
Word error rate for transcription is the number of substitutions, deletions, and insertions divided by the number of reference words, so it can exceed one when a system is worse than useless. Always report it alongside a confidence interval computed over utterances rather than over words, because utterance lengths vary and treating every word as independent understates the uncertainty.
For classification, accuracy rarely suffices. Report per-class recall, since a rare but critical sound such as an alarm can be systematically missed while overall accuracy looks fine, and inspect the confusion matrix to find classes the model genuinely cannot distinguish. Many apparent model failures are label failures: two classes defined so that even humans disagree will cap accuracy at the human agreement rate, and the fix is annotation guidelines rather than a deeper network.
One practical note on dataset construction: balance your evaluation set across speakers, recording conditions, and noise levels rather than relying on a random split that may over-represent easy clean audio. A held-out set that mirrors the production conditions gives a much more honest picture of how the system will behave once real users arrive.
Common Mistakes
Feeding audio at mixed sample rates into a model trained at sixteen kilohertz
Fix: Resample once at ingestion, assert the rate when loading, and reject files that cannot be converted cleanly.
Applying augmentation to the validation split
Fix: Keep validation deterministic and augment only in the training loop, so metric changes reflect model changes.
Optimising the network while annotation guidelines remain ambiguous
Fix: Measure human agreement on a sample first, then treat that ceiling as the target for any architecture work.
Best Practices
- Resample every recording to one sample rate and make it a pipeline constant
- Plot a mel spectrogram per dataset to catch bandwidth and compression issues early
- Report word error rate with an utterance-level confidence interval
- Use SpecAugment on spectrograms and channel-matched noise on waveforms
- Freeze the feature encoder for the first epochs of speech model fine-tuning
Key Takeaways
- Frames of roughly twenty-five milliseconds make speech look stationary enough to analyse
- Mel spectrograms retain detail for CNNs, MFCCs trade that detail for compactness
- Self-supervised speech models reach strong accuracy with minutes of labelled audio
- Augmentation should imitate the recording channel rather than add arbitrary noise
- Error analysis starts with per-class recall and human agreement, not with a deeper model