Classify sounds with MFCCs and an SVM
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:
- Split the audio into short frames (about 25 ms).
- Take the frequency spectrum of each frame.
- Group frequencies into bands on the mel scale, which is finer at low pitches like our ears.
- 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
- Record at least 30 to 50 examples per class, in the real setting.
- Include a "none" class of background noise, typing and taps on other objects.
- Save the trained pipeline with
joblibso the daemon starts instantly.