Algorithm Search⌘K

Algorithmadvanced

Iterative hard thresholding

Also called IHT.

Recover an s-sparse vector from y = Ax + e by a gradient step on the least squares residual followed by keeping only the s largest entries, repeated.

Time
O(K m n) worst
Space
O(m + n) extra
Where
K = the number of iterations; m = the number of measurements; n = the length of the signal
Properties
not convexdeterministiciterativematrix freeneeds sparsity level
Origin
Thomas Blumensath, Mike E. Davies, 2008

Iterative hard thresholding (IHT) recovers a vector x∈Rnx \in \mathbb{R}^n with at most ss nonzero entries from m<nm < n linear measurements y=Ax+ey = Ax + e. Each step takes a gradient step on 12∥y−Ax∥2\tfrac12\|y - Ax\|^2 and then keeps only the ss entries of largest magnitude: xk+1=Hs(xk+AT(y−Axk))x^{k+1} = H_s(x^k + A^T(y - Ax^k)). It works directly on the nonconvex problem min⁡∥y−Ax∥2\min \|y - Ax\|^2 subject to ∥x∥0≤s\|x\|_0 \le s of sparse signal recovery. This is the difference to iterative shrinkage-thresholding, which applies soft thresholding (the proximal operator of the ℓ1\ell_1 norm) and solves a convex problem with a weight λ\lambda instead of a known ss. It also differs from orthogonal matching pursuit, which adds one column per step and never removes one: IHT can change the whole support in every step. If the restricted isometry constant satisfies δ3s<1/2\delta_{3s} < 1/2, the error contracts by the factor 2δ3s2\delta_{3s} per step up to a multiple of the noise. The cost of a step is one product with AA and one with ATA^T, so the method suits large problems with fast operators.

The problem

Given a real m×nm \times n matrix AA, a vector y∈Rmy \in \mathbb{R}^m and a sparsity level ss, find

x^∈arg⁡min⁡∥z∥0≤s∥y−Az∥2.\hat x \in \arg\min_{\|z\|_0 \le s} \|y - Az\|^2.

This problem is NP-hard in general (see sparse signal recovery). IHT is a local method for it. The guarantee is for the compressed sensing setting: y=Ax+ey = Ax + e with an ss-sparse xx and a matrix with a small restricted isometry constant, where IHT returns a point within a fixed multiple of ∥e∥\|e\| from xx. The input is AA (or routines for AzAz and ATrA^Tr), yy, ss and a number of steps KK. The output is an ss-sparse vector.

The algorithm

Hs(v)H_s(v) keeps the ss entries of vv of largest magnitude and sets the others to zero. Ties are broken by a fixed rule, here the lower index.

  1. IHT(A, y, s, μ, K)
  2. 1x ← 0 ▷ any s-sparse start
  3. 2for k = 1 to K
  4. 3r ← y - A x ▷ residual
  5. 4g ← Aᵀ r ▷ minus the gradient of ½‖y - Ax‖²
  6. 5x ← H_s(x + μ g) ▷ gradient step, then keep the s largest entries
  7. 6return x

The plain method of Blumensath and Davies uses μ=1\mu = 1 and assumes that AA is scaled so that ∥ASz∥≈∥z∥\|A_Sz\| \approx \|z\| on sparse vectors. Line L5 is a projection: Hs(v)H_s(v) is the closest ss-sparse vector to vv. So IHT is projected gradient descent onto the nonconvex set of ss-sparse vectors. A practical loop also stops when the residual or the change in xx is small.

Example

Take m=4m = 4, n=8n = 8 and A=[I∣H/2]A = [I \mid H/2], where HH is the 4×44 \times 4 Sylvester Hadamard matrix with rows (1,1,1,1)(1,1,1,1), (1,−1,1,−1)(1,-1,1,-1), (1,1,−1,−1)(1,1,-1,-1), (1,−1,−1,1)(1,-1,-1,1). The columns have unit norm. Let xx have x1=1x_1 = 1 and x6=2x_6 = 2, all other entries zero, so s=2s = 2 and y=e1+2⋅12(1,−1,1,−1)=(2,−1,1,−1)y = e_1 + 2 \cdot \tfrac12(1, -1, 1, -1) = (2, -1, 1, -1).

