ML on Audio Signals

Since I’ve exclusively done ML work on image/video signals, I wanted to try and do some processing and learning on audio signals.
Hence, I decided to take audio clips from one of my favorite podcasts to see if I can build a prediction model that recognizes who’s voice it is in that sample. I sampled audio from the very bad wizards podcast, episode 240 specifically. Then I tried classifying the 1 second audio samples into 3 categories (2 hosts and 1 other signal) - david (D), tamler (T), and other (O).
The other category included music, random noise and samples from instances where they’re both talking. Essentially, anything that doesn’t fall neatly into D or T goes to O.

Loading and listening to the data

First of all, I found a script online that helps me play audio snippets in Jupyter. The snippet is shown below. Since it is hard to “visualize” audio, we need this:

import IPython.display
import numpy as np
import json


def Audio(audio: np.ndarray, sr: int):
    """
    Use instead of IPython.display.Audio as a workaround for VS Code.
    `audio` is an array with shape (channels, samples) or just (samples,)
    for mono.
    """

    if np.ndim(audio) == 1:
        channels = [audio.tolist()]
    else:
        channels = audio.tolist()

    return IPython.display.HTML("""
        <script>
            if (!window.audioContext) {
                window.audioContext = new AudioContext();
                window.playAudio = function(audioChannels, sr) {
                    const buffer = audioContext.createBuffer(
                        audioChannels.length, audioChannels[0].length, sr
                    );
                    for (let [channel, data] of audioChannels.entries()) {
                        buffer.copyToChannel(Float32Array.from(data), channel);
                    }
            
                    const source = audioContext.createBufferSource();
                    source.buffer = buffer;
                    source.connect(audioContext.destination);
                    source.start();
                }
            }
        </script>
        <button onclick="playAudio(%s, %s)">Play</button>
    """ % (json.dumps(channels), sr))

My first attempt was unsupervised learning. It wasn’t completely garbage, but it wasn’t very good either. I may revisit unsupervised learning once I make some headway with supervised. But after some initial experiments, I decided to move onto supervised methods. For this, I labeled data in 3 batches with 200 1-second samples each. Then I loaded them and used samples from 2 batches as training and 1 batch as test. Overall, I had 400 train and 200 test data points with each sampled labeled as D, T or O.

# loading data (some helper code omitted)
import os

import librosa
import soundfile as sf


def load_audio_file(file):
    audio_vals, freq = librosa.load(file)
    return audio_vals, freq


# since we're sampling at 22khz, I downsample the signal
# by a factor of 5 for easier processing.
def load_data_batch(batch_dictionary):
    X_orig, X_fft, y = [], [], []
    for audio_file_path, lbl in batch_dictionary.items():
        assert lbl in ('D', 'T', 'O')
        audio_vals, freq = load_audio_file(audio_file_path)
        yf = np.fft.fft(audio_vals)
        X_orig.append(audio_vals)
        X_fft.append(np.abs(yf)[::5])
        y.append(lbl)
    return X_orig, X_fft, y


def load_train_test_data():
    # Train
    X_train_orig, X_train, y_train = [], [], []
    X_train_orig_batch_1, X_train_batch_1, y_train_batch_1 = (
        load_data_batch(lbl_group_1_file_lbl)
    )
    X_train_orig_batch_2, X_train_batch_2, y_train_batch_2 = (
        load_data_batch(lbl_group_2_file_lbl)
    )
    X_train_orig = X_train_orig_batch_1 + X_train_orig_batch_2
    X_train = X_train_batch_1 + X_train_batch_2
    y_train = y_train_batch_1 + y_train_batch_2

    # Test
    X_test_orig, X_test, y_test = load_data_batch(lbl_group_3_file_lbl)
    
    X_train = np.array(X_train)
    y_train = np.array(y_train)

    X_test = np.array(X_test)
    y_test = np.array(y_test)

    X_train_orig = np.array(X_train_orig)
    X_test_orig = np.array(X_test_orig)

    return X_train_orig, X_train, y_train, X_test_orig, X_test, y_test


X_train_orig, X_train, y_train, X_test_orig, X_test, y_test = (
    load_train_test_data()
)

print(X_train.shape, X_test.shape)

(400, 4410) (200, 4410)

Working on amplitude vs fourier domain

Before moving further, let’s check out what a signal looks like (in amplitude and fourier domain), and sounds like.
Example below shows the signal when Tamler (T) is talking for a second and its fourier transform. Note that since this is speech signal, most of the signal is concentrated with +/-2Khz.

