Proximal methods: ISTA, FISTA and the Moreau envelope
Introduce the proximal operator as a generalization of projection that handles simple nonsmooth terms exactly. Use it to build proximal gradient (ISTA) for composite f + g problems, its accelerated FISTA version, and the Moreau envelope, which smooths nondifferentiable functions while preserving their minimizers.
After this lesson you can
- Define the proximal operator and calculate it for the ℓ1 and ℓ2 norms, convex indicators and the nuclear norm.
- Derive proximal gradient by minimizing a quadratic model plus the nonsmooth term.
- Prove ISTA's O(1/k) rate and explain how FISTA achieves O(1/k²).
- Use the Moreau envelope and decomposition to relate the proximal operator of f to that of its conjugate.
- Implement ISTA and FISTA with backtracking for lasso and matrix completion.
Before you start
Motivation: smooth plus simple
Almost all regularized learning problems have the same form:
where is convex and differentiable (a fitting error: least squares, logistic regression) and is convex but nondifferentiable, so it can be described very simply: a norm, a constraint, a rank penalty. Three recurring examples:
- Lasso. and . The penalty is nondifferentiable at every point with a zero coordinate, exactly the points of interest: sparse models.
- Constraints. Minimizing over a closed convex set is equivalent to minimizing , with if and otherwise. Here is not even finite.
- Low rank. Matrix completion for ratings minimizes , where the nuclear norm (sum of singular values) is the matrix analogue of .
In the previous lesson we handled with subgradients. The subgradient method works but pays a high price: rate even when is smooth and, worse, in practice it never produces exact zeros: iterates bounce around the corner without landing on it. For a sparse model, a method that returns no zero coordinates misses the most valuable part of the problem.
This lesson’s idea is not to approximate at all. Leave to the gradient and solve exactly with an elementary operation, the proximal operator. For this is one line of code; for the nuclear norm, an SVD. The resulting method retains the form of gradient descent, converges at (and with acceleration, at , which is optimal) and lands exactly on zeros.
The proximal operator
Start with one variable. We want to reduce with step , where is a subgradient. From with , the explicit step gives : it crossed the vertex and ended farther away. An implicit step does something else: it finds such that
so the subgradient is evaluated at the destination, not the starting point. This is analogous to backward versus forward Euler and has the same advantage: it cannot cross the vertex. If the vertex is within reach, it stays there. Passing from the equation to the minimization problem is immediate and defines the proximal operator.
Proof
The function is proper and closed. A proper closed convex function has an affine lower bound, , so as : is coercive and lower semicontinuous, and attains its minimum. It is also -strongly convex, and a strongly convex function has at most one minimizer.
For the characterization, minimizes iff . Since the quadratic term is finite and differentiable throughout the space, the sum rule of subdifferential calculus gives , and belongs to that sum exactly when .
∎The characterization says , i.e. : the proximal operator is the inverse of “identity plus times the subdifferential”. This is why it is called the implicit step and why it exists and is unique even when is multivalued: can always be inverted.
As you move in the figure, look at the readouts below. The last checks the theorem’s optimality condition: the quotient must lie in the subdifferential of at . Where is differentiable, the subdifferential is one point and the proximal operator solves an equation; at a corner it is an interval, and the longer it is, the more values of land on that corner. This gives the lesson’s central phenomenon: corners of trap the proximal point, and the corners of are at zero.
Two properties will be used below. For , is the identity; and the proximal operator is stronger than merely nonexpansive.
Proof
By the characterization, and . A convex function’s subdifferential is a monotone operator: (add the two subgradient inequalities). Multiplying by , , the first inequality. The second follows from Cauchy–Schwarz: .
∎A catalog of proximal operators
Calculating a proximal operator solves a small problem, and for functions used in practice this has a closed-form solution. The table collects those you need; here is the proximal parameter and functions are applied coordinatewise where indicated.
| Name | ||
|---|---|---|
| identity | ||
| soft thresholding | ||
| shrinkage | ||
| block thresholding | ||
| , projection onto | projection | |
| clipping | ||
| singular-value thresholding | ||
| elastic net | ||
| (nonconvex) | if , otherwise | hard thresholding |
Two calculus rules go a long way. If is separable, minimization splits into one problem per coordinate and the proximal operator applies coordinatewise (giving from ). And if the argument is shifted, . There is no general sum rule: the proximal operator of is not the composition of the two (you will check this in common mistakes).
Soft thresholding
The case that gives this lesson and its star algorithm their name is the norm. One variable suffices: minimize . For , is a parabola with derivative , zero at ; that point is admissible only if . For , the derivative is , zero at , admissible only if . If , each branch’s parabola keeps falling toward the vertex and the minimum is at . In summary:
It is continuous, piecewise linear, and has three regions: a dead zone where the result is exactly zero, and two branches moving the value a distance toward the origin. Compare hard thresholding (zero small values and leave large ones alone), the proximal operator of the “norm”, which is discontinuous. This difference matters when discussing convexity.
One interpretation explains almost everything: soft thresholding is identity minus clipping, . The Moreau decomposition will soon explain why.
The proximal operator of the unsquared Euclidean norm, , does the same in higher dimensions: if it returns ; otherwise it shrinks the entire vector a length toward the origin while retaining its direction. This is block thresholding, used to zero whole groups of coefficients at once (group lasso). The proximal operator of an indicator is always a projection: if , then is outside and inside, so the problem reduces to minimizing over , whose solution is the Euclidean projection , without involving . The proximal operator thus generalizes projection: projection is the proximal operator of a constraint.
The nuclear norm: singular-value thresholding
For matrices, the analogue of is the nuclear norm , and its proximal operator is soft thresholding… applied to singular values.
Proof
Use the nuclear norm’s subdifferential description (Watson, 1992): if is a compact SVD of with positive singular values, . Split , with the singular values above and the rest, and let . Then
We have , and . Thus and by the proximal characterization, .
∎The proof also shows the result: retain singular vectors, subtract from each singular value and zero those below . Thus the nuclear norm’s proximal operator reduces rank: output rank is the number of singular values of exceeding .
The Moreau envelope
The proximal operator is computed by minimization; the value of that minimum is another very useful function.
For and the minimum is attained at and equals ; for it is attained at and equals . This is the Huber function: a parabola rounding the tip of and continuing as straight lines. The envelope smooths the corner without moving the minimum.
Proof
(1) is jointly convex, and minimizing a jointly convex function with respect to one variable gives a convex function of the other. It is finite because the minimum exists and is attained (previous theorem), and by taking .
(2) Let and . Using as candidate in the envelope of another point , . Subtract and expand to obtain
If , convexity gives , and with (A), . Taking with yields , so : the subdifferential is a singleton and is differentiable with gradient . For the Lipschitz constant, the gradient is ; if and are the proximal points of and , firm nonexpansiveness gives
(3) for all , and if minimizes then : the minimum value is the same and minimizes . Conversely, if minimizes , then , i.e. , and the proximal characterization means . This chain also shows the final statement.
∎Two readings of the theorem. First, smoothing: the envelope is a differentiable version of that resembles it more as gets smaller ( as ), and its smoothness worsens as . This is the universal smoothing tradeoff: accuracy versus conditioning. Second, an identity unifies the lesson’s two concepts:
The proximal operator is a gradient descent step on the envelope with step , the largest allowed by its smoothness. Iterating (the proximal point method) is thus gradient descent on a smooth function with the same minimizers as , converging to one at gradient methods’ rate.
The Moreau decomposition
We still need to explain “soft thresholding equals identity minus clipping”. It is an instance of a general law relating the proximal operator of to that of its conjugate .
Proof
Let and . By the characterization, , and by Fenchel–Young equality for closed convex functions this is equivalent to . Now , so , characterizing . Substituting, .
∎Apply it to : its conjugate is the indicator of the unit ball, , whose proximal operator is clipping regardless of parameter. With ,
Soft thresholding is what remains after clipping. For the Euclidean norm, is the unit ball indicator and block thresholding is minus its projection onto the ball of radius . For the norm, whose conjugate is the ball indicator, the proximal operator reduces to projection onto the ball: the decomposition transfers a difficult calculation to the other side when it is easier.
Proximal gradient (ISTA)
Return to the composite problem . Assumptions throughout: is convex and differentiable throughout with -Lipschitz gradient (it is -smooth), is proper, closed and convex, and the problem has a minimizer . The method follows a gradient descent idea: the descent lemma states , a quadratic model majorizing . Gradient descent minimizes that model. For minimize the model plus unchanged :
Notice the threshold: , not . The proximal parameter is the step , and regularization is already inside . With and , the threshold at each iteration is .
Three familiar cases are special cases, a good sign that the design is right:
- : the proximal operator is identity, leaving gradient descent.
- : the proximal operator is projection, leaving projected gradient.
- : the proximal point method remains, .
The method has the desired property: its fixed points are exactly the solutions.
Proof
By the proximal characterization, equality is equivalent to , i.e. , or , convex optimality.
∎The rate
The proof needs a single lemma, valid for both ISTA and FISTA. It is the composite analogue of the descent lemma in the smooth case.
Proof
Three inequalities. The descent lemma gives . Convexity of gives . Added together, . By the proximal characterization, , and the subgradient inequality gives . Adding the last two cancels the term:
Finally, , whence .
∎Proof
Apply the lemma with and . With it gives : ISTA is a (monotone) descent method. With , . Summing from to , the right side telescopes and . Since decreases, each summand is at least , giving .
∎The rate matches gradient descent in the smooth case: adding and solving it with the proximal operator costs nothing in the bound. If is also -strongly convex, convergence is linear, with factor in (Beck, 2017, ch. 10), as in the smooth case.
The safe step is the one proved. The figure shows why the actual limit is : in a direction of curvature , the gradient step multiplies error by , whose absolute value is less than 1 only if . The proximal operator cannot fix a diverging step, because it is nonexpansive and cannot recover what the gradient has already amplified.
FISTA: acceleration for composite problems
Nesterov acceleration improved to in the smooth case by extrapolating before evaluating the gradient. Beck and Teboulle (2009) showed the same idea survives intact with a proximal operator in between, calling the result FISTA (Fast ISTA).
This is ISTA with one change: gradient and proximal operator are evaluated at extrapolated instead of . Per-iteration cost is the same. With this is exactly lesson 9’s Nesterov acceleration (with indices shifted by one).
Proof
Two properties of sequence : (from the definition, since ) and (by induction, ). Let and, for , (with ).
Apply the fundamental inequality at with . By convexity of , , so
Multiply by . We have , and the definitions of and give and . With :
and for (with ), . The quantity is a Lyapunov function: it does not increase. Thus , and yields the bound.
∎This has the same structure as the smooth case: energy that the method does not let increase. The rate is optimal: no first-order method improves it in the class of convex problems with -Lipschitz gradient (lesson 9’s lower bound), so nothing better can be sought in this class using only gradients and proximal operators.
What FISTA does not promise
The theorem bounds from above with an envelope; it does not say falls at every iteration. Indeed it does not: momentum makes iterates overshoot the minimum and rise for several consecutive iterations, and the error curve ripples with peaks (visible on the previous figure’s logarithmic scale). ISTA, by contrast, is monotone, as proved. There are two remedies, as for smooth acceleration (adaptive restart):
- Function restart. Whenever , discard the step, set (erase momentum) and repeat from as an ISTA step, which cannot increase . The resulting monotone curve often converges faster in practice than FISTA without restart, especially when the problem is locally well conditioned, as lasso near its sparse solution. O’Donoghue and Candès (2015) proposed adaptive restart and analyzed it for strongly convex quadratics; their version only erases momentum and continues without repeating the step, so may rise on the restart iteration. Repeating the step as ISTA guarantees an exactly monotone curve; this lesson implements that variant.
- Monotone variant (MFISTA). Keep the better of the new and previous candidates.
The theorem’s guarantee applies to FISTA without restart; restart gains monotonicity and observed speed, not a new bound. A later result (Chambolle and Dossal, 2015) also proved FISTA iterates converge (with sequence for ), which was unknown for the original version.
Backtracking and stopping criterion
The method needs , which is rarely known: for lasso it is , calculable but expensive; for logistic loss or a network loss it is a loose bound. The answer is as in backtracking line search: try estimate and check what the proof actually uses, the descent lemma at the two points involved,
If it fails, multiply by a factor (e.g. 2) and repeat. Each attempt costs a proximal operation and an evaluation of , never a new gradient. The proofs above use only that inequality, not the global constant, so they hold with replaced by ; FISTA additionally needs nondecreasing (so behaves well). Thus even need not be correct: an underestimate corrects itself and an overestimate only makes steps too short. The final bound is the original with replaced by .
We still need to know when to stop. As in the previous lesson, the norm of an arbitrary subgradient of is unsuitable: near a corner it does not tend to zero. A cheap criterion is the difference between iterates, , measuring fixed-point residual, but it does not bound . For lasso there is something much better: an optimality certificate from duality.
Proof
For feasible , , so . Check that, with ,
using and . Scaling is feasible by construction, and the final claim follows from .
∎The gap costs one extra matrix-vector product, is always at least the true error, and converges to zero with the iterates: a guaranteed stopping criterion. Also, is optimal iff (optimality condition ), so is the value above which the model is empty and the natural scale for scanning values.
Something remarkable happens in that figure: ISTA and FISTA identify support (which coefficients are nonzero) before converging in value. With default regularization FISTA fixes final support at iteration 61, when error is of order and still has about three orders of magnitude to fall in 300 iterations; ISTA does so at 221, with error of order . This directly follows from the proximal operator: once is close enough to the solution, coefficients that are zero at the optimum fall in soft thresholding’s dead zone and become zero, remaining there. The method discovers structure and then refines values on it. A subgradient method cannot do this because it has no operation sending a value exactly to zero.
Implementation from scratch
Start with proximal operators and check the theory: soft thresholding minimizes its problem (against a fine grid), it is “identity minus clipping”, the envelope of is the Huber function, and its gradient is .
import numpy as np
def soft(v, t):
"""Umbral suave: prox de t*|.| aplicado componente a componente."""
return np.sign(v) * np.maximum(np.abs(v) - t, 0.0)
def prox_l2(v, t):
"""Umbral por bloques: prox de t*||.||_2 (encoge el vector entero hacia 0)."""
n = np.linalg.norm(v)
return np.zeros_like(v) if n <= t else (1 - t / n) * v
def prox_box(v, lo, hi):
"""Proximal de la indicatriz de [lo, hi]^n: la proyección."""
return np.clip(v, lo, hi)
# 1) comprobación por fuerza bruta: el proximal es el mínimo de g(x) + (x - v)^2/(2 lam)
rng = np.random.default_rng(0)
xs = np.linspace(-6, 6, 120001)
peor = 0.0
for _ in range(200):
v, lam = rng.uniform(-4, 4), rng.uniform(0.1, 2)
h = np.abs(xs) + (xs - v) ** 2 / (2 * lam)
peor = max(peor, abs(xs[np.argmin(h)] - soft(v, lam)))
print(f"proximal de |x|: error máximo frente a la rejilla fina = {peor:.1e}")
# 2) el umbral suave es 'identidad menos recorte' (descomposición de Moreau con g* = indicatriz de [-1, 1])
v, lam = rng.normal(size=1000) * 3, 0.8
print("soft(v, lam) == v - lam*clip(v/lam, -1, 1):", np.allclose(soft(v, lam), v - lam * np.clip(v / lam, -1, 1)))
# 3) la envolvente de Moreau de |x| es la función de Huber, y su gradiente es (v - prox)/lam
def moreau_abs(v, lam):
p = soft(v, lam)
return np.abs(p) + (p - v) ** 2 / (2 * lam)
def huber(v, lam):
return np.where(np.abs(v) <= lam, v ** 2 / (2 * lam), np.abs(v) - lam / 2)
v = np.linspace(-3, 3, 13)
print("envolvente == Huber:", np.allclose(moreau_abs(v, 0.8), huber(v, 0.8)))
eps = 1e-6
grad_num = (moreau_abs(v + eps, 0.8) - moreau_abs(v - eps, 0.8)) / (2 * eps)
print("gradiente numérico == (v - prox)/lam:", np.allclose(grad_num, (v - soft(v, 0.8)) / 0.8, atol=1e-5))
print("pendiente máxima del gradiente = 1/lam =", 1 / 0.8)
# 4) bloques y caja
w = np.array([3.0, 4.0])
print("prox de 2*||.||_2 en (3, 4):", prox_l2(w, 2.0), " norma:", np.linalg.norm(prox_l2(w, 2.0)))
print("prox de la caja [-1, 1] en (2.5, -0.3):", prox_box(np.array([2.5, -0.3]), -1, 1))Now the algorithm. One loop serves ISTA and FISTA; function restart repeats the step without momentum from when rises. The problem is lasso with and correlated columns, where FISTA stands out. The objective uses scikit-learn’s normalization, , enabling comparison below. The previous section’s duality gap is included.
import numpy as np
def prox_grad(f, grad_f, g, prox_g, x0, L, iters, accel=False, restart=False):
"""ISTA (accel=False) o FISTA (accel=True) con paso 1/L. prox_g(v, t) es el prox de t*g en v."""
x, y, t = x0.copy(), x0.copy(), 1.0
Fx = f(x) + g(x)
xs, Fs = [x], [Fx]
for _ in range(iters):
x_new = prox_g(y - grad_f(y) / L, 1.0 / L)
F_new = f(x_new) + g(x_new)
if accel and restart and F_new > Fx: # reinicio por función: repetir sin momento desde x
t = 1.0
x_new = prox_g(x - grad_f(x) / L, 1.0 / L)
F_new = f(x_new) + g(x_new)
if accel:
t_new = (1 + np.sqrt(1 + 4 * t * t)) / 2
y = x_new + ((t - 1) / t_new) * (x_new - x)
t = t_new
else:
y = x_new
x, Fx = x_new, F_new
xs.append(x)
Fs.append(Fx)
return xs, np.array(Fs)
# ---- el problema: lasso 0.5/n ||Xw - y||^2 + lam ||w||_1 con columnas correlacionadas (rho = 0.8) y n < d
rng = np.random.default_rng(1)
n, d, k = 100, 200, 8
Z = rng.normal(size=(n, d))
X = Z.copy()
for j in range(1, d):
X[:, j] = 0.8 * X[:, j - 1] + 0.6 * Z[:, j]
w_true = np.zeros(d)
w_true[rng.choice(d, k, replace=False)] = rng.choice([-1, 1], k) * rng.uniform(1, 2, k)
y = X @ w_true + 0.1 * rng.normal(size=n)
lam_max = np.max(np.abs(X.T @ y)) / n
lam = 0.03 * lam_max
f = lambda w: 0.5 / n * np.sum((X @ w - y) ** 2)
grad_f = lambda w: X.T @ (X @ w - y) / n
g = lambda w: lam * np.sum(np.abs(w))
prox_g = lambda v, t: soft(v, t * lam) # el umbral es t*lam, con t = 1/L
L = np.linalg.norm(X, 2) ** 2 / n # constante de Lipschitz de grad_f
print(f"L = {L:.3f} lambda = {lam:.4f} = 0.03 lambda_max")
def gap(w):
"""Gap de dualidad: P(w) - D(theta), con theta = residuo escalado a ||X^T theta||_inf <= n lam."""
r = y - X @ w
a = n * lam
s = min(1.0, a / np.max(np.abs(X.T @ r)))
theta = s * r
primal = 0.5 * r @ r + a * np.sum(np.abs(w))
dual = 0.5 * y @ y - 0.5 * np.sum((y - theta) ** 2)
return (primal - dual) / n
x0 = np.zeros(d)
W_ref, F_ref = prox_grad(f, grad_f, g, prox_g, x0, L, 3000, accel=True, restart=True)
F_star, w_star = F_ref.min(), W_ref[int(np.argmin(F_ref))]
print(f"F* = {F_star:.8f} no nulos en el óptimo: {np.count_nonzero(w_star)} gap de dualidad = {gap(w_star):.1e}")
N = 1000
runs = {
"ISTA": prox_grad(f, grad_f, g, prox_g, x0, L, N),
"FISTA": prox_grad(f, grad_f, g, prox_g, x0, L, N, accel=True),
"FISTA con reinicio": prox_grad(f, grad_f, g, prox_g, x0, L, N, accel=True, restart=True),
}
R2 = np.sum((x0 - w_star) ** 2)
ks = np.arange(1, N + 1)
for nombre, (W, Fs) in runs.items():
err = Fs - F_star
k6 = int(np.argmax(err < 1e-6)) if np.any(err < 1e-6) else None
subidas = int(np.sum(np.diff(Fs) > 1e-13))
print(f"{nombre:19s} F-F* tras {N} it.: {err[-1]:.1e} it. hasta 1e-6: {k6} no nulos: {np.count_nonzero(W[-1])} subidas de F: {subidas} gap: {gap(W[-1]):.1e}")
print("ISTA cumple L R^2/(2k):", np.all(runs["ISTA"][1][1:] - F_star <= L * R2 / (2 * ks) + 1e-9))
print("FISTA cumple 2 L R^2/(k+1)^2:", np.all(runs["FISTA"][1][1:] - F_star <= 2 * L * R2 / (ks + 1) ** 2 + 1e-9))The last two lines numerically check the theorem bounds on one problem. The numbers tell the preceding sections’ story. After 1000 iterations ISTA has error and has never fallen below , whereas FISTA reaches at iteration 239 and with restart at 119. ISTA never increases ; FISTA increases it in 434 of 1000 iterations; function restart never does. All three end with the same 13 nonzero coefficients, but ISTA’s final duality gap () is still large: the certificate requires more iterations than the true error. Plot the curves with the bounds.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7.5, 4))
for nombre, (W, Fs), c in zip(runs, runs.values(), ["tab:orange", "tab:green", "tab:blue"]):
err = np.maximum(Fs - F_star, 1e-16)
ax.semilogy(err, label=nombre, color=c, lw=1.6)
ax.semilogy(ks, L * R2 / (2 * ks), "--", color="tab:orange", lw=1, label="cota ISTA $LR^2/(2k)$")
ax.semilogy(ks, 2 * L * R2 / (ks + 1) ** 2, "--", color="tab:green", lw=1, label="cota FISTA $2LR^2/(k+1)^2$")
ax.set_ylim(1e-12, 10)
ax.set_xlabel("iteración k"); ax.set_ylabel("F(x_k) - F*"); ax.legend(fontsize=8)
plt.show()FISTA without restart oscillates and remains well below its bound; ISTA is monotone and much slower. One piece remains: backtracking, avoiding the need for , together with stopping by duality gap.
def fista_bt(f, grad_f, g, prox_g, x0, L0, gap_fn, tol=1e-6, max_iter=5000, gamma=2.0):
"""FISTA con retroceso (L nunca decrece) que para cuando gap_fn(x) < tol. Devuelve x e información."""
x, y, t, L = x0.copy(), x0.copy(), 1.0, L0
intentos = 0
for k in range(1, max_iter + 1):
gy, fy = grad_f(y), f(y)
while True:
x_new = prox_g(y - gy / L, 1.0 / L)
dlt = x_new - y
if f(x_new) <= fy + gy @ dlt + 0.5 * L * (dlt @ dlt) + 1e-12 * abs(fy):
break # el modelo cuadrático majora a f: paso válido
L *= gamma
intentos += 1
t_new = (1 + np.sqrt(1 + 4 * t * t)) / 2
y = x_new + ((t - 1) / t_new) * (x_new - x)
x, t = x_new, t_new
if k % 5 == 0 and gap_fn(x) < tol: # el gap cuesta un producto matriz-vector: no se mira siempre
break
return x, {"iteraciones": k, "L_final": round(float(L), 3), "retrocesos": intentos}
for L0 in [0.01 * L, L, 100 * L]:
xb, info = fista_bt(f, grad_f, g, prox_g, x0, L0, gap, tol=1e-6)
print(f"L0 = {L0:9.3f}: {info} F - F* = {f(xb) + g(xb) - F_star:.1e} gap = {gap(xb):.1e}")
print(f"(L verdadera = {L:.3f})")Three readings. With a hundred times smaller than the true value, backtracking needs only 6 failed attempts, and the resulting (8.47) is below the global constant (13.24): the descent lemma is needed only along points visited by the method, and that local constant is smaller. It therefore finishes in 1040 iterations, fewer than 1375 for fixed step with exact . With a hundred times larger, backtracking cannot lower and steps are a hundred times too short: after 5000 iterations the gap remains . This asymmetry was predicted by theory. Gap stopping guarantees that when the loop ends true error is below without needing .
Using libraries
In practice lasso and elastic net are solved by coordinate descent (proximal coordinate descent), as sklearn.linear_model.Lasso does: update one variable at a time with the same soft threshold. This is a useful comparison and validation of our code because it should reach the same minimizer. For elastic net, has the table’s proximal operator (threshold then shrink) and plugs into the same loop unchanged.
from sklearn.linear_model import Lasso, ElasticNet
# lasso: nuestro FISTA con reinicio frente a la implementación de scikit-learn (descenso por coordenadas)
sk = Lasso(alpha=lam, fit_intercept=False, tol=1e-12, max_iter=200000).fit(X, y)
print(f"lasso: |w_FISTA - w_sklearn|_inf = {np.max(np.abs(w_star - sk.coef_)):.1e} "
f"no nulos: {np.count_nonzero(w_star)} frente a {np.count_nonzero(sk.coef_)}")
# elastic net: solo cambia el proximal
rho = 0.5
g_en = lambda w: lam * (rho * np.sum(np.abs(w)) + 0.5 * (1 - rho) * w @ w)
prox_en = lambda v, t: soft(v, t * lam * rho) / (1 + t * lam * (1 - rho))
L_en = L # la parte suave es la misma; el término l2 está en el proximal
W_en, F_en = prox_grad(f, grad_f, g_en, prox_en, x0, L_en, 3000, accel=True, restart=True)
w_en = W_en[-1]
sk_en = ElasticNet(alpha=lam, l1_ratio=rho, fit_intercept=False, tol=1e-12, max_iter=200000).fit(X, y)
print(f"elastic net: |w_FISTA - w_sklearn|_inf = {np.max(np.abs(w_en - sk_en.coef_)):.1e} "
f"no nulos: {np.count_nonzero(w_en)} (lasso: {np.count_nonzero(w_star)})")
print("tamaño de los coeficientes: ||w_lasso||_2 =", round(float(np.linalg.norm(w_star)), 3), " ||w_enet||_2 =", round(float(np.linalg.norm(w_en)), 3))The two solutions match scikit-learn to and , respectively. Elastic net retains many more variables than lasso (57 versus 13) with correlated columns: the term shares weight among nearly identical columns instead of choosing one at random, and shrinks coefficient norm (3.41 versus 4.01). In PyTorch soft thresholding already exists as torch.nn.functional.softshrink, and since the proximal operator is nondifferentiable at corners, it is usually applied by hand after the optimizer step during training:
import torch
import torch.nn.functional as F
w = torch.nn.Parameter(torch.randn(200))
opt = torch.optim.SGD([w], lr=0.1)
lam, lr = 0.05, 0.1
loss = (w ** 2).sum() * 0.01 # ... la parte suave del objetivo
loss.backward()
opt.step() # paso de gradiente sobre la parte suave
with torch.no_grad():
w.copy_(F.softshrink(w, lambd=lr * lam)) # proximal de lr * lam * ||w||_1: el umbral es lr*lam, no lam
opt.zero_grad()
This is stochastic proximal gradient: the threshold includes the step (lr * lam), as in ISTA. If instead lam * w.abs().sum() is added to the loss and left to Adam, coefficients become very small but almost never exactly zero: the corner is crossed in jumps and not landed on.
Matrix completion
A second laboratory with the matrix proximal operator. A ratings matrix has rank 2, and only half its entries are observed (plus noise). Recover the missing ones by solving
where zeros unobserved entries. The smooth part’s gradient is , which is 1-Lipschitz (), and the proximal operator is singular-value thresholding at level : this is Soft-Impute (Mazumder, Hastie and Tibshirani, 2010), and accelerated it is FISTA. Since the optimum is above , sweep from largest to smallest, starting each from the previous solution (continuation), saving nearly all iterations.
import numpy as np, time
def svt(Z, tau):
"""Proximal de tau*||.||_*: umbral suave sobre los valores singulares."""
U, s, Vt = np.linalg.svd(Z, full_matrices=False)
s = np.maximum(s - tau, 0.0)
r = int(np.count_nonzero(s))
return (U[:, :r] * s[:r]) @ Vt[:r], r
rng = np.random.default_rng(3)
m, n, r0 = 40, 30, 2
M = rng.normal(size=(m, r0)) @ rng.normal(size=(r0, n)) # matriz verdadera de rango 2
mask = rng.random((m, n)) < 0.5 # alrededor de la mitad de las entradas observadas
Y = M + 0.3 * rng.normal(size=(m, n))
print(f"observadas: {mask.mean():.0%} valores singulares de M: {np.round(np.linalg.svd(M, compute_uv=False)[:3], 2)}")
def completar(lam, X0, iters=200):
"""FISTA para 0.5*||P_Omega(X - Y)||_F^2 + lam*||X||_* (L = 1: el gradiente es P_Omega(X - Y))."""
X, Z, t = X0.copy(), X0.copy(), 1.0
for _ in range(iters):
X_new, r = svt(Z - mask * (Z - Y), lam)
t_new = (1 + np.sqrt(1 + 4 * t * t)) / 2
Z = X_new + ((t - 1) / t_new) * (X_new - X)
X, t = X_new, t_new
return X, r
lam_max = np.linalg.norm(mask * Y, 2) # por encima de esto, X = 0
print(f"lambda_max = {lam_max:.2f}")
X = np.zeros((m, n))
t0 = time.perf_counter()
print(" lambda rango error en observadas error en ocultas")
for lam in lam_max * np.array([0.4, 0.2, 0.1, 0.05, 0.025, 0.01]):
X, r = completar(lam, X)
e_obs = np.linalg.norm(mask * (X - M)) / np.linalg.norm(mask * M)
e_ocu = np.linalg.norm((~mask) * (X - M)) / np.linalg.norm((~mask) * M)
print(f"{lam:8.3f} {r:6d} {e_obs:19.3f} {e_ocu:18.3f}")
if abs(lam - lam_max * 0.4) < 1e-9:
print(" valores singulares de X:", np.round(np.linalg.svd(X, compute_uv=False)[:3], 2), "(los verdaderos son mayores: el umbral suave encoge)")
print("tiempo (s):", round(time.perf_counter() - t0, 2))The table tells a three-act story. With large rank is correct (2), but the solution is biased: its singular values (21.0 and 16.1) are far below the true values (42.1 and 35.4) and hidden-entry error is 62%. Lowering reduces bias and that error to 20%, but spurious singular values enter (rank rises to 12), fitting noise in observations, and below hidden error rises again. The best for predicting hidden entries is not the one giving true rank, but a compromise. This is convex regularization’s general pattern and why in practice the proximal operator often selects support or rank, then the model is refitted there without penalty.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 3. Assume . What does the condition say?
Step 1 of 3. Write the problem defining . What do you observe about ?
fista_restart(f, grad_f, g, prox_g, x0, L0, iters). Return (x, hist), with x the last iterate and hist the list of values of (length iters + 1). prox_g(v, t) is the proximal operator of . Rules: (1) backtracking: at each step, starting with current , multiply by 2 while the quadratic model does not majorize (never decrease it); (2) FISTA momentum with ; (3) function restart: if the momentum step makes rise relative to the previous iterate, discard it, set and repeat the step (with backtracking) from without momentum. Thus hist is nonincreasing.import numpy as np
def fista_restart(f, grad_f, g, prox_g, x0, L0, iters):
"""Devuelve (x, hist): el último iterado y [F(x_0), ..., F(x_iters)]."""
# tu código: retroceso para L, momento de FISTA y reinicio por función
x = x0.copy()
return x, [f(x) + g(x)]Summary
- exists uniquely and is characterized by . It is projection for indicators and soft thresholding for ; for the nuclear norm, soft thresholding of singular values.
- The Moreau envelope is a differentiable version of with gradient , -Lipschitz, preserving the minimum and minimizers. The proximal operator is its gradient step. The Moreau decomposition relates the proximal operator of to that of its conjugate: soft thresholding is identity minus clipping.
- ISTA, , minimizes the quadratic model of plus . It is monotone and satisfies . The threshold is , not .
- FISTA adds Nesterov momentum: , optimal for first order. It is not monotone; function restart fixes this.
- Backtracking removes the need to know ; for lasso the duality gap gives a guaranteed stopping criterion. With a nonconvex proximal operator (like ) the guarantees disappear.