Step 1 starts from x0=0x^0 = 0. Then u=ATy=(2,−1,1,−1,0.5,2.5,0.5,0.5)u = A^Ty = (2, -1, 1, -1, 0.5, 2.5, 0.5, 0.5), and H2H_2 keeps entries 6 and 1. So x1x^1 has x1=2x_1 = 2 and x6=2.5x_6 = 2.5, with the correct support. From now on the support stays fixed, and the step acts on the two entries as z↦z+(I−G)(target−z)z \mapsto z + (I - G)(\text{target} - z) with G=(11/21/21)G = \begin{pmatrix} 1 & 1/2 \\ 1/2 & 1\end{pmatrix}. The matrix I−GI - G has eigenvalues ±12\pm\tfrac12, so the error halves in each step.

kk x1kx^k_1 x6kx^k_6 ∥xk−x∥\lVert x^k - x\rVert
1 2 2.5 1.1180
2 0.75 1.5 0.5590
3 1.25 2.125 0.2795
4 0.9375 1.875 0.1398
5 1.0625 2.03125 0.0699

The same matrix shows that the method can fail. With x1=2x_1 = 2 and x6=−1x_6 = -1, so y=(1.5,0.5,−0.5,0.5)y = (1.5, 0.5, -0.5, 0.5), the iterates from x0=0x^0 = 0 alternate for ever between the vector with x1=1.5x_1 = 1.5, x5=1x_5 = 1 and the vector with x1=1x_1 = 1, x3=−1x_3 = -1. The residual norms alternate between about 1.118 and 1, so the residual also grows in every second step. The true xx is a fixed point of the iteration, but the run never reaches it. This matrix has coherence 1/21/2 and ∥A∥2=2\|A\|^2 = 2, so neither the recovery theorem nor the descent theorem below applies.

Correctness

The full proof is in proofs/correctness.md. It has two parts.

The first part is the recovery guarantee. Let TT be the union of the supports of xx, xkx^k and xk+1x^{k+1}, so ∣T∣≤3s|T| \le 3s. On TT, the step is uT−xT=(I−ATTAT)(xk−x)T+ATTeu_T - x_T = (I - A_T^TA_T)(x^k - x)_T + A_T^Te, and the restricted isometry property bounds ∥I−ATTAT∥≤δ3s\|I - A_T^TA_T\| \le \delta_{3s}. Since xk+1x^{k+1} is the best ss-term approximation of uu, it is at least as close to uTu_T as xx is, and the triangle inequality gives

∥xk+1−x∥≤2δ3s∥xk−x∥+21+δ3s ∥e∥.\|x^{k+1} - x\| \le 2\delta_{3s}\|x^k - x\| + 2\sqrt{1 + \delta_{3s}}\,\|e\|.

So for δ3s<1/2\delta_{3s} < 1/2 the error falls geometrically to at most 21+δ3s ∥e∥/(1−2δ3s)2\sqrt{1 + \delta_{3s}}\,\|e\|/(1 - 2\delta_{3s}). This simple argument gives the condition δ3s<1/2\delta_{3s} < 1/2. Blumensath and Davies (2009) state their theorem under δ3s<1/32\delta_{3s} < 1/\sqrt{32}, and Foucart (2011) proves recovery under δ3s<1/3\delta_{3s} < 1/\sqrt{3}; these are cited, not proved here.

The second part holds for every yy: if ∥A∥≤1\|A\| \le 1, the residual ∥y−Axk∥\|y - Ax^k\| does not increase from k=1k = 1 on. The proof writes the step as the exact minimization of a surrogate function that lies above ∥y−Ax∥2\|y - Ax\|^2 and touches it at the current iterate. This is a statement about the residual, not about the distance to xx.

Proof: IHT with unit step converges linearly to an s-sparse x when delta_3s < 1/2, and its residual does not increase when ||A|| <= 1full

