Algorithm Search⌘K

Algorithmresearch

Learned ISTA

Also called LISTA.

A fixed number of ISTA-shaped layers soft(W_e y + S x, theta) whose matrices and thresholds are trained on data, to approximate sparse codes in fewer steps than ISTA.

Time
O(K (m n + n^2)) worst
Space
O(n) extra
Where
K = the number of layers; m = the number of measurements; n = the number of unknowns
Properties
deterministicnot exactiterativelearned
Origin
Karol Gregor, Yann LeCun, 2010

Learned ISTA (LISTA) is a network of KK layers, each of the form x←soft⁡(Wey+Sx,θ)x \leftarrow \operatorname{soft}(W_e y + S x, \theta), that maps data yy to an approximate sparse code xx. With the weights We=AT/LW_e = A^T/L, S=I−ATA/LS = I - A^TA/L and θ=λ/L\theta = \lambda/L it is exactly KK steps of ISTA for the lasso min⁡x12∥Ax−y∥2+λ∥x∥1\min_x \tfrac12\|Ax - y\|^2 + \lambda\|x\|_1. LISTA instead trains WeW_e, SS and θ\theta on examples, so that a few layers give codes that ISTA needs many more steps to reach. Gregor and LeCun (2010) introduced it, and it was the first unrolled network (see algorithm unrolling). The equality with ISTA is a theorem. The speed-up is a measurement on a data distribution, and the trained network has no correctness guarantee for data outside that distribution.

In plain words

ISTA finds a sparse code by small steps. Each step does a fixed matrix product, adds a fixed vector made from the data, and then sets the small entries to zero and shrinks the others. It needs many steps, because the step rules were chosen to work for every possible input.

LISTA keeps the shape of one step but lets a computer tune its numbers from examples. You run the tuned step a few times, for example three times, and stop. If the new inputs look like the examples, the tuned steps reach a good code much sooner than the general ones. If they do not, nothing promises a good answer.

The problem

The input is a vector y∈Rmy \in \mathbb{R}^m and trained weights: for each layer k=1,…,Kk = 1, \ldots, K an n×mn \times m matrix WekW_e^k, an n×nn \times n matrix SkS^k and a vector θk≥0\theta^k \ge 0 of nn thresholds. With tied weights all layers share one triple. The output is a code x∈Rnx \in \mathbb{R}^n.

The training problem behind the weights is this. For a dictionary or forward operator A∈Rm×nA \in \mathbb{R}^{m \times n} and a weight λ>0\lambda > 0, let x⋆(y)x^\star(y) be the lasso solution arg⁡min⁡x12∥Ax−y∥2+λ∥x∥1\arg\min_x \tfrac12\|Ax - y\|^2 + \lambda\|x\|_1 (see sparse signal recovery and lasso regression). Gregor and LeCun choose the weights that minimize the mean of 12∥xK(y)−x⋆(y)∥2\tfrac12\|x^K(y) - x^\star(y)\|^2 over a training set of data vectors yy. Other papers train against the true sparse signal instead of the lasso solution.

The algorithm

Here soft⁡(v,θ)i=sign⁡(vi)max⁡(∣vi∣−θi,0)\operatorname{soft}(v, \theta)_i = \operatorname{sign}(v_i)\max(|v_i| - \theta_i, 0).

  1. LISTA(y, (W_e^k, S^k, θ^k) for k = 1..K)
  2. 1x ← 0
  3. 2for k = 1 to K
  4. 3c ← W_e^k y + S^k x ▷ linear part of layer k
  5. 4x ← soft(c, θ^k) ▷ shrinkage with learned thresholds
  6. 5return x

Line L3 is the only place where the data enters. With tied weights the vector WeyW_e y is computed once before the loop. Gregor and LeCun write the first layer as soft⁡(Wey,θ)\operatorname{soft}(W_e y, \theta); it is the case x=0x = 0 of line L3.

The ISTA weights. ISTA for the lasso with step 1/L1/L, L≥∥A∥2L \ge \|A\|^2, is x←soft⁡(x−1LAT(Ax−y),λ/L)x \leftarrow \operatorname{soft}(x - \tfrac1L A^T(Ax - y), \lambda/L). Expand the argument: x−1LATAx+1LATy=Sx+Weyx - \tfrac1L A^TAx + \tfrac1L A^Ty = Sx + W_e y with We=AT/LW_e = A^T/L and S=I−ATA/LS = I - A^TA/L. So one layer with these weights and θ=(λ/L)1\theta = (\lambda/L)\mathbf{1} is one ISTA step.

