← All tutorials

Non-negative Matrix Factorization (NMF)

Splitting non-negative data into parts that only add.

On this page

Non-negative matrix factorization (NMF) writes a non-negative data matrix, such as a spectrogram, as a few non-negative templates times how strongly each is used, so the parts can only add.

1spectrogramV1templates Wtimes H2why theyare parts3scorethe fit4updateW and H5how manytemplates7.1, 7.2mask, backto sound7.3, 7.4sounds overtime, rooms
Figure 1. Each box's marker is the section that teaches it.

NMF iterates on one whole matrix. In supervised use the templates are learned beforehand from clean examples of each sound (Section 7.1), and only the activations are fitted for each new recording.

1 A spectrogram as templates times activations

A spectrogram is a grid whose rows are frequencies and whose columns are short time slices, and each cell says how loud that frequency is at that moment. Each column is a mix of a few spectral templates, each turned up or down over time. NMF is matrix factorization with non-negative factors, the same idea recommender systems use with user and movie factors.

Take an illustrative spectrogram with 4 frequency bins and 3 frames, with a low note in frame 1, a high note in frame 2 and both in frame 3, as when two piano keys are played one after the other and then together. This is how NMF tells which note sounds when in a music recording, and which part of a noisy recording is speech (Section 7).

V202101011022highlow123frame=W2010010212templateH101011123frame1frame 3 = 1 × template 1 + 1 × template 21
Figure 2. Illustrative two-note spectrogram V as templates W times activations H.
CaseData VFactors W and H
This toy, 4 by 3, 2 templates128 + 6 = 14
Illustrative 10 s clip at 16 kHz, 257 bins by 624 frames, 25 templates160,3686,425 + 15,600 = 22,025

How many numbers the data and the factors store.

On the toy the factors are bigger than the data; on a real spectrogram they are about 7 times smaller, which forces the templates to be shared.

Every frame is built by adding a few spectral templates, each scaled by how loud it is at that moment, and nothing can be subtracted.
V ≈ W H
Each column of V is W times the same column of H. In Figure 2, column 3 of H is (1, 1), so frame 3 is template 1 plus template 2, which is (2, 1, 1, 2) from low bin to high.
V, W, H ≥ 0
Every entry of all three is zero or positive, so a template can be turned up or switched off but never subtracted.
V the data, a magnitude spectrogram, M frequency bins by N frames.W the templates, one column per sound, each a spectrum; M by K.H the activations, one row per template, how loud it is in each frame; K by N.K the rank, the number of templates, much smaller than M and N, which forces sharing; 2 in Figure 2.≥ 0 the only assumption NMF makes, with no statistics about the sources (Anushiravani 2016, p. 43, the audio-editing thesis Section 7 follows); it is what makes the templates read as parts (Section 2).

W and H are unknown; Section 3 scores a guess.

2 Why non-negative gives parts

With no subtraction allowed, blocks cannot cancel each other, so each block must look like a real piece of the data (Lee and Seung 1999). PCA is computed with the SVD, whose blocks may be negative. Figure 3 takes the SVD of V as it is, without PCA's subtraction of each bin's mean. Vector quantization goes the other way; like k-means, each frame takes exactly one block, winner takes all. NMF sits between, a few blocks per frame that only add.

SVD blocksNMF blocks2.4491.2251.2252.449block 11.4140.707−0.707−1.414block 22100note 10012note 2high note =0.408 × block 1− 0.707 × block 2high note =1 × note 2
Figure 3. The same V split into blocks by the uncentred SVD and by NMF.

Both fits are exact with 2 blocks, but the SVD builds the high note from block 1 minus block 2, a low-minus-high contrast, while NMF's blocks are the two notes themselves.

3 Squared error and KL divergence

Before W and H are known, start from a rough guess, two templates that each lean toward one note, with every activation 1. Each cell of the rebuild is then 1.5, one template giving 1 and the other 0.5, and the two costs below score how far that is from V.

Start guessValue, low bin to high
Template 1 in W1, 1, 0.5, 0.5
Template 2 in W0.5, 0.5, 1, 1
Every activation in H1
Rebuild WH1.5 in every cell

The start guess, scored here and updated in Section 4.