Setting. AA is a real m×nm \times n matrix, x∈Rnx \in \mathbb{R}^n has at most ss nonzero entries, and y=Ax+ey = Ax + e. The hard thresholding operator Hs(v)H_s(v) keeps the ss entries of vv of largest magnitude and sets the others to zero. The iteration with unit step is uk=xk+AT(y−Axk)u^k = x^k + A^T(y - Ax^k) and xk+1=Hs(uk)x^{k+1} = H_s(u^k). For a set T⊆{1,…,n}T \subseteq \{1, \dots, n\}, ATA_T is the submatrix of the columns in TT and vTv_T is the restriction of a vector vv to TT. The restricted isometry constant δk\delta_k is the smallest δ≥0\delta \ge 0 with (1−δ)∥z∥2≤∥Az∥2≤(1+δ)∥z∥2(1 - \delta)\|z\|^2 \le \|Az\|^2 \le (1 + \delta)\|z\|^2 for every zz with at most kk nonzero entries.

Part 1: a contraction under the restricted isometry property

Lemma 1 (best ss-term approximation). For every vv, the vector Hs(v)H_s(v) minimizes ∥v−z∥\|v - z\| over all zz with at most ss nonzero entries.

Proof. For zz with support SS, ∣S∣≤s|S| \le s, we have ∥v−z∥2=∥vS−zS∥2+∑i∉Svi2≥∑i∉Svi2\|v - z\|^2 = \|v_S - z_S\|^2 + \sum_{i \notin S} v_i^2 \ge \sum_{i \notin S} v_i^2, with equality for z=vSz = v_S. The sum ∑i∉Svi2=∥v∥2−∑i∈Svi2\sum_{i \notin S} v_i^2 = \|v\|^2 - \sum_{i \in S} v_i^2 is smallest when SS holds the ss largest values of ∣vi∣|v_i|, and then z=vS=Hs(v)z = v_S = H_s(v). □\square

Lemma 2 (restricted operators). If ∣T∣≤k|T| \le k, then every eigenvalue of ATTATA_T^TA_T lies in [1−δk,1+δk][1 - \delta_k, 1 + \delta_k]. Hence ∥I−ATTAT∥≤δk\|I - A_T^TA_T\| \le \delta_k and ∥ATTe∥≤1+δk ∥e∥\|A_T^Te\| \le \sqrt{1 + \delta_k}\,\|e\|.

Proof. For z∈RTz \in \mathbb{R}^T, the Rayleigh quotient zTATTATz/∥z∥2=∥ATz∥2/∥z∥2z^TA_T^TA_Tz/\|z\|^2 = \|A_Tz\|^2/\|z\|^2 lies in [1−δk,1+δk][1 - \delta_k, 1 + \delta_k] by the definition of δk\delta_k. The symmetric matrix I−ATTATI - A_T^TA_T has eigenvalues in [−δk,δk][-\delta_k, \delta_k], so its norm is at most δk\delta_k. Finally ∥ATT∥=∥AT∥≤1+δk\|A_T^T\| = \|A_T\| \le \sqrt{1 + \delta_k}. □\square

Theorem 1. Let δ=δ3s\delta = \delta_{3s}. For every k≥0k \ge 0 with xkx^k at most ss-sparse,

∥xk+1−x∥≤2δ ∥xk−x∥+21+δ ∥e∥.\|x^{k+1} - x\| \le 2\delta\,\|x^k - x\| + 2\sqrt{1 + \delta}\,\|e\|.

If δ<1/2\delta < 1/2 and x0=0x^0 = 0, then for all kk

∥xk−x∥≤(2δ)k∥x∥+21+δ1−2δ∥e∥.\|x^k - x\| \le (2\delta)^k\|x\| + \frac{2\sqrt{1 + \delta}}{1 - 2\delta}\|e\|.