Training. The weights are fitted by stochastic gradient descent on the loss above. The gradient comes from backpropagation through lines L3 and L4: soft thresholding passes the gradient through the active entries (∣ci∣>θi|c_i| > \theta_i) and blocks it at the others, and its derivative in θi\theta_i is −sign⁡(ci)-\operatorname{sign}(c_i) on the active entries. The implementation writes these formulas by hand and checks them against finite differences.

Example

Take A=(100.6010.8)A = \begin{pmatrix}1 & 0 & 0.6\\ 0 & 1 & 0.8\end{pmatrix}, y=(0.6,0.8)y = (0.6, 0.8) and λ=0.1\lambda = 0.1. The third column of AA has norm 1 and equals yy. The lasso solution is x⋆=(0,0,0.9)x^\star = (0, 0, 0.9): at this point the residual is y−Ax⋆=(0.06,0.08)y - Ax^\star = (0.06, 0.08) and AT(y−Ax⋆)=(0.06,0.08,0.1)A^T(y - Ax^\star) = (0.06, 0.08, 0.1), which is λ\lambda on the support and less than λ\lambda in absolute value elsewhere. The matrix AATAA^T has the eigenvalues 2 and 1, so L=∥A∥2=2L = \|A\|^2 = 2 and θ=0.05\theta = 0.05.

LISTA with the ISTA weights, run for KK layers, gives the ISTA iterates:

KK xKx^K ∥xK−x⋆∥\|x^K - x^\star\|
1 (0.25, 0.35, 0.45) 0.6225
2 (0.24, 0.345, 0.46) 0.6085
10 (0.188016, 0.283988, 0.54) 0.4956
40 (0.008, 0.044, 0.84) 0.0748
46 (0, 0, 0.889332) 0.0107
50 (0, 0, 0.899333) 0.000667

The first layer gives soft⁡(ATy/2,0.05)=soft⁡((0.3,0.4,0.5),0.05)\operatorname{soft}(A^Ty/2, 0.05) = \operatorname{soft}((0.3, 0.4, 0.5), 0.05). The false entries x1x_1 and x2x_2 fall slowly, and ISTA finds the correct support only at step 46. After that the error halves at each step, because on the support the step multiplies the error by 1−∥a3∥2/L=1/21 - \|a_3\|^2/L = 1/2. Step 50 is the first with an error below 0.001.

Now take a hand-made network of one layer: WeW_e has the rows (0,0)(0, 0), (0,0)(0, 0) and (0.6,0.8)(0.6, 0.8), S=0S = 0 and θ=(0,0,0.1)\theta = (0, 0, 0.1). For every y=t (0.6,0.8)y = t\,(0.6, 0.8) with t>0.1t > 0.1 it returns (0,0,t−0.1)(0, 0, t - 0.1), and this is the lasso solution for that yy by the same check as above. So on this family of inputs one layer does the work of 50 ISTA steps. For y=(1,0)y = (1, 0), outside the family, the lasso solution is (0.9,0,0)(0.9, 0, 0), but the same layer returns (0,0,0.5)(0, 0, 0.5). This is the whole story of LISTA in small form: weights fitted to a family of inputs can be much faster than ISTA on it, and can be wrong off it.

Correctness

Three statements are proved in the proof file below. First, one layer with the ISTA weights is one ISTA step, so the network is ISTA by induction. Second, with these weights the fixed points of a layer are exactly the lasso solutions, because soft thresholding is the proximal operator of the ℓ1\ell_1 norm. Third, the backpropagation formulas give the gradient of the training loss wherever no entry sits exactly on a threshold.

For trained weights there is no correctness theorem. What is known is about existence. Chen, Liu, Wang and Yin (2018) assume a noise level, entries of x⋆x^\star bounded by BB and at most ss nonzero entries. Theorem 1 of their paper: if a network recovers every such x⋆x^\star from noiseless data as K→∞K \to \infty, with bounded weights, then Sk−(I−WekA)→0S^k - (I - W_e^kA) \to 0 and θk→0\theta^k \to 0. This coupling motivates LISTA-CP, with layers x←soft⁡(x+(Wk)T(y−Ax),θk)x \leftarrow \operatorname{soft}(x + (W^k)^T(y - Ax), \theta^k). Theorem 2: if ss is small enough, there are weights and thresholds for LISTA-CP with ∥xk−x⋆∥≤sBe−ck+Cσ\|x^k - x^\star\| \le sB e^{-ck} + C\sigma for constants c,C>0c, C > 0 and a noise bound σ\sigma. The theorem does not say that training finds these weights.