squared error0.252.250.250.252.250.252.250.250.252.250.250.2512total 11.0KL0.0751.50.0750.0951.50.0951.50.0950.0951.50.0750.07512total 6.68
Figure 4. Illustrative cost per cell of the start guess; 1 loud, 2 quiet.
Both count how far the rebuilt spectrogram is from the real one, cell by cell. Squared error punishes big misses most, wherever they are. KL compares ratios, so a quiet bin that is off by a factor counts too, which suits audio magnitudes; the thesis uses KL (eq 4.25, p. 44).
SE = Σij (Vij − (WH)ij)2
Cells 1 and 2 both miss by 0.5 and both cost 0.25; the cells where V is 0 miss by 1.5 and cost 2.25, for a total of 11.0.
KL = Σij [ Vij log Vij(WH)ij − Vij + (WH)ij ]
The loud cell 1 costs 0.075 and the quiet cell 2 costs 0.095, since the same miss is a bigger ratio when the cell is quiet. The total is 6.68, on a different scale from 11.0, so the two totals are never compared.
Σij adds over every cell, every bin i and frame j; on this page Σ is always a sum.(WH)ij the rebuilt value in bin i, frame j.(Vij − (WH)ij)2 the miss in one cell, squared.V log(V over WH) the ratio miss, 0 when rebuilt equals real; a cell with V = 0 adds nothing here, since 0 log 0 counts as 0. log is the natural log, so the cost is in nats, the unit of the natural log, as bits are the unit of log base 2.SE the squared error.KL, in full KL(V ‖ WH), read aloud as the KL divergence of V from the rebuild WH.− V + WH keeps the cost at 0 for a perfect fit and above 0 otherwise, even when the totals of V and WH differ. This is the generalized KL divergence. The KL Divergence page compares lists of chances that each sum to 1, and here the totals need not match.Each cost is 0 only when V = WH, so lowering either drives the rebuild toward the data.

Section 4 lowers these costs while keeping every entry non-negative.

4 Multiplicative updates

Each update multiplies every entry by a ratio, what the data asks for over what the model already gives. From the start guess of Section 3, one update of H under squared error runs like this; WT is W turned on its side, its transpose.

QuantityValue
WTV, the data side3, 1.5, 4.51.5, 3, 4.5
WTWH, the model side4.5 in every cell
Half the gradient, model side minus data side1.5, 3, 03, 1.5, 0
New H, H minus that row times H over 4.50.667, 0.333, 10.333, 0.667, 1
Squared error11.0, then 5.56 after H, 3.68 after W

The first update of H from the start guess, under squared error.

Deriving the gradient row from the squared error of Section 3 shows why this step size turns a gradient step into a multiplication.

Nudging one activation changes its frame's rebuild by that template, so its gradient adds up the frame's misses weighted by the template. Taking a step against it, with a step size chosen per entry, gives a ratio.
∂SE∂H = 2 WT(WH − V)
Here a miss is rebuild minus data, the opposite sign from the miss of Section 3. For template 1 in frame 1 the misses are 1.5 minus (2, 1, 0, 0), or −0.5, 0.5, 1.5, 1.5 from low bin to high. Weighted by template 1, which is 1, 1, 0.5, 0.5, they add up to 1.5, so this gradient entry is 2 times 1.5, or 3.
G = WTWH − WTV
Opening the bracket and halving gives G, model side minus data side from the first two table rows; it is the third row, which starts with that 1.5.
H ← H − η ⊙ G
A gradient descent step on half the gradient, with its own learning rate for every entry of H.
η = HWTWH
At the start every learning rate is 1 over 4.5, so the first entry becomes 1 minus 1.5 over 4.5, which is 0.667, the New H row. With this choice the model side cancels, and what is left is H times data side over model side, the first line of the card in Figure 5.
∂SE∂H the gradient, how fast SE changes as each entry of H is nudged.WT(WH − V) each cell's miss passed back through the templates; the 2 comes from the square.G half the gradient.η the learning rate, here a separate one for each entry of H.⊙ entry-by-entry product.

Figure 5. Steps 0 to 3 are one fit; step 4 is a separate stuck run.