Proof. Let T=supp⁡(x)∪supp⁡(xk)∪supp⁡(xk+1)T = \operatorname{supp}(x) \cup \operatorname{supp}(x^k) \cup \operatorname{supp}(x^{k+1}), so ∣T∣≤3s|T| \le 3s. The vectors xx, xkx^k and xk+1x^{k+1} all vanish off TT, so A(x−xk)=AT(x−xk)TA(x - x^k) = A_T(x - x^k)_T. Restrict uku^k to TT:

uTk=xTk+ATT(AT(x−xk)T+e),uTk−xT=(I−ATTAT)(xk−x)T+ATTe.u^k_T = x^k_T + A_T^T\big(A_T(x - x^k)_T + e\big),\qquad u^k_T - x_T = (I - A_T^TA_T)(x^k - x)_T + A_T^Te.

By Lemma 2, ∥uTk−xT∥≤δ∥xk−x∥+1+δ ∥e∥\|u^k_T - x_T\| \le \delta\|x^k - x\| + \sqrt{1 + \delta}\,\|e\|.

Next compare xk+1x^{k+1} with xx. Both are ss-sparse, so Lemma 1 gives ∥uk−xk+1∥≤∥uk−x∥\|u^k - x^{k+1}\| \le \|u^k - x\|. For any zz that vanishes off TT, ∥uk−z∥2=∥uTk−zT∥2+∥uTck∥2\|u^k - z\|^2 = \|u^k_T - z_T\|^2 + \|u^k_{T^c}\|^2. Both xk+1x^{k+1} and xx vanish off TT, so the common term cancels and ∥uTk−xTk+1∥≤∥uTk−xT∥\|u^k_T - x^{k+1}_T\| \le \|u^k_T - x_T\|. The triangle inequality gives

∥xk+1−x∥=∥xTk+1−xT∥≤∥xTk+1−uTk∥+∥uTk−xT∥≤2∥uTk−xT∥,\|x^{k+1} - x\| = \|x^{k+1}_T - x_T\| \le \|x^{k+1}_T - u^k_T\| + \|u^k_T - x_T\| \le 2\|u^k_T - x_T\|,

which is the one-step bound. Every iterate xkx^k with k≥1k \ge 1 is ss-sparse because it is an output of HsH_s, and x0=0x^0 = 0 is ss-sparse. With ρ=2δ<1\rho = 2\delta < 1 and c=21+δ∥e∥c = 2\sqrt{1 + \delta}\|e\|, induction on the one-step bound gives ∥xk−x∥≤ρk∥x0−x∥+c(1+ρ+⋯+ρk−1)≤ρk∥x∥+c/(1−ρ)\|x^k - x\| \le \rho^k\|x^0 - x\| + c(1 + \rho + \dots + \rho^{k-1}) \le \rho^k\|x\| + c/(1 - \rho). □\square

In particular, without noise the iterates converge to xx with rate (2δ3s)k(2\delta_{3s})^k, and xx is the only ss-sparse fixed point. The proof uses only ∥I−ATTAT∥\|I - A_T^TA_T\| and ∥ATTe∥\|A_T^Te\| for the sets TT that occur, so the one-step bound holds with these quantities for every matrix. The test file checks this local form on a Gaussian matrix where δ3s\delta_{3s} is not small.

Part 2: the residual does not increase when ∥A∥≤1\|A\| \le 1

Theorem 2. If ∥A∥≤1\|A\| \le 1, then for every yy, every start and every k≥1k \ge 1, ∥y−Axk+1∥≤∥y−Axk∥\|y - Ax^{k+1}\| \le \|y - Ax^k\|.

Proof. Define the surrogate, for x,z∈Rnx, z \in \mathbb{R}^n,

C(x,z)=∥y−Ax∥2+∥x−z∥2−∥A(x−z)∥2.C(x, z) = \|y - Ax\|^2 + \|x - z\|^2 - \|A(x - z)\|^2.

Since ∥A(x−z)∥≤∥A∥ ∥x−z∥≤∥x−z∥\|A(x - z)\| \le \|A\|\,\|x - z\| \le \|x - z\|, we have C(x,z)≥∥y−Ax∥2C(x, z) \ge \|y - Ax\|^2, with equality at x=zx = z. Expand the squares:

