Rishabh Kataria

Classify sounds with MFCCs and an SVM

By Rishabh Kataria ·

To classify short sounds, turn each sound into MFCC features and train a support vector machine (SVM) on labelled examples. This works well on small datasets and runs fast on a CPU, which is how EchoBind tells which part of a desk was knocked.

What are MFCCs?

Mel-frequency cepstral coefficients summarize the shape of a sound's spectrum the way human hearing perceives it:

  1. Split the audio into short frames (about 25 ms).
  2. Take the frequency spectrum of each frame.
  3. Group frequencies into bands on the mel scale, which is finer at low pitches like our ears.
  4. Take the log of each band's energy, then a discrete cosine transform.

The first 13 or so coefficients describe the sound's timbre compactly.

Extract features

import numpy as np
import librosa

def features(path):
    y, sr = librosa.load(path, sr=22050, mono=True)
    mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)
    # A fixed-length vector: mean and spread of each coefficient over time
    return np.concatenate([mfcc.mean(axis=1), mfcc.std(axis=1)])

For stereo input, compute features for each channel and add the level difference between left and right; it carries location information.

Train and test

from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X = np.array([features(p) for p in paths])   # paths: recorded clips
y = np.array(labels)                          # e.g. "top-left", "top-right"

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y)
model = make_pipeline(StandardScaler(), SVC(kernel="rbf", C=10, probability=True))
model.fit(X_train, y_train)
print("accuracy", model.score(X_test, y_test))

Scaling matters: SVMs are sensitive to features on different scales.

Detect when to classify

Do not classify every frame. Watch the RMS energy of the live stream and only run the model when it jumps above a threshold. That is the "knock". Then reject predictions below a confidence cut-off (using predict_proba) to avoid false triggers.

Tips