Search

Search papers and lessons

Dictionary Learning

Level 3 · 12 min read

Dictionary learning finds a set of building blocks, the dictionary, so that every data point can be written as a combination of only a few of them.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Linear algebra
  • Probability
  • Losses & regularization
  • Optimization
  • ReadReady to readNot yet

TL;DR

Dictionary learning is a way to find a set of building blocks, called atoms, from a pile of data, so that each data point can be rebuilt by adding up only a few of them. The set of atoms is the dictionary, and the short list of weights used for one data point is its code. The method solves a problem that appears everywhere: raw data is long and noisy, but its useful structure is often simple once the right pieces are known.

Builds on: Matrix Factorization, Sparse Signal, Lasso Regression · Leads to: sparse autoencoders, Mechanistic Interpretability

Where it's used

Image compression and denoising. Take small square patches of a photograph, say 8 by 8 pixels, which is 64 numbers each. Learn a dictionary of a few hundred atoms from many such patches. Then each patch is stored as a handful of weights on a handful of atoms. The K-SVD method, which learns the dictionary and the codes in alternating steps, was developed with image patches in mind. Noise is spread across all 64 pixels and is rarely captured by the few atoms that describe the real image, so rebuilding from the sparse code also removes much of the noise.

Neuroscience models of vision. In 1996 Bruno Olshausen and David Field trained a sparse code on small patches of natural scenes. The atoms that came out looked like localized, oriented edges, similar to the receptive fields found in the primary visual cortex of mammals. The result showed that a simple rule, describe each patch with few active components, is enough to produce structure like that seen in real neurons.

Interpreting neural networks. A language model stores information in its internal activation vectors, and many concepts overlap inside each one. A sparse dictionary learned from those activations tries to split them into atoms that each mean one thing. This is the idea behind sparse autoencoders, a neural-network autoencoder version of dictionary learning, and it is a central tool in Mechanistic Interpretability.

How it works

Here is one tiny instance traced from start to finish. The data lives in two dimensions. The dictionary has three atoms, all of length 1:

  • d1 = (1, 0)
  • d2 = (0, 1)
  • d3 = (0.6, 0.8)

The data point is x = (2, 1.5). We want to write x as a weighted sum of a few atoms.

  1. Score every atom against the data. Compute the dot product of each atom with x. Dot product is "multiply matching entries and add": d1 · x = 1 × 2 + 0 × 1.5 = 2. d2 · x = 1.5. d3 · x = 0.6 × 2 + 0.8 × 1.5 = 1.2 + 1.2 = 2.4. Check: the largest score is 2.4, so d3 is the atom that points most along x.

  2. Take the best atom and subtract what it explains. Use weight 2.4 on d3, so the part of x that d3 explains is 2.4 × (0.6, 0.8) = (1.44, 1.92). The leftover, called the residual, is x minus that: (2 − 1.44, 1.5 − 1.92) = (0.56, −0.42). Check: adding the explained part and the residual gives back (2, 1.5).

  3. Score the atoms against the residual. d1 · residual = 0.56, d2 · residual = −0.42. The largest size is 0.56, so d1 is next. Check: d3 scores 0 against this residual, because it has already been used.

  4. Refit all chosen atoms together. Here is the subtle step. If you kept the weights 2.4 and 0.56 from steps 1 and 3, the sum would be (2.4 × 0.6 + 0.56, 2.4 × 0.8) = (2, 1.92), which misses x in the second entry. So instead solve for the two weights jointly, with atoms d3 and d1 together. The second entry gives 0.8 × a3 = 1.5, so a3 = 1.875. The first entry gives a1 + 0.6 × 1.875 = 2, so a1 = 0.875. Check: 0.875 × (1, 0) + 1.875 × (0.6, 0.8) = (0.875 + 1.125, 1.5) = (2, 1.5). Exact.

  5. Read off the code. The code for x is a = (a1, a2, a3) = (0.875, 0, 1.875). One of the three weights is zero, so the data point is stored as two nonzero numbers plus which atoms they belong to.

This procedure is greedy matching pursuit with refitting, the method in Orthogonal Matching Pursuit. It finds a sparse code for one data point when the dictionary is known. Dictionary learning adds the second half of the job: the dictionary itself is also unknown, and must be improved using the codes.

flowchart LR
  A["Many data points"] --> B["Sparse coding: fix the dictionary, find a sparse code for each point"]
  B --> C["Dictionary update: fix the codes, improve each atom"]
  C --> D["Repeat until the rebuilding error stops falling"]
  D --> B
  D --> E["Output: dictionary and codes"]

The math

Definition: Dictionary learning

