Algorithm Search⌘K

Algorithmadvanced

K-SVD

Also called K-SVD dictionary learning.

Learn a dictionary by alternating sparse coding with an update of each atom and its coefficients by a rank one SVD of the residual.

Time
O(J N s n (K + n)) worst
Space
O(n (K + N)) extra
Where
J = the number of iterations; K = the number of atoms; N = the number of signals; n = the length of a signal; s = the number of atoms per signal
Properties
not convexdeterministiciterative
Origin
Michal Aharon, Michael Elad, Alfred Bruckstein, 2006

K-SVD is an algorithm for the dictionary learning problem: given NN signals yi∈Rny_i \in \mathbb{R}^n, find KK unit atoms dkd_k and codes xix_i with at most ss nonzero entries each, so that ∥Y−DX∥F2\|Y - DX\|_F^2 is small. Like k-means, it alternates two steps: code every signal with the current dictionary, then update the dictionary. With s=1s = 1, coefficients fixed to 1 and no normalization of the atoms, it reduces to k-means. Its difference from the earlier method of optimal directions (MOD), which solves for all atoms at once by least squares, is the update: K-SVD updates one atom at a time, together with the coefficients of that atom, by a rank one singular value decomposition of the error on the signals that use the atom. The coding step uses a sparse coder such as orthogonal matching pursuit. Compared with convolutional sparse coding, K-SVD learns atoms for small independent patches, not filters for a whole image.

The problem

Given the n×Nn \times N signal matrix YY, a number of atoms KK (usually K>nK > n, an overcomplete dictionary) and a sparsity ss, find an n×Kn \times K dictionary DD with unit columns and a K×NK \times N code matrix XX that minimize

F(D,X)=∥Y−DX∥F2subject to∥xi∥0≤s for every i.F(D, X) = \|Y - DX\|_F^2 \quad\text{subject to}\quad \|x_i\|_0 \le s \text{ for every } i.

The output is DD and XX. The problem is not convex and is NP-hard in general, so K-SVD is a local method: it lowers FF from a starting dictionary, often a random choice of normalized signals or a fixed transform such as an overcomplete DCT.

The algorithm

Write xkx^k for row kk of XX, the coefficients of atom kk in all signals.

  1. K-SVD(Y, D, s, J)
  2. 1for j = 1 to J
  3. 2for i = 1 to N: x_i ← SparseCode(D, y_i, s) ▷ for example OMP
  4. 3for k = 1 to K
  5. 4ω ← {i : x^k_i ≠ 0} ▷ the signals that use atom k
  6. 5if ω is empty: replace d_k by the worst represented signal, normalized; continue
  7. 6E ← columns ω of Y - Σ_{j≠k} d_j x^j ▷ error without atom k
  8. 7(u, σ, v) ← largest singular triple of E
  9. 8d_k ← u, x^k_ω ← σ v ▷ best rank one fit of E
  10. 9return D, X

Line L6 keeps only the columns in ω\omega. This is the main idea: the new coefficients σv\sigma v fill only the positions that were already nonzero, so the sparsity pattern of XX does not grow. A rank one fit of all columns would give a dense row. Line L6 uses the new values of the atoms 1,…,k−11, \dots, k - 1 and of their coefficients, as in a Gauss-Seidel sweep.

Example

Take n=2n = 2, K=2K = 2, s=1s = 1, the start D=(e1,e2)D = (e_1, e_2) and three signals y1=(2,1)y_1 = (2, 1), y2=(4,2)y_2 = (4, 2), y3=(1,−2)y_3 = (1, -2).

Coding (L2). OMP with one atom picks the atom with the largest ∣⟨dk,yi⟩∣|\langle d_k, y_i\rangle|: y1↦2e1y_1 \mapsto 2e_1, y2↦4e1y_2 \mapsto 4e_1, y3↦−2e2y_3 \mapsto -2e_2. The residuals are (0,1)(0, 1), (0,2)(0, 2) and (1,0)(1, 0), so F=1+4+1=6F = 1 + 4 + 1 = 6.

Atom 1 (L4 to L8). ω={1,2}\omega = \{1, 2\} and no other atom is used by these signals, so

E=(2412)=(21)(12).E = \begin{pmatrix}2 & 4\\ 1 & 2\end{pmatrix} = \begin{pmatrix}2\\1\end{pmatrix}\begin{pmatrix}1 & 2\end{pmatrix}.

EE has rank 1, with σ=5\sigma = 5, u=(2,1)/5u = (2, 1)/\sqrt5 and v=(1,2)/5v = (1, 2)/\sqrt5. The new atom is d1=(2,1)/5d_1 = (2, 1)/\sqrt5 with coefficients σv=(5,25)\sigma v = (\sqrt5, 2\sqrt5), which fit y1y_1 and y2y_2 exactly. Now F=1F = 1.

