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.
- Solves
- Dictionary learning
- 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
- Model
- Real RAM
- Properties
- not convexdeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Michal Aharon, Michael Elad, Alfred Bruckstein, 2006
K-SVD is an algorithm for the dictionary learning problem: given signals , find unit atoms and codes with at most nonzero entries each, so that is small. Like k-means, it alternates two steps: code every signal with the current dictionary, then update the dictionary. With , 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 signal matrix , a number of atoms (usually , an overcomplete dictionary) and a sparsity , find an dictionary with unit columns and a code matrix that minimize
The output is and . The problem is not convex and is NP-hard in general, so K-SVD is a local method: it lowers from a starting dictionary, often a random choice of normalized signals or a fixed transform such as an overcomplete DCT.
The algorithm
Write for row of , the coefficients of atom in all signals.
K-SVD(Y, D, s, J)- 1
for j = 1 to J - 2
for i = 1 to N: x_i ← SparseCode(D, y_i, s) ▷ for example OMP - 3
for k = 1 to K - 4
ω ← {i : x^k_i ≠ 0} ▷ the signals that use atom k - 5
if ω is empty: replace d_k by the worst represented signal, normalized; continue - 6
E ← columns ω of Y - Σ_{j≠k} d_j x^j ▷ error without atom k - 7
(u, σ, v) ← largest singular triple of E - 8
d_k ← u, x^k_ω ← σ v ▷ best rank one fit of E - 9
return D, X
Line L6 keeps only the columns in . This is the main idea: the new coefficients fill only the positions that were already nonzero, so the sparsity pattern of does not grow. A rank one fit of all columns would give a dense row. Line L6 uses the new values of the atoms and of their coefficients, as in a Gauss-Seidel sweep.
Example
Take , , , the start and three signals , , .
Coding (L2). OMP with one atom picks the atom with the largest : , , . The residuals are , and , so .
Atom 1 (L4 to L8). and no other atom is used by these signals, so
has rank 1, with , and . The new atom is with coefficients , which fit and exactly. Now .
Atom 2. and is the single column . Its best rank one fit is itself: (up to sign) with coefficient . Now .
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 is the best rank one fit: for any matrix , over unit is , reached at , . 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 atoms), the codes of the previous iteration are feasible for it, so the coding step does not increase the objective either. Then 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. is a real matrix whose columns are the signals. A dictionary is with columns of norm 1. A code matrix is , with columns that have at most nonzero entries; denotes row of . The objective is
One K-SVD iteration first replaces every by the output of a sparse coder, and then, for in turn, updates and as follows. Let . If is empty, the atom may be replaced by any unit vector (the implementation uses the normalized residual of the worst represented signal). Otherwise let , let be the columns of with index in , and let be its largest singular value and a pair of singular vectors. The update sets , for (in the order of ), and leaves for .
Lemma 1: the best rank one fit
For a real matrix with largest singular value ,
and the minimum is reached at , .
Proof. Fix a unit vector . The function is a convex quadratic with minimizer and minimum . Now , and its maximum over unit vectors is the largest eigenvalue of the symmetric matrix (the Rayleigh quotient), which is , reached at . Then .
Lemma 2: the atom update does not increase the objective
Let be any pair whose codes have at most nonzeros per column, and let be the result of the update of atom . Then , every column of has at most nonzero entries, and .
Proof. If is empty, then , so does not appear in , and changing it does not change . Otherwise write , so that , and only and change. Split the columns into and its complement. On the complement, before and after, so those columns of do not change. On , the columns form , a fit of by a unit vector times a row. By Lemma 1, the new pair gives the smallest possible value, , which is at most the value of the old pair . So does not increase.
The new row is zero outside , so the support of each column either stays the same or loses entry (when ). It never gains an entry, so each column still has at most nonzeros. Finally .
The restriction to is what keeps the sparsity: a rank one fit of the full would in general make dense.
Theorem: monotone objective with an exact sparse coder
Assume the coder is exact, that is, for each it returns a minimizer of over all with at most nonzero entries. Let be the objective at the end of iteration , and the objective after its coding step. Then
so the sequence of objective values converges.
Proof. At the start of iteration , the codes from iteration have at most nonzeros per column (Lemma 2). They are feasible for the coding problem of each column with the current , so the exact coder returns a column with residual at most . Summing over gives . Within an iteration, the atom updates each do not increase (Lemma 2), so . All values are nonnegative. A nonincreasing sequence that is bounded below converges.
The implementation's exact coder tries every support of size and solves least squares on it. This is exact: a support with fewer than atoms is contained in one with exactly 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 , 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 ), the objective is a different one, and the argument above applies only to the atom update step.
Complexity
With OMP, coding one signal costs for the correlations plus the cost of small least squares problems, so the coding step costs when is small. In the update of atom , building costs per column, and the columns of all atoms together number at most . A rank one SVD of the matrix costs per step of power iteration, or per sweep of a full SVD, which is what the implementation uses. One iteration is therefore , and iterations cost . The memory beyond is for the dictionary, for sparse codes and in the worst case for the restricted error matrix. In practice the coding step dominates; batch OMP, which precomputes and , 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 , the coefficients forced to 1 and no normalization, the update of atom becomes the mean of its signals, and K-SVD is k-means. With and free coefficients it is gain-shape vector quantization.
Variants and improvements
- Approximate K-SVD replaces the SVD by one step of alternating updates, then , which avoids forming explicitly. Together with batch OMP this is the common fast version (Rubinstein, Zibulevsky and Elad, 2008).
- MOD updates all atoms at once by and then normalizes. Each iteration costs more, but it is simple.
- Error target coding codes each signal until instead of with exactly atoms. This is the form used for denoising, with set from the noise level.
- Online dictionary learning (Mairal, Bach, Ponce and Sapiro) processes signals in small batches with an 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 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 , , and 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 ).
- With OMP, the objective is not monotone. In four measured runs with , , and , 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.
# 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W1 outline |
|
Tag 0XCKNF Edit this page History Report an error Markdown