Each entry is multiplied by a ratio, what the data pulls toward over what the current model already gives. If the rebuild is too small, the ratio is above 1 and the entry grows; if it is too big, the ratio is below 1 and the entry shrinks; at a perfect fit the ratio is 1 and the entry stays. Positive times positive stays positive, so no clipping is needed.
H ← H ⊙ WTVWTWH
From the start every ratio is the data side over 4.5, so H becomes the New H row of the table and the error falls from 11.0 to 5.56.
W ← W ⊙ VHTWHHT
The same comparison from the activations' side updates the templates, and the error falls to 3.68. From this start, alternating the two lines 500 times brings it to about 0 (step 3).
WTV how strongly each template matches each frame of the data.WTWH the same match measured on the current rebuild.⊙ and the fraction bar work entry by entry.VHT and WHHT the data and the rebuild, matched against each activation row.
The same ratio idea for the KL cost of Section 3, the form the thesis uses (eq 4.26).
H ← H ⊙ WT VWHWT 1
Each cell's ratio of data to rebuild is passed back through the templates and divided by how much each template is used; from the same start guess it gives the same new H as the table.
W ← W ⊙ VWH HT1 HT
The same from the activations' side, divided by how much each activation row is used.
V over WH the cell-by-cell ratio of data to rebuild, 1 wherever the fit is perfect.1 a matrix of ones the size of V, so WT 1 and 1 HT add up how much each template and each activation is used.

Each KL line is also a gradient step with a step size per entry, chosen as in the gradient card so that the step becomes a ratio. The authors prove the cost never goes up and state that it stops changing at a stationary point, where the gradient is zero so the update no longer moves (the same authors, 2001, Theorems 1 and 2). An entry stuck at 0 also stops changing, and a global minimum is not guaranteed, as the separate run in step 4 of Figure 5 shows. Alternating the two lines of either card is the whole algorithm.

Section 5 chooses how many templates to fit.

5 Choosing the rank

Too few templates blur sounds together; too many split one sound or copy noise. On the two-note example, rank 1 leaves a squared error of 5.0, and ranks 2 and 3 bring it to about 0. In its two-burst example the thesis assumes the number of sources is known, and points to a way to estimate it (p. 45).

Take an illustrative recording with three sounds, a steady hum that stops partway, speech-band bursts like syllables, and a keyboard click every 12 frames. A fit starts from random positive templates and activations, scaled to the data's loudness and fixed so every visit shows the same fit. One round is steps 1 and 2 of Figure 5, the H line and then the W line, and no round can raise the error.

Rank

round 300, squared error about 0

Figure 6. 1 Rounds find sounds; 2 too few share, too many split.

At rank 3 each sound gets its own template; the click template dips at the speech bins and the speech template fills that dip back in. At rank 2 the hum and the click share one template, so the clicks come back faint; at rank 4 the hum splits across two blue templates and the error does not drop further. Rank 1 settles by round 3 at a squared error of about 30, since one template can only average the three sounds.

6 NMF in code

x is any mono recording. This is the unsupervised version, one fit on one recording with no templates learned beforehand. Passing V with frequency bins as rows makes scikit-learn's W the templates and H the activations, the names on this page; scikit-learn's own docs warn that the literature often swaps them.

import numpy as np
import scipy.signal as ss
import sklearn.decomposition as sd

_, _, Z = ss.stft(x, nperseg=512)
V = np.abs(Z)

nmf = sd.NMF(3, solver="mu")
nmf.set_params(beta_loss=1)
W = nmf.fit_transform(V)
H = nmf.components_
  1. 1The complex STFT Z and its magnitude V, the matrix of Section 1.
  2. 2Rank 3 with multiplicative updates; beta_loss=1 is the KL cost of Section 3 and needs solver="mu". The default start here is "nndsvda", built from the SVD with its zero entries filled by the data average, so it is the same on every run.
  3. 3Fits the model of Section 1; W is 257 bins by 3 and H is 3 by the number of frames.

The next block runs the squared-error updates of Section 4 on the two-note spectrogram of Figure 2.

