Genre Recognition#

import IPython.display as ipd
import matplotlib.pyplot as plt
import librosa.display
import numpy
import pandas
import sklearn

from mirdotcom import mirdotcom

mirdotcom.init()

Load Audio#

Load 30 seconds of an audio file:

filename_brahms = mirdotcom.get_audio("brahms_hungarian_dance_5.mp3")
x_brahms, sr_brahms = librosa.load(filename_brahms, duration=30)

Load 30 seconds of another audio file:

filename_busta = mirdotcom.get_audio("busta_rhymes_hits_for_days.mp3")
x_busta, sr_busta = librosa.load(filename_busta, duration=30)

Play the audio files:

ipd.Audio(x_brahms, rate=sr_brahms)
ipd.Audio(x_busta, rate=sr_busta)

Plot the time-domain waveform of the audio signals:

plt.figure(figsize=(14, 5))
librosa.display.waveshow(x_brahms, sr=sr_brahms)
plt.ylabel("Autocorrelation")
<matplotlib.collections.PolyCollection at 0x1128cce80>
../../_images/e9d8a04b3a26aebd5e6eea517c3648438e8582337b161ea3e84d6d334428e5f0.png
plt.figure(figsize=(14, 5))
librosa.display.waveshow(x_busta, sr=sr_busta)
plt.ylabel("Autocorrelation")
<matplotlib.collections.PolyCollection at 0x112b20b38>
../../_images/17707f78452ef652520fef93a9f4d2227e121318975dd10c411264009be69ed6.png

Compute the power melspectrogram:

S_brahms = librosa.feature.melspectrogram(y=x_brahms, sr=sr_brahms, power=2.0)

Convert amplitude to decibels:

Sdb_brahms = librosa.power_to_db(S_brahms)
plt.figure(figsize=(15, 5))
librosa.display.specshow(Sdb_brahms, sr=sr_brahms, x_axis="time", y_axis="mel")
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x111636240>
../../_images/7f9924d94d90f25d0198fffe7f77854af96d8f6a4ba34e57c6786a0d592a3408.png
S_busta = librosa.feature.melspectrogram(y=x_busta, sr=sr_busta, power=2.0)
Sdb_busta = librosa.power_to_db(S_busta)
plt.figure(figsize=(15, 5))
librosa.display.specshow(Sdb_busta, sr=sr_busta, x_axis="time", y_axis="mel")
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x1116a8dd8>
../../_images/b24df095841578223528aeed022ed001c70cfe57e8f237a6d2a069d6d4b37396.png

In what ways do the time-domain waveform and spectrogram differ between the two files? What differences in musical attributes might this reflect? What additional insights are gained from plotting the spectrogram?

Extract Features#

For each segment, compute the MFCCs. Experiment with n_mfcc to select a different number of coefficients, e.g. 12.

n_mfcc = 12
mfcc_brahms = librosa.feature.mfcc(y=x_brahms, sr=sr_brahms, n_mfcc=n_mfcc).T

We transpose the result to accommodate scikit-learn which assumes that each row is one observation, and each column is one feature dimension:

mfcc_brahms.shape
(1292, 12)
mfcc_brahms.mean(axis=0)
array([-220.93906043,  135.8146764 ,  -16.1986192 ,   60.09800836,
        -10.74171479,   24.57344387,  -10.06327054,    9.731529  ,
         -8.28940164,    5.63699785,   -3.99416235,   -2.94650237])
mfcc_brahms.std(axis=0)
array([77.8507174 , 18.85226412, 14.43771304, 11.0615969 , 11.15194374,
        9.53373496,  8.30995864,  8.35195864,  8.34518744,  7.3264163 ,
        6.02968518,  5.75487171])

Scale the features to have zero mean and unit variance:

scaler = sklearn.preprocessing.StandardScaler()
mfcc_brahms_scaled = scaler.fit_transform(mfcc_brahms)
# is equivalent to:
#  scaler.fit(mfcc_brahms)
#  mfcc_brahms_scaled = scaler.transform(mfcc_brahms)

Verify that the scaling worked:

mfcc_brahms_scaled.mean(axis=0)
array([ 2.39780676e-15, -1.24975709e-14,  1.43783334e-16, -1.83547707e-15,
       -7.79390312e-16, -1.24393100e-15, -7.93998510e-16, -1.64694539e-15,
        6.99152638e-16,  5.68860404e-17,  9.52110767e-17,  1.04525951e-15])
mfcc_brahms_scaled.std(axis=0)
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])

Extract MFCCs from the second audio file.

mfcc_busta = librosa.feature.mfcc(y=x_busta, sr=sr_busta, n_mfcc=n_mfcc).T

We transpose the resulting matrix so that each row is one observation, i.e. one set of MFCCs. Note that the shape and size of the resulting MFCC matrix is equivalent to that for the first audio file:

print(mfcc_brahms.shape)
print(mfcc_busta.shape)
(1292, 12)
(1292, 12)

Scale the resulting MFCC features to have approximately zero mean and unit variance. Re-use the scaler from above.

mfcc_busta_scaled = scaler.transform(mfcc_busta)

Verify that the mean of the MFCCs for the second audio file is approximately equal to zero and the variance is approximately equal to one.

mfcc_busta_scaled.mean(axis=0)
array([ 2.27178743, -0.98521415, -1.01236983, -0.62225477, -2.07693829,
        0.70574552, -0.99776438,  1.37918189, -1.1971934 ,  0.98541195,
       -1.05935641,  1.65934091])
mfcc_busta_scaled.std(axis=0)
array([0.63033628, 1.26643623, 1.30243229, 1.47714284, 1.49474468,
       1.66052301, 1.65450649, 1.50051709, 1.2635102 , 1.31561208,
       1.64746289, 1.63874381])

Train a Classifier#

Concatenate all of the scaled feature vectors into one feature table.

features = numpy.vstack((mfcc_brahms_scaled, mfcc_busta_scaled))
features.shape
(2584, 12)

Construct a vector of target/reference labels, where 0 refers to the first audio file, and 1 refers to the second audio file.

labels = numpy.concatenate(
    (numpy.zeros(len(mfcc_brahms_scaled)), numpy.ones(len(mfcc_busta_scaled)))
)
labels.shape
(2584,)

Create a classifer model object:

# Support Vector Machine
model = sklearn.svm.SVC()

Train the classifier:

model.fit(features, labels)
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False)

Run the Classifier#

To test the classifier, we will extract an unused 10-second segment from the earlier audio fields as test excerpts:

x_brahms_test, sr_brahms = librosa.load(filename_brahms, duration=10, offset=120)
x_busta_test, sr_busta = librosa.load(filename_busta, duration=10, offset=120)

Listen to both of the test audio excerpts:

ipd.display(ipd.Audio(x_brahms_test, rate=sr_brahms))
ipd.display(ipd.Audio(x_busta_test, rate=sr_brahms))
ipd.Audio(x_busta_test, rate=sr_busta)