Nonnegative Matrix Factorization

Nonnegative matrix factorization (NMF) is an algorithm that factorizes a nonnegative matrix, $X$, into a product of two nonnegative matrices, $W$ and $H$. It is an unsupervised iterative algorithm that minimizes a distance between $X$ and the product $WH$:

$$ \min_{W, H} d(X, WH) $$

If $X$ has dimensions $M$ by $N$, then $W$ will have dimensions $M$ by $R$, and $H$ will have dimensions $R$ by $N$, where inner dimension $R$ is the rank or number of components of the decomposition.

When applied to a musical signal, we find that NMF can decompose the signal into separate note events. Therefore, NMF is quite useful and popular for tasks such as transcription and source separation.

The input, $X$, is often a magnitude spectrogram. In such a case, we find that the columns of $W$ represent spectra of note events, and the rows of $H$ represent temporal envelopes of the same note events.

Let's load a signal:

In [2]:
x, sr = librosa.load('audio/conga_groove.wav')
Out[3]:

Compute the STFT:

In [4]:
S = librosa.stft(x)
Out[5]:
<matplotlib.colorbar.Colorbar at 0x10c59e6d8>

librosa.decompose.decompose

We will use librosa.decompose.decompose to perform our factorization. librosa uses sklearn.decomposition.NMF by default as its factorization method.

In [6]:
X, X_phase = librosa.magphase(S)
n_components = 6
W, H = librosa.decompose.decompose(X, n_components=n_components, sort=True)
In [7]:
print(W.shape)
print(H.shape)
(1025, 6)
(6, 188)

Let's display the spectral profiles, $\{w_1, ..., w_R\}$:

Let's display the temporal activations, $\{h_1, ..., h_R\}$:

Finally, re-create the individual components, and listen to them. To do this, we will reconstruct the magnitude spectrogram from the NMF outputs and use the phase spectrogram from the original signal.

Component 0:
Component 1:
Component 2:
Component 3:
Component 4:
Component 5:

Listen to the reconstructed full mix:

Out[11]:

Listen to the residual:

Out[12]:

For Further Exploration

Use different audio files.

Alter the rank of the decomposition, n_components. What happens when n_components is too large? too small?

NMF is a useful preprocessor for MIR tasks such as music transcription. Using the steps above, build your own simple transcription system that returns a sequence of note events, [(onset time, class label, volume/gain)...].