Proof: LISTA with the ISTA weights is ISTA, its fixed points are the lasso solutions, and the backpropagation formulas give the gradient of the training lossfull

Setting. A∈Rm×nA \in \mathbb{R}^{m \times n}, y∈Rmy \in \mathbb{R}^m, λ>0\lambda > 0 and L≥∥A∥2L \ge \|A\|^2. The lasso objective is F(x)=12∥Ax−y∥2+λ∥x∥1F(x) = \tfrac12\|Ax - y\|^2 + \lambda\|x\|_1. Soft thresholding with a vector of thresholds θ≥0\theta \ge 0 is soft⁡(v,θ)i=sign⁡(vi)max⁡(∣vi∣−θi,0)\operatorname{soft}(v, \theta)_i = \operatorname{sign}(v_i)\max(|v_i| - \theta_i, 0). A LISTA layer with weights (We,S,θ)(W_e, S, \theta) maps xx to soft⁡(Wey+Sx,θ)\operatorname{soft}(W_e y + S x, \theta), and the network starts from x0=0x^0 = 0 (lines L1 to L5).

What is proved here is a statement about the algorithm around the weights. Nothing is proved about trained weights: for them the page reports measurements only.

Fact (P). For t>0t > 0, soft⁡(v,t1)\operatorname{soft}(v, t\mathbf{1}) is the proximal operator of t∥⋅∥1t\|\cdot\|_1: it is the unique minimizer of u↦t∥u∥1+12∥u−v∥2u \mapsto t\|u\|_1 + \tfrac12\|u - v\|^2. Proof. The function is separable and strongly convex, so it has one minimizer, and each coordinate solves min⁡uit∣ui∣+12(ui−vi)2\min_{u_i} t|u_i| + \tfrac12(u_i - v_i)^2. The optimality condition 0∈t ∂∣ui∣+ui−vi0 \in t\,\partial|u_i| + u_i - v_i gives ui=vi−tu_i = v_i - t if vi>tv_i > t, ui=vi+tu_i = v_i + t if vi<−tv_i < -t, and ui=0u_i = 0 if ∣vi∣≤t|v_i| \le t, because then vi/t∈[−1,1]=∂∣0∣v_i/t \in [-1, 1] = \partial|0|. This is the soft threshold.

Lemma 1 (one layer is one ISTA step). Let We=AT/LW_e = A^T/L, S=I−ATA/LS = I - A^TA/L and θ=(λ/L)1\theta = (\lambda/L)\mathbf{1}. Then for every xx,

soft⁡(Wey+Sx,θ)=soft⁡(x−1LAT(Ax−y),λL),\operatorname{soft}(W_e y + Sx, \theta) = \operatorname{soft}\big(x - \tfrac1L A^T(Ax - y), \tfrac{\lambda}{L}\big),

the ISTA step with step 1/L1/L. Proof. Wey+Sx=1LATy+x−1LATAx=x−1LAT(Ax−y)W_e y + Sx = \tfrac1L A^Ty + x - \tfrac1L A^TAx = x - \tfrac1L A^T(Ax - y). The thresholds are equal.

Corollary. By induction on kk, the KK-layer network with these weights in every layer returns the ISTA iterate xKx^K started at x0=0x^0 = 0. The base case is x0=0x^0 = 0 in both; the step is Lemma 1. The test test_lista_with_ista_weights_is_ista checks this for K=1,…,11K = 1, \ldots, 11.

Lemma 2 (fixed points). With the weights of Lemma 1, xx is a fixed point of the layer if and only if xx minimizes FF. Proof. By (P), x=soft⁡(v,λ/L)x = \operatorname{soft}(v, \lambda/L) with v=x−1LAT(Ax−y)v = x - \tfrac1L A^T(Ax - y) holds if and only if v−x∈(λ/L) ∂∥x∥1v - x \in (\lambda/L)\,\partial\|x\|_1, that is −1LAT(Ax−y)∈λL∂∥x∥1-\tfrac1L A^T(Ax - y) \in \tfrac{\lambda}{L}\partial\|x\|_1. Multiply by LL: this is 0∈AT(Ax−y)+λ ∂∥x∥1=∂F(x)0 \in A^T(Ax - y) + \lambda\,\partial\|x\|_1 = \partial F(x). Since FF is convex, 0∈∂F(x)0 \in \partial F(x) is the condition for a minimizer.

So with the ISTA weights a deep enough network approaches a lasso solution: ISTA converges for L≥∥A∥2L \ge \|A\|^2, with F(xK)−F∗≤L∥x0−x∗∥2/(2K)F(x^K) - F^* \le L\|x^0 - x^*\|^2/(2K) (Beck and Teboulle 2009, Theorem 3.1; see iterative shrinkage-thresholding). LISTA with other weights has no such guarantee in general.