random_example_file = (
    '/Users/nripesh/Projects/audio fun/1s_samples_group1/sample_2.wav'
)
audio_signal, freq = load_audio_file(random_example_file)
signal_fft = np.fft.fft(audio_signal)
xf = np.fft.fftfreq(len(audio_signal), 1 / freq)

fig, axs = plt.subplots(1, 2)
fig.set_figheight(5)
fig.set_figwidth(12)

axs[0].plot(audio_signal)
axs[0].set_title('audio signal')

axs[1].plot(xf, np.abs(signal_fft))
axs[1].set_xlim(-5000, 5000)
axs[1].set_title('fft')

FREQ = 22e3
Audio(audio_signal, sr=FREQ)

png

Below is an example of an almost monotone music signal. The FFT signal shows that clearly with the strong peaks at around 500Hz and no other dominant frequencies.

png

Classifier 1: SVM

# linear SVM - on original signal

from sklearn.svm import SVC
from collections import Counter
from sklearn.metrics import f1_score, confusion_matrix


svc_model = SVC(C=1, kernel='linear')
svc_model.fit(X_train_orig, y_train)

y_pred = svc_model.predict(X_test_orig)

print(confusion_matrix(y_test, y_pred))
print('f1-score for raw signal SVM model: {:0.3f}'.format(
    f1_score(y_test, y_pred, average='micro'))
)
[[54 17  8]
 [ 8  1  2]
 [55 24 31]]
f1-score for raw signal SVM model: 0.430
# linear SVM - on FFT signal

svc_model = SVC(C=1, kernel='linear')
svc_model.fit(X_train, y_train)

y_pred = svc_model.predict(X_test)

print(confusion_matrix(y_test, y_pred))
print('f1-score for fft signal SVM model: {:0.3f}'.format(
    f1_score(y_test, y_pred, average='micro'))
)
[[70  5  4]
 [ 5  1  5]
 [15  8 87]]
f1-score for fft signal SVM model: 0.790

As we can see, performance is pretty poor with SVM applied on raw signals. I actually tried few other classifiers before realizing that the problem was with the signal and not really the models. Hence, for audio, it was natural to attempt fourier transform on the signal before classification.
Next, I trid gradient boosted trees:

Classifier 2: Gradient Boosted Trees

from sklearn.ensemble import GradientBoostingClassifier

tree = GradientBoostingClassifier(n_estimators=100, random_state=42)
tree.fit(X_train, y_train)

y_pred = tree.predict(X_test)
display(confusion_matrix(y_test, y_pred))
print('f1-score for fft signal GBM model: {:0.3f}'.format(
    f1_score(y_test, y_pred, average='micro'))
)
array([[ 72,   4,   3],
       [  3,   0,   8],
       [  8,   1, 101]])


f1-score for fft signal GBM model: 0.865

Let’s listen to some wrongly classified outputs


def return_wrongly_labeled_signal_and_label():
    while True:
        rand_ind = np.random.choice(len(X_test))
        x_i = np.expand_dims(X_test[rand_ind], 0)
        x_i_orig = X_test_orig[rand_ind]
        y_pred_i = tree.predict(x_i)
        y_test_i = y_test[rand_ind]

        if y_test_i != y_pred_i:
            return x_i_orig, y_test_i, y_pred_i

x_1_orig, y_1, y_1_pred = return_wrongly_labeled_signal_and_label()
print(y_1, y_1_pred)
Audio(x_1_orig, sr=FREQ)
T ['D']

x_2_orig, y_2, y_2_pred = return_wrongly_labeled_signal_and_label()
print(y_2, y_2_pred)
Audio(x_2_orig, sr=FREQ)
O ['T']

x_3_orig, y_3, y_3_pred = return_wrongly_labeled_signal_and_label()
print(y_3, y_3_pred)
Audio(x_3_orig, sr=FREQ)
O ['D']

2/3 mistakes displayed above are when O category gets misclassified to D or T. This makes sense if we look at the confusion matrix as well, where unfortunately, none of the O are correctly identified. We see this issue with all 3 types of classifiers we tried.
Lastly, I tried a neural network with 1D convolutional network. Since the data dimension is high (4410), I didn’t want to use dense layers since they would take much longer to train.

Classifier 3: 1D CNN


from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras import metrics

#create model
cnn_model = keras.Sequential(
    [
        keras.Input(shape=(X_train.shape[1], 1)),
        layers.Conv1D(8, kernel_size=3, activation="relu"),
        layers.MaxPool1D(2),
        layers.Conv1D(4, kernel_size=3, activation="relu"),
        layers.MaxPool1D(2),
        layers.Flatten(),
        layers.Dense(
            3, activation="softmax", 
        ),
    ]
)

cnn_model.summary()

