Module contents
Lesson 14 of 24Advanced 100 min

Non-negative matrix factorization, sparse coding and dictionary learning

Nonnegative matrix factorization, sparse coding and dictionary learning.

After this lesson you can

  • Explain nonnegative factorization and multiplicative updates.
  • Derive sparse coding and dictionary learning methods.
  • Compare interpretable representations and assess their limitations.

Before you start

Motivation: parts, topics and atoms

PCA as the best linear reconstruction solves a specific problem: minimize squared error with kk directions. But its directions are global and signed. Each component touches nearly every pixel, word or sensor, and an image is reconstructed by adding and subtracting patterns that cancel. That is optimal for compression and poor for understanding. Many applications want something else: readable feature extraction.

  • Face parts. Lee and Seung (1999) applied PCA, vector quantization and an all-nonnegative factorization to m=2429m = 2429 faces of 19×1919 \times 19 pixels, with r=49r = 49 basis images. PCA gave global “eigenfaces”; vector quantization gave whole-face prototypes; nonnegative factorization gave localized images resembling eyes, noses and mouths. Their explanation is this lesson’s thesis: if only addition is allowed there is no cancellation, and reconstruction must combine parts.
  • Document topics. With the same factorization on word counts from 30,991 Grolier encyclopedia articles (vocabulary 15,276 words) and r=200r = 200, each basis column became a semantic topic, a group of co-occurring words, and each article a sum of topics.
  • Signal atoms. Olshausen and Field (1996) asked a linear code for 16×1616 \times 16 natural-image patches to use few coefficients at once. Without imposing anything else, basis elements became localized, oriented and band-limited, like receptive fields of primary visual cortex simple cells.

All three use factorization X≈WH\mat{X} \approx \mat{W}\mat{H} with different constraints: nonnegativity or sparsity. This lesson studies them in order: nonnegative factorization with multiplicative updates (an MM algorithm), sparse coding with ISTA, dictionary learning (alternating, K-SVD and online), sparse PCA, and finally the connection to sparse autoencoders now used to decompose LLM activations.

One factorization, four constraints

By platform convention, X∈Rn×d\mat{X} \in \R^{n \times d} has one example per row. A rank-kk factorization writes each row as a combination of kk basis vectors:

X≈WH,W∈Rn×k (codes, one row per example),H∈Rk×d (atoms, one per row).\mat{X} \approx \mat{W}\mat{H}, \qquad \mat{W} \in \R^{n \times k} \text{ (codes, one row per example)}, \qquad \mat{H} \in \R^{k \times d} \text{ (atoms, one per row)}.

This is the sklearn convention (W = modelo.transform(X), H = modelo.components_). Lee and Seung write V≈WH\mat{V} \approx \mat{W}\mat{H} with an example per column, so their W\mat{W} (basis) is our H⊤\mat{H}\T; take care reading the paper. Methods differ in what each factor must satisfy:

MethodConstraint on W\mat{W} (codes)Constraint on H\mat{H} (atoms)What it learns
Vector quantization (kk-means)each row is canonical vector ec\vb{e}_cnonewhole prototypes
PCAorthogonal columns (uncorrelated scores)orthonormal rowsglobal signed patterns
NMFW≥0\mat{W} \ge 0H≥0\mat{H} \ge 0additive parts
Sparse coding / dictionariessparse rows (ℓ1\ell_1 penalty)row norms ≤1\le 1signal atoms
Sparse PCAnone (column norms ≤1\le 1)sparse rowsinterpretable loadings

Vector quantization is the rigid extreme: one atom per example, coefficient 1. PCA is the free extreme: all atoms, any sign. NMF and sparse coding lie between: several atoms at once, but few (sparsity) or only adding (nonnegativity). The constraints are related: nonnegativity produces sparsity almost unasked.

Nonnegative factorization

The second is generalized because neither X\mat{X} nor Y\mat{Y} must sum to 1: if both do, −xij+yij-x_{ij} + y_{ij} terms cancel, leaving ordinary KL divergence. Each term is nonnegative (function xlog⁡(x/y)−x+yx\log(x/y) - x + y is convex in yy with minimum 0 at y=xy = x) and divergence is zero only if Y=X\mat{Y} = \mat{X}. Both losses are disguised likelihoods:

  • Frobenius is −log⁡p-\log p up to constants if xij∼N((WH)ij,σ2)x_{ij} \sim \Normal((\mat{W}\mat{H})_{ij}, \sigma^2): additive Gaussian noise, appropriate for intensities.
  • Generalized KL is −log⁡p-\log p up to constants if xij∼Pois⁡((WH)ij)x_{ij} \sim \Pois((\mat{W}\mat{H})_{ij}), because −log⁡Pois⁡(x∣y)=y−xlog⁡y+log⁡x!-\log\Pois(x \given y) = y - x\log y + \log x!. This is natural for counts (words, photons, sequencing reads). It is exactly what Lee and Seung maximized in 1999, F=∑i,μ[Viμlog⁡(WH)iμ−(WH)iμ]F = \sum_{i,\mu}[V_{i\mu}\log(WH)_{i\mu} - (WH)_{i\mu}], interpreted as the likelihood of generating each pixel with added Poisson noise.

Parts versus components

Before a proof, see the phenomenon. The figure fits NMF and PCA to the same 500 handwritten 8×88 \times 8 digits (even indices from load_digits) and reconstructs test digits neither saw. NMF uses Frobenius loss with the algorithm derived shortly; all calculations run in your browser.

InteractiveParts versus components
NMF: additive parts
The 16 atoms (rows of H\mathbf{H}, all ≥0\ge 0)
original
4 terms
Terms by contribution (coefficient below)
13.2
8.2
4.9
5.3
PCA: global signed patterns
The first 16 components (orange +, blue −)
original
mean + 4 terms
Terms by contribution (coefficient below)
−18.8
15.5
12.0
12.0
Errors are sums of squares over the 64 pixels (levels 0 to 16). Blue marks pixels below zero in the reconstructions. The active atoms have magenta borders.
16
4
No. 14 (a 3)
Error on this digit with 4 terms: NMF462
Error on this digit with 4 terms: PCA295
Mean error with all 16 atoms (40 test digits): NMF / PCA360 / 228
Near-zero pixels in the atoms (< 5% of the maximum): NMF / PCA71 % / 28 %
Exactly zero coefficients for this digit (NMF)6 of 16
At the top of each panel, the kk atoms: NMF atoms (rows of H\mathbf{H}, all ≥0\ge 0) in gray; PCA components orange (positive) and blue (negative). Below, a test digit reconstructed from the largest contributing terms in order: NMF starts at zero and adds strokes; PCA starts from the mean and adds and subtracts patterns. Increase 'activated atoms' one by one and compare reconstruction; then change rank kk and watch NMF atoms change (PCA components are only added: the first 16 do not depend on kk).

Three things visible in the figure and quantified in the lab below on 898 test digits:

  1. NMF atoms are strokes. With k=16k = 16, 71% of NMF atom values (over the 59 pixels ever lit) are below 5% of their atom’s maximum; PCA components, 28%. An NMF atom occupies one region; a PCA component nearly the entire image.
  2. NMF codes are sparse. With fixed atoms, each test digit’s optimal nonnegative code averages 38% of coefficients exactly zero. PCA has no zero coefficients.
  3. PCA reconstructs better. With k=16k = 16, mean squared error per test digit is 204.1 for PCA and 331.1 for NMF. This is no accident. On training data, the Eckart-Young theorem says no rank-kk factorization approximates better than truncated SVD, and PCA with mean (the best kk-dimensional affine subspace) does better still; NMF is rank-kk factorization with added constraints. There is no test theorem, but the difference remains. Interpretability costs error.

Why does nonnegativity produce parts? If xi=∑awiaha\vb{x}_i = \sum_a w_{ia}\vb{h}_a is all nonnegative, no summand can erase another’s contribution: each pixel lit in ha\vb{h}_a appears in every digit using ha\vb{h}_a. A large diffuse atom would spoil reconstruction of every digit without ink in that region, with no subtraction to fix it. The algorithm benefits when each atom covers only what its examples share: pieces. Do not overstate it: nonnegativity favors parts, but does not guarantee them. If data are not made of minimally overlapping pieces, NMF can return global atoms; Hoyer (2004) therefore proposed explicitly imposing sparsity on W\mathbf{W} or H\mathbf{H}.

NMF is not unique

PCA’s solution is unique up to signs (with distinct eigenvalues). NMF’s almost never is, affecting interpretation of atoms. If (W,H)(\mat{W}, \mat{H}) is a solution and invertible Q∈Rk×k\mat{Q} \in \R^{k \times k} satisfies WQ≥0\mat{W}\mat{Q} \ge 0 and Q−1H≥0\mat{Q}\inv\mat{H} \ge 0, then (WQ,Q−1H)(\mat{W}\mat{Q}, \mat{Q}\inv\mat{H}) yields the same product and is another solution. There are two kinds of Q\mat{Q}:

Proof