Lemma 3 (why SS and WeW_e must be coupled). Take no thresholds (θ=0\theta = 0) and tied weights. If every x∈Rnx \in \mathbb{R}^n is a fixed point of the layer for the data y=Axy = Ax, then S=I−WeAS = I - W_eA. Proof. With θ=0\theta = 0 the layer is the linear map x↦WeAx+Sxx \mapsto W_eAx + Sx. If it fixes every xx, then (WeA+S−I)x=0(W_eA + S - I)x = 0 for all xx, so WeA+S−I=0W_eA + S - I = 0. Chen, Liu, Wang and Yin (2018, Theorem 1) prove the same coupling in the limit, with thresholds, for networks that recover every sparse xx; this motivates LISTA-CP, which sets Sk=I−WkAS^k = I - W^kA in each layer.

Lemma 4 (backpropagation). Let ck=Weky+Skxk−1c^k = W_e^k y + S^k x^{k-1} and xk=soft⁡(ck,θk)x^k = \operatorname{soft}(c^k, \theta^k) for k=1,…,Kk = 1, \ldots, K, and let ℓ=12∥xK−x⋆∥2\ell = \tfrac12\|x^K - x^\star\|^2 for a target x⋆x^\star. Suppose ∣cik∣≠θik|c^k_i| \ne \theta^k_i for all kk and ii. Set gK=xK−x⋆g^K = x^K - x^\star, and for k=K,…,1k = K, \ldots, 1 let aik=1a^k_i = 1 if ∣cik∣>θik|c^k_i| > \theta^k_i and 00 otherwise, dk=ak⊙gkd^k = a^k \odot g^k and gk−1=(Sk)Tdkg^{k-1} = (S^k)^T d^k. Then

∂ℓ∂Wek=dkyT,∂ℓ∂Sk=dk(xk−1)T,∂ℓ∂θik=−sign⁡(cik) aik gik.\frac{\partial \ell}{\partial W_e^k} = d^k y^T,\qquad \frac{\partial \ell}{\partial S^k} = d^k (x^{k-1})^T,\qquad \frac{\partial \ell}{\partial \theta^k_i} = -\operatorname{sign}(c^k_i)\, a^k_i\, g^k_i.

Proof. Under the assumption, each soft⁡(⋅,⋅)i\operatorname{soft}(\cdot, \cdot)_i is differentiable near (cik,θik)(c^k_i, \theta^k_i): on the active branch it is ci−sign⁡(ci)θic_i - \operatorname{sign}(c_i)\theta_i, with derivative 1 in cic_i and −sign⁡(ci)-\operatorname{sign}(c_i) in θi\theta_i; on the dead branch it is 0 near the point. We show by downward induction that gk=∂ℓ/∂xkg^k = \partial\ell/\partial x^k. For k=Kk = K this is the derivative of ℓ\ell. If it holds for kk, the chain rule through xk=soft⁡(ck,θk)x^k = \operatorname{soft}(c^k, \theta^k) gives ∂ℓ/∂ck=ak⊙gk=dk\partial\ell/\partial c^k = a^k \odot g^k = d^k, and through ck=Weky+Skxk−1c^k = W_e^k y + S^k x^{k-1} it gives ∂ℓ/∂xk−1=(Sk)Tdk=gk−1\partial\ell/\partial x^{k-1} = (S^k)^T d^k = g^{k-1}. The weight WekW_e^k enters ℓ\ell only through ckc^k, linearly with ∂cik/∂(Wek)ij=yj\partial c^k_i/\partial (W_e^k)_{ij} = y_j, which gives dkyTd^k y^T; the same argument gives dk(xk−1)Td^k (x^{k-1})^T for SkS^k, and the threshold formula is the chain rule through the active branch. For tied weights, the gradient is the sum of the KK layer gradients, because the tied weight enters each layer once. The set where some ∣cik∣=θik|c^k_i| = \theta^k_i has measure zero in the data for fixed weights, and the test checks the formulas against central differences.

Complexity

The model is real-ram. A layer with general weights costs one product with WekW_e^k (mnmn operations), one with SkS^k (n2n^2 operations) and O(n)O(n) for the threshold. So KK layers cost O(K(mn+n2))O(K(mn + n^2)) time and O(n)O(n) extra space, and with tied weights O(mn+Kn2)O(mn + Kn^2). The weights take O(K(mn+n2))O(K(mn + n^2)) memory, or O(mn+n2)O(mn + n^2) when tied.

