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]:

`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)
```

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.