If Q=PΛ\mat{Q} = \mat{P}\mat{\Lambda}, its inverse Λ−1P⊤\mat{\Lambda}\inv\mat{P}\T is nonnegative. Conversely let R=Q−1≥0\mat{R} = \mat{Q}\inv \ge 0. For i≠ji \neq j, 0=(QR)ij=∑lqilrlj0 = (\mat{Q}\mat{R})_{ij} = \sum_l q_{il}r_{lj} is a sum of nonnegative terms, so qilrlj=0q_{il}r_{lj} = 0 for every ll. If qil>0q_{il} > 0, row ll of R\mat{R} vanishes outside column ii. If one column ll of Q\mat{Q} had two positive entries qil,qi′lq_{il}, q_{i'l} with i≠i′i \neq i', row ll of R\mat{R} would vanish outside ii and outside i′i', hence entirely, making R\mat{R} singular. Each column of Q\mat{Q} therefore has exactly one positive entry (at least one by invertibility), and invertibility places these entries in distinct rows: Q\mat{Q} is monomial.

∎

Permutations and positive rescalings (WΛ\mat{W}\mat{\Lambda}, Λ−1H\mat{\Lambda}\inv\mat{H}) are therefore the only ambiguities present for all factorizations. The first is harmless (atom order means nothing). The second requires fixing scale before comparing magnitudes: a “stronger” atom may merely have a smaller column of W\mat{W}. Lee and Seung removed it by normalizing basis columns to sum to 1.

For specific data, however, many more nonmonomial matrices Q\mat{Q} are usually valid, genuinely changing the factorization. Geometry explains this. Normalize each row of X\mat{X} to sum to 1 (nothing essential changes: if X=WH\mat{X} = \mat{W}\mat{H}, dividing row ii of X\mat{X} by a number only requires dividing row ii of W\mat{W} by it), and rescale atoms to sum to 1, passing scale into W\mat{W}. Then 1=X1=WH1=W1\vb{1} = \mat{X}\vb{1} = \mat{W}\mat{H}\vb{1} = \mat{W}\vb{1}: rows of W\mat{W} also sum to 1, and X=WH\mat{X} = \mat{W}\mat{H} with nonnegative factors says each observation is a convex combination of atoms: data lie inside the polytope with vertices h1,…,hk\vb{h}_1, \dots, \vb{h}_k, itself inside simplex Δ\Delta (because H≥0\mat{H} \ge 0). Any polytope between the data cloud and Δ\Delta works.

InteractiveWhy NMF is not unique
Simplex Δ\Delta (gray triangle), data points, and the triangle of draggable atoms h1,h2,h3\mathbf{h}_1, \mathbf{h}_2, \mathbf{h}_3
  • data
  • triangle of atoms (draggable)
  • atoms used to generate the data
Data
Points outside the triangle0 of 45
Total squared distance from outside points to the triangle0.0000
Row 1 of H\mathbf{H}(0.72, 0.18, 0.10)
Row 2 of H\mathbf{H}(0.12, 0.76, 0.12)
Row 3 of H\mathbf{H}(0.14, 0.16, 0.70)
Exact factorization: X=WH\mathbf{X} = \mathbf{W}\mathbf{H} with W,H≥0\mathbf{W}, \mathbf{H} \ge 0 (the rows of W\mathbf{W} are each point's barycentric coordinates).
With d=k=3d = k = 3 and normalized rows, each observation is a point in simplex Δ\Delta (gray triangle), and an exact factorization with W,H≥0\mathbf{W}, \mathbf{H} \ge 0 is an atom triangle containing every point and fitting inside Δ\Delta. Drag vertices: while no point lies outside (red), it is a different exact factorization. Press 'Another solution' to see one with atoms on edges of Δ\Delta. Then select 'data to the edges': when data approach the sides of Δ\Delta, little room remains to move vertices.

The figure has infinitely many exact solutions while data lie inside; with k=dk = d the trivial W=X\mat{W} = \mat{X}, H=I\mathbf{H} = \mat{I} always exists (the whole Δ\Delta), teaching nothing, so NMF uses k<dk < d. Geometry is the same then: seek a cone of kk generators between the data cone and positive orthant. Uniqueness arises when data are sufficiently spread toward orthant faces, leaving no slack: Donoho and Stodden (2003) gave first such conditions (“when does NMF give a correct parts decomposition?”). Difficulty is intrinsic: Vavasis (2009) proved deciding whether an exact nonnegative factorization of given rank exists is NP-hard. Every practical NMF algorithm is therefore local.

Multiplicative updates as an MM algorithm

The NMF objective is not jointly convex in (W,H)(\mat{W}, \mat{H}) (symmetry WH=(WQ)(Q−1H)\mat{W}\mat{H} = (\mat{W}\mat{Q})(\mat{Q}\inv\mat{H}) already prevents it), but is convex in either block with the other fixed. With fixed W\mat{W}, the H\mat{H} problem also separates by columns: column jj of X\mat{X}, v∈R≥0n\vb{v} \in \R_{\ge 0}^n, is approximated by Wh\mat{W}\vb{h} with h∈R≥0k\vb{h} \in \R_{\ge 0}^k column jj of H\mat{H}. The W\mat{W} problem is its transpose (X⊤≈H⊤W⊤\mat{X}\T \approx \mat{H}\T\mat{W}\T). It suffices to study

min⁡h≥0F(h)=12∥v−Wh∥2,∇F(h)=W⊤Wh−W⊤v.\min_{\vb{h} \ge 0} F(\vb{h}) = \tfrac12\norm{\vb{v} - \mat{W}\vb{h}}^2, \qquad \grad F(\vb{h}) = \mat{W}\T\mat{W}\vb{h} - \mat{W}\T\vb{v}.

Gradient descent with coordinate step ηa\eta_a is ha←ha−ηa[(W⊤Wh)a−(W⊤v)a]h_a \leftarrow h_a - \eta_a[(\mat{W}\T\mat{W}\vb{h})_a - (\mat{W}\T\vb{v})_a]. Lee and Seung (2001) chose ηa=ha/(W⊤Wh)a\eta_a = h_a/(\mat{W}\T\mat{W}\vb{h})_a, combining terms into a product:

ha←ha (W⊤v)a(W⊤Wh)a.h_a \leftarrow h_a\,\frac{(\mat{W}\T\vb{v})_a}{(\mat{W}\T\mat{W}\vb{h})_a}.

They have three advantages: no learning rate to tune, nonnegativity preserves itself (products and ratios of nonnegative numbers), and each iteration uses only matrix products at cost O(ndk)\bigO(ndk). What is not obvious is objective decrease. A gradient step with arbitrary ηa\eta_a could increase it. The guarantee comes from recognizing an MM algorithm.

The auxiliary function

Recall MM algorithms: if G(h,h′)G(\vb{h}, \vb{h}') satisfies G(h,h′)≥F(h)G(\vb{h}, \vb{h}') \ge F(\vb{h}) for all h\vb{h} and G(h′,h′)=F(h′)G(\vb{h}', \vb{h}') = F(\vb{h}') (an auxiliary function or majorizer touching FF at h′\vb{h}'), then ht+1=arg min⁡hG(h,ht)\vb{h}^{t+1} = \argmin_{\vb{h}} G(\vb{h}, \vb{h}^t) satisfies

F(ht+1)≤G(ht+1,ht)≤G(ht,ht)=F(ht).F(\vb{h}^{t+1}) \le G(\vb{h}^{t+1}, \vb{h}^t) \le G(\vb{h}^t, \vb{h}^t) = F(\vb{h}^t).

The Frobenius proof’s centerpiece checks that K(ht)−W⊤W\mat{K}(\vb{h}^t) - \mat{W}\T\mat{W} is positive semidefinite; the final proof exercise gives every step. Once accepted, minimizing GG solves ∇F(ht)+K(h−ht)=0\grad F(\vb{h}^t) + \mat{K}(\vb{h} - \vb{h}^t) = \vb{0}, namely ha=hat−[(W⊤Wht)a−(W⊤v)a] hat/(W⊤Wht)ah_a = h^t_a - [(\mat{W}\T\mat{W}\vb{h}^t)_a - (\mat{W}\T\vb{v})_a]\,h^t_a/(\mat{W}\T\mat{W}\vb{h}^t)_a, exactly the update. Matrix K\mat{K} tells us: projected gradient descent with step 1/L1/L, L=λmax⁡(W⊤W)L = \lambda_{\max}(\mat{W}\T\mat{W}), uses majorizer K=L I\mat{K} = L\,\mat{I}, one curvature in every direction; the multiplicative update uses a different curvature per coordinate adapted to the current point, still a valid majorizer even when some entries fall below LL.

For generalized KL, the auxiliary function follows from Jensen’s inequality, as in EM. Here it is in full.

Proof

With fixed W\mat{W}, F(h)=∑i[vilog⁡vi−vi+∑aWiaha−vilog⁡∑aWiaha]F(\vb{h}) = \sum_i\big[v_i\log v_i - v_i + \sum_a W_{ia}h_a - v_i\log\sum_a W_{ia}h_a\big]. For each ii with vi>0v_i > 0, take weights αia=Wiahat/∑bWibhbt\alpha_{ia} = W_{ia}h^t_a / \sum_b W_{ib}h^t_b, nonnegative and summing to 1 over aa. Since −log⁡-\log is convex, Jensen gives

−log⁡∑aWiaha=−log⁡∑aαiaWiahaαia≤−∑aαialog⁡Wiahaαia,-\log\sum_a W_{ia}h_a = -\log\sum_a \alpha_{ia}\frac{W_{ia}h_a}{\alpha_{ia}} \le -\sum_a \alpha_{ia}\log\frac{W_{ia}h_a}{\alpha_{ia}},

with equality if h=ht\vb{h} = \vb{h}^t, because all ratios Wiaha/αiaW_{ia}h_a/\alpha_{ia} then equal ∑bWibhbt\sum_b W_{ib}h^t_b. Substitution gives auxiliary function G(h,ht)=∑i[vilog⁡vi−vi]+∑i,aWiaha−∑i,aviαia[log⁡(Wiaha)−log⁡αia]G(\vb{h}, \vb{h}^t) = \sum_i[v_i\log v_i - v_i] + \sum_{i,a}W_{ia}h_a - \sum_{i,a}v_i\alpha_{ia}[\log(W_{ia}h_a) - \log\alpha_{ia}]. It is convex and separable in hah_a, with derivative ∑iWia−∑iviαia/ha\sum_i W_{ia} - \sum_i v_i\alpha_{ia}/h_a. Setting it to zero,

ha=∑iviαia∑iWia=hat ∑iWia vi/(Wht)i∑iWia,h_a = \frac{\sum_i v_i\alpha_{ia}}{\sum_i W_{ia}} = h^t_a\,\frac{\sum_i W_{ia}\,v_i/(\mat{W}\vb{h}^t)_i}{\sum_i W_{ia}},

which is the generalized KL update (column by column of H\mat{H}). The solution is nonnegative, so constraint h≥0\vb{h} \ge 0 does not activate.

∎

Weights αia\alpha_{ia} have a latent-variable interpretation: if each count viv_i is the sum of kk hidden Poisson counts, one per atom, αia\alpha_{ia} is the expected fraction of viv_i from atom aa. The update is that model’s E-step (distribute) followed by M-step (re-estimate); with fixed W\mat{W} it is essentially Richardson and Lucy’s (1972 and 1974) astronomical-image deblurring algorithm, a resemblance Lee and Seung note.

InteractiveThe multiplicative update as MM
Plane (h1,h2)(h_1, h_2) with h≥0\mathbf{h} \ge 0
  • F contour through hᵗ⁻¹
  • G(·, hᵗ⁻¹) contour through hᵗ⁻¹
  • MU iterates
Slice along the update line h(s)=ht−1+s (ht−ht−1)\mathbf{h}(s) = \mathbf{h}^{t-1} + s\,(\mathbf{h}^{t} - \mathbf{h}^{t-1})
  • F
  • G(·, hᵗ⁻¹)
The curves touch at s=0s = 0. The upper curve GG reaches its minimum at the new iterate s=1s = 1. Thus F(ht)≤G(ht,ht−1)≤F(ht−1)F(\mathbf{h}^{t}) \le G(\mathbf{h}^{t}, \mathbf{h}^{t-1}) \le F(\mathbf{h}^{t-1}).
Case
1
F(ht−1)F(\mathbf{h}^{t-1})0.4881
G(ht,ht−1)G(\mathbf{h}^{t}, \mathbf{h}^{t-1})0.4416
F(ht)F(\mathbf{h}^{t})0.4054
Diagonal of K\mathbf{K} versus λmax⁡(W⊤W)\lambda_{\max}(\mathbf{W}^\top\mathbf{W})7.91, 1.58 | 2.29
ht\mathbf{h}^{t}(0.333, 1.643)
Explicit model: F(h)=12∥v−Wh∥2F(\mathbf{h}) = \tfrac12\lVert\mathbf{v} - \mathbf{W}\mathbf{h}\rVert^2 with fixed nonnegative W∈R3×2\mathbf{W} \in \mathbb{R}^{3\times 2}. Left, in the (h1,h2)(h_1, h_2) plane, the FF contour through the previous iterate (blue) and auxiliary function G(⋅,ht−1)G(\cdot, \mathbf{h}^{t-1}) contour through the same point (magenta): since G≥FG \ge F, the GG ellipse always lies inside the FF ellipse, touching at ht−1\mathbf{h}^{t-1}, and the new iterate is its center. Right, both functions along the step line. Advance tt, drag h0\mathbf{h}^0, compare projected gradient and switch to an optimum at the boundary: what happens to speed when the solution has h2=0h_2 = 0? Finally select 'start with h2=0h_2 = 0'.

Zeros that do not return and convergence

Monotonicity has fine print, shown by the figure’s last two experiments.

  • Zero is absorbing. If ha=0h_a = 0 at any time, multiplication leaves hah_a at 0 forever, even if gradient calls for increase. Multiplicative updates require strictly positive initialization, and initialization matters greatly (measured in the lab).
  • Slow convergence at the boundary. When the optimum has zero coordinates, hah_a approaches 0 by multiplying factors tending to 1, giving slow convergence. This is typical because NMF solutions are sparse.
  • Monotonicity is not convergence. Decreasing FF bounded below guarantees values converge, not that iterates reach a stationary point. Lin (2007) identified this gap and proposed a variant proven to converge to stationary points. In practice small ε\eps are added to denominators (sklearn does this), and faster algorithms are preferred, such as block-column coordinate descent, HALS (Cichocki and Phan, 2009), solver="cd" in sklearn.

Standard initialization is NNDSVD (Boutsidis and Gallopoulos, 2008): take the first kk singular triplets (uj,σj,vj)(\vb{u}_j, \sigma_j, \vb{v}_j) of X\mat{X}; the first in absolute value (by Perron-Frobenius, for X≥0\mat{X} \ge 0 it can be nonnegative), and for each remaining pair retain the positive or sign-flipped negative parts of uj\vb{u}_j and vj\vb{v}_j, whichever has greater ∥u±∥∥v±∥\norm{\vb{u}_\pm}\norm{\vb{v}_\pm}, scaling by σj∥u±∥∥v±∥\sqrt{\sigma_j\norm{\vb{u}_\pm}\norm{\vb{v}_\pm}}. This starts from the best rank-kk approximation but has many exact zeros, lethal to multiplicative updates. NNDSVDa fills them with the mean of X\mat{X}.

Lab: NMF with multiplicative updates

Implement both losses from scratch on the figure’s 500 training digits with k=16k = 16, NNDSVDa initialization and 300 iterations, checking monotonicity every iteration.

[ ]NMF from scratch: Frobenius and generalized KLBrowser
import numpy as np, time
from sklearn.datasets import load_digits

X_all = load_digits().data          # 1797 dígitos de 8x8, niveles de gris 0..16
X = X_all[::2][:500]                # entrenamiento: 500 dígitos de índice par
X_te = X_all[1::2]                  # prueba: los 898 de índice impar
EPS = 1e-10                         # como sklearn: evita 0/0 en los denominadores

def nndsvd(X, k, rellenar=True):
    """NNDSVD (Boutsidis y Gallopoulos, 2008). Con rellenar=True es la variante NNDSVDa."""
    U, s, Vt = np.linalg.svd(X, full_matrices=False)
    W = np.zeros((X.shape[0], k)); H = np.zeros((k, X.shape[1]))
    W[:, 0] = np.sqrt(s[0]) * np.abs(U[:, 0]); H[0] = np.sqrt(s[0]) * np.abs(Vt[0])
    for j in range(1, k):
        u, v = U[:, j], Vt[j]
        partes = [(np.maximum(u, 0), np.maximum(v, 0)), (np.maximum(-u, 0), np.maximum(-v, 0))]
        a, b = max(partes, key=lambda p: np.linalg.norm(p[0]) * np.linalg.norm(p[1]))
        na, nb = np.linalg.norm(a), np.linalg.norm(b)
        W[:, j] = np.sqrt(s[j] * na * nb) * a / na
        H[j] = np.sqrt(s[j] * na * nb) * b / nb
    if rellenar:
        m = X.mean(); W[W == 0] = m; H[H == 0] = m
    return W, H

def kl_gen(X, Y):
    m = X > 0
    return (X[m] * np.log(X[m] / Y[m])).sum() - X.sum() + Y.sum()

def nmf_mu(X, W, H, iters, perdida="fro"):
    W, H = W.copy(), H.copy(); hist = []
    for _ in range(iters):
        if perdida == "fro":
            H *= (W.T @ X) / (W.T @ W @ H + EPS)
            W *= (X @ H.T) / (W @ (H @ H.T) + EPS)
            hist.append(0.5 * ((X - W @ H) ** 2).sum())
        else:
            H *= (W.T @ (X / (W @ H + EPS))) / (W.sum(axis=0)[:, None] + EPS)
            W *= ((X / (W @ H + EPS)) @ H.T) / (H.sum(axis=1)[None, :] + EPS)
            hist.append(kl_gen(X, W @ H))
    return W, H, np.array(hist)

k = 16
W0, H0 = nndsvd(X, k)
W_f, H_f, h_f = nmf_mu(X, W0, H0, 300, "fro")
W_k, H_k, h_k = nmf_mu(X, W0, H0, 300, "kl")
for nombre, h in [("Frobenius", h_f), ("KL generalizada", h_k)]:
    print(f"{nombre:16s} objetivo: {h[0]:9.1f} (it 1) -> {h[49]:9.1f} (it 50) -> {h[-1]:9.1f} (it 300); "
          f"mayor variación relativa entre iteraciones: {np.max(np.diff(h) / h[:-1]):.1e}")
print(f"error relativo de Frobenius: {np.linalg.norm(X - W_f @ H_f) / np.linalg.norm(X):.4f}")

Both curves strictly decrease: the greatest relative change between consecutive iterations is negative in both cases, as guaranteed. Most descent occurs early (Frobenius: 253529.0 after first iteration to 91299.2 after fiftieth, then only to 70890.4 over the next 250), similar to Lee and Seung’s report for faces: the algorithm was “almost converged in less than 50 iterations.” Final relative error ∥X−WH∥F/∥X∥F=0.2705\norm{\mat{X} - \mat{W}\mat{H}}_F/\norm{\mat{X}}_F = 0.2705 makes clear 16 parts cannot reproduce every stroke.

[ ]Parts, absorbing zeros and sklearnBrowser
from sklearn.decomposition import NMF, PCA
from scipy.optimize import nnls

pca = PCA(n_components=k).fit(X)
activos = X.std(axis=0) > 0                      # píxeles que alguna vez cambian
def casi_nulos(M, tol=0.05):
    M = np.abs(M[:, activos]); return (M < tol * M.max(axis=1, keepdims=True)).mean()
print(f"valores casi nulos en los átomos ({activos.sum()} píxeles activos): NMF {casi_nulos(H_f):.0%}, PCA {casi_nulos(pca.components_):.0%}")

W_te = np.array([nnls(H_f.T, x)[0] for x in X_te])              # códigos no negativos con H fija
e_nmf = ((X_te - W_te @ H_f) ** 2).sum(1).mean()
e_pca = ((X_te - pca.inverse_transform(pca.transform(X_te))) ** 2).sum(1).mean()
print(f"prueba (898 dígitos): error medio NMF {e_nmf:.1f}, PCA {e_pca:.1f}; coeficientes nulos NMF {(W_te == 0).mean():.0%}")

W1, H1 = nndsvd(X, k, rellenar=False)                           # NNDSVD sin relleno
z0 = ((W1 == 0).sum() + (H1 == 0).sum()) / (W1.size + H1.size)
W2, H2, h2 = nmf_mu(X, W1, H1, 300, "fro")
z1 = ((W2 == 0).sum() + (H2 == 0).sum()) / (W2.size + H2.size)
siguen = np.all(W2[W1 == 0] == 0) and np.all(H2[H1 == 0] == 0)
print(f"NNDSVD sin relleno: {z0:.1%} de ceros al empezar y {z1:.1%} al acabar; ¿siguen a cero los iniciales? {siguen}")
print(f"objetivo tras 300 iteraciones: NNDSVD {h2[-1]:.1f}, NNDSVDa {h_f[-1]:.1f}")

for solver in ["mu", "cd"]:
    m = NMF(n_components=k, init="nndsvda", solver=solver, max_iter=300, tol=0, random_state=0).fit(X)
    print(f"sklearn solver={solver}: objetivo {0.5 * m.reconstruction_err_ ** 2:.1f}")

Numbers confirm the figure and add practical lessons:

  • Parts and sparsity: 71% of NMF atom values are near zero versus PCA’s 28%; test codes have 38% exact zeros. In exchange, mean test error is 331.1 versus 204.1.
  • Absorbing zero, measured: unfilled NNDSVD starts with 47.4% zero entries, all still zero after 300 iterations. Finally there are even more (47.8%): H\mat{H} entries for pixels always zero in digits vanish on the first update because numerator (W⊤X)aj(\mat{W}\T\mat{X})_{aj} is 0. The objective stalls at 100849.5, 42% above NNDSVDa’s 70890.4. Same algorithm and information; only half the model is frozen from the start.
  • sklearn: solver="mu" reaches 70413.9, practically matching our version (details differ: sklearn uses randomized SVD for initialization and updates W\mat{W} before H\mat{H}). Its solver="cd" reaches 59509.0 with the same 300 iterations: multiplicative updates are historical and easiest to reason about, but not fastest. In practice use cd.

Document topics

For text, each row of X\mat{X} is a document and each column a word, with TF-IDF weights. NMF writes each document as a nonnegative sum of kk topics (rows of H\mat{H}, weights over vocabulary), and each row of W\mat{W} is the document’s topic mixture. SVD of the same matrix is latent semantic analysis, with the usual problem: its “topics” have negative word weights without meaning. The Bayesian probabilistic version with Dirichlet mixtures is latent Dirichlet allocation; NMF with generalized KL is its maximum-likelihood relative (Hofmann’s pLSA).

InteractiveTopics with NMF
Topics: the six most weighted Spanish words in each row of H\mathbf{H} (bars relative to the first)
Tema 1
harina
tomate
horno
receta
aceite
salsa
Tema 2
banco
interés
bolsa
acciones
inflación
sube
Tema 3
galaxia
telescopio
luz
órbita
estrellas
estrella
Tema 4
partido
gol
liga
equipo
último
entrenador
Topic mixture for each sentence (rows of W\mathbf{W} normalized to sum to 1). The left column shows the original topic used to write each sentence (astronomy, cooking, soccer, or finance), hidden from NMF.
Selected sentence: “El club de fútbol sale a bolsa: los inversores compran acciones del equipo para pagar a sus jugadores.” (original topic: soccer + finance).
4
Loss
Relative error ∥X−WH∥F/∥X∥F\lVert\mathbf{X}-\mathbf{W}\mathbf{H}\rVert_F / \lVert\mathbf{X}\rVert_F0.703
TF-IDF matrix22 sentences × 39 words
Selected mixtureT1 0 % · T2 69 % · T3 0 % · T4 31 %
A toy corpus of 22 sentences written for this lesson: 18 from four topics (astronomy, cooking, football and finance) and 4 mixing two. Convert to a TF-IDF matrix like sklearn's TfidfVectorizer (words present in at least 2 sentences) and factorize with NNDSVDa and 400 multiplicative updates. Above: highest-weight words in each topic; below: each sentence's topic mixture. Click the last four sentences and change kk and loss.

With k=4k = 4 and Frobenius, all four topics are clean (their Spanish source words mean flour, tomato, oven; bank, interest, stock market; galaxy, telescope, light; and match, goal, league), and each single-topic sentence puts almost all weight on one. Mixed sentences split: the football club going public is 69% finance and 31% football. With k=2k = 2 topics merge; at k=5k = 5 cooking splits into “bread and oven” versus “tomato sauce”; at k=6k = 6 a “football business” topic appears (Spanish words for players, team, investors, club). There is no true kk: there are granularities, and choosing one is a modeling decision.

Sparse coding

Change the constraint from sign to count. Fix a dictionary D=[d1⋯dK]∈Rd×K\mat{D} = [\vb{d}_1 \cdots \vb{d}_K] \in \R^{d \times K} of unit-norm atoms (in this part atoms are columns, as throughout sparse-coding literature; relative to NMF, D=H⊤\mat{D} = \mat{H}\T and code z\vb{z} of x\vb{x} is a row of W\mat{W}). If K>dK > d, the dictionary is overcomplete: more atoms than dimensions, and Dz=x\mat{D}\vb{z} = \vb{x} has infinitely many solutions, an affine subspace of dimension K−rank⁡D≥K−dK - \rank\mat{D} \ge K - d. To choose one, require few atoms.

What we really want is to minimize atom count ∥z∥0\norm{\vb{z}}_0, but that is generally NP-hard (Natarajan, 1995). Two options: greedy algorithms like OMP (orthogonal matching pursuit: choose the atom most correlated with residual, refit selected atoms by least squares, repeat), or convex ℓ1\ell_1 relaxation, studied here. Its optimality conditions are a rule about correlations with residual r=x−Dz⋆\vb{r} = \vb{x} - \mat{D}\vb{z}^\star:

dj⊤r=λ signo⁡(zj⋆)  if zj⋆≠0,∣dj⊤r∣≤λ  if zj⋆=0.\vb{d}_j\T\vb{r} = \lambda\,\operatorname{signo}(z^\star_j) \ \text{ if } z^\star_j \neq 0, \qquad \abs{\vb{d}_j\T\vb{r}} \le \lambda \ \text{ if } z^\star_j = 0.

An atom activates exactly when its correlation with the unexplained part reaches λ\lambda. In particular, at z=0\vb{z} = \vb{0} the residual is x\vb{x}, so code is zero if and only if λ≥λmax⁡=∥D⊤x∥∞\lambda \ge \lambda_{\max} = \norm{\mat{D}\T\vb{x}}_\infty. Lowering λ\lambda traces the regularization path: the first atom to activate is most correlated with x\vb{x}, and others enter (and sometimes leave) as residual changes.

InteractiveWhich atoms activate
Atoms, target x\mathbf{x}, and reconstruction Dz\mathbf{D}\mathbf{z} (sum of scaled atoms)
  • target x (draggable)
  • Dz
  • zⱼ dⱼ for active atoms
Solution path zj(λ)z_j(\lambda)
Correlation with the residual ∣dj⊤r∣\lvert\mathbf{d}_j^\top\mathbf{r}\rvert versus λ\lambda (line)
d₁0.440d₂0.880d₃0.880
0.550
λ\lambda y λmax⁡=∥D⊤x∥∞\lambda_{\max} = \lVert \mathbf{D}^\top\mathbf{x} \rVert_\infty0.880 / 1.600
z1z_1 (atom d1\mathbf{d}_1)0.000
z2z_2 (atom d2\mathbf{d}_2)0.200
z3z_3 (atom d3\mathbf{d}_3)0.600
Active atomsd₂, d₃
12∥x−Dz∥2\tfrac12\lVert\mathbf{x} - \mathbf{D}\mathbf{z}\rVert^2 and ∥z∥1\lVert\mathbf{z}\rVert_10.4840 | 0.800
An overcomplete dictionary of three atoms in the plane (drag their tips) and target x\mathbf{x} (the draggable blue point). For each λ\lambda lasso is solved exactly. Left: Dz\mathbf{D}\mathbf{z} as a sum of scaled active atoms; top right: path zj(λ)z_j(\lambda) with a line at current λ\lambda; below: correlations ∣dj⊤r∣\lvert\mathbf{d}_j^\top\mathbf{r}\rvert with line at λ\lambda: active ones touch it exactly, inactive ones remain below. Lower λ\lambda from λmax⁡\lambda_{\max} and observe activation order; then disable normalization and lengthen an atom.

Initially D⊤x=(0.6,1.44,1.6)\mat{D}\T\vb{x} = (0.6, 1.44, 1.6): first atom to activate is d3\vb{d}_3 at λ=1.6\lambda = 1.6, next d2\vb{d}_2, its directional neighbor. As λ→0\lambda \to 0, code tends to the exact minimum-ℓ1\ell_1-norm solution, here using d2\vb{d}_2 and d3\vb{d}_3 (x=0.75 d2+1.15 d3\vb{x} = 0.75\,\vb{d}_2 + 1.15\,\vb{d}_3, norm 1.9) rather than d1\vb{d}_1 and d3\vb{d}_3 (norm 2.2): ℓ1\ell_1 favors atoms “surrounding” x\vb{x}. Although the exact system has infinitely many solutions, lasso has one: if columns of D\mat{D} are in general position (no affine subspace of dimension m<dm < d contains more than m+1m + 1 of vectors ±dj\pm\vb{d}_j, almost surely true for continuously distributed atoms), the solution is unique for every λ>0\lambda > 0 and uses at most dd atoms (Tibshirani, 2013).

The figure also shows the danger of not normalizing atoms. If ∥dj∥=c\norm{\vb{d}_j} = c, writing zjdj=(czj)(dj/c)z_j\vb{d}_j = (c z_j)(\vb{d}_j/c) shows effective penalty on the unit atom is λ/c\lambda/c: long atoms are cheap and activate earlier due to size rather than resemblance. One λ\lambda means the same for all atoms only when norms match.

ISTA and FISTA

Lasso sums smooth f(z)=12∥x−Dz∥2f(\vb{z}) = \frac12\norm{\vb{x} - \mat{D}\vb{z}}^2, whose gradient D⊤(Dz−x)\mat{D}\T(\mat{D}\vb{z} - \vb{x}) is Lipschitz with constant L=∥D∥22=λmax⁡(D⊤D)L = \norm{\mat{D}}_2^2 = \lambda_{\max}(\mat{D}\T\mat{D}), and nonsmooth but separable λ∥z∥1\lambda\norm{\vb{z}}_1. This is the case for which proximal gradient was invented: a gradient step on ff followed by the proximal of λL∥⋅∥1\frac{\lambda}{L}\norm{\cdot}_1, componentwise soft thresholding,

Sτ(u)=signo⁡(u)max⁡(∣u∣−τ,0),zt+1=Sλ/L(zt−1LD⊤(Dzt−x)).S_\tau(u) = \operatorname{signo}(u)\max(\abs{u} - \tau, 0), \qquad \vb{z}^{t+1} = S_{\lambda/L}\Big(\vb{z}^t - \tfrac1L\mat{D}\T(\mat{D}\vb{z}^t - \vb{x})\Big).

This is ISTA (iterative shrinkage-thresholding algorithm; Daubechies, Defrise and De Mol, 2004). Thresholding does two things: shrink large coefficients toward zero (costing λ\lambda per unit) and set those below λ/L\lambda/L exactly to zero. The result is truly sparse: each iteration a coefficient survives only if its residual correlation on the step scale compensates its penalty. ISTA guarantees F(zt)−F⋆≤L∥z0−z⋆∥2/(2t)F(\vb{z}^t) - F^\star \le L\norm{\vb{z}^0 - \vb{z}^\star}^2/(2t); accelerated FISTA (Beck and Teboulle, 2009), extrapolating with Nesterov momentum, gives 2L∥z0−z⋆∥2/(t+1)22L\norm{\vb{z}^0 - \vb{z}^\star}^2/(t+1)^2.

[ ]ISTA and FISTA on an overcomplete dictionaryBrowser
import numpy as np
from sklearn.linear_model import Lasso

rng = np.random.default_rng(0)
d, K = 64, 128                                   # diccionario 2 veces sobrecompleto
D = rng.standard_normal((d, K)); D /= np.linalg.norm(D, axis=0)
z_true = np.zeros(K); sop = rng.choice(K, 6, replace=False); z_true[sop] = 2 * rng.standard_normal(6)
x = D @ z_true + 0.05 * rng.standard_normal(d)

def soft(v, t):
    return np.sign(v) * np.maximum(np.abs(v) - t, 0.0)

def ista(D, x, lam, n_iter, acelerar=False):
    L = np.linalg.norm(D, 2) ** 2                # constante de Lipschitz del gradiente
    z = np.zeros(D.shape[1]); y = z.copy(); t = 1.0; hist = []
    for _ in range(n_iter):
        z_new = soft(y - D.T @ (D @ y - x) / L, lam / L)
        if acelerar:                             # FISTA: extrapolación de Nesterov
            t_new = (1 + np.sqrt(1 + 4 * t * t)) / 2
            y = z_new + (t - 1) / t_new * (z_new - z); t = t_new
        else:
            y = z_new
        z = z_new
        hist.append(0.5 * np.sum((x - D @ z) ** 2) + lam * np.abs(z).sum())
    return z, np.array(hist)

lam_max = np.abs(D.T @ x).max()
lam = 0.05 * lam_max
z_ref, h_ref = ista(D, x, lam, 4000, acelerar=True)
F_ref = h_ref[-1]
_, h_i = ista(D, x, lam, 1000)
_, h_f = ista(D, x, lam, 1000, acelerar=True)
print(f"lambda_max = {lam_max:.3f}, lambda = {lam:.4f}, L = {np.linalg.norm(D, 2) ** 2:.2f}")
for tol in [1e-2, 1e-4, 1e-6]:
    it_i = np.argmax((h_i - F_ref) / F_ref < tol) + 1
    it_f = np.argmax((h_f - F_ref) / F_ref < tol) + 1
    print(f"error relativo del objetivo < {tol:.0e}: ISTA en {it_i} iteraciones, FISTA en {it_f}")
ref = Lasso(alpha=lam / d, fit_intercept=False, tol=1e-12, max_iter=100000).fit(D, x).coef_
print(f"máx |z_FISTA - z_sklearn| = {np.abs(z_ref - ref).max():.1e}")
print(f"no nulos: {np.count_nonzero(z_ref)} de {K}; soporte verdadero recuperado: {np.isin(sop, np.flatnonzero(z_ref)).sum()} de 6")

FISTA reaches 1% of optimum in 18 iterations versus ISTA’s 54, and 10−610^{-6} in 65 versus 103. The advantage narrows at the end for a concrete reason: once support is identified, the problem restricted to those 8 coordinates is strongly convex and ISTA converges linearly, faster than its O(1/t)\bigO(1/t) bound. The solution matches sklearn to 10−1210^{-12}, with necessary rescaling: Lasso minimizes 12n∥y−Xw∥2+α∥w∥1\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{w}}^2 + \alpha\norm{\vb{w}}_1 with nn rows (here d=64d = 64), so our λ\lambda corresponds to α=λ/d\alpha = \lambda/d. The code uses 8 of 128 atoms and contains all 6 support atoms used to generate x\vb{x}.

Learning the dictionary

So far the dictionary was given. The interesting part is learning it from data, as NMF learns parts.

Constraint C\mathcal{C} is not decorative. Without it, (D,zi)↦(cD,zi/c)(\mat{D}, \vb{z}_i) \mapsto (c\mat{D}, \vb{z}_i/c) leaves reconstruction unchanged and divides penalty by cc: as c→∞c \to \infty the objective approaches pure least squares and sparsity disappears. This is the same scaling ambiguity as NMF, lethal here. With the constraint, used atoms end at norm exactly 1 (if smaller, lengthening them and shrinking coefficients lowers penalty).

The problem is not jointly convex in (D,Z)(\mat{D}, \mat{Z}) but is in each block, suggesting alternation:

  1. Codes with fixed D\mat{D}: nn independent lassos, via ISTA or FISTA.
  2. Dictionary with fixed codes: norm-constrained least squares, via columnwise block coordinate descent.

Step 2 has a columnwise closed form. With A=∑izizi⊤\mat{A} = \sum_i\vb{z}_i\vb{z}_i\T and B=∑ixizi⊤\mat{B} = \sum_i\vb{x}_i\vb{z}_i\T, the objective part depending on dj\vb{d}_j (other columns fixed) is

∑i12∥xi−∑l≠jdlzil−djzij∥2=Ajj2∥dj−uj∥2+const,uj=dj+bj−DajAjj,\sum_i \tfrac12\Big\lVert\vb{x}_i - \sum_{l\neq j}\vb{d}_l z_{il} - \vb{d}_j z_{ij}\Big\rVert^2 = \tfrac{A_{jj}}{2}\norm{\vb{d}_j - \vb{u}_j}^2 + \text{const}, \qquad \vb{u}_j = \vb{d}_j + \frac{\vb{b}_j - \mat{D}\vb{a}_j}{A_{jj}},

where aj\vb{a}_j and bj\vb{b}_j are columns jj of A\mat{A} and B\mat{B}. Since the quadratic is isotropic, the unit-ball minimizer is the projection of uj\vb{u}_j: dj←uj/max⁡(1,∥uj∥)\vb{d}_j \leftarrow \vb{u}_j/\max(1, \norm{\vb{u}_j}). Each alternating step cannot increase the objective; as in NMF, values converge and the result depends on initialization. Step 2 needs only A\mat{A} (K×KK \times K) and B\mat{B} (d×Kd \times K), not data: key to the online method.

K-SVD: k-means with multiple atoms

Aharon, Elad and Bruckstein (2006) tackle the ℓ0\ell_0 version: min⁡∑i∥xi−Dzi∥2\min\sum_i\norm{\vb{x}_i - \mat{D}\vb{z}_i}^2 with ∥zi∥0≤T\norm{\vb{z}_i}_0 \le T. Codes use OMP. The dictionary updates atom by atom, with the trick of updating both atom and coefficients together. For atom jj, take only examples using it, ωj={i:zij≠0}\omega_j = \{i : z_{ij} \neq 0\}, and residual without dj\vb{d}_j‘s contribution, matrix Ej\mat{E}_j with rows xi−∑l≠jzildl\vb{x}_i - \sum_{l \neq j}z_{il}\vb{d}_l for i∈ωji \in \omega_j. The best pair (dj,coefficients)(\vb{d}_j, \text{coefficients}) is Ej\mat{E}_j‘s best rank-1 approximation from SVD: dj\vb{d}_j is its first right singular vector and new coefficients σ1\sigma_1 times the first left one. Restricting to ωj\omega_j preserves code support and hence constraint ∥zi∥0≤T\norm{\vb{z}_i}_0 \le T.

The name comes from k-means. If each code uses one atom with coefficient exactly 1 (zi=ec(i)\vb{z}_i = \vb{e}_{c(i)}), the objective is ∑i∥xi−dc(i)∥2\sum_i\norm{\vb{x}_i - \vb{d}_{c(i)}}^2: coding assigns each point to its nearest atom, and updating each atom averages its points. This is Lloyd’s algorithm, generalized by K-SVD with KK SVD updates instead of KK means. Between lies one atom with free coefficient, “gain-shape” quantization, where each atom is the best line through the origin for its points.

Online dictionary learning

Alternating over all data is infeasible with millions of patches. Mairal, Bach, Ponce and Sapiro (2010) observed step 2 needs only statistics A\mat{A} and B\mat{B}, accumulable one at a time. Their algorithm, for t=1,2,…t = 1, 2, \dots:

  1. Take an example (or minibatch) xt\vb{x}_t and calculate code zt\vb{z}_t with current dictionary Dt−1\mat{D}_{t-1}.
  2. Accumulate At=At−1+ztzt⊤\mat{A}_t = \mat{A}_{t-1} + \vb{z}_t\vb{z}_t\T and Bt=Bt−1+xtzt⊤\mat{B}_t = \mat{B}_{t-1} + \vb{x}_t\vb{z}_t\T.
  3. Update Dt\mat{D}_t using one or a few block-descent passes initialized from Dt−1\mat{D}_{t-1}.

Step 3 minimizes surrogate g^t(D)=1t∑s≤t(12∥xs−Dzs∥2+λ∥zs∥1)\hat{g}_t(\mat{D}) = \frac1t\sum_{s \le t}\big(\frac12\norm{\vb{x}_s - \mat{D}\vb{z}_s}^2 + \lambda\norm{\vb{z}_s}_1\big), with old codes frozen. Since those codes need not be optimal for new D\mat{D}, g^t\hat{g}_t lies above empirical cost with optimal codes: another majorization, now stochastic. Under technical assumptions (bounded data, unique lasso solution, curvature of g^t\hat{g}_t bounded below), they prove the dictionary converges almost surely to a stationary point of expected cost, scaling to millions of examples with O(dK+K2)\bigO(dK + K^2) memory. This is implemented by sklearn.decomposition.MiniBatchDictionaryLearning.

InteractiveEdge detectors emerge
The 36 atoms of D\mathbf{D} (8×8) after 0 patches
Source image for the patches
Initial state: normalized Gaussian noise
Mean cost on held-out patches versus patches seen (log scale)
0 patches seen
Penalty λ\lambda
Patches seen0
Mean cost 12∥x−Dz∥2+λ∥z∥1\tfrac12\lVert\mathbf{x}-\mathbf{D}\mathbf{z}\rVert^2 + \lambda\lVert\mathbf{z}\rVert_1 (100 held-out patches)n/a
Active atoms per patch (mean across 36)n/a
Computation-2 %
Online learning of 36 atoms from 8×88\times 8 patches of a photo (scikit-learn's china.jpg, grayscale and reduced by 3), subtracting each patch mean, with λ=1.5\lambda = 1.5 and minibatches of 32 patches. The dictionary starts from Gaussian noise (small grid) and everything runs in your browser: open the figure to see live learning up to 19,200 patches, then replay step by step. In the first minibatches atoms stop being noise; after a few thousand patches they become edges, bars and corners at different orientations. Change λ\lambda and compare how many atoms each patch uses.

Held-out patch cost drops mostly in the first few hundred patches, followed by slow fine-tuning: typical stochastic behavior. What is striking is atom shape. Nobody told the algorithm to seek edges: we asked for reconstruction with few atoms, and in natural images the most repeated features at this scale are transitions between smooth regions at different orientations. This is a small-scale version of Olshausen and Field’s result. Our atoms resemble Gabor filters less than classic basis functions because the image was not whitened: smooth brightness variations, holding most natural-image variance, still weigh heavily. Whitening, common in this literature, attenuates them and emphasizes high frequencies.

Lab: sparse coding and dictionaries from scratch

Now by hand with separated data: learn a dictionary from patches in the first 140 image columns, measure on patches from the remaining 73, and finally denoise a crop of that unseen region.

[ ]Block dictionary learning on patchesBrowser
import numpy as np
from PIL import Image                                    # load_sample_image necesita Pillow para leer el jpg
from sklearn.datasets import load_sample_image
from numpy.lib.stride_tricks import sliding_window_view

g = load_sample_image("china.jpg").astype(float).mean(axis=2)
g = g[: g.shape[0] // 3 * 3, : g.shape[1] // 3 * 3]
img = g.reshape(g.shape[0] // 3, 3, g.shape[1] // 3, 3).mean(axis=(1, 3)) / 255   # 142 x 213, como en la figura
p = 8
def parches(region):
    P = sliding_window_view(region, (p, p)).reshape(-1, p * p)
    return P - P.mean(axis=1, keepdims=True)            # sin el brillo medio de cada parche
X_tr = parches(img[:, :140]); s = X_tr.std(); X_tr /= s   # entrenamiento: columnas 0 a 139
X_val = parches(img[:, 140:]) / s                        # validación: columnas 140 a 212
X_val = X_val[np.random.default_rng(1).integers(0, len(X_val), 500)]
print(f"{len(X_tr)} parches de entrenamiento; escala s = {s:.4f}")

def codigos(D, X, lam, n_iter=40):
    """FISTA por lotes: X tiene un ejemplo por fila; devuelve Z (n x K)."""
    G = D.T @ D; L = np.linalg.eigvalsh(G)[-1]; DX = X @ D
    Z = np.zeros((len(X), D.shape[1])); Y = Z.copy(); t = 1.0
    for _ in range(n_iter):
        Zn = Y - (Y @ G - DX) / L
        Zn = np.sign(Zn) * np.maximum(np.abs(Zn) - lam / L, 0.0)
        tn = (1 + np.sqrt(1 + 4 * t * t)) / 2
        Y = Zn + (t - 1) / tn * (Zn - Z); Z, t = Zn, tn
    return Z

def coste(D, X, lam):
    Z = codigos(D, X, lam, 100)
    return 0.5 * ((X - Z @ D.T) ** 2).sum(1).mean() + lam * np.abs(Z).sum(1).mean(), (Z != 0).sum(1).mean()

def aprender(X, K, lam, n_lotes, lote, semilla=0):
    g = np.random.default_rng(semilla)
    D = g.standard_normal((X.shape[1], K)); D /= np.linalg.norm(D, axis=0)
    A = np.zeros((K, K)); B = np.zeros((X.shape[1], K))
    for _ in range(n_lotes):
        Xb = X[g.integers(0, len(X), lote)]
        Z = codigos(D, Xb, lam)
        A += Z.T @ Z; B += Xb.T @ Z                         # estadísticos acumulados
        for j in range(K):                                  # una pasada por bloques sobre las columnas
            if A[j, j] < 1e-10: continue
            u = D[:, j] + (B[:, j] - D @ A[:, j]) / A[j, j]
            D[:, j] = u / max(1.0, np.linalg.norm(u))
    return D

lam = 1.5
D0 = np.random.default_rng(0).standard_normal((64, 36)); D0 /= np.linalg.norm(D0, axis=0)
D = aprender(X_tr, 36, lam, 400, 64)
print("validación, diccionario aleatorio:  coste %.2f, %.2f átomos por parche" % coste(D0, X_val, lam))
print("validación, tras 400 lotes de 64:   coste %.2f, %.2f átomos por parche" % coste(D, X_val, lam))

On unseen validation patches, cost falls from 17.76 with the initial random dictionary to 12.15 after 25,600 patches, with similar atom count per patch (2.38 versus 2.62). With the same sparsity budget, the learned dictionary explains substantially more of each patch. The real test is to use it.

[ ]The same problem with sklearnBrowser
from sklearn.decomposition import MiniBatchDictionaryLearning

sk = MiniBatchDictionaryLearning(n_components=36, alpha=lam, batch_size=64, max_iter=1,
                                 fit_algorithm="cd", random_state=0).fit(X_tr)
D_sk = sk.components_.T                                        # sklearn guarda los átomos por filas
print("validación, diccionario de sklearn: coste %.2f, %.2f átomos por parche" % coste(D_sk, X_val, lam))
[ ]Denoising with the dictionaryBrowser
def psnr(a, b):
    return 10 * np.log10(1.0 / np.mean((a - b) ** 2))

def limpiar(ruidosa, D, lam):
    P = sliding_window_view(ruidosa, (p, p))                   # todos los parches solapados
    h, w = P.shape[:2]; P = P.reshape(-1, p * p)
    m = P.mean(axis=1, keepdims=True)
    R = (codigos(D, (P - m) / s, lam, 60) @ D.T) * s + m       # cada parche, con pocos átomos
    out = np.zeros_like(ruidosa); cnt = np.zeros_like(ruidosa)
    for a in range(p):                                         # suma cada píxel de cada parche en su sitio
        for b in range(p):
            out[a:a + h, b:b + w] += R[:, a * p + b].reshape(h, w); cnt[a:a + h, b:b + w] += 1
    return out / cnt                                           # promedio de los parches solapados

limpia = img[40:104, 145:209]                                  # 64 x 64 de la zona no vista
ruidosa = limpia + 0.1 * np.random.default_rng(5).standard_normal(limpia.shape)
print(f"ruidosa: PSNR = {psnr(ruidosa, limpia):.2f} dB")
for lam_d in [0.5, 1.0, 2.0]:
    r = [psnr(limpiar(ruidosa, M, lam_d), limpia) for M in (D, D_sk, D0)]
    print(f"lambda = {lam_d}: nuestro D {r[0]:.2f} dB, sklearn {r[1]:.2f} dB, aleatorio {r[2]:.2f} dB")

Gaussian noise with standard deviation 0.1 leaves the crop at 20.01 dB PSNR. Reconstructing overlapping patches with few atoms and averaging raises this to about 25 dB with the learned dictionary, over a decibel above the random dictionary at each one’s best λ\lambda. The sklearn dictionary, fitted with the same α=λ\alpha = \lambda (its per-example objective matches ours) and one data pass, essentially ties ours in validation cost and PSNR. Good denoising λ\lambda is lower than training’s and depends on noise level; here we choose it by inspecting the clean image, legitimate only for demonstration.

Sparse PCA

PCA has the same readability problem as with faces, but in variables: each component combines all original variables, and with hundreds of genes, risk factors or sensors a 0.03 loading on each says nothing. Sparse PCA seeks components explaining nearly as much variance as PCA but with many exactly zero loadings. Several formulations exist:

  • SCoTLASS (Jolliffe, Trendafilov and Uddin, 2003): max⁡vv⊤Sv\max_{\vb{v}}\vb{v}\T\mat{S}\vb{v} with ∥v∥2=1\norm{\vb{v}}_2 = 1 and ∥v∥1≤t\norm{\vb{v}}_1 \le t. Direct but nonconvex and hard to optimize.
  • Zou, Hastie and Tibshirani (2006) rewrite PCA as regression: with A⊤A=Ik\mat{A}\T\mat{A} = \mat{I}_k, minimize ∑i∥xi−AB⊤xi∥2+λ∑j∥βj∥2+∑jλ1,j∥βj∥1\sum_i\norm{\vb{x}_i - \mat{A}\mat{B}\T\vb{x}_i}^2 + \lambda\sum_j\norm{\vb{\beta}_j}^2 + \sum_j\lambda_{1,j}\norm{\vb{\beta}_j}_1. Without the ℓ1\ell_1 penalty, columns of B\mat{B} are proportional to principal components for any λ>0\lambda > 0; with it, the B\mat{B} problem is elastic net and loadings βj/∥βj∥\vb{\beta}_j/\norm{\vb{\beta}_j} become sparse. Alternate B\mat{B} (elastic nets) and A\mat{A} (an SVD-solvable Procrustes problem).
  • As dictionary learning with roles reversed. sklearn.decomposition.SparsePCA solves min⁡12∥X−UV∥F2+α∥V∥1,1\min\frac12\norm{\mat{X} - \mat{U}\mat{V}}_F^2 + \alpha\norm{\mat{V}}_{1,1} with U\mat{U} columns of norm ≤1\le 1: sparsity lies in atoms (rows of V\mat{V}, loadings), not codes. This is the starting table’s symmetry.

There is a price: sparse components are no longer orthogonal nor their scores uncorrelated, so “explained” variance cannot be added componentwise without double-counting overlap. Zou, Hastie and Tibshirani propose adjusted variance: QR-decompose scores XV⊤=QR\mat{X}\mat{V}\T = \mat{Q}\mat{R} and sum Rjj2R_{jj}^2, variance each component contributes after removing what predecessors explain.

[ ]Sparse PCA on a three-factor modelBrowser
import numpy as np
from sklearn.decomposition import PCA, SparsePCA

g = np.random.default_rng(0)
n = 400
V1 = g.normal(0, np.sqrt(290), n); V2 = g.normal(0, np.sqrt(300), n)
V3 = -0.3 * V1 + 0.925 * V2 + g.normal(0, 1, n)          # tercer factor, mezcla de los otros dos
F = np.column_stack([V1] * 4 + [V2] * 4 + [V3] * 2)        # X1..X4 miden V1, X5..X8 V2, X9 y X10 V3
Xf = F + g.normal(0, 1, F.shape); Xf -= Xf.mean(axis=0)
np.set_printoptions(precision=2, suppress=True, linewidth=110)

def var_ajustada(C):
    R = np.linalg.qr(Xf @ C.T)[1]
    return (np.diag(R) ** 2).sum() / (Xf ** 2).sum()

pca = PCA(2).fit(Xf)
print("PCA, cargas:"); print(pca.components_)
print(f"varianza explicada: {var_ajustada(pca.components_):.4f}")
for a in [1, 50]:
    sp = SparsePCA(n_components=2, alpha=a, ridge_alpha=0.01, random_state=0, max_iter=200).fit(Xf)
    C = sp.components_ / np.linalg.norm(sp.components_, axis=1, keepdims=True)
    print(f"SparsePCA alpha = {a}, cargas:"); print(C)
    print(f"cargas exactamente nulas por componente: {(C == 0).sum(axis=1)}; varianza ajustada: {var_ajustada(C):.4f}")

The model is explicit: four variables measure factor V1V_1, another four factor V2V_2, and two a third factor mixing the first two. PCA gives two almost readable components, but with small loadings everywhere (second has 0.06 on V2V_2 variables and −0.09-0.09 and −0.1-0.1 on V3V_3). Sparse PCA at α=1\alpha = 1 reduces cross-loadings below 0.005 in absolute value (4 exactly zero); at α=50\alpha = 50 all vanish, 4 per component: first uses only X5,…,X10X_5, \dots, X_{10} and second is nearly clean on X1,…,X4X_1, \dots, X_4, with residual −0.05-0.05 on V3V_3 variables sharing information with V1V_1. Adjusted variance falls from 0.9968 to 0.9918 and 0.9908: less than one percentage point for self-explanatory components.

Three bases for the same data

PCANMFSparse dictionary
Atomsorthonormal, global, signednonnegative, localizedunit norm, any sign, often overcomplete
Codesdense, signednonnegative, naturally sparsesparse through penalty
Reconstruction with fixed kkbest possible (Eckart-Young)worse (digits: 331.1 versus 204.1)depends on λ\lambda; with K>dK > d each example selects its own atoms, unlike a fixed basis
Uniquenessup to signs with distinct eigenvaluesalmost never; always permutation and scaleno; local minima and permutations
Computationone global SVDnonconvex, NP-hard; local methodsnonconvex; alternating or online
Interpretabilitylow in data with partshigh if data sum partshigh for signals: edges, topics, features

From visual cortex to LLMs

This lesson’s story begins in neuroscience. Olshausen and Field asked why V1 simple cells respond to localized oriented edges. Their answer: that basis describes natural images with few neurons active at once. One year later Bell and Sejnowski (1997) obtained similar edge filters by maximizing output independence with the previous lesson’s Infomax ICA: on natural images, independence and sparsity lead to nearby places.

Almost thirty years later the same idea is used to read neural networks. The superposition hypothesis proposes that a layer of dd neurons represents many more than dd features, each as a direction, exploiting few active at once. Individual neurons would then be unreadable mixtures, and recovery requires an overcomplete dictionary of directions with sparse codes: this lesson’s problem. Sparse autoencoders solve it in a particular form:

f(x)=ReLU⁡(We(x−bd)+be),x^=Wdf(x)+bd,L=∥x−x^∥2+λ∥f(x)∥1.\vb{f}(\vb{x}) = \relu\big(\mat{W}_e(\vb{x} - \vb{b}_d) + \vb{b}_e\big), \qquad \hat{\vb{x}} = \mat{W}_d\vb{f}(\vb{x}) + \vb{b}_d, \qquad \Loss = \norm{\vb{x} - \hat{\vb{x}}}^2 + \lambda\norm{\vb{f}(\vb{x})}_1.

Columns of Wd\mat{W}_d are dictionary atoms (normalized for the same scale reason), f(x)\vb{f}(\vb{x}) is the code, and loss is dictionary learning with nonnegative codes. The only difference is how code is obtained: instead of solving lasso for each x\vb{x}, a one-layer encoder predicts it (amortized inference). The link is literal: one ISTA step from z=0\vb{z} = \vb{0} with nonnegative codes is max⁡(0,D⊤x/L−λ/L)\max(0, \mat{D}\T\vb{x}/L - \lambda/L), a linear layer followed by ReLU with negative bias and weights tied to the dictionary. Gregor and LeCun (2010) pushed this with LISTA, unrolling a few ISTA iterations and training their matrices.

The next cell measures gains and losses. It generates synthetic activations with superposition (32 features in 16 dimensions, 3 active per example, positive coefficients), learns the dictionary with the lab’s aprender function, and compares FISTA codes with a one-step encoder.

[ ]Toy superposition: recovering featuresBrowser
g = np.random.default_rng(3)
d_a, K_a = 16, 32                                   # 32 características en 16 dimensiones
D_v = g.standard_normal((d_a, K_a)); D_v /= np.linalg.norm(D_v, axis=0)
def activaciones(n):
    Z = np.zeros((n, K_a))
    for i in range(n):
        Z[i, g.choice(K_a, 3, replace=False)] = g.uniform(0.5, 2.0, 3)   # 3 activas, positivas
    return Z @ D_v.T + 0.01 * g.standard_normal((n, d_a)), Z

X_a, _ = activaciones(10000)
D_a = aprender(X_a, K_a, 0.5, 300, 64, semilla=1)
mejor = np.abs(D_v.T @ D_a).max(axis=1)              # mejor |coseno| de cada característica verdadera
print(f"características recuperadas (|cos| > 0.9): {(mejor > 0.9).sum()} de {K_a}; mediana del mejor |cos|: {np.median(mejor):.3f}")
print(f"coherencia del diccionario verdadero (máx |cos| entre átomos): {np.abs(D_v.T @ D_v - np.eye(K_a)).max():.2f}")

X_p, Z_p = activaciones(2000)
def f1(Z):
    a, b = Z > 1e-6, Z_p > 0
    pr, re = (a & b).sum() / max(a.sum(), 1), (a & b).sum() / b.sum()
    return 2 * pr * re / (pr + re)
print(f"F1 del soporte con el diccionario verdadero: FISTA {f1(codigos(D_v, X_p, 0.1, 200)):.3f}")
for b in [0.0, 0.3, 0.6]:
    print(f"  un paso, ReLU(D^T x - {b}): {f1(np.maximum(X_p @ D_v - b, 0)):.3f}")

With 10,000 examples and 300 minibatches, online learning recovers 28 of 32 true directions with cosine above 0.9 (median best cosine 0.977), despite twice as many features as dimensions and true atom pairs with cosine 0.67. But the one-step tied-weight encoder identifies active features much worse: with the true dictionary, support F1 is 0.914 for FISTA and 0.27–0.48 for one step depending on threshold. In superposition, D⊤x\mat{D}\T\vb{x} mixes correlations of active features with neighbors; only iteration (subtracting what is already explained) separates them. This is the amortization gap. Sparse autoencoders reduce it by training encoder separately from decoder, but do not eliminate it entirely, one reason interpretability research explores more elaborate encoders.

Real scale is enormous. Bricken et al. (2023) trained sparse autoencoders on activations of a 512-neuron MLP layer in a one-layer transformer, using 8000 million activation vectors and dictionaries of 512 to 131,072 features (1 to 256 times neuron count). Their detailed analysis focuses on one 4096-feature run and concludes features are much more interpretable than neurons: many respond to one concept, such as one activating on Arabic-script text. You will revisit them in mechanistic interpretability.

Common mistakes

Exercises

ProofThe multiplicative update does not increase the objective
Prove: Let W∈R≥0n×k\mathbf{W} \in \mathbb{R}_{\ge 0}^{n \times k}, v∈R≥0n\mathbf{v} \in \mathbb{R}_{\ge 0}^{n}, F(h)=12∥v−Wh∥2F(\mathbf{h}) = \tfrac12\lVert\mathbf{v} - \mathbf{W}\mathbf{h}\rVert^2 and ht>0\mathbf{h}^t > 0 with (W⊤Wht)a>0(\mathbf{W}^\top\mathbf{W}\mathbf{h}^t)_a > 0 for all aa. Then hat+1=hat(W⊤v)a/(W⊤Wht)ah^{t+1}_a = h^t_a(\mathbf{W}^\top\mathbf{v})_a/(\mathbf{W}^\top\mathbf{W}\mathbf{h}^t)_a satisfies F(ht+1)≤F(ht)F(\mathbf{h}^{t+1}) \le F(\mathbf{h}^t).
0
Define K=diag⁡((W⊤Wht)a/hat)\mathbf{K} = \operatorname{diag}\big((\mathbf{W}^\top\mathbf{W}\mathbf{h}^t)_a/h^t_a\big) and G(h)=F(ht)+(h−ht)⊤∇F(ht)+12(h−ht)⊤K(h−ht)G(\mathbf{h}) = F(\mathbf{h}^t) + (\mathbf{h} - \mathbf{h}^t)^\top\nabla F(\mathbf{h}^t) + \tfrac12(\mathbf{h} - \mathbf{h}^t)^\top\mathbf{K}(\mathbf{h} - \mathbf{h}^t). Show that GG is auxiliary and the update minimizes it.

Step 1 of 4. G(ht)=F(ht)G(\vb{h}^t) = F(\vb{h}^t) is immediate. Why does K−W⊤W⪰0\mat{K} - \mat{W}\T\mat{W} \succeq 0 suffice for G≥FG \ge F?

NumericSoft thresholding
Calculate soft threshold Sλ(x)S_\lambda(x) for x=0.7x = 0.7 and λ=0.3\lambda = 0.3.
NumericWhen does everything switch off?
With atoms d1=(1,0)\mathbf{d}_1 = (1, 0), d2=(0,1)\mathbf{d}_2 = (0, 1) and d3=(0.6,0.8)\mathbf{d}_3 = (0.6, 0.8) and target x=(1,2)\mathbf{x} = (1, 2), what is the smallest λ\lambda at which lasso code arg⁡min⁡z12∥x−Dz∥2+λ∥z∥1\arg\min_{\mathbf{z}} \tfrac12\lVert\mathbf{x} - \mathbf{D}\mathbf{z}\rVert^2 + \lambda\lVert\mathbf{z}\rVert_1 is zero?
NumericA multiplicative step by hand
With W=[1011]\mathbf{W} = \begin{bmatrix} 1 & 0 \\ 1 & 1 \end{bmatrix}, v=(1,3)\mathbf{v} = (1, 3) and ht=(1,1)\mathbf{h}^t = (1, 1), calculate first coordinate h1t+1h^{t+1}_1 after a Frobenius multiplicative update.
CodeISTA from scratch
Implement ista(D, x, lam, n_iter) approximating arg⁡min⁡z12∥x−Dz∥2+λ∥z∥1\arg\min_{\mathbf{z}}\tfrac12\lVert\mathbf{x} - \mathbf{D}\mathbf{z}\rVert^2 + \lambda\lVert\mathbf{z}\rVert_1 using n_iter ISTA iterations from z=0\mathbf{z} = \mathbf{0} with step 1/L1/L, where L=∥D∥22L = \lVert\mathbf{D}\rVert_2^2. Columns of D need not have unit norm. Tests compare with sklearn.linear_model.Lasso(fit_intercept=False), whose objective is 12n∥y−Xw∥2+α∥w∥1\tfrac{1}{2n}\lVert\mathbf{y} - \mathbf{X}\mathbf{w}\rVert^2 + \alpha\lVert\mathbf{w}\rVert_1 with nn rows: work out which α\alpha corresponds to your λ\lambda if testing independently.
import numpy as np

def ista(D, x, lam, n_iter):
  """ISTA para 0.5 |x - D z|^2 + lam |z|_1, desde z = 0, con paso 1/L."""
  D = np.asarray(D, dtype=float)
  x = np.asarray(x, dtype=float)
  z = np.zeros(D.shape[1])
  # tu código: calcula L, y en cada iteración un paso de gradiente sobre la parte suave
  # seguido de la umbralización suave con el umbral adecuado
  return z
Shift+Enter to run
QuizWell-defined codes
With an overcomplete dictionary D∈Rd×K\mathbf{D} \in \mathbb{R}^{d \times K}, K>dK > d, of rank dd, why is a sparsity penalty needed for the code of x\mathbf{x} to be well-defined?
QuizK-SVD with one atom
In K-SVD, what happens if each code can use only one atom with coefficient exactly 1?
QuizWhat leaves the product unchanged
Let X=WH\mathbf{X} = \mathbf{W}\mathbf{H} with W,H≥0\mathbf{W}, \mathbf{H} \ge 0 and k=3k = 3. Which pairs (W′,H′)(\mathbf{W}', \mathbf{H}') are always, for any W,H≥0\mathbf{W}, \mathbf{H} \ge 0, another exact nonnegative factorization of X\mathbf{X}?

More than one answer may be correct.

QuizA sparse autoencoder as a dictionary
In sparse autoencoder f(x)=ReLU⁡(We(x−bd)+be)\mathbf{f}(\mathbf{x}) = \operatorname{ReLU}(\mathbf{W}_e(\mathbf{x} - \mathbf{b}_d) + \mathbf{b}_e), x^=Wdf(x)+bd\hat{\mathbf{x}} = \mathbf{W}_d\mathbf{f}(\mathbf{x}) + \mathbf{b}_d, trained with ∥x−x^∥2+λ∥f(x)∥1\lVert\mathbf{x} - \hat{\mathbf{x}}\rVert^2 + \lambda\lVert\mathbf{f}(\mathbf{x})\rVert_1, which statement is correct?

Summary

Key idea
Many useful representations factor X≈WH\mathbf{X} \approx \mathbf{W}\mathbf{H}, trading PCA freedom for a readable constraint: nonnegativity (NMF), sparse codes (dictionaries) or sparse loadings (sparse PCA). These constraints turn global signed patterns into parts, topics and atoms, at the cost of some error and uniqueness.
  • NMF minimizes Frobenius (Gaussian noise) or generalized KL (Poisson counts) with W,H≥0\mathbf{W}, \mathbf{H} \ge 0. Without subtraction, parts and sparse codes emerge; for digits, 71% of atom values are nearly zero, at test error 331.1 versus PCA’s 204.1.
  • NMF is not unique: always permutation and scale (monomial matrices are the only nonnegative ones with nonnegative inverse), and for particular data whole solution families (polytopes between data and simplex). Exact NMF is NP-hard.
  • Multiplicative updates are gradient descent with a coordinatewise step and, above all, MM: they minimize a diagonal quadratic majorizer (Frobenius) or Jensen’s (KL). Monotone, but zero is absorbing and boundary convergence slow; coordinate descent is practically better.
  • Sparse coding is lasso with the dictionary as design. An atom activates when its residual correlation reaches λ\lambda; ISTA alternates gradient step and soft threshold Sλ/LS_{\lambda/L}, while FISTA accelerates O(1/t)\bigO(1/t) to O(1/t2)\bigO(1/t^2).
  • Dictionary learning alternates lassos with block updates needing only A=∑zz⊤\mathbf{A} = \sum\mathbf{z}\mathbf{z}^\top and B=∑xz⊤\mathbf{B} = \sum\mathbf{x}\mathbf{z}^\top; this enables Mairal et al.’s online version. K-SVD uses ℓ0\ell_0, OMP and rank-1 SVD, and with one unit-coefficient atom is k-means. Natural-image patches yield edge detectors.
  • Sparse autoencoders in interpretability are dictionary learning with amortized inference: decoder is dictionary, encoder a trained ISTA step.