One ISTA step costs one product with AA and one with ATA^T: O(mn)O(mn) for a dense matrix, or the cost of these two calls for a matrix-free operator. So a layer of LISTA costs about the same as a step of ISTA when nn is close to mm, and more when n≫mn \gg m, because SS is a dense n×nn \times n matrix. LISTA-CP and ALISTA keep the form x+WT(y−Ax)x + W^T(y - Ax), which costs O(mn)O(mn) per layer and stores AA only once.

Training is outside the cost of the reconstruction. By backpropagation, one gradient on one example costs a small constant times the forward pass, and it stores the KK intermediate vectors ckc^k, so O(Kn)O(Kn) memory.

Properties

  • ISTA is a special case. With the ISTA weights, LISTA is ISTA, so it inherits the bound F(xK)−F⋆≤L∥x⋆∥2/(2K)F(x^K) - F^\star \le L\|x^\star\|^2/(2K) of Beck and Teboulle (2009, Theorem 3.1) for the start x0=0x^0 = 0.
  • Fixed depth. The number of layers is chosen before training, so the cost of a reconstruction is known in advance. There is no stopping rule.
  • Learned for a distribution. The speed-up holds on data like the training data. Gregor and LeCun measured it on 10×1010 \times 10 patches of natural images from the Berkeley data set, with λ=0.5\lambda = 0.5 and the squared error to the optimal code as the metric: for 100 code units FISTA needed 18 steps to reach the error of one LISTA layer, and for 400 code units 35 steps. This is a measurement, not a property of the algorithm.
  • Not a lasso solver. With trained weights the output is in general not a lasso solution for any λ\lambda, even when it is close to one.

Variants and improvements

  • Untied layers. Each layer has its own (Wek,Sk,θk)(W_e^k, S^k, \theta^k). This is the form of the pseudocode above.
  • LISTA-CP and LISTA-CPSS (Chen, Liu, Wang and Yin 2018). Couple Sk=I−WkAS^k = I - W^kA, as Theorem 1 requires, and optionally keep the largest entries out of the threshold (support selection).
  • ALISTA (Liu, Chen, Wang and Yin, ICLR 2019). Compute WW from AA by a data-free optimization and train only one step size and one threshold per layer.
  • Learned coordinate descent (LCoD). In the same paper, Gregor and LeCun truncate and train coordinate descent in the same way.
  • Learned AMP. Unfold approximate message passing instead of ISTA.
  • Unrolling in general. Any iterative solver can be truncated and trained in the same way; see algorithm unrolling and learned primal-dual.

When to use it

Use LISTA when you must compute sparse codes for many inputs from one distribution under a fixed time budget, and you have enough training data from that distribution. Typical uses are fast feature extraction and the encoder of a sparse autoencoder. Do not use it when the inputs change their statistics, when you need the exact lasso solution, or when the forward operator AA changes from case to case: then use ISTA or FISTA, which work for every input.

Pitfalls

  • Wrong scaling of the ISTA start. Initializing with L<∥A∥2L < \|A\|^2 gives a network that does not even match a convergent ISTA. Compute ∥A∥2\|A\|^2 by power iteration and add a small margin.
  • Negative thresholds. A gradient step can push θi\theta_i below 0, which turns shrinkage into expansion. Project the thresholds to θ≥0\theta \ge 0 after each step.
  • Kinks. Soft thresholding is not differentiable at ∣ci∣=θi|c_i| = \theta_i. A finite difference check at such a point fails for a correct gradient; test at random points.
  • Reading a measured speed-up as a rate. "One layer is worth 18 FISTA steps" was measured on one data set and one λ\lambda. It is not a bound.
  • Evaluating on the training data. The loss must be measured on held-out examples; the example above shows how a network can be exact on its family and wrong off it.

Implementations

The network is a given input: the code takes the list of layer weights (Wek,Sk,θk)(W_e^k, S^k, \theta^k) as an argument and runs lines L1 to L5 around it. The tests build the weights by hand (the ISTA weights and the one-layer network of the example) or from a fixed seed, and train small tied networks on synthetic data. No real data and no downloaded weights are used. The tests check that LISTA with the ISTA weights equals an independent ISTA for 1 to 11 layers, the example values, the backpropagation formulas against central differences, and that a trained 3-layer network has less than a quarter of the loss of 3 ISTA steps on its training set.

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.