Atom 2. ω={3}\omega = \{3\} and EE is the single column y3y_3. Its best rank one fit is y3y_3 itself: d2=(1,−2)/5d_2 = (1, -2)/\sqrt5 (up to sign) with coefficient 5\sqrt5. Now F=0F = 0.

One iteration found a dictionary in which each signal is one atom times a coefficient. The test file checks these numbers.

Correctness

The full proof is in proofs/correctness.md. In short:

  • The update of atom kk is the best rank one fit: for any matrix EE, min⁡∥E−dwT∥F2\min\|E - dw^T\|_F^2 over unit dd is ∥E∥F2−σ12\|E\|_F^2 - \sigma_1^2, reached at d=u1d = u_1, w=σ1v1w = \sigma_1v_1. The old atom and its coefficients are one candidate, so the objective does not increase, and the support of each code does not grow.
  • If the coder is exact (it returns the best code with at most ss atoms), the codes of the previous iteration are feasible for it, so the coding step does not increase the objective either. Then FF is nonincreasing over the whole run and converges.

Practical K-SVD uses OMP, which is not exact. Then only the atom update is guaranteed to help, and the coding step can raise the objective. The values converge to a limit, but the theorem says nothing about the global minimum or about recovering a true dictionary.

Proof: The K-SVD atom update is the best rank one fit on the signals that use the atom, and with an exact sparse coder the objective never increasesfull

Setting. YY is a real n×Nn \times N matrix whose columns yiy_i are the signals. A dictionary DD is n×Kn \times K with columns dkd_k of norm 1. A code matrix XX is K×NK \times N, with columns xix_i that have at most ss nonzero entries; xkx^k denotes row kk of XX. The objective is

F(D,X)=∥Y−DX∥F2=∑i∥yi−Dxi∥2.F(D, X) = \|Y - DX\|_F^2 = \sum_i \|y_i - Dx_i\|^2.

One K-SVD iteration first replaces every xix_i by the output of a sparse coder, and then, for k=1,…,Kk = 1, \dots, K in turn, updates dkd_k and xkx^k as follows. Let ω={i:xik≠0}\omega = \{i : x^k_i \ne 0\}. If ω\omega is empty, the atom may be replaced by any unit vector (the implementation uses the normalized residual of the worst represented signal). Otherwise let E=Y−∑j≠kdjxjE = Y - \sum_{j \ne k} d_jx^j, let ERE^R be the columns of EE with index in ω\omega, and let σ1,u1,v1\sigma_1, u_1, v_1 be its largest singular value and a pair of singular vectors. The update sets dk=u1d_k = u_1, xik=σ1(v1)ix^k_i = \sigma_1(v_1)_i for i∈ωi \in \omega (in the order of ω\omega), and leaves xik=0x^k_i = 0 for i∉ωi \notin \omega.

Lemma 1: the best rank one fit

For a real n×pn \times p matrix EE with largest singular value σ1\sigma_1,

min⁡∥d∥=1,  w∈Rp∥E−dwT∥F2=∥E∥F2−σ12,\min_{\|d\| = 1,\; w \in \mathbb{R}^p}\|E - dw^T\|_F^2 = \|E\|_F^2 - \sigma_1^2,

and the minimum is reached at d=u1d = u_1, w=σ1v1w = \sigma_1v_1.

Proof. Fix a unit vector dd. The function w↦∥E−dwT∥F2=∥E∥F2−2wTETd+∥w∥2w \mapsto \|E - dw^T\|_F^2 = \|E\|_F^2 - 2w^TE^Td + \|w\|^2 is a convex quadratic with minimizer w=ETdw = E^Td and minimum ∥E∥F2−∥ETd∥2\|E\|_F^2 - \|E^Td\|^2. Now ∥ETd∥2=dTEETd\|E^Td\|^2 = d^TEE^Td, and its maximum over unit vectors dd is the largest eigenvalue of the symmetric matrix EETEE^T (the Rayleigh quotient), which is σ12\sigma_1^2, reached at d=u1d = u_1. Then w=ETu1=σ1v1w = E^Tu_1 = \sigma_1v_1. □\square

Lemma 2: the atom update does not increase the objective

Let (D,X)(D, X) be any pair whose codes have at most ss nonzeros per column, and let (D′,X′)(D', X') be the result of the update of atom kk. Then F(D′,X′)≤F(D,X)F(D', X') \le F(D, X), every column of X′X' has at most ss nonzero entries, and ∥dk′∥=1\|d'_k\| = 1.