Given data points x_1 to x_m, each in a space of dimension n, find a dictionary D with k columns d_1 to d_k, each of length 1, and a code a_i for every data point, so that each x_i is close to D a_i and most entries of each a_i are exactly zero.

Step 1 in symbols: the objective

Stack the data points as columns. Each point is rebuilt as D times its code, and the error is the squared length of the difference. The sparsity is enforced by adding the sum of the absolute values of each code, the L1 penalty, weighted by a constant λ:

min⁡D, A ∑i=1m(∥xi−Dai∥22+λ ∥ai∥1)subject to∥dj∥2=1 for every atom j.\min_{D,\,A}\ \sum_{i=1}^{m}\Big(\|\mathbf{x}_i - D\mathbf{a}_i\|_2^2 + \lambda\,\|\mathbf{a}_i\|_1\Big) \quad\text{subject to}\quad \|\mathbf{d}_j\|_2 = 1 \text{ for every atom } j.

Here x_i is the i-th data point, a_i is its code, ‖·‖₂ is the ordinary length, and ‖a_i‖₁ is the sum of absolute values of its entries. The constraint that each atom has length 1 stops the solver from making the atoms huge and the codes tiny, which would hide the sparsity penalty.

Step 2 in symbols: sparse coding with the dictionary fixed

When D is fixed, each code is found separately. For one point x:

min⁡a ∥x−Da∥22+λ ∥a∥1.\min_{\mathbf{a}}\ \|\mathbf{x} - D\mathbf{a}\|_2^2 + \lambda\,\|\mathbf{a}\|_1.

This is a lasso problem in the unknown code a, with the dictionary playing the role of the design matrix. Greedy methods such as Orthogonal Matching Pursuit solve the same problem approximately and are often faster.

Step 3 in symbols: dictionary update with the codes fixed

With the codes A = [a_1, …, a_m] held fixed, the error is a plain least-squares problem in D. Setting its gradient to zero gives

D=XAT(AAT)−1,D = X A^{\mathsf{T}}\big(A A^{\mathsf{T}}\big)^{-1},

whenever A A^T is invertible. After this, each column is rescaled to length 1. The rescaling changes the error slightly, which is why the two steps are repeated. K-SVD does a different update: it changes one atom at a time, and it also updates that atom's nonzero weights together, which usually gives a smaller error.

Putting it together

Alternate Step 2 and Step 3. Each step is designed to lower the objective, but the rescaling in Step 3 can slightly undo that, so the process is not guaranteed to fall at every pass. It settles at a local answer that depends on the starting dictionary, because the problem is not convex in D and A together.

Worked examples

Example
Example 1: one atom explains the point exactly

Dictionary: d1 = (1, 0), d2 = (0, 1), d3 = (0.6, 0.8). Data point x = (1.2, 1.6).

  1. Score the atoms: d1 · x = 1.2, d2 · x = 1.6, d3 · x = 0.72 + 1.28 = 2.0.
  2. The largest score is 2.0, on d3. Use weight 2.0.
  3. Compute the explained part: 2.0 × (0.6, 0.8) = (1.2, 1.6).
  4. Compute the residual: (1.2, 1.6) − (1.2, 1.6) = (0, 0).
  5. The residual is zero, so the code is a = (0, 0, 2). One nonzero weight rebuilds the point exactly.

Interpretation: the point lies along one atom, so a code with one entry is the sparsest possible. Using d1 and d2 instead would need two nonzero weights.

Example
Example 2: two atoms and a negative weight

Same dictionary. Data point x = (1.5, 2.5).

  1. Score the atoms: d1 · x = 1.5, d2 · x = 2.5, d3 · x = 0.9 + 2.0 = 2.9.
  2. The largest score is 2.9, on d3. Its explained part is 2.9 × (0.6, 0.8) = (1.74, 2.32).
  3. The residual is (1.5 − 1.74, 2.5 − 2.32) = (−0.24, 0.18). Its length is 0.3.
  4. Score against the residual: d1 · residual = −0.24, d2 · residual = 0.18. The larger size is 0.24, so d1 is chosen.
  5. Refit d3 and d1 together. The second entry gives 0.8 × a3 = 2.5, so a3 = 3.125. The first entry gives a1 + 0.6 × 3.125 = 1.5, so a1 = 1.5 − 1.875 = −0.375.
  6. Check: −0.375 × (1, 0) + 3.125 × (0.6, 0.8) = (−0.375 + 1.875, 2.5) = (1.5, 2.5). Exact.

Interpretation: with only d3, the error has length 0.3. Adding d1 removes it completely. The weight on d1 is negative, which is allowed: it means subtract a little of d1. Sparse codes do not need to be positive.