∥y−Ax∥2−∥Ax−Az∥2=∥y∥2−2⟨Ax,y−Az⟩−∥Az∥2,\|y - Ax\|^2 - \|Ax - Az\|^2 = \|y\|^2 - 2\langle Ax, y - Az\rangle - \|Az\|^2,
∥x−z∥2=∥x∥2−2⟨x,z⟩+∥z∥2.\|x - z\|^2 = \|x\|^2 - 2\langle x, z\rangle + \|z\|^2.

Adding these, C(x,z)=∥x−u∥2+c(z)C(x, z) = \|x - u\|^2 + c(z) with u=z+AT(y−Az)u = z + A^T(y - Az) and a number c(z)c(z) that does not depend on xx. By Lemma 1, xk+1=Hs(uk)x^{k+1} = H_s(u^k) minimizes C(⋅,xk)C(\cdot, x^k) over the ss-sparse vectors. For k≥1k \ge 1, xkx^k is itself ss-sparse, so

∥y−Axk+1∥2≤C(xk+1,xk)≤C(xk,xk)=∥y−Axk∥2.□\|y - Ax^{k+1}\|^2 \le C(x^{k+1}, x^k) \le C(x^k, x^k) = \|y - Ax^k\|^2. \qquad \square

This is a majorization-minimization argument, as in Blumensath and Davies (2008). It needs no sparsity of the true signal and no restricted isometry property, but it gives no statement about the distance to xx. It is the reason for the condition ∥A∥<1\|A\| < 1 in that paper. Without it the residual can grow: the example on the main page with ∥A∥2=2\|A\|^2 = 2 cycles between two points with different residuals.

Complexity

Each iteration costs one product with AA, one with ATA^T and one selection of the ss largest entries. For a dense matrix this is O(mn)O(mn) time per step, so KK steps cost O(Kmn)O(Kmn). The selection costs O(n)O(n) with a linear time selection algorithm or O(nlog⁡n)O(n \log n) with a sort, which is less than the products. For a partial Fourier or Hadamard matrix the products cost O(nlog⁡n)O(n \log n) with the FFT or the fast Walsh-Hadamard transform. The extra memory is O(m+n)O(m + n) for rr, gg and xx. Under δ3s<1/2\delta_{3s} < 1/2 the number of steps to reach accuracy ε∥x∥\varepsilon\|x\| without noise is O(log⁡(1/ε))O(\log(1/\varepsilon)) by the contraction factor 2δ3s2\delta_{3s}.

Properties

  • Every iterate is exactly ss-sparse (or sparser), unlike the iterates of ISTA.
  • The true xx is a fixed point when e=0e = 0, because then AT(y−Ax)=0A^T(y - Ax) = 0 and Hs(x)=xH_s(x) = x. Other ss-sparse fixed points and cycles can exist when the restricted isometry property fails, as the example shows.
  • The guarantee is uniform: one matrix with δ3s<1/2\delta_{3s} < 1/2 recovers every ss-sparse xx, and the error bound is linear in ∥e∥\|e\|. If xx is not exactly sparse, the bound holds with xx replaced by its best ss-term approximation and ee by e+A(x−Hs(x))e + A(x - H_s(x)).
  • It is not scale invariant: multiplying AA by 2 changes the iterates, because the step is fixed. The theory needs AA to be close to an isometry on sparse vectors.
  • It needs only products with AA and ATA^T, so it is matrix free.

Variants and improvements

  • Normalized IHT (Blumensath and Davies 2010) chooses the step μk=∥gS∥2/∥ASgS∥2\mu_k = \|g_S\|^2/\|A_Sg_S\|^2 on the current support SS and shrinks it when the support changes and the residual would grow. This removes the dependence on the scaling of AA and gives guarantees that do not depend on that scaling.
  • Hard thresholding pursuit (Foucart 2011) uses the support chosen by line L5 and then solves least squares on it. It stops after a finite number of steps when the support repeats.
  • CoSaMP and subspace pursuit pick a larger candidate set, solve least squares on it and prune to ss entries. They cost more per step and have similar guarantees.
  • The same projected gradient idea works for low rank matrices, with a truncated SVD in place of HsH_s, and for other structured sparsity models with a projection onto the model set.
  • Accelerated forms add a momentum term as in FISTA. They are heuristics: the recovery theorems are for the plain form.