Proof. If ω\omega is empty, then xk=0x^k = 0, so dkd_k does not appear in DXDX, and changing it does not change FF. Otherwise write DX=∑j≠kdjxj+dkxkDX = \sum_{j \ne k}d_jx^j + d_kx^k, so that F(D,X)=∥E−dkxk∥F2F(D, X) = \|E - d_kx^k\|_F^2, and only dkd_k and xkx^k change. Split the columns into ω\omega and its complement. On the complement, xik=0x^k_i = 0 before and after, so those columns of E−dkxkE - d_kx^k do not change. On ω\omega, the columns form ER−dk(xωk)TE^R - d_k(x^k_\omega)^T, a fit of ERE^R by a unit vector times a row. By Lemma 1, the new pair (u1,σ1v1)(u_1, \sigma_1v_1) gives the smallest possible value, ∥ER∥F2−σ12\|E^R\|_F^2 - \sigma_1^2, which is at most the value of the old pair (dk,xωk)(d_k, x^k_\omega). So FF does not increase.

The new row xkx^k is zero outside ω\omega, so the support of each column xix_i either stays the same or loses entry kk (when (v1)i=0(v_1)_i = 0). It never gains an entry, so each column still has at most ss nonzeros. Finally ∥u1∥=1\|u_1\| = 1. □\square

The restriction to ω\omega is what keeps the sparsity: a rank one fit of the full EE would in general make xkx^k dense.

Theorem: monotone objective with an exact sparse coder

Assume the coder is exact, that is, for each ii it returns a minimizer of ∥yi−Dx∥2\|y_i - Dx\|^2 over all xx with at most ss nonzero entries. Let FjF_j be the objective at the end of iteration jj, and GjG_j the objective after its coding step. Then

G1≥F1≥G2≥F2≥⋯≥0,G_1 \ge F_1 \ge G_2 \ge F_2 \ge \dots \ge 0,

so the sequence of objective values converges.

Proof. At the start of iteration j+1j + 1, the codes XX from iteration jj have at most ss nonzeros per column (Lemma 2). They are feasible for the coding problem of each column with the current DD, so the exact coder returns a column with residual at most ∥yi−Dxi∥2\|y_i - Dx_i\|^2. Summing over ii gives Gj+1≤FjG_{j+1} \le F_j. Within an iteration, the KK atom updates each do not increase FF (Lemma 2), so Fj≤GjF_j \le G_j. All values are nonnegative. A nonincreasing sequence that is bounded below converges. □\square

The implementation's exact coder tries every support of size min⁡(s,K)\min(s, K) and solves least squares on it. This is exact: a support with fewer than ss atoms is contained in one with exactly ss atoms, and least squares on a larger set of columns has a residual that is not larger.

What the theorem does not say

  • It is about the values FjF_j, not about the dictionaries. The iterates need not converge, and the limit need not be a global minimizer; finding the best dictionary is NP-hard in general (Tillmann, 2015).
  • It needs an exact coder. Exact sparse coding is itself NP-hard, so practical K-SVD uses orthogonal matching pursuit or another greedy coder. Then the coding step can increase the objective, and the sequence is not monotone; the page reports such increases measured on planted problems. The test file checks monotonicity only with the brute force coder on a small problem, and checks the atom update step alone with OMP codes.
  • With a coder that has an error target instead of a sparsity target (code each signal until ∥yi−Dxi∥≤ϵ\|y_i - Dx_i\| \le \epsilon), the objective is a different one, and the argument above applies only to the atom update step.

Complexity

With OMP, coding one signal costs O(snK)O(snK) for the correlations plus the cost of small least squares problems, so the coding step costs O(NsnK)O(NsnK) when ss is small. In the update of atom kk, building EE costs O(ns)O(ns) per column, and the columns of all atoms together number at most NsNs. A rank one SVD of the n×∣ω∣n \times |\omega| matrix costs O(n∣ω∣)O(n|\omega|) per step of power iteration, or O(n∣ω∣min⁡(n,∣ω∣))O(n|\omega|\min(n, |\omega|)) per sweep of a full SVD, which is what the implementation uses. One iteration is therefore O(Nsn(K+n))O(Nsn(K + n)), and JJ iterations cost O(JNsn(K+n))O(JNsn(K + n)). The memory beyond YY is O(nK)O(nK) for the dictionary, O(Ns)O(Ns) for sparse codes and O(nN)O(nN) in the worst case for the restricted error matrix. In practice the coding step dominates; batch OMP, which precomputes DTDD^TD and DTYD^TY, makes it much faster.

