A sound is a grid of energies that are never below zero. Split it into parts that can only add, never subtract, and a mix of two notes and a drum falls apart into two notes and a drum.
Learn how one grid of numbers becomes a few readable parts and a recipe for mixing them, and why the same idea connects to neural networks and to k-means.
Choose PCA, then NMF, and drag the number of parts to 3. Watch what each method hands back for the same sound. Then we build, piece by piece, the factorization, its tricks, and where it leads.
You need matrix multiplication (rows times columns, added up) and the idea of a minimum (the lowest point of a curve). We build the rest from zero.
Based on the nonnegative matrix factorization lecture of Stanford EE269: Signal Processing for Machine Learning, taught by Mert Pilanci. Lecture slides (PDF). Every idea is re-taught here in our own words and devices.
Toy sound, made here: 12 frequency bins by 24 time frames, the sum of a note (A), a second note (B) and a drum, plus a little seeded noise. Blue cells are the sound, warm bars are a part’s template, purple lines show when it is active, red marks a negative number. PCA here is the truncated SVD of the grid, with no centring. Both methods are computed live in your browser.
Chapter 0
See why a grid that can never go below zero wants to be split into parts that only add
You record a short clip: one note on a guitar, a second note on a flute, and a hand tapping a drum. Then you turn the clip into a picture. The picture is a grid. Each row is a pitch, from low to high. Each column is a moment in time. Each cell is bright where that pitch is loud at that moment.
This grid is a spectrogram. It is the output of the short-time Fourier transform, which cuts the clip into slices and measures the loudness of every pitch in each slice. Our STFT lesson builds it from zero. Here you only need one fact: every cell holds an energy, and an energy is never below zero. A pitch cannot be less than silent.
Now ask the question this whole lesson answers. Can a computer look at the grid and hand back the three things you hear? That means the shape of note A, the shape of note B, the shape of the drum, and the moments when each one plays.
Sound energy is one example. A photo is another: each pixel is a brightness, and the darkest possible pixel is zero. A table of word counts is a third: a document uses a word 0, 1 or 7 times, never minus 2 times. The lecture lists the same trio: pixel values, energies and counts.
We call such a grid a data matrix and write it X. The lecture gives X the size n × d: n rows and d columns. In our sound, n is 12 pitch bins and d is 24 time frames. A cell of X sits at row i and column j, and we write it Xij.
The usual tool for finding structure in a grid is PCA, principal component analysis. It finds a few basis vectors: patterns such that every column of the grid is close to a weighted sum of them. The first pattern captures the most variation, the second captures the most of what is left, and so on. Fisher’s discriminant (our Fisher lesson) picks its patterns to separate classes instead.
Nothing in either method forces a pattern to stay at or above zero. A PCA pattern is a list of numbers, and some of them are almost always negative. The lecture shows the result on faces. The basis images that PCA and Fisher learn look like ghostly faces with bright zones and dark zones. Its one-line verdict: these basis vectors are hard to interpret.
Why are they hard? A negative number in a pattern means subtract this much. To rebuild a face, the recipe says: add a lot of this ghost, then take some of that ghost away. For sound, it says: add this pattern, then remove some sound. Nobody can point at the result and say “that is a flute”. It is an anti-sound, a pattern that only makes sense in a sum with others.
Think of building with bricks. A recipe that says “take two red bricks and three flat bricks” is easy to follow, and each brick is a real thing. A recipe that also says “remove one brick from the wall” forces you to look at the whole wall to know what you did.
Nonnegative matrix factorization, or NMF, takes the brick rule seriously. It writes the grid as a sum of parts. It forbids two things at once. A part may not have a negative cell, and a recipe may not have a negative weight. Everything adds. Nothing cancels. Each part is then a thing you can look at, like a note or an eyebrow.
Try it on the smallest picture that shows the idea. A tiny 6 × 6 image is always a horizontal bar, a vertical bar, or both at different strengths. Pick a picture, and read what recipe each method gives.
The top row builds the picture from NMF parts. The bottom row builds it from PCA directions. Blue is a positive cell, red is a negative cell. Pick a picture and compare the weights.
Toy data: 30 six-by-six pictures, each a random strength of a horizontal bar plus a random strength of a vertical bar, seeded so they are the same on every visit. NMF and PCA (truncated SVD, no centring) each learn two basis images from all 30, live in your browser. Both rebuild every picture exactly, since the data has only two parts.
Look at the top row. The two parts are the two bars. Every picture is some amount of one bar plus some amount of the other. Both weights are zero or more. Now look at the bottom row. The first direction is a blend of both bars, and the second direction has a bright vertical bar and a red horizontal bar. To make a picture that is mostly horizontal, PCA must subtract the vertical bar it just added.
Both rows are correct. Both rebuild the picture exactly. The top row is the one a person can read.
The lecture states the whole problem in one line. Given the data matrix X of size n × d, find two matrices W and Z. Every number in both must be at or above zero. Make W times Z as close to X as possible.
The number k is how many parts you ask for. You choose it. The hero at the top of the page lets you try 1 to 4. The next chapters take this one line apart: what the product means, why it has no tidy answer, how to find a good pair anyway, and where the idea leads.
Chapter 1
Read a matrix product two ways, count what it saves, and learn what the error number means
Picture a mixing desk with three faders. Each fader controls one instrument. At every instant you set the three levels, and the speaker plays the sum. Record the output for 24 instants and you have a grid with 24 columns. Each column is one instant of sound.
Matrix factorization says the grid came from such a desk. The instruments are the columns of W. The fader positions over time are the rows of Z. The product of the two is the sound.
Take one instant, one column of X. Call it xj. It holds 12 numbers, one per pitch. The factorization says this column is a weighted sum of the columns of W. The weights come from column j of Z.
Here is a tiny case with every number shown. Let W have 3 rows and 2 columns, and Z have 2 rows and 4 columns. Row 1 of Z is the fader for part 1, row 2 is the fader for part 2.
W =
| 2 | 0 |
| 1 | 1 |
| 0 | 3 |
| 1 | 0 | 2 | 1 |
| 0 | 1 | 1 | 2 |
Take column 3 of Z, which is (2, 1). Column 3 of the product is 2 times column 1 of W plus 1 times column 2 of W. That is 2 × (2, 1, 0) + 1 × (0, 1, 3) = (4, 2, 0) + (0, 1, 3) = (4, 3, 3). Doing all four columns gives the full product:
WZ =
| 2 | 0 | 4 | 2 |
| 1 | 1 | 3 | 3 |
| 0 | 3 | 3 | 6 |
Read one cell instead of one column. Cell (row 2, column 3) of the product is W21 × Z13 + W22 × Z23 = 1 × 2 + 1 × 1 = 3. That is the entry you see in the full product above. Every cell of X is a short sum of k products, and each product is one part’s contribution at that pitch and that moment.
Now the data flow. The input of NMF is one grid X of size n × d, and a choice of k. The output is two grids, W of size n × k and Z of size k × d. Nothing else is stored. The algorithm’s only job is to move the numbers inside W and Z until the product matches X.
There is a second way to read it, and it is the one that explains the word parts. Take part i alone: column i of W times row i of Z. A column times a row gives a full grid. That grid is one layer: the sound that part i contributes by itself. The product is all the layers added.
Try it with the three parts of our toy sound. Switch layers off and watch what the rebuild loses.
Top left: the sound. Top right: the rebuild from the parts you keep. Bottom: each part’s own layer. Switch a part off and see which part of the sound goes missing.
Toy sound from the hero, factored live by NMF with 3 parts. Parts are named by whichever of the toy sound’s three true sources their template matches best. Error is the relative Frobenius error, the square root of the squared error divided by the squared size of the sound.
Check what the factorization found. The toy sound was built from a note A whose overtones have strengths 1, 0.7, 0.45 and 0.3 at 220, 440, 660 and 880 Hz. NMF was never told this. Its first template, scaled to a maximum of 1, reads 1.00, 0.71, 0.46 and 0.31 at those four pitches, and almost zero everywhere else. It found the comb from the grid alone. The matching row of Z is high for the first nine frames and then drops to zero, which is when note A plays.
Each layer has a single pattern: the template stretched along time by the fader. A note that plays for nine frames makes a layer of nine bright columns. A drum that taps five times makes five thin bright columns. Remove a layer and exactly that pattern vanishes from the rebuild.
How close is the rebuild to the sound? The lecture uses the squared Frobenius norm. Subtract the rebuild from the sound, cell by cell. Square each difference. Add all the squares. That one number is the squared error.
Use the tiny case. Keep only part 1. Its layer is (2, 1, 0) times (1, 0, 2, 1), which is rows (2, 0, 4, 2), (1, 0, 2, 1) and (0, 0, 0, 0). The sound has rows (2, 0, 4, 2), (1, 1, 3, 3) and (0, 3, 3, 6). The differences are zero in row 1, then (0, 1, 1, 2) in row 2, then (0, 3, 3, 6) in row 3.
1² + 1² + 2² + 3² + 3² + 6² = 1 + 1 + 4 + 9 + 9 + 36 = 60
The sound itself has squared size 24 + 20 + 54 = 98. So the rebuild misses a share of 60 / 98 = 0.61 of the squared size. Take the square root and the relative error is 0.78, or 78%. The devices on this page quote this relative error, since a percentage is easier to feel than a squared sum.
Why square? Squaring makes every miss positive, so misses cannot cancel. It also punishes one large miss more than several small ones. It is also the natural ruler when the leftover noise is bell-shaped. Other rulers exist, such as a divergence made for counts, but this lecture uses the squared Frobenius norm.
The grid has n × d numbers. The factorization stores n × k for W and k × d for Z. For the toy sound that is 12 × 24 = 288 numbers against 12 × 3 + 3 × 24 = 108. For a real song with 1,000 pitch bins, 5,000 frames and 10 parts, it is 5,000,000 numbers against 60,000. The product is a compression, and the parts are the reason it works: a few patterns repeat many times.
Here are real sizes. Take a 10 second clip sampled 16,000 times a second, which is 160,000 samples. Cut it into slices of 1,024 samples that move forward by 256 samples each time. These are common choices, not the lecture’s. The STFT gives 513 pitch bins and about 620 frames, so X is 513 × 620, about 318,000 cells. Ask for k = 10 parts. Then W is 513 × 10 and Z is 10 × 620, which is 5,130 + 6,200 = 11,330 numbers, about 3.6% of the grid.
How do you choose k? Ask for more parts and the error falls. At some point it stops falling much. That bend in the curve tells you how many real parts the data has. Move the slider and look for the bend.
The warm line is NMF and the blue line is PCA, for 1 to 6 parts. Drag the slider to see each method’s error at that many parts.
Toy sound from the hero, which has three sources. NMF is fitted live with 600 multiplicative updates per point; PCA is the truncated SVD, the best possible fit with no sign rule, so it can never sit above NMF.
Think of k as a budget. Each part you allow costs n + d numbers, and it buys one repeating pattern. If the data repeats three patterns, three parts are enough and the fourth is wasted. If it repeats ten, three parts must squeeze ten patterns into three and some will blur together.
Two failures are worth naming. If k is too small, parts merge: two sources share one template and the error stays high, 15.4% at 2 parts here. If k is too large, parts split: one source is spread over two templates and the extra part adds almost nothing. Both show up as the error curve, which is why you plot it first.
Chapter 2
See two facts the lecture warns about: no closed form, and a solution that is never unique
Two engineers factor the same recording. Both get a tiny error. Both get three parts. But their templates look different, and one engineer’s drum is the other engineer’s part 2. Who is right?
Both are. The slide says so in two bullets: no closed form solution, and the solution is not unique. This chapter explains each one, shows what it costs, and shows the fix.
Some problems have a recipe that gives the answer in a fixed number of steps. For PCA, you compute the eigenvectors of one matrix and keep the biggest ones. Our linear systems lesson and the PCA material before it work this way. You run the recipe once, and the answer is the best one possible.
The theorem behind that recipe carries two names, Eckart and Young. It says that keeping the top k pieces of the singular value decomposition gives the best rank-k fit in squared Frobenius error. It is a statement about a problem with no sign rule, which is why it does not carry over to NMF.
NMF has no such recipe. The sign rule makes the problem harder. The best pair (W, Z) must sit in a region where every cell is at or above zero, and no formula lands on its corner. You can only search: start from a guess and improve it step by step. The next chapter shows how.
Now the second bullet. Here is the lecture’s line, in full: X = W D D−1 Z = (W D)(D−1 Z). The matrix D is a diagonal matrix: it has numbers on its diagonal and zeros elsewhere. Multiplying W by D scales each column of W. Multiplying Z by D−1 undoes that, scaling each row of Z by the inverse.
Check it with the tiny example from Chapter 1. Pick D with 1/2 for part 1 and 2 for part 2. Then W D has columns (1, 0.5, 0) and (0, 2, 6). And D−1 Z has rows 2 × (1, 0, 2, 1) = (2, 0, 4, 2) and 0.5 × (0, 1, 1, 2) = (0, 0.5, 0.5, 1). Row 2 of the product is 0.5 × (2, 0, 4, 2) + 2 × (0, 0.5, 0.5, 1) = (1, 0, 2, 1) + (0, 1, 1, 2) = (1, 1, 3, 3). That is row 2 of X again. Every other row matches too.
Put it in your own hands. Slide the scale of part 1 and watch the template grow while the fader shrinks.
Part 1 of the toy sound. Drag the scale D. The template is multiplied by D and the activation by 1 / D. The axes stay fixed so you can see the heights move.
Part 1 of a live NMF fit with 3 parts. The axes are fixed: template to 4, activation to 10. The rebuild is recomputed from the scaled factors, not assumed, and compared with the original rebuild cell by cell.
The template can be as loud as you like, as long as the fader is as quiet as the template is loud. The product, and therefore the error, never moves. The slide uses this fact to warn you: the numbers inside W and Z do not mean anything in absolute size. Only the shape of a part and the pattern of its fader mean something.
The fix is a convention. Scale every column of W so its largest value is 1, and push the scale into the matching row of Z. This page does it for every device. You can also scale each column to add up to 1. Any one rule is fine, as long as you apply it every time.
The same trick works with a swap: put part 2 first and part 1 second, and the product is unchanged. Scales and swaps are the harmless kinds of non-uniqueness. A matrix D that keeps both D and its inverse non-negative can only be a scale and a swap together.
There is one more cost. Picture the error as a landscape, where every position is a choice of (W, Z) and the height is the error. PCA’s problem is a single bowl: from anywhere, a ball rolls to the same bottom. The word for that is convex.
NMF’s landscape is non-convex. It has several dips. A ball dropped at a random start can come to rest in a shallow dip, a local minimum, while a much lower dip sits next door. The problem is convex in W alone if Z is held fixed, and convex in Z alone if W is held fixed. It is not convex in both together.
Two numbers show both problems at once. Suppose the data is the single number 4, and we factor it as w × z. The pairs (1, 4), (2, 2) and (4, 1) all give error 0. There are infinitely many perfect answers, which is the non-uniqueness. Now average the two perfect pairs (1, 4) and (4, 1). The midpoint is (2.5, 2.5), and 2.5 × 2.5 = 6.25, which misses 4 by 2.25. The squared error is 5.06. Two perfect answers have a poor midpoint, so the landscape is not a single bowl.
Here is the symptom, the measurement and the fix. The symptom: the same data and the same k give a different answer each time you run the search. The measurement: print the final error of each run. The fix: start from several random points and keep the run with the lowest error. Try it on a set of 40 small faces, each made of up to five parts.
Press the button. Each bar is one run of NMF with 5 parts from a different random start. Tap a bar to see the five templates that run found.
Toy data: 40 ten-by-ten faces. Each face switches on each of five parts (brow, left eye, right eye, nose, mouth) with probability 0.6 and a random brightness. Every run uses 800 multiplicative updates, computed live in your browser from seeds 1 to 6.
Five of the six starts end near 0.2% error and find the five parts. One start settles at 13.4%: it found a worse dip, and three of its five templates each blend two features, such as brow and mouth. If you had run only that start, you would have blamed the method. The error number is what tells you.
Why do restarts help? Each start is an independent draw. Suppose one start in six gets stuck, as in this run. Then the chance that all six get stuck is (1/6)6, about 2 in 100,000. That figure is an illustration of the rate, not a measured law, but it shows why a handful of starts is usually enough.
You may have noticed a related effect in Chapter 0. Both NMF bars carried a faint trace of the other bar, about 0.1. The data is exactly built from two bars, yet several non-negative pairs rebuild it with no error at all. Scale and order are the harmless kinds of freedom. Faint leaks like this are another kind, and they come from the data, not from a bug.
In practice this means you should compare runs only after fixing the scale rule, and after putting the parts in a fixed order, for example by the time at which each activation peaks. This page does both before it draws anything.
Chapter 3
Work the lecture’s heuristic by hand, then watch it race a classic rival on a real grid
You are tuning two knobs at once in a dark room, and you cannot see the whole landscape. A sensible trick is to fix the left knob and find the best right-hand setting. Then fix the right knob and find the best left-hand setting. Then go back to the first. Each step is easy. Together they walk downhill.
That is the lecture’s heuristic. The two knobs are W and Z. The slide writes it as four lines that repeat.
A least-squares problem asks: which W makes WZ closest to X? When Z has independent rows, the answer has a neat form. The pseudoinverse of Z is Z† = ZT(ZZT)−1. Then W = XZ† is the best fit, and no other W does better. It is the same recipe as fitting a line to dots, done for every row of X at once.
Run one full round by hand on a tiny grid. Let X have rows (4, 2, 0) and (2, 2, 2). Ask for one part, so Z is one row. Start with Z = (1, 1, 1). The sum of squares of X is 16 + 4 + 0 + 4 + 4 + 4 = 32.
No clip was needed, since every number stayed positive. Each half step either lowered the error or left it alone, because each one is the exact minimum over one matrix.
Each pseudoinverse needs the inverse of a k × k matrix. For k = 3 that is a 3 × 3 matrix, which is tiny. If two parts become identical, that matrix has no inverse. Software then adds a very small number to its diagonal so the solve still works. The page’s code does exactly that.
Now an example where the clip matters. Let a row of X be x = (2, 1, 0), and let Z have rows (1, 1, 0) and (1, 2, 1). Least squares gives the weights w = (2, −1/3). The rebuild is (1.67, 1.33, −0.33), and the squared miss is 0.33.
The weight −1/3 is forbidden. Clip it to zero and w = (2, 0). The rebuild is (2, 2, 0), and the squared miss is 1. The clip made the error three times larger on that row.
The reason is simple. The pseudoinverse solves the problem without the sign rule. Clipping then forces the rule on afterward. The result is not the best non-negative W for this half step, which would need a method called non-negative least squares. The clip is a cheap stand-in. It is usually good enough and has no guarantee.
The classic rival is the multiplicative update of Lee and Seung (NeurIPS 2000). Each number is multiplied by a ratio that is always at or above zero, so a number that starts positive never turns negative. The authors prove that the error never rises. It uses no pseudoinverse and no clip, but it takes more rounds.
Race them on the toy sound. Both start from the same random point. One round is one W step and one Z step.
The top chart plots error after each round for both methods. Press Play, or drag the round. Below it, the three parts that the chosen method holds at that round.
Toy sound from the hero, 3 parts, both methods started from the same seeded random W and Z, computed live. Alternate-and-clip uses a least-squares solve with a small safety term, then clips. The error axis stops at 100%; the shared start is above it.
Alternate-and-clip drops to 3.4% error in five rounds and 2.4% in six. The multiplicative rule is still above 20% at that point and needs about 60 rounds. Each round of the clip method costs more, since it solves a small linear system. The multiplicative rule uses only products and divisions.
Look closely at the end of the clip curve. It sits flat near 1.8%, and many of its half steps raise the error by a hair (the largest rise in this run is 0.004 points). That is the clip at work: a half step that is exact without the sign rule can lose a little when the rule is forced on. The multiplicative curve never rises, and by round 60 it reaches 1.9%, close to the same floor.
How do you know when to stop? Watch the error. When a full round changes it by less than a small threshold, say 0.01 points, the search has settled. Then restart from a few other random points, as in Chapter 2, and keep the best.
Chapter 4
Run the mixing desk forward, then run it backward and hear each source on its own
A friend plays you a chord on a piano and asks which notes are in it. You can answer after a moment of listening. A computer sees only a grid of energies. The lecture shows what NMF does with such a grid and gives it one line: columns of W contain frequencies (for example musical notes), rows of Z contain time information.
That line is the whole picture of NMF on sound. A column of W is a template: the pitches that one note or one instrument lights up. A row of Z is an activation: when that template is playing, and how loudly. The slide’s figure shows a piano roll, with each note switched on and off over time, next to the spectrogram it produces.
Does the sound of two instruments really equal the sum of their two grids? Almost. Waves can cancel, since one wave goes up while another goes down. But the loudness of two unrelated sources, measured over a short slice, adds up close to the sum. NMF uses that approximation. It is a model, and it can be wrong when two sources are tightly locked together.
One refinement. Many systems square the sizes first, giving a power spectrogram, because the powers of unrelated signals add on average. Either choice is non-negative, so NMF applies to both. We use plain sizes in this lesson to keep the numbers readable.
A plucked string does not make one pure pitch. It makes a base pitch, the fundamental, plus quieter copies at two, three and four times that pitch, called overtones. On a pitch axis they look like the teeth of a comb. Different instruments weight the teeth differently, and that is most of what a timbre is.
Our toy sound has twelve pitch bins, at 110, 220, 330 and on up to 1,320 Hz. Note A has a fundamental at 220 Hz with overtones at 440, 660 and 880 Hz. Note B has a fundamental at 330 Hz with overtones at 660, 990 and 1,320 Hz. The drum is different: it lights every bin, from low to high, and only for an instant. Notice that both notes share 660 Hz. A template may overlap with another, and NMF can still pull them apart because they differ in the other bins and in time.
Real separation follows five steps. The first four build the grid and find the parts. The last one gives you sound again.
Look at the drum in the toy sound. It is a single tall column, one frame wide, repeated five times. Its activation is five spikes. A note is the opposite shape: a few thin rows that last many frames, and an activation that is a long hill. Templates and activations together capture both the colour and the rhythm of each source.
First play with the model in the direction it was written. You are the mixing desk: three rows of Z, one per source, and 24 time slots. A switched-on cell means the source plays in that slot. The templates are fixed. The machine computes W times Z and shows the spectrogram that results.
Tap a cell in the top grid to switch a source on or off at that moment. The grid below is the spectrogram that W times Z makes. Press Play to hear it.
Toy model, made here: the three templates are the toy sound’s own (note A, note B, drum), and each switched-on cell is loudness 1. Playback is a resynthesis: twelve sine tones at 110 Hz times 1 to 12, each as loud as its row of the grid, 150 ms per frame. The drum is all twelve tones at once, so it sounds like a short chord burst, not a real drum.
One switched-on cell in Z lights a whole column of the spectrogram: the template, at the chosen loudness. Switch on the drum in one slot and a full-height bar appears. Switch on note A for several slots and a comb of four horizontal stripes appears. The spectrogram is made of layers, as in Chapter 1.
NMF solves the opposite problem. It sees only the spectrogram and must find W and Z. Suppose it has done so. How do you listen to one source alone? Take that source’s layer, which is its template times its activation. Then compute its share of every cell: its layer divided by the sum of all the layers.
The share is a mask, a number from 0 to 1 for every cell. Multiply the mask by the real spectrogram and you get that source’s part of the real sound. The masks of all sources add to 1 in every cell, so the separated parts add back to the original. Turning a spectrogram back into a wave needs one more step, reusing the timing information (the phase) of the mix. Our player skips that and plays the grid directly.
Take the toy sound, factor it with 3 parts, and pull it apart. Each cell below is coloured by the part that owns most of it.
Each cell is coloured by the part that owns most of it. Switch parts off to silence them and press Play to hear what is left.
Toy sound from the hero, factored live by NMF with 3 parts and unmixed by the masks above. The accuracy figure compares the recovered part with the true layer that the toy sound was built from, which a real recording never gives you. Playback uses the same twelve-tone resynthesis as the device above.
With all three parts on, you hear the original. Switch off the drum and the clicks vanish while both notes keep playing. Switch off both notes and only the drum remains. This is source separation, and no one told the algorithm what a note or a drum was. It only knew that the energies add and that nothing is negative.
Look at what goes wrong when you ask for too few parts. With 2 parts, the drum has nowhere to go: its energy is split between the two note parts, and every note part carries a faint tick. The symptom is a bleed that you can hear. The measurement is the error, 15.4% against 1.7% in Chapter 1. The fix is more parts, until the error stops dropping.
Two limits are worth knowing. First, a real piano note does not keep one template: the first instant, the strike, sounds unlike the long decay after it. One template per note is an approximation, and a fix is to allow several parts per note. Second, two sources that play the same pitches at the same moments leave NMF nothing to separate them with. It gives one part for both, and no setting of k changes that.
Chapter 5
Stack photos as columns, factor them, and count how local each part is
Take a small photo of a face, 10 pixels wide and 10 tall. Each pixel is a brightness from 0 (black) up. Now flatten the photo: read the pixels row by row and write them as one column of 100 numbers. A second photo gives a second column. Forty photos give a grid with 100 rows and 40 columns.
That grid is the data matrix X again, now with n = 100 pixels and d = 40 photos. The slide for images shows the same formula as the audio slide, X ≈ WZ, with the same two sign rules. Only the meaning of the factors changes.
Here is the same bookkeeping at a bigger size. A 64 × 64 photo becomes a column of 4,096 numbers. Four hundred photos make X of size 4,096 × 400, which is 1,638,400 numbers. Ask for k = 25 parts. Then W is 4,096 × 25 and Z is 25 × 400, which is 102,400 + 10,000 = 112,400 numbers. These sizes are an illustration, not the lecture’s.
A column of W has 100 numbers, one per pixel. Fold it back into a 10 × 10 square and it is a small picture: a template image. A column of Z has k numbers and belongs to one photo. Each number says how strongly that template is present in the photo.
So a photo is a recipe. To build it, take a bit of template 1, a bit of template 2, and so on, and add them. Written per pixel, the brightness of pixel p in photo j is the sum over parts i of W[p, i] × Z[i, j]. If a pixel lies inside only one template, the pixel’s brightness is simply that part’s weight.
The slide puts the two methods side by side on a face. PCA gives templates that are whole faces, with bright and dark zones and a mix of signs. NMF gives templates that are small pieces. The lecture’s earlier slide had already complained that PCA’s templates are hard to interpret. Here is the repair.
The reason is the no-cancel rule. Say a template is bright over an eye and also bright over the mouth. Then every photo that uses it gets both an eye and a mouth. If the data has photos with eyes and no mouth, there is no way to remove the mouth: nothing may subtract. So NMF is pushed toward templates that match a feature that comes and goes as a unit. Eyes come and go together with their own pixels, so each eye tends to become its own template.
This is a tendency, not a law. It comes from the structure of the data. If every photo always had both eyes, one template would hold both. The famous paper on this effect is Lee and Seung’s “Learning the parts of objects by non-negative matrix factorization” (Nature, 1999).
Our toy faces are built from five features: a brow, a left eye, a right eye, a nose and a mouth. Each photo switches on each feature with probability 0.6, at a random brightness. We know the truth, so we can check what each method finds.
To say how local a template is, count its support: the number of pixels where it is at least 20% as bright as its own brightest pixel (for PCA, in absolute value). A small support means a small piece. Only 22 pixels in the whole 10 × 10 image are ever lit, so a support near 22 means the template spreads over everything.
Top row: NMF templates. Bottom row: PCA templates, with red for negative pixels. Drag the number of parts and watch the supports. The bars show the recipe each method gives for the face you choose.
Toy data: 40 ten-by-ten faces from five switchable features, seeded. NMF is the best of three random starts with 400 multiplicative updates each, fitted live when you choose a number of parts; PCA is the truncated SVD with no centring. Support counts pixels at 20% or more of the template’s own largest value.
The gap in locality shows up even when the fit is equal. At 3 parts the two methods have almost the same error, 36.1% for NMF and 35.9% for PCA. Yet NMF’s templates cover 8.7 pixels on average and PCA’s cover 20.7. The difference is not in how well they fit. It is in what each fit lets you read.
At 5 parts, NMF’s templates cover about 4 pixels each, which is the size of one eye, the nose or the mouth. PCA’s templates cover about 20 of the 22 lit pixels each. PCA rebuilds the faces without any error, since five independent features make a grid of rank 5. NMF reaches 0.3% error. The 0.3% is the price of the sign rule, and the small supports are what it buys.
Now read a recipe. Pick a face and look at the bars. NMF’s recipe has some bars at zero, for features that are off in that face, and some positive bars, for features that are on. You can read the face from the bars: brow on, left eye on, nose off. PCA’s recipe has bars above and below zero for almost every direction. You cannot read the face from them.
The columns of Z are useful on their own. Each photo has a short list of k non-negative numbers, and photos with similar lists share parts. You can sort photos by their largest entry to group them. That previews the last chapter, where clustering and factorization meet.
Two failures show up here. Ask for too few parts, say 3, and NMF merges features: one template covers both eyes and another covers the nose and the mouth together. The error is 36% instead of 0.3%. Ask for too many, say 7, and it repeats features: the left eye turns up in three templates, and the error does not improve. In both cases the support and the error tell you. The third failure is the bad start from Chapter 2, which shows as a high error at the right k.
This idea sits next to two others in the course. Autoencoders learn a compressed code with a neural network and no sign rule. Dictionary learning asks for templates plus a recipe that uses only a few of them. NMF is the version where every number is non-negative.
Chapter 6
Free one factor from the sign rule, so the method can fit data that dips below zero
A vibration sensor on a bridge reports a number 1,000 times a second. The number goes up when the deck lifts and down when it falls. It is positive half the time and negative half the time. Centred audio, EEG traces and any data from which you subtracted an average share this property.
Plain NMF is built for grids that never dip below zero. What does it do with this sensor? It fails in a way you can calculate.
Let Y be the data, with some negative cells. Any product WZ with both factors non-negative has only non-negative cells. Look at one cell where Y is −3. The best the product can offer is 0, which misses by 3. Any positive value misses by more than 3. The squared miss is at least 9.
That holds for every negative cell. So no non-negative factorization can have a squared error below the total of the squared negative cells of Y. Call this the floor. If a large share of the data’s energy sits in negative cells, the floor is large, whatever the number of parts.
Make that real. Take the toy sound from Chapter 0 and centre it: subtract from each row its own average over time. Cells that were quieter than their pitch’s average now go negative. In this grid, 42% of the squared energy lies in negative cells. The floor is the square root of 0.42, which is 65%. Plain NMF cannot get below a 65% relative error.
The lecture’s fix is small. Keep the sign rule on one factor and lift it from the other. The slide writes it as min over W ≥ 0 and Z of the squared Frobenius norm of WZ − Y, and adds one bullet: the second component Z is not constrained. This is semi-nonnegative matrix factorization, or semi-NMF.
In this chapter, read each row of Y as one thing you measure. For the centred sound, a row is one pitch bin, a time series of 24 numbers. W is non-negative, so each pitch uses a mix of the parts with weights at or above zero. Z holds the time curves, and these may go below zero: quieter than average.
Recall the heuristic from Chapter 3. For W fixed, the best Z is W†Y, and without the sign rule on Z there is nothing to clip. That half step is exact and needs no repair. Only the W half step must respect the sign rule.
For that half, a rule of the multiplicative kind exists. It was described by Ding, Li and Jordan (“Convex and semi-nonnegative matrix factorizations”, IEEE TPAMI, 2010) in a version with the roles swapped. Split any matrix A into its positive part A+ (negatives set to 0) and its negative part A− (positives set to 0, signs flipped). The update is:
Wij ← Wij · √( [ (YZT)+ + W(ZZT)− ]ij / [ (YZT)− + W(ZZT)+ ]ij )
You do not need to memorise it. Read it as: scale each weight by a ratio that is never negative. A weight that starts positive stays positive, and the sign of Y and Z only changes the size of the ratio. This page uses it with the exact Z step, alternating until the error settles.
Now compare. The sound below is centred. Plain NMF can only aim at the positive cells. Semi-NMF is allowed to use the negative ones.
Top left: the centred sound, blue above zero and red below. Top right: the rebuild. Below: each part, with its non-negative template and its time curve. Choose a method and a number of parts.
The toy sound from the hero with each pitch’s time average subtracted. Plain NMF is fitted to the positive part of the centred sound with multiplicative updates, since that is all it can reach. Semi-NMF alternates an exact least-squares Z with the multiplicative W rule, 400 rounds, from seed 1. Both run live in your browser.
At 3 parts, plain NMF sits near 65% error, right at the floor. Its rebuild has no red cells at all, so the whole negative half of the data is missing. Semi-NMF reaches about 2.5%. The red cells are back, and the parts show them: each time curve dips below zero in the moments where its pitches go quieter than average.
What did semi-NMF give up? The time curves are signed, so you lose the plain reading of “this part is playing now”. A negative value means less than usual. The templates in W stay non-negative, so the picture across pitches still reads as a pattern you can name.
You may ask: why not just add a constant to the data so that nothing is negative? You can, and sometimes it is fine. But the constant changes what the numbers mean. A value of zero used to mean “average” and now means “the lowest value there is”. Semi-NMF keeps the meaning of the data and moves the freedom into the factor that can use it.
Chapter 7
Derive, line by line, why the sign rule of NMF is the same thing as a ReLU
Here is the surprise of the lecture. Two ideas that seem to live in different worlds turn out to be the same problem. One is semi-NMF, from the last chapter. The other is a small neural network. The slides give three steps of algebra. This chapter slows each step down and lets you check the result with numbers.
Start with data X of size n × d: n samples, one per row, each with d features. A two-layer ReLU network first multiplies X by a weight matrix W1 of size d × m. That gives n × m numbers, one row per sample, one column per hidden unit. Next the ReLU (rectified linear unit) clips every negative number to zero. Then it multiplies by a second matrix W2 of size m × c, which gives the n × c outputs. We want the outputs close to targets Y.
Compare it with semi-NMF: a non-negative matrix times a free matrix. In the network, the hidden layer is non-negative because the ReLU makes it so. The output weights are free. The shapes already match: the hidden layer plays W (n × m, at or above zero) and W2 plays Z (m × c, free).
One half of the match is free. Whatever W1 and W2 you choose, define W = (XW1)+ and Z = W2. Then W is non-negative, and the network’s output is exactly WZ. So the network can never beat semi-NMF. The question is whether it can match it, and that is where the whitening in the slide comes in.
The lecture assumes the data is whitened: XXT = I. Read it as: the n rows of X have length 1 and point in perpendicular directions. It needs n ≤ d, as the slide’s footnote says, since you cannot fit more than d perpendicular directions in d dimensions.
The slide ends with the line: the minimum over W1 and W2 of ‖(W1)+W2 − Y‖ equals the minimum over W1 ≥ 0 of ‖W1W2 − Y‖. Identical to the semi-NMF model. The sign rule of NMF and the ReLU of a network are the same device, seen from two sides.
Why must n be at most d? Whitened data asks for n rows that are perpendicular and of length 1. In 8 dimensions you can place 6 such rows, as the device below does. You cannot place 10. So the equality describes wide data, with more features than samples, as in many modern problems that have thousands of features and fewer examples.
Try it on 6 samples with 8 features and targets of 2 numbers each. First semi-NMF finds W and Z. Then you move them into a network by W1 = XTW and W2 = Z, and read what the network does. With whitened X the hidden layer comes out equal to W. With ordinary X it does not.
Left: the semi-NMF weights W. Middle: the network’s hidden layer, built from W1 = XᵀW. Right: how far apart they are. Switch the data between whitened and ordinary, or draw new targets.
Toy data, seeded: 6 samples, 8 features, 2 targets in [−1, 1]. Whitened X has exactly perpendicular unit rows; ordinary X is the same rows after a random invertible mixing. Semi-NMF runs 600 rounds live. The loss is the squared Frobenius error, not divided by anything.
With whitened data, the two grids on the left and middle are the same picture, the third grid is blank, and the network’s loss equals the semi-NMF loss. With ordinary data the hidden layer is a different grid, and the loss moves. That is exactly what the whitening condition buys.
The read-out also runs the check in the other direction. It takes a random network, forms W = (XW1)+ and Z = W2, and compares the two losses. They are identical every time, for either kind of data, because that direction needs no whitening.
The statement is about the best value the two problems can reach. It is not a promise that training reaches it. In a network, a hidden unit whose inputs are all negative outputs zero, and its gradient is zero too. That unit is dead and stays dead. In semi-NMF language it is a column of W that is all zeros. Gradient descent on the network can get stuck this way. The alternating method of Chapter 6 works on W directly and does not have this trouble in the same form.
It also says nothing about a network with more layers or other activation functions. The next chapter takes a step in that direction by stacking factors. For a different route to the same kind of equivalence, see our convex neural networks lesson. For the basics of such networks, see neural networks.
Chapter 8
Stack factorizations so the parts themselves are built from simpler parts
Think about a face again. Pixels make eyes and mouths. Eyes and mouths make an expression. An expression, together with a head pose, makes the photo you see. That is three levels. One factorization gives you only one of them.
The lecture’s next move is to stack. If W times Z explains the data, then apply the same idea to Z, and again to what you get, and so on. The slide calls the result deep NMF, and deep semi-NMF when the last factor is free.
Begin with Y ≈ W1Z1. Here W1 holds k1 small parts and Z1 says how strongly each is used. Now treat Z1 like new data and factor it: Z1 ≈ W2Z2, with k2 parts, a smaller number than k1. Put it back: Y ≈ W1W2Z2. Do it once more and you get Y ≈ W1W2W3, with the last Z renamed W3.
Each matrix has a job. W1 (n × k1) holds the smallest parts. W2 (k1 × k2) says how those small parts group into bigger components. The product W1W2 (n × k2) is the bigger components drawn in the original space. In the paper that gave the slide’s figure, Trigeorgis, Bousmalis, Zafeiriou and Schuller (ICML 2014), the three levels of one face collection learn features for pose, then expression, then identity.
One note on notation. The paper writes the chain with the free matrices first and the non-negative representation last, the transpose of the slide’s layout. The idea is the same: a stack of mappings, each simpler than the one below.
Count the numbers a stack stores. With sizes n, k1, …, kL−1, d it stores n·k1 + k1·k2 + … + kL−1·d numbers. For the toy sound with k1 = 8 and k2 = 3 that is 12 × 8 + 8 × 3 + 3 × 24 = 192. A single layer with 3 parts stores 12 × 3 + 3 × 24 = 108.
Finding all L matrices at once is a harder search than finding one pair. The paper pre-trains the layers one at a time: factor the data, then factor the result, and so on. It then fine-tunes all the factors together on the full error. We do the same on the toy sound, with all factors non-negative. Each fine-tuning step is the multiplicative rule from Chapter 3, applied to every matrix in the chain in turn.
Why build the layers one at a time first? A product of several matrices has many more dips in its error landscape than a single pair, as Chapter 2 warned. Starting each layer from the result of the one below gives the joint search a start that is already close. Then the fine-tuning only has to polish.
Try it. Level 1 has 8 small parts. Level 2 has 3 components, one for each source. Switch between one layer, two layers built layer by layer, and two layers after joint fine-tuning.
Left to right: the small parts W1, the grouping matrix W2, and the three components they build together. Below: how loud each component is over time. Choose how the stack is built.
Toy sound from the hero. Layer 1 is NMF with 8 parts (500 multiplicative updates); layer 2 is NMF with 3 parts on layer 1’s activations; fine-tuning is 300 multiplicative updates on every factor at once. Everything is non-negative, so this is deep NMF rather than deep semi-NMF. Group purity counts the small parts that send at least 80% of their weight to one component.
Read the grouping matrix W2. Each row is one small part, and its brightest cell says which component it joins. Most small parts send almost all their weight to a single component. That is the hierarchy: the 8 small parts are pieces of three bigger things.
The fine-tuning is quick. Starting from the layer-by-layer answer at 6.7% error, 50 joint updates bring it to 2.0%, and 300 bring it to 1.8%. Each update changes W1, then W2, then Z in turn, each by the same non-negative ratio rule as before. No clip and no pseudoinverse is needed.
Now be honest about what depth bought. On this toy, the error after layer-by-layer building is higher than for one layer, and the stack stores more numbers (192 against 108). Joint fine-tuning brings the error back to the one-layer level but does not beat it. The toy sound has only one level of structure, three sources. Depth pays when the data has several levels, as the paper’s faces do. Here it only adds a second, readable view of the same answer.
The same pattern fits sound. The small parts could be single overtones and short bursts, and the second level could group them into notes and drums. That is a hierarchy of the kind a person would draw.
The lecture’s last words on the idea: it works well for speech, signal and image separation and clustering. Clustering is where the next chapter goes, since a stacked representation feeds naturally into one.
Chapter 9
Rewrite clustering as X ≈ C Bᵀ, and see how one relaxed rule turns it into semi-NMF
You have 24 snapshots of a machine, and you suspect it runs in three modes. Nobody labelled them. You want to sort the snapshots into three piles so that the snapshots in each pile look alike. That is clustering, and the classic method is k-means.
The last slide of the lecture does something small and useful. It writes k-means in the same shape as everything before it: a data matrix equals a product of two matrices, up to an error. Seeing this shows that clustering and NMF are close relatives.
Pick k centres: k points in the data space. Give every snapshot to its nearest centre. That sorts the snapshots into k piles. Move each centre to the average of its pile. Repeat the last two steps until nothing changes. This loop is Lloyd’s algorithm.
The quantity it lowers is the total squared distance from each snapshot to its own centre. The slide writes it as a double sum: for each cluster j, and each point xi in cluster Cj, add ‖xi − cj‖2.
Here is the slide’s rewrite. In this chapter, put each observation in a column of X, as the slide does. X has d rows (the features) and n columns (the observations). Let C = [c1, …, ck] be the centroid matrix, with one centre per column. Let B be the assignment matrix, of size n × k, where Bij = 1 if observation i belongs to cluster j, and 0 otherwise. Each row of B has exactly one 1.
Why are the two sides equal? Look at column i of CBT. It is C times column i of BT, and that column has a single 1. So it picks out one column of C: the centre of observation i’s own cluster. The rebuild of each observation is its cluster’s centre. The Frobenius error adds up the squared difference between each observation and its rebuild, which is the cost.
Work a small case. Four points in the plane: (1, 1), (2, 1), (8, 9) and (9, 9). Put the first two in cluster 1 and the last two in cluster 2. The centres are the averages: c1 = (1.5, 1) and c2 = (8.5, 9). Distances to the centres are 0.5, 0.5, 0.5 and 0.5, each along the x axis. The squares are 0.25 each, so the cost is 1.0. Now the matrix side: CBT repeats c1 twice and c2 twice. X − CBT has top row (−0.5, 0.5, −0.5, 0.5) and bottom row all zeros. Its squared Frobenius norm is 4 × 0.25 = 1.0. Both routes agree.
This view gives you something extra. Fix B. The best C for that B is the least-squares answer from Chapter 3, C = XB(BTB)−1. Since each row of B has a single 1, the matrix BTB is diagonal and holds the cluster sizes. So the formula divides each cluster’s column-sum by its size. It is the average, which is exactly Lloyd’s move step.
Now fix C. The best one-hot B gives each observation to its nearest centre. That is the assign step. So k-means alternates two exact minimisations, one per factor. It is the same loop as Chapter 3, with a one-hot rule on B in place of the clip. Step through it:
Left: 24 points and 3 centres. Right: the matrix B, one row per point with a single 1. Press Assign, then Move, and repeat. Or press Run.
Toy data, seeded: 24 points around three made-up centres, as a 2 × 24 matrix X. Each new start picks three data points as the first centres. The cost is computed twice, as a sum of squared distances and as the squared Frobenius norm of X minus CBᵀ, and the two are shown side by side.
The same cautions apply as for NMF. You choose k, and the error curve shows a bend. Lloyd’s loop finds a local minimum, so two starts can end in different piles. Run several starts and keep the one with the lowest cost, exactly as in Chapter 2.
Now compare the two shapes. k-means is X ≈ CBT with B non-negative and each row a single 1. Semi-NMF is a product of a non-negative matrix and a free matrix. Drop the one-hot demand on B, keep B ≥ 0, and let C be free: you have semi-NMF, with the roles of the matrices named differently. Each row of B is no longer a hard label. It is a set of non-negative weights, which you can read as a soft membership: how much of each cluster an observation belongs to.
That is why the paper from Chapter 8 can say that semi-NMF learns a low-dimensional representation of a dataset that lends itself to a clustering interpretation. It explains why the lecture ends on this slide: a tool for separating signals is also a tool for grouping them.
See the difference on the toy sound. Sort its 24 time frames into three groups two ways. k-means gives each frame one label. NMF gives each frame a set of shares. Frames where a note and the drum play together are the hard cases.
Each column is one time frame. Top: the shares NMF assigns to its three parts. Bottom: the single label k-means gives. Press the button to try another k-means start.
Toy sound from the hero. The shares are each frame’s activations from NMF with 3 parts, divided by their sum. k-means clusters the 24 frames, each a 12-number column, into 3 groups. It keeps the best of five starts, with 25 rounds each, and the seeds shift on each press. Cluster colours match the NMF part that holds most of that cluster’s share.
About half the frames are clean: one share is nearly 1, and k-means agrees. The other half, with a note and a drum together or a note handing over to the next, show two coloured shares, and k-means must pick one colour. Nothing is wrong with either method. k-means answers “which pile?” and NMF answers “how much of each?”.
Chapter 10
Keep the numbers, the checklist and the core code, and find where to go next
Here is the lecture in one paragraph. Many grids can never go below zero: sound energies, pixel brightnesses, counts. NMF writes such a grid X as a product WZ of two non-negative matrices, so the data is a sum of parts that only add. The problem has no formula and no unique answer, so you search with alternating steps and keep the best of several starts. Free one factor from the sign rule and you get semi-NMF, which fits signed data and equals a two-layer ReLU network for whitened inputs. Stack the factors and you get a hierarchy of parts. Make the weights one-hot and you get k-means.
| Quantity | Value | Where it came from |
|---|---|---|
| Shapes of the toy sound | X 12 × 24 (288 numbers); W 12 × 3; Z 3 × 24 (108 numbers) | Chapter 1, toy |
| Relative error by number of parts | 1 part 44.5%, 2 parts 15.4%, 3 parts 1.7%, 4 parts 1.7% | Chapter 1, toy, NMF |
| Squared error by hand | 60 of 98, so a relative error of 78% | Chapter 1, worked example |
| Random restarts on faces | Five of six starts reach about 0.2% error; one sticks at 13.4% | Chapter 2, toy, seeds 1 to 6 |
| Clip heuristic against multiplicative | 3.4% against 29% after 5 rounds; 1.8% against 1.9% after 60 | Chapter 3, toy, same start |
| Locality of parts | NMF templates cover 4.4 pixels, PCA directions cover 20.0, at 5 parts | Chapter 5, toy faces |
| Floor under plain NMF | 42% of the energy is negative, so the error cannot go below 65%; semi-NMF reaches 2.5% | Chapter 6, centred toy sound |
| Deep stack against one layer | 192 numbers at 6.7% (1.8% after tuning) against 108 numbers at 1.7% | Chapter 8, toy |
| k-means cost by hand | 1.0, equal as a sum of distances and as ‖X − CBT‖F2 | Chapter 9, worked example |
Every toy number comes from the small made-up sounds, pictures and points on this page, which are seeded and computed live. They illustrate the ideas; they are not results on real recordings. The lecture itself gives no numbers beyond its formulas.
| Term | Meaning | Chapter |
|---|---|---|
| NMF | min over W ≥ 0, Z ≥ 0 of ‖X − WZ‖F2: the data as a sum of non-negative parts | 0, 1 |
| Template, activation | A column of W (what a part looks like) and a row of Z (how strongly it is present) | 4 |
| Scale ambiguity | X = WDD−1Z: scaling a part up and its activation down changes nothing | 2 |
| Local minimum | A dip in the error landscape that is not the lowest; fixed by restarts | 2 |
| Alternate and clip | W ← (XZ†)+, then Z ← (W†X)+, repeated | 3 |
| Semi-NMF | min over W ≥ 0, Z free of ‖WZ − Y‖F2: for data with signs | 6 |
| ReLU equivalence | For whitened X (XXT = I, n ≤ d), a two-layer ReLU network has the same optimum as semi-NMF | 7 |
| Deep NMF | A chain W1W2…WL fitted to the data: parts of parts | 8 |
| k-means as factorization | ‖X − CBT‖F2 with B one-hot; relax B ≥ 0 for semi-NMF | 9 |
Four short functions cover the lecture: the multiplicative search, the slide’s alternate-and-clip heuristic, semi-NMF with an exact Z step, and k-means written as a factorization. The sizes in each docstring are the shapes from the chapters.
import numpy as np def nmf_mu(X, k, iters=500, seed=0, eps=1e-9): """X (n, d) >= 0 -> W (n, k) >= 0 and Z (k, d) >= 0 with X ~ W @ Z.""" rng = np.random.default_rng(seed) n, d = X.shape s = np.sqrt(X.mean() / k) W = (0.1 + rng.random((n, k))) * s Z = (0.1 + rng.random((k, d))) * s for _ in range(iters): Z *= (W.T @ X) / (W.T @ W @ Z + eps) # multiplicative step for Z W *= (X @ Z.T) / (W @ Z @ Z.T + eps) # multiplicative step for W return W, Z def nmf_als_clip(X, k, iters=60, seed=0): """The slide's heuristic: least squares with the pseudoinverse, then clip.""" rng = np.random.default_rng(seed) Z = 0.1 + rng.random((k, X.shape[1])) for _ in range(iters): W = np.maximum(X @ np.linalg.pinv(Z), 0) # W <- (X Z^+)_+ Z = np.maximum(np.linalg.pinv(W) @ X, 0) # Z <- (W^+ X)_+ return W, Z def semi_nmf(Y, k, iters=400, seed=0, eps=1e-9): """Y (n, d) any sign -> W (n, k) >= 0 and Z (k, d) free with Y ~ W @ Z.""" rng = np.random.default_rng(seed) pos = lambda A: (np.abs(A) + A) / 2 neg = lambda A: (np.abs(A) - A) / 2 W = 0.1 + 0.5 * rng.random((Y.shape[0], k)) for _ in range(iters): Z = np.linalg.lstsq(W, Y, rcond=None)[0] # exact: Z has no sign rule A, B = Y @ Z.T, Z @ Z.T W *= np.sqrt((pos(A) + W @ neg(B)) / (neg(A) + W @ pos(B) + eps)) return W, np.linalg.lstsq(W, Y, rcond=None)[0] def kmeans_as_factorization(X, C, iters=20): """X (d, n) with observations as columns, C (d, k): X ~ C @ B.T, B one-hot.""" for _ in range(iters): D = ((X[:, :, None] - C[:, None, :]) ** 2).sum(0) # (n, k) squared distances B = np.eye(C.shape[1])[D.argmin(1)] # assign: one 1 per row C = X @ B / np.maximum(B.sum(0), 1) # move: means = X B (B^T B)^-1 return C, B
NMF is one of the oldest ways to learn a dictionary from data. Dictionary learning, next in the course, keeps the templates and asks that each recipe use only a few of them. Autoencoders learn a code with a network and no sign rule. The ReLU bridge in Chapter 7 links NMF to the network lessons, and convex neural networks pursue a related equivalence by a different route.
Press Present to rehearse this lesson aloud, or Teach to explain it on a whiteboard, then go back to the instrument at the top and unmix the sound again. This page re-teaches the lecture of Mert Pilanci’s Stanford EE269, Signal Processing for Machine Learning, in our own words and devices. The slides, the course site and the credit belong to the course: web.stanford.edu/class/ee269.