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:
x, sr = librosa.load('audio/conga_groove.wav')
Compute the STFT:
S = librosa.stft(x)
librosa.decompose.decompose
¶We will use librosa.decompose.decompose
to perform our factorization. librosa
uses sklearn.decomposition.NMF
by default as its factorization method.
X, X_phase = librosa.magphase(S)
n_components = 6
W, H = librosa.decompose.decompose(X, n_components=n_components, sort=True)
print(W.shape)
print(H.shape)
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.
Listen to the reconstructed full mix:
Listen to the residual:
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)...]
.