Properties

  • It is a block coordinate method: each atom update is an exact minimization over one atom and its coefficients, with the support fixed.
  • The atoms keep norm 1. The scale sits in the coefficients, and the sign of an atom is not determined.
  • The sparsity pattern found by the coder is kept during the atom updates, and can only lose entries.
  • It is not convex and depends on the start. Different starts give different dictionaries, and some atoms may stay unused or repeat.
  • With s=1s = 1, the coefficients forced to 1 and no normalization, the update of atom kk becomes the mean of its signals, and K-SVD is k-means. With s=1s = 1 and free coefficients it is gain-shape vector quantization.

Variants and improvements

  • Approximate K-SVD replaces the SVD by one step of alternating updates, d←Ex/∥Ex∥d \leftarrow Ex/\|Ex\| then x←ETdx \leftarrow E^Td, which avoids forming EE explicitly. Together with batch OMP this is the common fast version (Rubinstein, Zibulevsky and Elad, 2008).
  • MOD updates all atoms at once by D=YXT(XXT)−1D = YX^T(XX^T)^{-1} and then normalizes. Each iteration costs more, but it is simple.
  • Error target coding codes each signal until ∥yi−Dxi∥≤ϵ\|y_i - Dx_i\| \le \epsilon instead of with exactly ss atoms. This is the form used for denoising, with ϵ\epsilon set from the noise level.
  • Online dictionary learning (Mairal, Bach, Ponce and Sapiro) processes signals in small batches with an ℓ1\ell_1 coder, which scales to millions of patches.
  • Structured and multiscale variants learn dictionaries for color images, for several scales, or with a separable or sparse structure that gives a fast transform.
  • Convolutional versions learn filters for whole images instead of atoms for patches; see convolutional sparse coding.

When to use it

Use K-SVD when there are many examples of a class of signals, such as image patches of 8×88 \times 8 pixels, and a fixed transform such as a wavelet or DCT basis does not give codes that are sparse enough. The classic use is image denoising and inpainting with dictionaries trained on the corrupted image itself. For very large training sets, online methods are faster. For signals with a known good transform, or when no training data is available, use a fixed dictionary. When the atoms must be shift invariant over a whole image, use convolutional sparse coding.

Pitfalls

  • The result depends on the start, and K-SVD often stops in a local minimum. In a measurement on planted problems with n=8n = 8, K=10K = 10, s=2s = 2 and N=200N = 200 noiseless signals, started from 10 normalized signals and run for 30 iterations, eight random seeds found 10, 8, 2, 8, 1, 9, 7 and 7 of the 10 true atoms (an atom counts as found when 1−∣⟨d,dtrue⟩∣<0.011 - |\langle d, d_{\text{true}}\rangle| < 0.01).
  • With OMP, the objective is not monotone. In four measured runs with n=8n = 8, K=12K = 12, s=2s = 2 and N=150N = 150, the coding step raised the objective in at least 3 of the 25 iterations of every run. Monitor the objective after the atom updates, and do not use "the objective went up" as a sign of a bug.
  • Even with every atom found, OMP can pick a wrong support for some signals when the atoms are coherent. In a measured run of the test file started near the true dictionary, all 10 atoms were found but the objective stayed at 4.7 (from 28.0 after the first coding step), not 0.
  • Atoms can become unused, or two atoms can become almost equal. Replace such atoms, for example by the worst represented signal, and watch the mutual coherence of the dictionary.
  • Remove the mean of each patch before training if the dictionary should model texture and not brightness; otherwise one atom is spent on the constant patch in many codes.
  • The signs and the order of the atoms are arbitrary. Compare dictionaries up to sign and permutation.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

imgla.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).

A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""

import math


def _flat(x):
    """Flatten a list of rows (an image) into one list; a vector is returned as is."""
    if x and isinstance(x[0], (list, tuple)):
        return [v for row in x for v in row]
    return x


def zeros(m, n):
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n):
    """The n x n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1.0
    return out


def transpose(a):
    """A^T."""
    return [list(col) for col in zip(*a)]


def conj_transpose(a):
    """A^H, the conjugate transpose."""
    return [[v.conjugate() for v in col] for col in zip(*a)]


def matmul(a, b):
    """The product A B."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """The product A x."""
    return [sum(v * w for v, w in zip(row, x)) for row in a]


def rmatvec(a, y):
    """The product A^H y."""
    n = len(a[0]) if a else 0
    out = [0.0] * n
    for row, yi in zip(a, y):
        if yi == 0:
            continue
        for j, v in enumerate(row):
            out[j] += v.conjugate() * yi
    return out


def dot(u, v):
    """<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
    return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))


def norm2(x):
    """The Euclidean norm. Images (lists of rows) are flattened."""
    return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))