import numpy as np
Wt = np.c_[[2,1,0,0], [0,0,1,2]]
V = Wt @ [[1, 0, 1], [0, 1, 1]]
rng = np.random.default_rng(0)
W = rng.random((4, 2)) + 0.1
H = rng.random((2, 3)) + 0.1
e = 1e-9
for _ in range(200):
    H *= W.T@V / (W.T@W@H + e)
    W *= V@H.T / (W@H@H.T + e)
  1. 1Builds V from the two notes and their activations, as in Figure 2.
  2. 2A random positive start; + 0.1 keeps every entry above 0, since a 0 never changes under multiplication (Section 8).
  3. 3The guard e, which avoids dividing by 0, the loop and the activation update.
  4. 4The template update.

It returns the two notes up to scale, so each template can come back multiplied by some number, with its activation row divided by the same number.

7 NMF for audio

Separation with fixed templates comes first, then the way back to sound with the mixture phase, templates that last several frames, and the thesis's room matching.

7.1 Separating sounds with learned templates

Learn speech templates from clean speech and noise templates from noise alone. On a noisy recording, keep both sets fixed and fit only the activations; the speech templates times their activations rebuild the speech (the thesis, section 4.7.1, eqs 4.27 to 4.29).

cleanspeechW speechnoisealoneW noisenoisyrecordingfit H, both W fixedmask7.2times themix STFTinverseSTFT
Figure 7. Supervised separation, from templates to cleaned waveform.

7.2 Reusing the mixture phase

Each STFT cell is a complex number. Its size is the loudness kept in V, its angle says where the wave is in its cycle, and NMF throws the angle away. Say NMF rebuilds one noisy cell as speech 3 plus noise 1.

60°312size 3.75, angle 60°mask 0.75, 3 of 4size 5speech magnitude alone, 3
Figure 8. Illustrative. 1 noisy cell, 2 cleaned cell, 3 their shared angle.

Speech 3 plus noise 1 rebuild a size of 4, while the real cell has size 5. Using the speech magnitude 3 directly would ignore that miss; dividing by the rebuild and scaling the real cell corrects the size and borrows the angle (the thesis notes this compensates for “misestimation in the magnitude spectrogram”, p. 49).

Keep the speech share of every cell, take the angle from the recording itself, and go back to a waveform (thesis eqs 4.29 and 4.34). The shares come from the model of Section 1, split into speech and noise templates.
Ŝ = Ws HsW H ⊙ Y
In Figure 8 the speech share is 3 over 4, or 0.75, so the cleaned cell is 0.75 times the noisy cell, size 3.75 at the same 60 degrees.
ŝ = inverse STFT of Ŝ
Every cleaned cell, size from the share and angle from the mix, goes back to a waveform.
Ws Hs the rebuild from the speech templates only (eq 4.29).W H the rebuild from all templates, speech and noise, with H fitted by the KL H line of Section 4 while both sets of templates stay fixed (eq 4.28).Their ratio a mask between 0 and 1 per cell, the same idea as the Wiener gain.Y the complex STFT of the recording; multiplying by it reuses the mixture phase, as spectral subtraction does (eq 4.34).ŝ the separated waveform, rebuilt by overlap-add.

Continuing the first block of Section 6, the next block keeps template k's share of every cell, puts it on the complex Z and inverts. Section 7.1's supervised version fixes W before fitting; this one just picks a template.

k = 0
Vk = np.outer(W[:, k], H[k])
mask = Vk / (W @ H + 1e-9)
Sk = mask * Z
_, xk = ss.istft(Sk, nperseg=512)
  1. 1Rebuilds template k's part and divides by the full rebuild, the mask of the first card line.
  2. 2Applies the mask to the complex Z, so the mixture phase is kept, and inverts, the second card line.

Plain NMF treats every frame alone. Sounds and rooms have time patterns, so Section 7.3 lets templates last several frames.

7.3 Convolutive NMF

A sound is a short movie, not one spectrum. In convolutive NMF (Smaragdis 2004) each template lasts a few frames and slides along time, the same sliding weighted sum as an FIR filter.

H12345frameV2102101001template210101its framelow bin at the bottom
Figure 9. Illustrative 2-frame template played by the spikes of H.

Plain NMF would need two separate templates, (2, 0) and (1, 1), and would lose the fact that one always follows the other.