lista.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lista/. The authors are listed in prov/KG5S6M.jsonl.
"""Learned ISTA (LISTA) of Gregor and LeCun.

The network is given: a list of layers, each a triple (W_e, S, theta) with
W_e an n x m matrix, S an n x n matrix and theta a list of n thresholds.
Layer k maps x to soft(W_e y + S x, theta). With W_e = A^T / L,
S = I - A^T A / L and theta = lambda / L in every layer, K layers are
K steps of ISTA for the lasso (1/2)||A x - y||^2 + lambda ||x||_1.

Matrices are lists of rows. Vectors are lists of floats.
"""


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


def soft(v, theta):
    """Soft thresholding: sign(v_i) max(|v_i| - theta_i, 0), entry by entry."""
    out = []
    for vi, ti in zip(v, theta):
        if vi > ti:
            out.append(vi - ti)
        elif vi < -ti:
            out.append(vi + ti)
        else:
            out.append(0.0)
    return out


def lista(y, layers):
    """Run the given layers on the data y and return the code x.

    layers is a list of K triples (W_e, S, theta). A network with tied
    weights repeats the same triple K times.
    Cost: K products with W_e (n m each) and with S (n^2 each).
    """
    n = len(layers[0][1])
    x = [0.0] * n  # @line L1
    for w_e, s, theta in layers:  # @line L2
        c = [a + b for a, b in zip(matvec(w_e, y), matvec(s, x))]  # @line L3
        x = soft(c, theta)  # @line L4
    return x  # @line L5


def ista_weights(a, lam, lip):
    """The triple (W_e, S, theta) for which one LISTA layer is one ISTA step.

    lip must be at least ||A||^2, the Lipschitz constant of the gradient of
    (1/2)||A x - y||^2.
    """
    m, n = len(a), len(a[0])
    w_e = [[a[i][j] / lip for i in range(m)] for j in range(n)]
    s = [[(1.0 if j == k else 0.0) - sum(a[i][j] * a[i][k] for i in range(m)) / lip
          for k in range(n)] for j in range(n)]
    return w_e, s, [lam / lip] * n


def ista(a, y, lam, lip, iters, x0=None):
    """Plain ISTA: x <- soft(x - A^T (A x - y) / lip, lam / lip), written from the gradient."""
    m, n = len(a), len(a[0])
    x = list(x0) if x0 is not None else [0.0] * n
    for _ in range(iters):
        r = [ax - yi for ax, yi in zip(matvec(a, x), y)]
        g = [sum(a[i][j] * r[i] for i in range(m)) for j in range(n)]
        x = soft([xj - gj / lip for xj, gj in zip(x, g)], [lam / lip] * n)
    return x


def lasso_objective(a, y, lam, x):
    """(1/2)||A x - y||^2 + lam ||x||_1."""
    r = [ax - yi for ax, yi in zip(matvec(a, x), y)]
    return 0.5 * sum(v * v for v in r) + lam * sum(abs(v) for v in x)


def lista_loss_and_grad(y, layers, target):
    """Loss (1/2)||x^K - target||^2 and its gradient in every weight, by backpropagation.

    Returns (loss, grads) with grads[k] = (dW_e, dS, dtheta) for layer k.
    Soft thresholding is not differentiable where |c_i| = theta_i; the
    formula uses the derivative of the active branch, which is right
    everywhere else.
    """
    n = len(layers[0][1])
    xs = [[0.0] * n]
    cs = []
    for w_e, s, theta in layers:
        c = [a + b for a, b in zip(matvec(w_e, y), matvec(s, xs[-1]))]
        cs.append(c)
        xs.append(soft(c, theta))
    g = [a - b for a, b in zip(xs[-1], target)]
    loss = 0.5 * sum(v * v for v in g)
    grads = [None] * len(layers)
    for k in range(len(layers) - 1, -1, -1):
        w_e, s, theta = layers[k]
        c, x_prev = cs[k], xs[k]
        dc = [gi if abs(ci) > ti else 0.0 for gi, ci, ti in zip(g, c, theta)]
        dtheta = [-gi * (1.0 if ci > 0 else -1.0) if abs(ci) > ti else 0.0
                  for gi, ci, ti in zip(g, c, theta)]
        d_we = [[dci * yj for yj in y] for dci in dc]
        d_s = [[dci * xj for xj in x_prev] for dci in dc]
        grads[k] = (d_we, d_s, dtheta)
        g = [sum(s[i][j] * dc[i] for i in range(n)) for j in range(n)]
    return loss, grads