When to use it

Use IHT when the sparsity level ss is known or can be bounded, when AA is applied through a fast transform and when memory is tight. Each step is as cheap as a step of ISTA, and the iterates are sparse. When ss is not known but a noise level or a weight is, ℓ1\ell_1 methods such as basis pursuit or ISTA are easier to tune. When ss is small and AA is explicit, orthogonal matching pursuit needs only ss steps. For Gaussian matrices in the large system limit, approximate message passing recovers more sparse vectors per measurement.

Pitfalls

  • The unit step is only safe when AA behaves like an isometry on sparse vectors. Random Gaussian matrices with entries of variance 1/m1/m have ∥A∥2≈(1+n/m)2\|A\|^2 \approx (1 + \sqrt{n/m})^2, and at small sizes their δ3s\delta_{3s} is far above 1/21/2. In a run with 20 random 32×6432 \times 64 Gaussian matrices and s=3s = 3, the unit step recovered xx in 15 cases, diverged in 3 and stopped at a wrong point in 2. This is a measurement. Use the normalized step or scale AA so that ∥A∥<1\|A\| < 1 when the theory does not apply.
  • With ∥A∥<1\|A\| < 1 the residual decreases, but the iterates can still stop at a wrong sparse point.
  • The sparsity level ss is an input. If it is too small, the result misses entries. If it is too large, the condition on δ3s\delta_{3s} is harder to meet and noise enters more entries.
  • When several entries have the same magnitude, the result of HsH_s depends on the tie rule. Fix the rule, or the runs are not reproducible.
  • Do not compare IHT and ISTA at the same step without care: ISTA needs a step at most 1/∥A∥21/\|A\|^2 for its descent theorem, while IHT with unit step relies on the restricted isometry property instead.

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
iterative_hard_thresholding.py 42 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-hard-thresholding/. The authors are listed in prov/M2CY6N.jsonl.
"""Iterative hard thresholding (IHT) for y = A x + e with an s-sparse x.

A is a list of m rows of length n. The iteration is
x <- H_s(x + mu A^T (y - A x)), where H_s keeps the s entries of largest
magnitude. The plain form of Blumensath and Davies uses mu = 1.
"""

from imgla import matvec, norm2, rmatvec


def hard_threshold(v, s):
    """H_s(v): keep the s entries of largest magnitude, set the others to 0.

    Ties are broken by the lower index, so the result is deterministic.
    """
    keep = sorted(range(len(v)), key=lambda i: (-abs(v[i]), i))[:s]
    out = [0.0] * len(v)
    for i in keep:
        out[i] = v[i]
    return out


def iht(a, y, s, iters=500, mu=1.0, x0=None, tol=0.0):
    """Run IHT and return (x, residual_norms).

    residual_norms[k] is ||y - A x^k|| for k = 0, 1, ..., so it has one more
    entry than the number of steps taken. The loop stops early when the
    residual is at most tol.
    """
    n = len(a[0])
    x = list(x0) if x0 is not None else [0.0] * n  # @line L1
    res = [norm2([yi - ai for yi, ai in zip(y, matvec(a, x))])]
    for _ in range(iters):  # @line L2
        if res[-1] <= tol:
            break
        r = [yi - ai for yi, ai in zip(y, matvec(a, x))]  # @line L3
        g = rmatvec(a, r)  # @line L4
        x = hard_threshold([xi + mu * gi for xi, gi in zip(x, g)], s)  # @line L5
        res.append(norm2([yi - ai for yi, ai in zip(y, matvec(a, x))]))
    return x, res  # @line L6
test_iterative_hard_thresholding.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-hard-thresholding/. The authors are listed in prov/M2CY6N.jsonl.

import itertools
import math
import random

