%matplotlib inline
import seaborn
import numpy, scipy, matplotlib.pyplot as plt, sklearn, IPython.display as ipd
import librosa, librosa.display
plt.rcParams['figure.figsize'] = (14, 4)
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')
print sr
Play the audio signal:
ipd.Audio(x, rate=sr)
Compute the STFT:
S = librosa.stft(x)
print S.shape
Display the spectrogram:
Smag = librosa.amplitude_to_db(S)
librosa.display.specshow(Smag, sr=sr, x_axis='time', y_axis='log')
plt.colorbar()
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 = numpy.absolute(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 spectra:
plt.figure(figsize=(12, 6))
logW = numpy.log10(W)
for n in range(n_components):
plt.subplot(numpy.ceil(n_components/2.0), 2, n+1)
plt.plot(logW[:,n])
plt.ylim(-2, logW.max())
plt.xlim(0, W.shape[0])
plt.ylabel('Component %d' % n)
Let's display the temporal activations:
plt.figure(figsize=(12, 6))
for n in range(n_components):
plt.subplot(numpy.ceil(n_components/2.0), 2, n+1)
plt.plot(H[n])
plt.ylim(0, H.max())
plt.xlim(0, H.shape[1])
plt.ylabel('Component %d' % n)
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.
reconstructed_signal = scipy.zeros(len(x))
for n in range(n_components):
Y = scipy.outer(W[:,n], H[n])*numpy.exp(1j*numpy.angle(S))
y = librosa.istft(Y)
reconstructed_signal[:len(y)] += y
ipd.display( ipd.Audio(y, rate=sr) )
Listen to the reconstructed full mix:
ipd.Audio(reconstructed_signal, rate=sr)
Listen to the residual:
residual = x - reconstructed_signal
residual[0] = 1 # hack to prevent automatic gain scaling
ipd.Audio(residual, rate=sr)