def train_tied(data, layers_count, start, step, epochs):
    """Fit tied weights (W_e, S, theta) by full-batch gradient descent.

    data is a list of pairs (y, target). start is the initial triple, for
    example the ISTA weights. The gradient of tied weights is the sum of the
    gradients of the K copies. Returns the trained triple.
    """
    w_e = [row[:] for row in start[0]]
    s = [row[:] for row in start[1]]
    theta = list(start[2])
    for _ in range(epochs):
        gw = [[0.0] * len(w_e[0]) for _ in w_e]
        gs = [[0.0] * len(s[0]) for _ in s]
        gt = [0.0] * len(theta)
        for y, target in data:
            _, grads = lista_loss_and_grad(y, [(w_e, s, theta)] * layers_count, target)
            for d_we, d_s, dth in grads:
                for i, row in enumerate(d_we):
                    for j, v in enumerate(row):
                        gw[i][j] += v
                for i, row in enumerate(d_s):
                    for j, v in enumerate(row):
                        gs[i][j] += v
                for i, v in enumerate(dth):
                    gt[i] += v
        scale = step / len(data)
        w_e = [[v - scale * d for v, d in zip(row, drow)] for row, drow in zip(w_e, gw)]
        s = [[v - scale * d for v, d in zip(row, drow)] for row, drow in zip(s, gs)]
        theta = [max(0.0, v - scale * d) for v, d in zip(theta, gt)]
    return w_e, s, theta
test_lista.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lista/. The authors are listed in prov/KG5S6M.jsonl.

import random

from lista import (
    ista,
    ista_weights,
    lasso_objective,
    lista,
    lista_loss_and_grad,
    matvec,
    soft,
    train_tied,
)

A = [[1.0, 0.0, 0.6], [0.0, 1.0, 0.8]]
Y = [0.6, 0.8]
LAM = 0.1
LIP = 2.0  # ||A||^2: the eigenvalues of A A^T are 2 and 1


def close(u, v, tol):
    return all(abs(a - b) <= tol for a, b in zip(u, v)) and len(u) == len(v)


def random_problem(rng, m, n):
    a = [[rng.gauss(0.0, 0.5) for _ in range(n)] for _ in range(m)]
    v = [1.0] * n
    nv = 1.0
    for _ in range(200):
        w = [sum(a[i][j] * sum(a[i][k] * v[k] for k in range(n)) for i in range(m)) for j in range(n)]
        nv = sum(t * t for t in w) ** 0.5
        v = [t / nv for t in w]
    return a, 1.01 * nv


def test_soft_thresholding():
    assert soft([0.3, -0.3, 0.05, -2.0], [0.1] * 4) == [0.3 - 0.1, -0.3 + 0.1, 0.0, -1.9]


def test_first_ista_step_of_the_example():
    x = lista(Y, [ista_weights(A, LAM, LIP)])
    assert close(x, [0.25, 0.35, 0.45], 1e-12)


def test_lista_with_ista_weights_is_ista():
    rng = random.Random(1)
    a, lip = random_problem(rng, 5, 8)
    y = [rng.gauss(0.0, 1.0) for _ in range(5)]
    w = ista_weights(a, 0.2, lip)
    for k in range(1, 12):
        assert close(lista(y, [w] * k), ista(a, y, 0.2, lip, k), 1e-12)


def test_ista_objective_does_not_increase():
    x = [0.0, 0.0, 0.0]
    f = lasso_objective(A, Y, LAM, x)
    for _ in range(60):
        x = ista(A, Y, LAM, LIP, 1, x)
        f_new = lasso_objective(A, Y, LAM, x)
        assert f_new <= f + 1e-15
        f = f_new
    assert abs(f - 0.095) < 1e-6


def test_example_ista_needs_46_steps_for_the_support():
    w = ista_weights(A, LAM, LIP)
    assert lista(Y, [w] * 45)[1] > 0.0
    x46 = lista(Y, [w] * 46)
    assert x46[0] == 0.0 and x46[1] == 0.0
    err50 = sum((a - b) ** 2 for a, b in zip(lista(Y, [w] * 50), [0.0, 0.0, 0.9])) ** 0.5
    err49 = sum((a - b) ** 2 for a, b in zip(lista(Y, [w] * 49), [0.0, 0.0, 0.9])) ** 0.5
    assert err50 < 1e-3 < err49


def test_one_hand_made_layer_is_exact_on_its_family_only():
    layer = ([[0.0, 0.0], [0.0, 0.0], [0.6, 0.8]], [[0.0] * 3 for _ in range(3)], [0.0, 0.0, 0.1])
    for t in (0.3, 0.9, 1.0, 2.5):
        y = [0.6 * t, 0.8 * t]
        assert close(lista(y, [layer]), [0.0, 0.0, t - 0.1], 1e-12)
        assert close(ista(A, y, LAM, LIP, 3000), [0.0, 0.0, t - 0.1], 1e-9)
    # Off the family the same layer is wrong: the lasso solution for y = (1, 0) is (0.9, 0, 0).
    assert close(ista(A, [1.0, 0.0], LAM, LIP, 3000), [0.9, 0.0, 0.0], 1e-9)
    assert close(lista([1.0, 0.0], [layer]), [0.0, 0.0, 0.5], 1e-12)