Example
Example 3: a realistic image patch

Take one 8 by 8 pixel patch, which is 64 numbers. Suppose a dictionary of 256 atoms was learned from many patches, and the sparse code for this patch uses 4 atoms with weights 0.9, −0.5, 0.3 and 0.2.

  1. Store the code: 4 weights plus 4 atom indices, which is 8 numbers in total.
  2. Compare with the raw patch: 64 numbers. The code is 8 / 64 = 1/8 of the size, counted in numbers.
  3. Rebuild the patch by adding the 4 weighted atoms. Pixel noise that the 4 atoms cannot express is not rebuilt, so the output is cleaner than the input.
  4. The rebuilt patch is only approximate. Whether the loss of detail is acceptable is a choice made by the designer, not a fact the method settles.

Try it: a patch uses 6 atoms. How many numbers are stored, and what fraction of the 64 raw values is that? Answer: 6 weights plus 6 indices is 12 numbers, and 12 / 64 = 3/16.

Common mistakes and tradeoffs

It is tempting to think the dictionary must be a basis of the space. In fact it is usually overcomplete: it has more atoms than dimensions, as in 256 atoms for 64-dimensional patches. This is what allows a sparse code to exist for many different points. A basis has exactly as many atoms as dimensions and forces every point to use all of them.

It is tempting to think the atoms are the principal components. In fact principal component analysis picks orthogonal directions ordered by how much variance they explain. Dictionary atoms need not be orthogonal, need not be ordered, and are chosen to make codes sparse, not to capture variance.

It is tempting to think the dictionary is sparse. In fact the codes are sparse, while the dictionary is usually dense.

It is tempting to think the greedy choice of the largest score is optimal. In fact it can pick a poor atom early, and the refit step only partly repairs this. Sparse coding is only approximately solved in practice.

Use dictionary learning when the data has a few recurring parts and you want those parts as the features. Do not use it when the data is already low-dimensional and dense, where Singular Value Decomposition (SVD) or Principal Component Analysis is simpler and gives an exact best low-rank fit. Alternatives include K-Means Clustering and Vector Quantization, which each use one atom per point, and the lasso applied to a fixed, hand-chosen dictionary.

History

In the 1990s, researchers in computational neuroscience asked why neurons in the visual cortex respond to edges. Olshausen and Field showed in 1996 that a sparse code learned from natural image patches yields edge-like atoms, which linked the idea of sparsity to neural coding.

Work on sparse signal representation had already shown that sparse codes could be found when the dictionary was known. The step that made learning practical was the alternating scheme of sparse coding and dictionary update. The K-SVD method, published in 2006, gave a clear and widely used version of that alternation, with an update that changes one atom at a time.

Dictionary learning became a standard tool in image processing and was later revived as the core of sparse autoencoders, which apply the same idea to the activations of neural networks.

Recap

  • A dictionary is a set of atoms, and each data point is rebuilt from a few of them.
  • The objective combines rebuilding error with an L1 penalty that makes the codes sparse.
  • Sparse coding fixes the dictionary and solves a lasso problem for each code, as in Lasso Regression.
  • The dictionary update fixes the codes and solves a least-squares problem, followed by rescaling.
  • The two steps repeat until the error stops falling.
  • Next, read sparse autoencoders, which use this idea on neural-network activations, and Mechanistic Interpretability, which uses them to read what a model computes.

Check yourself

QuestionRecall: what does it mean for a dictionary to be overcomplete?Show answer
It has more atoms than the dimension of the data. This is typical in practice, and it lets many different data points each have a sparse code.
QuestionComputation: the dictionary is d1 = (1, 0), d2 = (0, 1), d3 = (0.6, 0.8). For x = (1.8, 2.4), what weight does d3 get in the first greedy step?Show answer
The dot product d3 · x = 0.6 × 1.8 + 0.8 × 2.4 = 1.08 + 1.92 = 3.0. So the first weight is 3.0, and the residual is (1.8 − 1.8, 2.4 − 2.4) = (0, 0).
QuestionWhy: why does adding an L1 penalty produce sparse codes, while an L2 penalty does not?Show answer
The L1 penalty has corners on the axes, so the best solution often lands exactly on an axis, where some weights are zero. The L2 penalty is smooth and shrinks all weights toward zero without making them exactly zero.
QuestionApplied: a team learns a dictionary from sensor readings and finds that every code uses almost all atoms. What should they check?Show answer
They should check whether the penalty weight λ is too small, which lets codes stay dense. They should also check whether the data really has a few recurring parts. If it does not, a dense method such as PCA may be a better fit than a sparse code.

Sources