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
- 12PCA as minimum reconstruction errorMinorize-maximize algorithmsVector quantizationk-means objective (inertia)
- 11LassoRegularization path
- 06Soft-thresholdingProximal gradient methodFast iterative shrinkage-thresholding algorithmBlock coordinate descent and alternating minimization
- 07Kullback-Leibler divergence (relative entropy)
Motivation: parts, topics and atoms
PCA as the best linear reconstruction solves a specific problem: minimize squared error with 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 faces of pixels, with 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 , 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 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 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, has one example per row. A rank- factorization writes each row as a combination of basis vectors:
This is the sklearn convention (W = modelo.transform(X), H = modelo.components_). Lee and Seung write with an example per column, so their (basis) is our ; take care reading the paper. Methods differ in what each factor must satisfy:
| Method | Constraint on (codes) | Constraint on (atoms) | What it learns |
|---|---|---|---|
| Vector quantization (-means) | each row is canonical vector | none | whole prototypes |
| PCA | orthogonal columns (uncorrelated scores) | orthonormal rows | global signed patterns |
| NMF | additive parts | ||
| Sparse coding / dictionaries | sparse rows ( penalty) | row norms | signal atoms |
| Sparse PCA | none (column norms ) | sparse rows | interpretable 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 nor must sum to 1: if both do, terms cancel, leaving ordinary KL divergence. Each term is nonnegative (function is convex in with minimum 0 at ) and divergence is zero only if . Both losses are disguised likelihoods:
- Frobenius is up to constants if : additive Gaussian noise, appropriate for intensities.
- Generalized KL is up to constants if , because . This is natural for counts (words, photons, sequencing reads). It is exactly what Lee and Seung maximized in 1999, , 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 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.
Three things visible in the figure and quantified in the lab below on 898 test digits:
- NMF atoms are strokes. With , 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.
- 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.
- PCA reconstructs better. With , 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- factorization approximates better than truncated SVD, and PCA with mean (the best -dimensional affine subspace) does better still; NMF is rank- factorization with added constraints. There is no test theorem, but the difference remains. Interpretability costs error.
Why does nonnegativity produce parts? If is all nonnegative, no summand can erase another’s contribution: each pixel lit in appears in every digit using . 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 or .
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 is a solution and invertible satisfies and , then yields the same product and is another solution. There are two kinds of :
Proof
If , its inverse is nonnegative. Conversely let . For , is a sum of nonnegative terms, so for every . If , row of vanishes outside column . If one column of had two positive entries with , row of would vanish outside and outside , hence entirely, making singular. Each column of therefore has exactly one positive entry (at least one by invertibility), and invertibility places these entries in distinct rows: is monomial.
∎Permutations and positive rescalings (, ) 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 . Lee and Seung removed it by normalizing basis columns to sum to 1.
For specific data, however, many more nonmonomial matrices are usually valid, genuinely changing the factorization. Geometry explains this. Normalize each row of to sum to 1 (nothing essential changes: if , dividing row of by a number only requires dividing row of by it), and rescale atoms to sum to 1, passing scale into . Then : rows of also sum to 1, and with nonnegative factors says each observation is a convex combination of atoms: data lie inside the polytope with vertices , itself inside simplex (because ). Any polytope between the data cloud and works.
The figure has infinitely many exact solutions while data lie inside; with the trivial , always exists (the whole ), teaching nothing, so NMF uses . Geometry is the same then: seek a cone of 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 (symmetry already prevents it), but is convex in either block with the other fixed. With fixed , the problem also separates by columns: column of , , is approximated by with column of . The problem is its transpose (). It suffices to study
Gradient descent with coordinate step is . Lee and Seung (2001) chose , combining terms into a product:
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 . What is not obvious is objective decrease. A gradient step with arbitrary could increase it. The guarantee comes from recognizing an MM algorithm.
The auxiliary function
Recall MM algorithms: if satisfies for all and (an auxiliary function or majorizer touching at ), then satisfies
The Frobenius proof’s centerpiece checks that is positive semidefinite; the final proof exercise gives every step. Once accepted, minimizing solves , namely , exactly the update. Matrix tells us: projected gradient descent with step , , uses majorizer , 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 .
For generalized KL, the auxiliary function follows from Jensen’s inequality, as in EM. Here it is in full.
Proof
With fixed , . For each with , take weights , nonnegative and summing to 1 over . Since is convex, Jensen gives
with equality if , because all ratios then equal . Substitution gives auxiliary function . It is convex and separable in , with derivative . Setting it to zero,
which is the generalized KL update (column by column of ). The solution is nonnegative, so constraint does not activate.
∎Weights have a latent-variable interpretation: if each count is the sum of hidden Poisson counts, one per atom, is the expected fraction of from atom . The update is that model’s E-step (distribute) followed by M-step (re-estimate); with fixed it is essentially Richardson and Lucy’s (1972 and 1974) astronomical-image deblurring algorithm, a resemblance Lee and Seung note.
Zeros that do not return and convergence
Monotonicity has fine print, shown by the figure’s last two experiments.
- Zero is absorbing. If at any time, multiplication leaves 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, approaches 0 by multiplying factors tending to 1, giving slow convergence. This is typical because NMF solutions are sparse.
- Monotonicity is not convergence. Decreasing 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 are added to denominators (
sklearndoes this), and faster algorithms are preferred, such as block-column coordinate descent, HALS (Cichocki and Phan, 2009),solver="cd"insklearn.
Standard initialization is NNDSVD (Boutsidis and Gallopoulos, 2008): take the first singular triplets of ; the first in absolute value (by Perron-Frobenius, for it can be nonnegative), and for each remaining pair retain the positive or sign-flipped negative parts of and , whichever has greater , scaling by . This starts from the best rank- approximation but has many exact zeros, lethal to multiplicative updates. NNDSVDa fills them with the mean of .
Lab: NMF with multiplicative updates
Implement both losses from scratch on the figure’s 500 training digits with , NNDSVDa initialization and 300 iterations, checking monotonicity every iteration.
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 makes clear 16 parts cannot reproduce every stroke.
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%): entries for pixels always zero in digits vanish on the first update because numerator 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:sklearnuses randomized SVD for initialization and updates before ). Itssolver="cd"reaches 59509.0 with the same 300 iterations: multiplicative updates are historical and easiest to reason about, but not fastest. In practice usecd.
Document topics
For text, each row of is a document and each column a word, with TF-IDF weights. NMF writes each document as a nonnegative sum of topics (rows of , weights over vocabulary), and each row of 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).
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 and loss.With 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 topics merge; at cooking splits into “bread and oven” versus “tomato sauce”; at a “football business” topic appears (Spanish words for players, team, investors, club). There is no true : there are granularities, and choosing one is a modeling decision.
Sparse coding
Change the constraint from sign to count. Fix a dictionary of unit-norm atoms (in this part atoms are columns, as throughout sparse-coding literature; relative to NMF, and code of is a row of ). If , the dictionary is overcomplete: more atoms than dimensions, and has infinitely many solutions, an affine subspace of dimension . To choose one, require few atoms.
What we really want is to minimize atom count , 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 relaxation, studied here. Its optimality conditions are a rule about correlations with residual :
An atom activates exactly when its correlation with the unexplained part reaches . In particular, at the residual is , so code is zero if and only if . Lowering traces the regularization path: the first atom to activate is most correlated with , and others enter (and sometimes leave) as residual changes.
Initially : first atom to activate is at , next , its directional neighbor. As , code tends to the exact minimum--norm solution, here using and (, norm 1.9) rather than and (norm 2.2): favors atoms “surrounding” . Although the exact system has infinitely many solutions, lasso has one: if columns of are in general position (no affine subspace of dimension contains more than of vectors , almost surely true for continuously distributed atoms), the solution is unique for every and uses at most atoms (Tibshirani, 2013).
The figure also shows the danger of not normalizing atoms. If , writing shows effective penalty on the unit atom is : long atoms are cheap and activate earlier due to size rather than resemblance. One means the same for all atoms only when norms match.
ISTA and FISTA
Lasso sums smooth , whose gradient is Lipschitz with constant , and nonsmooth but separable . This is the case for which proximal gradient was invented: a gradient step on followed by the proximal of , componentwise soft thresholding,
This is ISTA (iterative shrinkage-thresholding algorithm; Daubechies, Defrise and De Mol, 2004). Thresholding does two things: shrink large coefficients toward zero (costing per unit) and set those below 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 ; accelerated FISTA (Beck and Teboulle, 2009), extrapolating with Nesterov momentum, gives .
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 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 bound. The solution matches sklearn to , with necessary rescaling: Lasso minimizes with rows (here ), so our corresponds to . The code uses 8 of 128 atoms and contains all 6 support atoms used to generate .
Learning the dictionary
So far the dictionary was given. The interesting part is learning it from data, as NMF learns parts.
Constraint is not decorative. Without it, leaves reconstruction unchanged and divides penalty by : as 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 but is in each block, suggesting alternation:
- Codes with fixed : independent lassos, via ISTA or FISTA.
- Dictionary with fixed codes: norm-constrained least squares, via columnwise block coordinate descent.
Step 2 has a columnwise closed form. With and , the objective part depending on (other columns fixed) is
where and are columns of and . Since the quadratic is isotropic, the unit-ball minimizer is the projection of : . Each alternating step cannot increase the objective; as in NMF, values converge and the result depends on initialization. Step 2 needs only () and (), not data: key to the online method.
K-SVD: k-means with multiple atoms
Aharon, Elad and Bruckstein (2006) tackle the version: with . Codes use OMP. The dictionary updates atom by atom, with the trick of updating both atom and coefficients together. For atom , take only examples using it, , and residual without ‘s contribution, matrix with rows for . The best pair is ‘s best rank-1 approximation from SVD: is its first right singular vector and new coefficients times the first left one. Restricting to preserves code support and hence constraint .
The name comes from k-means. If each code uses one atom with coefficient exactly 1 (), the objective is : 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 SVD updates instead of 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 and , accumulable one at a time. Their algorithm, for :
- Take an example (or minibatch) and calculate code with current dictionary .
- Accumulate and .
- Update using one or a few block-descent passes initialized from .
Step 3 minimizes surrogate , with old codes frozen. Since those codes need not be optimal for new , lies above empirical cost with optimal codes: another majorization, now stochastic. Under technical assumptions (bounded data, unique lasso solution, curvature of bounded below), they prove the dictionary converges almost surely to a stationary point of expected cost, scaling to millions of examples with memory. This is implemented by sklearn.decomposition.MiniBatchDictionaryLearning.
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.
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.
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))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 . The sklearn dictionary, fitted with the same (its per-example objective matches ours) and one data pass, essentially ties ours in validation cost and PSNR. Good denoising 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): with and . Direct but nonconvex and hard to optimize.
- Zou, Hastie and Tibshirani (2006) rewrite PCA as regression: with , minimize . Without the penalty, columns of are proportional to principal components for any ; with it, the problem is elastic net and loadings become sparse. Alternate (elastic nets) and (an SVD-solvable Procrustes problem).
- As dictionary learning with roles reversed.
sklearn.decomposition.SparsePCAsolves with columns of norm : sparsity lies in atoms (rows of , 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 and sum , variance each component contributes after removing what predecessors explain.
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 , another four factor , 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 variables and and on ). Sparse PCA at reduces cross-loadings below 0.005 in absolute value (4 exactly zero); at all vanish, 4 per component: first uses only and second is nearly clean on , with residual on variables sharing information with . 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
| PCA | NMF | Sparse dictionary | |
|---|---|---|---|
| Atoms | orthonormal, global, signed | nonnegative, localized | unit norm, any sign, often overcomplete |
| Codes | dense, signed | nonnegative, naturally sparse | sparse through penalty |
| Reconstruction with fixed | best possible (Eckart-Young) | worse (digits: 331.1 versus 204.1) | depends on ; with each example selects its own atoms, unlike a fixed basis |
| Uniqueness | up to signs with distinct eigenvalues | almost never; always permutation and scale | no; local minima and permutations |
| Computation | one global SVD | nonconvex, NP-hard; local methods | nonconvex; alternating or online |
| Interpretability | low in data with parts | high if data sum parts | high 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 neurons represents many more than 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:
Columns of are dictionary atoms (normalized for the same scale reason), 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 , a one-layer encoder predicts it (amortized inference). The link is literal: one ISTA step from with nonnegative codes is , 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.
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, 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
Step 1 of 4. is immediate. Why does suffice for ?
ista(D, x, lam, n_iter) approximating using n_iter ISTA iterations from with step , where . Columns of D need not have unit norm. Tests compare with sklearn.linear_model.Lasso(fit_intercept=False), whose objective is with rows: work out which corresponds to your 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 zMore than one answer may be correct.
Summary
- NMF minimizes Frobenius (Gaussian noise) or generalized KL (Poisson counts) with . 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 ; ISTA alternates gradient step and soft threshold , while FISTA accelerates to .
- Dictionary learning alternates lassos with block updates needing only and ; this enables Mairal et al.’s online version. K-SVD uses , 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.