def test_backpropagation_matches_finite_differences():
    rng = random.Random(3)
    m, n, k = 3, 4, 3
    layers = []
    for _ in range(k):
        w_e = [[rng.gauss(0.0, 0.5) for _ in range(m)] for _ in range(n)]
        s = [[rng.gauss(0.0, 0.3) for _ in range(n)] for _ in range(n)]
        theta = [rng.uniform(0.05, 0.2) for _ in range(n)]
        layers.append((w_e, s, theta))
    y = [rng.gauss(0.0, 1.0) for _ in range(m)]
    target = [rng.gauss(0.0, 1.0) for _ in range(n)]
    _, grads = lista_loss_and_grad(y, layers, target)
    h = 1e-6

    def loss_with(layer, part, i, j, delta):
        new = [(list(map(list, w)), list(map(list, s)), list(t)) for w, s, t in layers]
        if part == 2:
            new[layer][2][i] += delta
        else:
            new[layer][part][i][j] += delta
        return lista_loss_and_grad(y, new, target)[0]

    for layer in range(k):
        for part, rows, cols in ((0, n, m), (1, n, n), (2, n, 1)):
            for i in range(rows):
                for j in range(cols):
                    fd = (loss_with(layer, part, i, j, h) - loss_with(layer, part, i, j, -h)) / (2 * h)
                    g = grads[layer][part][i] if part == 2 else grads[layer][part][i][j]
                    assert abs(fd - g) < 1e-6 * (1.0 + abs(g))


def test_training_beats_ista_with_the_same_depth():
    rng = random.Random(7)
    m, n, k, lam = 4, 6, 3, 0.1
    a, lip = random_problem(rng, m, n)
    data = []
    for _ in range(20):
        xt = [0.0] * n
        for j in rng.sample(range(n), 2):
            xt[j] = rng.choice([-1.0, 1.0]) * rng.uniform(0.5, 1.5)
        y = matvec(a, xt)
        data.append((y, ista(a, y, lam, lip, 2000)))

    def mean_loss(w):
        return sum(lista_loss_and_grad(y, [w] * k, t)[0] for y, t in data) / len(data)

    start = ista_weights(a, lam, lip)
    trained = train_tied(data, k, start, 0.2, 150)
    assert mean_loss(trained) < 0.25 * mean_loss(start)

History

Gregor and LeCun (2010) observed that sparse coding by ISTA or coordinate descent is too slow for real-time feature extraction, wrote ISTA as a recurrent network with the matrices WeW_e and SS, and trained a truncated version to predict the optimal codes. This started the line of work now called algorithm unrolling or deep unfolding, surveyed by Monga, Li and Eldar (2021). Chen, Liu, Wang and Yin (2018) gave the first convergence theory, with the coupled form LISTA-CP, and ALISTA (2019) reduced the trained parameters to a few scalars per layer.

References

  1. Karol Gregor and Yann LeCun, Learning fast approximations of sparse coding, Proceedings of the 27th International Conference on Machine Learning (ICML), 2010, pages 399 to 406 (eq. 2 for ISTA in the form h_theta(W_e X + S Z), Section 3 and Algorithms 3 and 4 for the LISTA forward and backward pass, Table 1 for the comparison with FISTA)
  2. Xiaohan Chen, Jialin Liu, Zhangyang Wang and Wotao Yin, Theoretical linear convergence of unfolded ISTA and its practical weights and thresholds, Advances in Neural Information Processing Systems 31 (NeurIPS), 2018, Theorem 1 (the coupling of W and S is necessary) and Theorem 2 (LISTA-CP weights with linear convergence exist)
  3. Amir Beck and Marc Teboulle, A fast iterative shrinkage-thresholding algorithm for linear inverse problems, SIAM Journal on Imaging Sciences 2(1), 2009, Section 3, Theorem 3.1 (the O(1/k) bound of ISTA, which LISTA with the ISTA weights inherits)
  4. Vishal Monga, Yuelong Li and Yonina C. Eldar, Algorithm unrolling, interpretable, efficient deep learning for signal and image processing, IEEE Signal Processing Magazine 38(2), 2021, pages 18 to 44 (LISTA as the first unrolled network, and its later variants)

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)
WritingW2 basic
  • a scene preset for the example