A template becomes a short movie that slides along time, each of its frames played one step later than the one before.
V ≈ Σt=0T−1 W(t) shiftt(H)
In Figure 9 T = 2. W(0) times H puts 2 in the low bin at frames 1 and 4; W(1) times H shifted one frame adds 1 to both bins at frames 2 and 5, which gives V.
Σ over t adds the T shifted copies, one per template frame.W(t) frame t of every template, with T the template length in frames; T = 1 gives back plain NMF (Smaragdis 2004, eq 4; thesis eq 5.26, p. 69).shiftt(H) H moved t frames to the right with zeros filled in on the left, so each spike plays the whole template.

Learned from clean speech, such templates also serve the supervised separation of Section 7.1 (Smaragdis 2007).

7.4 Dereverberation and room matching

The thesis's goal is example-based editing, making a recording sound drier or making it sound like the room of an example recording. A room smears each sound with a decaying tail of echoes, the dry sound convolved with the room's response. In the thesis model speech is still built from the same dry templates, and each template's activation row is convolved with its own decaying tail.

dry, Hd400200room tail R10.50.25smeared421210.5drier, R2wetter, R0.5123456
Figure 10. Illustrative dry row smeared by tail R, then drier with R2, wetter with R0.5.
The convolutive card of Section 7.3 put a time pattern inside the templates; here the room's tail sits on the activations instead. Pulling that tail out gives a knob for how much room you hear, or lets you swap in the tail of an example recording's room.
Y ≈ Wd (Hd ∗ R)
In Figure 10 the dry row (4, 0, 0, 2) convolved with R = (1, 0.5, 0.25) is (4, 2, 1, 2, 1, 0.5), and the dry template Wd plays that smeared row.
R(t) = eλt
Figure 10's tail (1, 0.5, 0.25) halves each frame, an illustrative decay; the fit starts each kernel as this curve instead (eq 5.33, p. 72). With λ = −1 the values at frames 1, 2 and 3 are 0.37, 0.14 and 0.05; λ = −0.9 dies away a little slower and −1.5 faster.
Rnew = Rβ
With R scaled to peak 1, β = 2 gives (1, 0.25, 0.0625), a shorter tail and a drier sound, and β = 0.5 gives (1, 0.707, 0.5), a longer tail.
Y the reverberant spectrogram; Wd the dry speech templates, learned once from clean speech.Hd ∗ R each dry activation row convolved (∗) with its own decaying kernel (thesis eq 5.29, p. 71); with no kernel it is the model of Section 1.t the frame within the kernel, counted from 1; λ a negative decay factor set per frequency band, between −1.5 and −0.9 in the thesis.At each iteration the thesis raises the kernel entries to a power between 0.8 and 0.9, which it describes as enforcing sparsity on the kernel (eq 5.34). The dry templates were learned with the activations raised to a power between 0.9 and 0.98 each iteration, which it describes as sparsifying them (eq 5.31).β above 1 shortens the tail and below 1 lengthens it. For room matching the thesis fits β per component so that Rβ matches the example recording's kernel under KL, with β between 0.5 and 2 (eqs 5.36 and 5.37, p. 74).The reverberant recording's phase is reused (eq 5.39), so some old reverb can survive (Section 8).

The thesis learned the speech templates once offline (25 templates, 500 iterations), then decomposed each 10-second recording (section 5.13). Plain NMF and its mask undo a blend of parts in one recording, and convolutive NMF extends that to blends over time, the counterpart of the blend across sensors that Independent Component Analysis undoes.

8 NMF in practice

The table lists the settings that matter in scikit-learn 1.9.1 and in the thesis, what each one does, and its default.