def solve(a, b):
    """Solve A x = b by Gaussian elimination with partial pivoting.

    b is a vector or a matrix (a list of rows). A must be square and
    nonsingular; a zero pivot raises ValueError. Fractions stay exact.
    """
    n = len(a)
    vec = not (b and isinstance(b[0], (list, tuple)))
    rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
    m = [list(row) + rhs[i] for i, row in enumerate(a)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / piv
            if f != 0:
                mr, mc = m[r], m[c]
                for j in range(c, w):
                    mr[j] -= f * mc[j]
    x = [[0.0] * (w - n) for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(w - n):
            s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def cholesky(a):
    """Lower triangular L with A = L L^H for a Hermitian positive definite A."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
        d = d.real if isinstance(d, complex) else d
        if not d > 0:
            raise ValueError("matrix is not positive definite")
        ljj = math.sqrt(d)
        low[j][j] = ljj
        for i in range(j + 1, n):
            s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
            low[i][j] = s / ljj
    return low


def cho_solve(low, b):
    """Solve (L L^H) x = b, with L from cholesky."""
    n = len(low)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
        x[i] = s / low[i][i].conjugate()
    return x


def _rot_params(app, aqq, apq):
    """c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
    theta = (aqq - app) / (2.0 * apq)
    t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
    c = 1.0 / math.sqrt(1.0 + t * t)
    return c, c * t


def sym_eig(a, tol=1e-15, max_sweeps=100):
    """Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.

    Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
    """
    n = len(a)
    m = [[float(v) for v in row] for row in a]
    q = eye(n)
    for _ in range(max_sweeps):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(m[i][i] ** 2 for i in range(n)) + off
        if off <= (tol * tol) * scale or off == 0.0:
            break
        for p in range(n - 1):
            for r in range(p + 1, n):
                apq = m[p][r]
                if apq == 0.0:
                    continue
                c, s = _rot_params(m[p][p], m[r][r], apq)
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - s * mkr
                    m[k][r] = s * mkp + c * mkr
                mp, mr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = mp[k], mr[k]
                    mp[k] = c * mpk - s * mrk
                    mr[k] = s * mpk + c * mrk
                m[p][r] = m[r][p] = 0.0
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - s * qkr
                    q[k][r] = s * qkp + c * qkr
    order = sorted(range(n), key=lambda i: m[i][i])
    w = [m[i][i] for i in order]
    qs = [[q[k][i] for i in order] for k in range(n)]
    return w, qs


def _complete(cols, m):
    """Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
    for idx, col in enumerate(cols):
        if any(v != 0.0 for v in col):
            continue
        for e in range(m):
            cand = [0.0] * m
            cand[e] = 1.0
            for _ in range(2):
                for jdx, other in enumerate(cols):
                    if jdx == idx or not any(v != 0.0 for v in other):
                        continue
                    h = sum(a * b for a, b in zip(other, cand))
                    cand = [a - h * b for a, b in zip(cand, other)]
            nrm = math.sqrt(sum(v * v for v in cand))
            if nrm > 0.5:
                cols[idx] = [v / nrm for v in cand]
                break
    return cols


def svd(a, tol=1e-15, max_sweeps=100):
    """Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).

    Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
    descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
    """
    m, n = len(a), len(a[0])
    if m < n:
        v, s, u = svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(max_sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                cp, cr = cols[p], cols[r]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cr)
                gamma = sum(x * y for x, y in zip(cp, cr))
                if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                c, s = _rot_params(alpha, beta, gamma)
                cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
                cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
                vp, vr = vcols[p], vcols[r]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
                vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
        if not rotated:
            break
    sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
    # A column below 1e-150 times the largest one is zero to working precision;
    # its squares underflow, so its direction carries no information.
    floor = max(sig) * 1e-150 if sig else 0.0
    sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
    order = sorted(range(n), key=lambda j: -sig[j])
    s_out = [sig[j] for j in order]
    ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
    ucols = _complete(ucols, m)
    u = [[ucols[j][i] for j in range(n)] for i in range(m)]
    v = [[vcols[j][i] for j in order] for i in range(n)]
    return u, s_out, v


def adjoint_gap(apply_a, apply_ah, x, y):
    """|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.

    x and y may be vectors or images (lists of rows). If the denominator is
    zero, the absolute gap is returned.
    """
    ax = apply_a(x)
    gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
    den = norm2(ax) * norm2(y)
    return gap / den if den > 0.0 else gap
k_svd.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-svd/. The authors are listed in prov/0XCKNF.jsonl.
"""K-SVD dictionary learning (Aharon, Elad and Bruckstein, 2006).

Signals are a list of N vectors of length n. A dictionary is a list of K
atoms, each a vector of length n with norm 1. Codes are a list of N vectors
of length K with at most s nonzero entries each. The objective is

    F(D, X) = sum_i ||y_i - D x_i||^2  (the squared Frobenius norm of Y - D X).

Each iteration codes every signal with the current dictionary and then
updates the atoms one at a time. The update of atom k uses only the signals
whose code uses atom k, and replaces the atom and its coefficients on those
signals by the best rank 1 approximation of the restricted error matrix.
"""

from itertools import combinations

from imgla import svd


def _lstsq(cols, y, rcond=1e-12):
    """Minimum norm least squares coefficients of y on the given columns (by the SVD)."""
    n, p = len(y), len(cols)
    if p == 0:
        return []
    m = [[cols[j][i] for j in range(p)] for i in range(n)]
    u, sv, v = svd(m)
    if not sv or sv[0] == 0.0:
        return [0.0] * p
    coef = [0.0] * p
    for t, st in enumerate(sv):
        if st <= rcond * sv[0]:
            continue
        h = sum(u[i][t] * y[i] for i in range(n)) / st
        for j in range(p):
            coef[j] += v[j][t] * h
    return coef


def _combine(atoms, x):
    """D x for a dictionary given as a list of atoms."""
    n = len(atoms[0])
    out = [0.0] * n
    for k, xk in enumerate(x):
        if xk != 0.0:
            for i, v in enumerate(atoms[k]):
                out[i] += xk * v
    return out


def objective(signals, atoms, codes):
    """sum_i ||y_i - D x_i||^2."""
    total = 0.0
    for y, x in zip(signals, codes):
        total += sum((a - b) ** 2 for a, b in zip(y, _combine(atoms, x)))
    return total


def omp(atoms, y, s, tol=1e-12):
    """Orthogonal matching pursuit with at most s atoms. Ties go to the lower index."""
    kk = len(atoms)
    x = [0.0] * kk
    chosen = []
    r = list(y)
    ynorm = sum(v * v for v in y) ** 0.5
    for _ in range(min(s, kk)):
        best, best_c = -1, -1.0
        for k in range(kk):
            if k in chosen:
                continue
            c = abs(sum(a * b for a, b in zip(atoms[k], r)))
            if c > best_c:
                best, best_c = k, c
        if best_c <= tol * ynorm:
            break
        chosen.append(best)
        coef = _lstsq([atoms[k] for k in chosen], y)
        approx = _combine([atoms[k] for k in chosen], coef)
        r = [a - b for a, b in zip(y, approx)]
    if chosen:
        coef = _lstsq([atoms[k] for k in chosen], y)
        for k, c in zip(chosen, coef):
            x[k] = c
    return x


def exact_code(atoms, y, s):
    """The best code with at most s nonzero entries, by trying every support of size min(s, K)."""
    kk = len(atoms)
    best_x, best_r = [0.0] * kk, sum(v * v for v in y)
    for supp in combinations(range(kk), min(s, kk)):
        coef = _lstsq([atoms[k] for k in supp], y)
        approx = _combine([atoms[k] for k in supp], coef)
        r = sum((a - b) ** 2 for a, b in zip(y, approx))
        if r < best_r:
            best_r = r
            best_x = [0.0] * kk
            for k, c in zip(supp, coef):
                best_x[k] = c
    return best_x


def update_atom(signals, atoms, codes, k, replace_unused=True):
    """Update atom k and row k of the codes in place by a rank 1 SVD. Returns True if it changed."""
    omega = [i for i, x in enumerate(codes) if x[k] != 0.0]  # @line L4
    if not omega:  # @line L5
        if not replace_unused:
            return False
        # Replace an unused atom by the signal with the largest residual, normalized.
        # Row k of the codes is zero, so the objective does not change.
        worst, worst_r = -1, 0.0
        for i, (y, x) in enumerate(zip(signals, codes)):
            r = sum((a - b) ** 2 for a, b in zip(y, _combine(atoms, x)))
            if r > worst_r:
                worst, worst_r = i, r
        if worst < 0:
            return False
        res = [a - b for a, b in zip(signals[worst], _combine(atoms, codes[worst]))]
        nrm = sum(v * v for v in res) ** 0.5
        atoms[k] = [v / nrm for v in res]
        return True
    n = len(atoms[0])
    e_cols = []
    for i in omega:  # @line L6
        x = list(codes[i])
        x[k] = 0.0
        approx = _combine(atoms, x)
        e_cols.append([a - b for a, b in zip(signals[i], approx)])
    e = [[e_cols[c][r] for c in range(len(omega))] for r in range(n)]
    u, sv, v = svd(e)  # @line L7
    atoms[k] = [u[r][0] for r in range(n)]  # @line L8
    for c, i in enumerate(omega):
        codes[i][k] = sv[0] * v[c][0]
    return True


def ksvd(signals, atoms, s, iters=10, coder=omp, replace_unused=True):
    """Run K-SVD from the initial dictionary atoms (copied, not changed).

    Returns (atoms, codes, history), where history[j] is the pair
    (objective after the coding step, objective after the atom updates) of
    iteration j.
    """
    atoms = [list(a) for a in atoms]
    codes = []
    history = []
    for _ in range(iters):  # @line L1
        codes = [coder(atoms, y, s) for y in signals]  # @line L2
        after_coding = objective(signals, atoms, codes)
        for k in range(len(atoms)):  # @line L3
            update_atom(signals, atoms, codes, k, replace_unused)
        history.append((after_coding, objective(signals, atoms, codes)))
    return atoms, codes, history  # @line L9
test_k_svd.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-svd/. The authors are listed in prov/0XCKNF.jsonl.

import math
import random
from itertools import combinations

from imgla import sym_eig
from k_svd import exact_code, ksvd, objective, omp, update_atom


def unit(v):
    s = math.sqrt(sum(t * t for t in v))
    return [t / s for t in v]


def planted(rng, n, kk, s, count):
    true = [unit([rng.gauss(0.0, 1.0) for _ in range(n)]) for _ in range(kk)]
    signals = []
    for _ in range(count):
        y = [0.0] * n
        for k in rng.sample(range(kk), s):
            c = rng.choice([-1.0, 1.0]) * rng.uniform(0.5, 1.5)
            y = [a + c * b for a, b in zip(y, true[k])]
        signals.append(y)
    return true, signals


def recovered(true, atoms):
    # Aharon, Elad and Bruckstein count an atom as found when 1 - |<d, d_true>| < 0.01.
    count = 0
    for d in true:
        best = max(abs(sum(p * q for p, q in zip(d, a))) for a in atoms)
        if 1.0 - best < 0.01:
            count += 1
    return count


def test_hand_example():
    # D = (e1, e2), s = 1, signals (2, 1), (4, 2), (1, -2). The objective goes 6 -> 1 -> 0.
    signals = [[2.0, 1.0], [4.0, 2.0], [1.0, -2.0]]
    atoms = [[1.0, 0.0], [0.0, 1.0]]
    codes = [omp(atoms, y, 1) for y in signals]
    assert codes == [[2.0, 0.0], [4.0, 0.0], [0.0, -2.0]]
    assert abs(objective(signals, atoms, codes) - 6.0) <= 1e-12
    update_atom(signals, atoms, codes, 0)
    assert abs(abs(atoms[0][0]) - 2.0 / math.sqrt(5.0)) <= 1e-12
    assert abs(abs(codes[1][0]) - 2.0 * math.sqrt(5.0)) <= 1e-12
    assert abs(objective(signals, atoms, codes) - 1.0) <= 1e-12
    update_atom(signals, atoms, codes, 1)
    assert objective(signals, atoms, codes) <= 1e-24


def test_exact_coder_against_enumeration_of_supports():
    rng = random.Random(1)
    atoms = [unit([rng.gauss(0.0, 1.0) for _ in range(4)]) for _ in range(6)]
    for _ in range(5):
        y = [rng.gauss(0.0, 1.0) for _ in range(4)]
        x = exact_code(atoms, y, 2)
        assert sum(1 for v in x if v != 0.0) <= 2
        r = objective([y], atoms, [x])
        # No pair of atoms gives a smaller residual: solve the 2 x 2 normal
        # equations of each pair directly.
        for i, j in combinations(range(6), 2):
            a, b = atoms[i], atoms[j]
            g11 = sum(p * p for p in a)
            g12 = sum(p * q for p, q in zip(a, b))
            g22 = sum(q * q for q in b)
            h1 = sum(p * q for p, q in zip(a, y))
            h2 = sum(p * q for p, q in zip(b, y))
            det = g11 * g22 - g12 * g12
            c1 = (g22 * h1 - g12 * h2) / det
            c2 = (g11 * h2 - g12 * h1) / det
            res = sum((yy - c1 * p - c2 * q) ** 2 for yy, p, q in zip(y, a, b))
            assert r <= res + 1e-12
        # OMP is never better than the exact coder.
        assert r <= objective([y], atoms, [omp(atoms, y, 2)]) + 1e-12


def test_atom_update_is_the_best_rank_one_fit_and_does_not_increase_the_objective():
    rng = random.Random(2)
    n, kk, s = 6, 9, 2
    _, signals = planted(rng, n, kk, s, 40)
    atoms = [unit([rng.gauss(0.0, 1.0) for _ in range(n)]) for _ in range(kk)]
    codes = [omp(atoms, y, s) for y in signals]
    for k in range(kk):
        omega = [i for i, x in enumerate(codes) if x[k] != 0.0]
        before = objective(signals, atoms, codes)
        # The restricted error matrix E (columns indexed by omega) and its
        # largest singular value, from the eigenvalues of E E^T.
        rest = 0.0
        cols = []
        for i, (y, x) in enumerate(zip(signals, codes)):
            xr = list(x)
            if i in omega:
                xr[k] = 0.0
            approx = [sum(xr[j] * atoms[j][t] for j in range(kk)) for t in range(n)]
            e = [a - b for a, b in zip(y, approx)]
            if i in omega:
                cols.append(e)
            else:
                rest += sum(v * v for v in e)
        update_atom(signals, atoms, codes, k)
        after = objective(signals, atoms, codes)
        assert after <= before + 1e-10
        assert abs(sum(v * v for v in atoms[k]) - 1.0) <= 1e-12
        if cols:
            eet = [[sum(c[p] * c[q] for c in cols) for q in range(n)] for p in range(n)]
            w, _ = sym_eig(eet)
            frob = sum(v * v for c in cols for v in c)
            assert abs(after - (rest + frob - w[-1])) <= 1e-9 * (1.0 + frob)


def test_monotone_with_the_exact_coder():
    rng = random.Random(3)
    n, kk, s = 5, 7, 2
    _, signals = planted(rng, n, kk, s, 20)
    signals = [[v + rng.gauss(0.0, 0.05) for v in y] for y in signals]
    init = [unit(signals[i]) for i in range(kk)]
    _, _, hist = ksvd(signals, init, s, iters=4, coder=exact_code)
    prev = math.inf
    for after_coding, after_update in hist:
        assert after_coding <= prev + 1e-10
        assert after_update <= after_coding + 1e-10
        prev = after_update


def test_local_recovery_of_a_planted_dictionary():
    # Start near the true dictionary: K-SVD with OMP moves every atom onto
    # the true one (up to sign).
    rng = random.Random(40)
    n, kk, s = 8, 10, 2
    true, signals = planted(rng, n, kk, s, 120)
    init = [unit([v + 0.15 * rng.gauss(0.0, 1.0) for v in d]) for d in true]
    assert recovered(true, init) < kk
    atoms, _, hist = ksvd(signals, init, s, iters=8)
    assert recovered(true, atoms) == kk
    # The objective falls, but not to 0: OMP picks a wrong support for some signals.
    assert hist[-1][1] < 0.5 * hist[0][0]


def test_global_recovery_from_data_initialization():
    # Initialized with normalized signals. This is not guaranteed: on other
    # seeds the method stops in a local minimum with fewer atoms found.
    rng = random.Random(0)
    n, kk, s = 8, 10, 2
    true, signals = planted(rng, n, kk, s, 150)
    init = [unit(signals[i]) for i in rng.sample(range(len(signals)), kk)]
    atoms, _, _ = ksvd(signals, init, s, iters=15)
    assert recovered(true, atoms) >= 8

History

Olshausen and Field (1996) learned overcomplete dictionaries for natural image patches with a sparsity penalty and found atoms that look like the receptive fields of the visual cortex. Engan, Aase and Husoy (1999) proposed the method of optimal directions, which alternates sparse coding with a least squares dictionary update. Aharon, Elad and Bruckstein (2006) introduced K-SVD as a generalization of k-means, with the update of one atom and its coefficients by a rank one SVD, and showed on synthetic data that it recovers a planted dictionary more often than MOD. In the same year, Elad and Aharon used it for image denoising, which made it one of the standard tools of sparse representation in imaging. Later work made it faster (approximate K-SVD with batch OMP), online (Mairal and others, 2010) and convolutional.

References

  1. Michal Aharon, Michael Elad and Alfred Bruckstein, K-SVD, an algorithm for designing overcomplete dictionaries for sparse representation, IEEE Transactions on Signal Processing 54(11), 2006, pages 4311 to 4322 (the algorithm, the relation to k-means and the synthetic recovery experiments)
  2. Michael Elad and Michal Aharon, Image denoising via sparse and redundant representations over learned dictionaries, IEEE Transactions on Image Processing 15(12), 2006, pages 3736 to 3745
  3. Kjersti Engan, Sven Ole Aase and John Hakon Husoy, Method of optimal directions for frame design, IEEE International Conference on Acoustics, Speech, and Signal Processing, 1999, the dictionary update by least squares that K-SVD replaces

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW1 outline
  • In plain words