from imgla import matvec, norm2, svd, sym_eig
from iterative_hard_thresholding import hard_threshold, iht


def gauss_matrix(rng, m, n):
    return [[rng.gauss(0.0, 1.0) / math.sqrt(m) for _ in range(n)] for _ in range(m)]


def hadamard(m):
    """Sylvester Hadamard matrix of order m (a power of 2)."""
    h = [[1.0]]
    while len(h) < m:
        h = [row + row for row in h] + [row + [-v for v in row] for row in h]
    return h


def identity_hadamard(m):
    """[I | H / sqrt(m)]: two orthonormal bases with coherence 1 / sqrt(m)."""
    h = hadamard(m)
    c = 1.0 / math.sqrt(m)
    return [[1.0 if i == j else 0.0 for j in range(m)] + [c * v for v in h[i]] for i in range(m)]


def sparse_vector(rng, n, s):
    x = [0.0] * n
    for i in rng.sample(range(n), s):
        x[i] = rng.choice([-1.0, 1.0]) * (1.0 + rng.random())
    return x


def dist(u, v):
    return norm2([a - b for a, b in zip(u, v)])


def test_hard_threshold_is_best_s_term_approximation():
    rng = random.Random(1)
    for _ in range(30):
        v = [rng.gauss(0.0, 1.0) for _ in range(8)]
        for s in range(9):
            h = hard_threshold(v, s)
            assert sum(1 for t in h if t != 0.0) <= s
            best = min(
                math.sqrt(sum(v[i] ** 2 for i in range(8) if i not in set(sup)))
                for sup in itertools.combinations(range(8), s)
            )
            assert abs(dist(v, h) - best) <= 1e-12


def test_hard_threshold_ties_take_lower_index():
    assert hard_threshold([1.0, -1.0, 1.0, 0.5], 2) == [1.0, -1.0, 0.0, 0.0]


def test_linear_convergence_when_delta_3s_is_below_one_half():
    # A = [I | H/8] with m = 64 and s = 2. For 6 columns, k from I and 6 - k
    # from H/8, the Gram matrix is I plus a block C with entries +-1/8, so
    # delta_6 <= ||C||_F <= sqrt(9)/8 = 3/8 and the contraction is 2 delta <= 3/4.
    m, s, rho = 64, 2, 0.75
    a = identity_hadamard(m)
    rng = random.Random(2)
    for _ in range(3):
        x = sparse_vector(rng, 2 * m, s)
        y = matvec(a, x)
        x0 = [0.0] * (2 * m)
        xk = x0
        for k in range(1, 40):
            xk, _ = iht(a, y, s, iters=1, x0=xk)
            assert dist(xk, x) <= rho ** k * norm2(x) + 1e-12
        assert dist(xk, x) <= 1e-4


def test_noisy_error_bound_when_delta_3s_is_below_one_half():
    m, s, delta = 64, 2, 0.375
    a = identity_hadamard(m)
    rng = random.Random(3)
    x = sparse_vector(rng, 2 * m, s)
    e = [rng.gauss(0.0, 0.01) for _ in range(m)]
    y = [u + v for u, v in zip(matvec(a, x), e)]
    xk, _ = iht(a, y, s, iters=60)
    bound = 2.0 * math.sqrt(1.0 + delta) * norm2(e) / (1.0 - 2.0 * delta)
    assert dist(xk, x) <= 0.75 ** 60 * norm2(x) + bound