SettingRaise itLower itExtremesDefault
n_components, the rank Kfiner parts and lower error; past the true number, sounds split or noise gets a templatesounds merge into shared templates (Figure 6)a rank as large as the smaller side of V rebuilds it exactly and teaches nothing"auto", taken from W or H when given; the thesis used 25 speech templates (p. 76)
max_iterlower cost, slowerunconverged, blurry templatesmultiplicative updates slow down near the end200; 500 in the thesis (p. 76)
initA choice, not a scale. "nndsvda" is the SVD-based start of Section 6; "random" depends on the seed.identical columns never separate (stuck at 5.0, step 4 of Figure 5)None, meaning "nndsvda" when n_components is at most the smaller side of the data
beta_loss, not the kernel exponent βA choice, not a scale. "frobenius" or 2 is squared error; "kullback-leibler" or 1 is the KL cost and needs solver="mu".a choice; no extreme"frobenius"; KL in the thesis (eq 4.25)
alpha_W, alpha_H, l1_ratiosparser, more part-like templates or activations; too high zeros things outplain NMF0 turns the penalty off0, "same", 0
Thesis sparsity powers on the activations and the kernel (Section 7.4)nearer 1, a weaker pusha stronger push, which the thesis describes as sparsera power of 1 turns the push offactivations 0.9 to 0.98, kernel 0.8 to 0.9, applied each iteration (p. 72)
Size of the starting decay factor λ (thesis, Section 7.4)toward 1.5, the starting kernel dies away fastertoward 0.9, the starting kernel dies away slowernot given in the thesisλ between −1.5 and −0.9 per frequency band (eq 5.33, p. 72)
Kernel length (thesis)longer room tails can be captured, with more unknownstail cut short, leftover reverbtoo short cannot hold a hall45, 65 and 85 frames for a bedroom, a conference room and a living room (p. 76)
Kernel exponent β (thesis)shorter tail, drier soundlonger tail, more reverb1 leaves the room unchangedfitted per component between 0.5 and 2 (eq 5.36, p. 74)
CauseSymptomFix
identical starting templatesstuck at a rank 1 answer, error 5.0 in the two-note examplea random or "nndsvda" start
a zero entry in W or Hit stays zero forever under multiplicationstart every entry above 0, as + 0.1 does in the second block of Section 6
wrong ranktoo low merges sounds, too high splits them or models noisecompare a few ranks on held-out audio and listen
the reused mixture phasetraces of the original after separation or dereverberation; “some traces of the original reverberation can often persist” (Anushiravani and Smaragdis)accept it or use a phase-aware method

Common NMF failures, what they look like and the fix.

Feed NMF a magnitude STFT, as the thesis does, not power; power squares every cell, so the loudest bins would rule the fit even more. Scale the templates to peak 1 before comparing runs, since a template and its activation row can trade any scale. The cost should fall fast and then flatten; a curve still falling at max_iter needs more iterations, and a curve flat at a high value points to a bad start or too low a rank.

Next in the menu is t-SNE, which maps data to two dimensions for plotting rather than splitting it into parts.

9 References

  1. Anushiravani, R. (2016). “Example-based audio editing”. M.S. thesis, UIUC. hdl.handle.net/2142/95331. Sections 4.7 and 4.8 (NMF, KL cost and updates, supervised separation, mask and phase) and 5.10 to 5.13 (convolutive NMF, the room model and its settings) are the sources of Section 7 and the thesis rows of Section 8; it writes the KL cost as D(V‖W, H), eq 4.25.
  2. Anushiravani, R., and Smaragdis, P. “Seamless Acoustics Matching of Disparate Recordings”. Manuscript, undated. PDF. The source of the phase quote in Section 8.
  3. Lee, D. D., and Seung, H. S. (1999). Learning the parts of objects by non-negative matrix factorization. Nature 401, 788-791. doi:10.1038/44565. Parts from adding only, against PCA and vector quantization (Section 2).
  4. Lee, D. D., and Seung, H. S. (2001). Algorithms for non-negative matrix factorization. Advances in Neural Information Processing Systems 13. proceedings.neurips.cc. Both costs (eqs 2 and 3), both update pairs (eqs 4 and 5) and Theorems 1 and 2 (Section 3 and Section 4).
  5. Smaragdis, P. (2004). Non-negative matrix factor deconvolution; extraction of multiple sound sources from monophonic inputs. ICA 2004, LNCS 3195, 494-499. MERL TR2004-104. Convolutive NMF, eq 4 (Section 7.3).
  6. Smaragdis, P. (2007). Convolutive speech bases and their application to supervised speech separation. IEEE Transactions on Audio, Speech, and Language Processing 15(1), 1-12. MERL TR2007-002. Convolutive templates for supervised separation (Section 7.3).