Metal device set to: Apple M1
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv1d (Conv1D)              (None, 4408, 8)           32        
_________________________________________________________________
max_pooling1d (MaxPooling1D) (None, 2204, 8)           0         
_________________________________________________________________
conv1d_1 (Conv1D)            (None, 2202, 4)           100       
_________________________________________________________________
max_pooling1d_1 (MaxPooling1 (None, 1101, 4)           0         
_________________________________________________________________
flatten (Flatten)            (None, 4404)              0         
_________________________________________________________________
dense (Dense)                (None, 3)                 13215     
=================================================================
Total params: 13,347
Trainable params: 13,347
Non-trainable params: 0
_________________________________________________________________
from sklearn.preprocessing import OneHotEncoder

y_train_one_hot = OneHotEncoder(sparse=False).fit_transform(
    y_train.reshape(-1, 1),
).astype('float32')
y_test_one_hot = OneHotEncoder(sparse=False).fit_transform(
    y_test.reshape(-1, 1),
).astype('float32')

X_train_exp = np.expand_dims(X_train, -1)
X_test_exp = np.expand_dims(X_test, -1)

cnn_model.compile(
    optimizer='adam', 
    loss='categorical_crossentropy',
    metrics=[
        metrics.CategoricalAccuracy(),
    ]
)

cnn_model.fit(
    X_train_exp, y_train_one_hot,
    validation_data=(X_test_exp, y_test_one_hot),
    epochs=10,
)

y_pred = cnn_model.predict(X_test_exp)
y_test_pred = np.argmax(y_pred, axis=1)

int_to_lbl_map = {0: 'D', 1: 'O', 2: 'T'}
y_test_pred = [int_to_lbl_map[y_i] for y_i in y_test_pred]

display(confusion_matrix(y_test, y_test_pred))
print('f1-score for fft signal 1D CNN model: {:0.3f}'.format(
    f1_score(y_test, y_test_pred, average='micro'))
)
Epoch 1/10
 1/13 [=>............................] - ETA: 3s - loss: 0.0306 - categorical_accuracy: 1.0000
13/13 [==============================] - 1s 43ms/step - loss: 0.2149 - categorical_accuracy: 0.9275 - val_loss: 0.9147 - val_categorical_accuracy: 0.8050
Epoch 2/10
 1/13 [=>............................] - ETA: 0s - loss: 0.0934 - categorical_accuracy: 0.9375
13/13 [==============================] - 0s 27ms/step - loss: 0.0812 - categorical_accuracy: 0.9750 - val_loss: 0.6661 - val_categorical_accuracy: 0.8700
Epoch 3/10
13/13 [==============================] - 0s 32ms/step - loss: 0.0679 - categorical_accuracy: 0.9800 - val_loss: 0.6813 - val_categorical_accuracy: 0.8700
Epoch 4/10
13/13 [==============================] - 0s 30ms/step - loss: 0.0573 - categorical_accuracy: 0.9825 - val_loss: 0.6982 - val_categorical_accuracy: 0.8700
Epoch 5/10
13/13 [==============================] - 0s 30ms/step - loss: 0.0438 - categorical_accuracy: 0.9875 - val_loss: 0.6983 - val_categorical_accuracy: 0.8700
Epoch 6/10
13/13 [==============================] - 0s 30ms/step - loss: 0.0418 - categorical_accuracy: 0.9850 - val_loss: 0.7617 - val_categorical_accuracy: 0.8700
Epoch 7/10
13/13 [==============================] - 0s 30ms/step - loss: 0.0376 - categorical_accuracy: 0.9950 - val_loss: 0.7507 - val_categorical_accuracy: 0.8650
Epoch 8/10
13/13 [==============================] - 0s 30ms/step - loss: 0.0339 - categorical_accuracy: 0.9925 - val_loss: 0.7549 - val_categorical_accuracy: 0.8700
Epoch 9/10
13/13 [==============================] - 0s 30ms/step - loss: 0.0306 - categorical_accuracy: 0.9950 - val_loss: 0.9814 - val_categorical_accuracy: 0.8750
Epoch 10/10
13/13 [==============================] - 0s 30ms/step - loss: 0.0352 - categorical_accuracy: 0.9925 - val_loss: 0.8553 - val_categorical_accuracy: 0.8850


array([[ 72,   2,   5],
       [  3,   0,   8],
       [  5,   0, 105]])


f1-score for fft signal 1D CNN model: 0.885

Conclusions:

  • For audio signal, FFT prior to classification was immensely helpful. Not sure if this is universally true since this is my first time working on audio signals.
  • GBM and 1D-CNN seem slightly better than SVMs.
  • They all failed to classify the O class well. This is most likely due to low sample size.
Written on September 3, 2022