def test_one_step_bound_of_the_proof_holds_for_any_matrix():
    # ||x^{k+1} - x|| <= 2 ||I - A_T^T A_T|| ||x^k - x|| + 2 ||A_T^T e||, with
    # T = supp(x) + supp(x^k) + supp(x^{k+1}); no assumption on A is needed.
    rng = random.Random(4)
    m, n, s = 24, 48, 3
    a = gauss_matrix(rng, m, n)
    x = sparse_vector(rng, n, s)
    e = [rng.gauss(0.0, 0.05) for _ in range(m)]
    y = [u + v for u, v in zip(matvec(a, x), e)]
    xk = [0.0] * n
    for _ in range(25):
        xn, _ = iht(a, y, s, iters=1, x0=xk)
        t = sorted({i for i in range(n) if x[i] != 0.0 or xk[i] != 0.0 or xn[i] != 0.0})
        g = [[(1.0 if i == j else 0.0) - sum(a[r][i] * a[r][j] for r in range(m)) for j in t] for i in t]
        w, _ = sym_eig(g)
        op = max(abs(w[0]), abs(w[-1]))
        ate = norm2([sum(a[r][i] * e[r] for r in range(m)) for i in t])
        assert dist(xn, x) <= 2.0 * op * dist(xk, x) + 2.0 * ate + 1e-10
        xk = xn


def test_residual_does_not_increase_when_norm_of_a_is_below_one():
    rng = random.Random(5)
    m, n, s = 20, 40, 4
    a = gauss_matrix(rng, m, n)
    top = svd(a)[1][0]
    a = [[0.99 * v / top for v in row] for row in a]
    for trial in range(3):
        y = [rng.gauss(0.0, 1.0) for _ in range(m)]
        x0 = [rng.gauss(0.0, 1.0) for _ in range(n)] if trial else None
        _, res = iht(a, y, s, iters=80, x0=x0)
        for k in range(1, len(res) - 1):
            assert res[k + 1] <= res[k] + 1e-12


def test_exact_recovery_matches_exhaustive_l0_search():
    # Noiseless data, tiny sizes: the s-sparse least squares solution found
    # by trying all supports has zero residual only at the true x.
    a = identity_hadamard(8)
    rng = random.Random(6)
    x = sparse_vector(rng, 16, 1)
    y = matvec(a, x)
    xk, res = iht(a, y, 1, iters=200, tol=1e-13)
    best = None
    for j in range(16):
        col = [a[r][j] for r in range(8)]
        c = sum(u * v for u, v in zip(col, y)) / sum(u * u for u in col)
        r = norm2([u - c * v for u, v in zip(y, col)])
        if best is None or r < best[0]:
            best = (r, j, c)
    z = [0.0] * 16
    z[best[1]] = best[2]
    assert dist(z, x) <= 1e-12
    assert dist(xk, z) <= 1e-10
    assert res[-1] <= 1e-12

History

Blumensath and Davies (2008) studied iterative thresholding for the ℓ0\ell_0 penalized and the ℓ0\ell_0 constrained least squares problems. They derived the hard thresholding iteration as a majorization-minimization method and proved that it does not increase the cost when ∥A∥<1\|A\| < 1. In 2009 they proved that the method recovers sparse vectors stably under a condition on δ3s\delta_{3s}, with an error bound of the same form as that of CoSaMP. In 2010 they introduced the normalized form with an adaptive step. Foucart (2011) improved the condition and introduced hard thresholding pursuit, and the book of Foucart and Rauhut (2013) gives the method with its analysis.

References

  1. Thomas Blumensath and Mike E. Davies, Iterative thresholding for sparse approximations, Journal of Fourier Analysis and Applications 14(5-6), 2008, pages 629 to 654 (the iteration as a majorization-minimization method and the decrease of the residual for ||A|| < 1)
  2. Thomas Blumensath and Mike E. Davies, Iterative hard thresholding for compressed sensing, Applied and Computational Harmonic Analysis 27(3), 2009, pages 265 to 274 (the main recovery theorem under a bound on delta_3s)
  3. Thomas Blumensath and Mike E. Davies, Normalized iterative hard thresholding, guaranteed stability and performance, IEEE Journal of Selected Topics in Signal Processing 4(2), 2010, pages 298 to 309
  4. Simon Foucart, Hard thresholding pursuit, an algorithm for compressive sensing, SIAM Journal on Numerical Analysis 49(6), 2011, pages 2543 to 2563
  5. Simon Foucart and Holger Rauhut, A Mathematical Introduction to Compressive Sensing, Birkhauser, 2013, chapter 3 (the algorithm) and chapter 6 (its analysis under the restricted isometry property)

Where this leads

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