Skip to content

Sparse coding, dictionaries and K-SVD

Learn a dictionary of atoms so each sample uses only a handful of them. See the sparse-inference step as a lasso, the shrink-and-zero update that solves it, and how K-SVD refreshes atoms one at a time.

Advanced ~13 min8 steps

What runs in CodeSplash

You will be able to

  • Write the sparse coding objective and explain why atoms need a norm limit
  • Run one soft-thresholding update by hand and connect sparse inference to the lasso
  • Describe K-SVD's per-sample sparsity limit and its rank-one atom update

Read first

01

A few atoms per sample

Read

PCA gives every sample a value on every component. Sparse codingSparse codingDescribe each sample with only a few columns (atoms) of a learned dictionary, chosen by an L1 penalty or a limit on how many. asks for the opposite: a dictionary DD of many atoms (often more atoms than input columns, an overcomplete dictionary), and for each sample a code aa that uses only a few of them:

min⁡D,A  12∥X−AD∥F2+λ∥A∥1,∥dk∥≤1.\min_{D, A}\; \tfrac12 \lVert X - A D\rVert_F^2 + \lambda \lVert A\rVert_1, \qquad \lVert d_k\rVert \le 1 .

Image patches, sound frames and signals often look this way: each is built from a small number of recurring pieces.

02

Why atoms need a size limit

Read

Without ∥dk∥≤1\lVert d_k\rVert \le 1, the penalty can be dodged: double an atom and halve its codes, and the reconstruction is the same while ∥A∥1\lVert A\rVert_1 halves. Repeat forever and the codes shrink to nothing while the atoms blow up.

Atoms that are very similar to each other (coherent) make codes unstable: two near-duplicates can trade the same job back and forth.

03

Fix the dictionary: a lasso

Explore

With DD fixed, finding one sample's code is a lassoLassoPenalized regression that shrinks coefficients by their absolute size, setting some exactly to zero. regression: the atoms are the predictors, the sample is the outcome, and the L1 penalty picks a few atoms.

DExplorable · Regularization paths

What happens to each coefficient as the penalty gets stronger?

Three of the eight predictors really matter. How many coefficients will be exactly zero at this penalty?

4
How sure?

Penalty

−0.50
0.30
60
2.0
this penaltybest

Blue paths are the three predictors that matter; gray are the five that don't. Below, training error (orange) and new-data error (blue).

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Raise the penalty and watch coefficients hit zero one at a time. Sparse coding does that for every sample, against a learned dictionary instead of fixed columns.

04

Shrink and zero

Read

ISTA solves the lasso step with a gradient step followed by soft-thresholdingSoft-thresholding (L1 shrinkage)Shrink a value toward zero by a fixed amount and set it to zero if it would cross: sign(a)·max(|a| − t, 0). The L1 penalty's step.:

a←sign⁡(u) max⁡(∣u∣−tλ,  0),u=a+t D⊤(x−Da).a \leftarrow \operatorname{sign}(u)\,\max\big(\lvert u\rvert - t\lambda,\; 0\big), \qquad u = a + t\, D^\top (x - D a).

Entries smaller than tλt\lambda become exactly zero; larger ones shrink by tλt\lambda. The reference's example runs 50 steps on one sample with two atoms and a penalty of 0.20.2, and CodeSplash's run printed the code −4.543 and −0.80.

Python
dictionary = np.linalg.svd(X, full_matrices=False)[2][:2].T
signal = X[0]; code = np.zeros(2); penalty = .2
step = 1 / np.linalg.norm(dictionary, 2) ** 2
for _ in range(50):
    a = code + step * dictionary.T @ (signal - dictionary @ code)
    code = np.sign(a) * np.maximum(np.abs(a) - step * penalty, 0)
print(code)
R
dictionary <- svd(X)$v[, 1:2]; signal <- X[1, ]; code <- c(0, 0); penalty <- .2
step <- 1 / max(svd(dictionary)$d)^2
for (i in 1:50) {
  a <- code + step * drop(crossprod(dictionary, signal - dictionary %*% code))
  code <- sign(a) * pmax(abs(a) - step * penalty, 0)
}
print(code)
05

K-SVD: atoms one at a time

Read

K-SVDK-SVDDictionary learning that limits each sample to a few atoms and refreshes one atom at a time with a rank-one SVD of what it must explain. replaces the L1 penalty with a hard limit: each code may use at most T0T_0 atoms, ∥ai∥0≤T0\lVert a_i\rVert_0 \le T_0, found greedily by orthogonal matching pursuit. Then it refreshes atoms one by one:

  1. Remove atom kk's contribution from the reconstruction.
  2. Keep only the samples that use atom kk.
  3. Take the best rank-one approximation of their residual (its top singular vectors): the new atom and its coefficients.

Restricting step 3 to the samples already using the atom keeps the codes sparse. In the reference's example, the rank-one update leaves a residual of norm 1.716.

06

Readiness

Read

Sparse coding (REP018) and K-SVD (REP019) are explained here: CodeSplash has no dictionary-learning method. The reference examples run in both engines as notebooks, and related tools do run: the lasso for the sparse step, NMF for non-negative parts, and the sparse autoencoder in the neural track.

Pitfalls to keep: local minima are common, unused atoms can "die" and need restarting, and large dictionaries overfit.

Reference · REP018 · Explained hereSparse coding and dictionary learningLearn a possibly overcomplete set of atoms so each sample uses only a few, supporting denoising, compression, and interpretable local features. Reference · REP019 · Explained hereK-SVD dictionary learningLearn an overcomplete dictionary using explicit per-sample sparsity constraints and rank-one SVD atom updates. It is a named training algorithm, not an additional probabilistic model.
07

Check: sparse coding

Checkpoint

Check yourself

Why does sparse coding constrain each atom's norm?

Show the answer

Answer: a

The penalty only sees the codes. Bounding atom norms makes it meaningful.

Check yourself

Soft-threshold u=1.2u = 1.2 with threshold tλ=0.5t\lambda = 0.5. What is the result?

Show the answer

Answer: 0.7

sign⁡(1.2)⋅max⁡(1.2−0.5,0)=0.7\operatorname{sign}(1.2) \cdot \max(1.2 - 0.5, 0) = 0.7.

Check yourself

With the dictionary held fixed, finding one sample's sparse code is the same problem as…

Show the answer

Answer: a

The atoms act as predictors and the L1 penalty selects a few of them.

Check yourself

When K-SVD refreshes one atom, which samples does it use?

Show the answer

Answer: a

Restricting to the atom's current users keeps every other code's zeros intact. Using all samples would change the algorithm and break sparsity.

Check yourself

How does K-SVD's sparsity rule differ from the L1 penalty in ordinary sparse coding?

Show the answer

Answer: a

∥a∥0≤T0\lVert a\rVert_0 \le T_0 counts nonzeros; the L1 penalty sums magnitudes and shrinks the survivors too.

08

Recap

Recap
  • Sparse coding learns atoms so each sample uses a few; atom norms must be bounded.
  • With the dictionary fixed, the code is a lasso, solved by gradient steps plus soft-thresholding.
  • K-SVD caps nonzeros per sample and refreshes each atom with a rank-one SVD over its users. Both are explained here only.

Concepts in this lesson