Coordinate descent methods
Study methods that optimize one coordinate or block at a time: cyclic, randomized and block methods, with rates depending on coordinate Lipschitz constants. Understand why they dominate separable problems such as lasso, where they fail with nonseparable nonsmoothness, and their relationship with alternating minimization.
After this lesson you can
- Implement exact coordinate descent and 1/Lᵢ steps in cyclic and random order.
- Prove the expected convergence rate of randomized coordinate descent for strongly convex functions.
- Explain with a counterexample why coordinate descent stalls on nonseparable nonsmooth functions.
- Implement proximal coordinate descent for lasso with regularization paths and warm starts.
- Apply block alternating minimization (ALS) to matrix factorization and recognize its limited guarantees.
Before you start
Motivation: when one variable is cheap and the whole gradient is not
Consider lasso, with . Computing the smooth-part gradient costs two matrix-vector products, : first residual , then . But given the residual, one partial derivative is just a dot product,
and changing by updates the residual in another : . That is the lesson’s idea. A full gradient costs as much as partial derivatives, but sequential coordinate updates are more informative: each sees previous effects. This is the distinction between Jacobi (all coordinates use old information) and Gauss-Seidel (latest information); as you will see, it is literally the same distinction.
This structure, where inspecting or changing one variable is much cheaper than all of them, appears in many places:
- Regularized regression.
glmnetandsklearn.linear_model.Lassosolve lasso and elastic net by coordinates, with a closed-form update per variable (soft thresholding from proximal methods). - SVM duals. SMO, the classic support vector machine algorithm, is pairwise coordinate descent on the dual.
- Factorizations. Alternating least squares in recommender systems and nonnegative factorization optimize a block of variables (user vectors, then product vectors) keeping the other fixed.
- Inference. EM and variational mean field perform coordinate ascent on a lower bound.
- Linear algebra. Solving for symmetric positive definite with Gauss-Seidel is literally coordinate descent on a quadratic.
A candid caveat: deep networks have none of this structure. Backpropagation delivers all partial derivatives for the cost of a few forward passes, and one partial derivative costs nearly as much, so no coordinate is cheap. Coordinate methods suit structured models (linear, separable, with maintainable residuals), not networks.
We will see the method and its staircase path, guarantees under randomized ordering, why nonsmooth terms coupling variables make it fail while separable terms work, and how it powers lasso solvers and alternating block minimization.
The method and its staircase
Let be differentiable. Write and for the th standard basis vector.
The illuminating case is quadratic with symmetric positive definite . Minimizing in with others fixed solves a one-variable linear equation: , i.e.
This is exactly the Gauss-Seidel update for : solve the th equation using the newest values of other unknowns. Writing (strictly lower, diagonal and strictly upper parts), one exact cyclic sweep is . One exercise proves it step by step. What matters is what Gauss-Seidel inherits from coordinate descent: each update decreases (exact minimization along a line through the current point), by a measurable amount: updating by decreases exactly . This seeds the proof that Gauss-Seidel converges for every symmetric positive definite (Ostrowski–Reich theorem, completed in the exercise), which Jacobi does not guarantee.
The staircase
In two dimensions it is visible immediately. Each update moves parallel to an axis and stops where the level curve is tangent to that axis: the path is a staircase of horizontal and vertical segments.
The figure has an exact numerical description. In two variables, after the first sweep each iterate leaves its just-updated coordinate at its conditional optimum; with error , one sweep transforms ‘s error into times its previous value, where
is the normalized coupling between the variables. Indeed, after updating , ; the next sweep yields and restores to its conditional optimum, so is multiplied by each sweep. With independent variables (), and one sweep suffices; with near 1, each axis step undoes nearly everything done by the previous one.
For , coupling depends on rotation: zero with aligned axes ( or ), maximal at , where . Two cautions. First: Gauss-Seidel contracts error by per sweep and Jacobi by ; for these matrices Gauss-Seidel is twice as fast in the exponent. Thus coordinate descent beats gradient descent with in the figure even at , where the staircase is long. Second: this is a two-variable toy. The method’s interest is not that each sweep contracts more, but what each sweep costs at large with cheap updates.
Coordinate Lipschitz constants
A gradient step in one coordinate requires knowing how far to move. Global smoothness uses one constant for the entire gradient; here one per coordinate suffices.
For the quadratic, . For linear fitting loss with , the Hessian is and diagonal entry is at most , so , with the th column of (notation throughout). Standardizing columns changes and thus the method.
The inequality above gives, as in the global case, the coordinate descent lemma: , and minimizing the right side in (),
The exact step reduces at least as much, so everything proved for also holds for exact steps.
If is convex and twice differentiable, the familiar constants satisfy (a quadratic form at a unit vector is at most the largest eigenvalue), (the largest eigenvalue of a positive semidefinite matrix is at most its trace), hence
Both extremes occur. With diagonal , : no coupling, and the full gradient is no worse than one coordinate. With (all variables equal), and : global curvature is times each coordinate’s. Changing from to allows much longer steps on flat coordinates.
Randomization: Nesterov’s rate
Cyclic order is easy to implement but very hard to analyze: the next coordinate depends deterministically on previous ones. Nesterov (2012) observed random selection changes everything, because the expectation can be calculated.
Conditioned on , the conditional expectation of is a finite sum of terms, each satisfying (CD). With uniform sampling,
With , denominator cancels the probability’s and leaves . In both cases, in expectation, coordinate descent guarantees the same decrease as the descent lemma for a gradient step with constant or (both ): . To turn this into a rate use the Polyak–Łojasiewicz condition, satisfied by a -strongly convex function with constant : .
The first proof is the first proof exercise (the calculation above is the hard step; apply Polyak–Łojasiewicz and the law of iterated expectation). Interpret the rate by counting partial derivatives. A gradient step costs partial derivatives and, at rate , needs order steps per factor- reduction: derivatives total. Uniform descent needs updates, one derivative each. Since , the randomized method’s bound is never worse than gradient descent’s, and up to times better if , the strongly coupled case.
Three things the figure teaches that a bound alone does not:
- Bounds are worst-case. Actual curves fall well below theoretical lines.
- Cyclic order is not covered by the theorem and is sometimes worse. With highly correlated variables, always using the same order can be several times slower per update than reshuffling each sweep or sampling with replacement. Sun and Ye (2016) construct quadratics where cyclic needs order times more updates than random.
- The method is independent of variable units, but bounds are not. Multiplying variable by a constant changes accordingly, and exact, cyclic and uniform descent follow exactly the same rescaled path: curves stay put as spread increases. The uniform bound worsens because it uses , which changes. A scale-insensitive bound replaces by strong-convexity constant measured in weighted norm (for the quadratic, ); the uniform bound is (gray line), unchanged by units like the method. Importance sampling is not invariant: it visits larger-scale variables more, not necessarily those needing it, and in this family usually performs worse than uniform. Sampling by improves a bound, not necessarily the method. In practice rescale variables (e.g. standardize columns) and sample uniformly.
The code experiment verifies this numerically.
Nonsmooth functions: when it fails and why separability works
So far was differentiable. Lasso adds a nonsmooth term. Before seeing what works, look at what fails.
Consider . It is convex, uniquely minimized at with , and its only nonsmooth term has a corner along diagonal . At diagonal point , moving only by gives
whose one-sided derivative at is and at is . For to minimize, and , i.e. . By symmetry the same holds for . Thus every with is a coordinatewise minimum, and coordinate descent gets stuck there, although vanishes only at . Along the diagonal, however, does decrease when approaching .
This is not numerical failure. The four directions the method can test, and , all rise, yet the diagonal descends. Taking it requires moving both variables at once, which a coordinate method never does: the corner of couples them. With , each corner affects only its own variable and the problem disappears. The next result formalizes this.
Proof
For each , one-variable is convex and minimized at . Its one-sided directional derivatives at are nonnegative: and , where is a one-sided directional derivative of . By convexity (with sign according to whether lies right or left), so for all . For arbitrary , convexity of gives , and adding the ,
because each summand is nonnegative by the above with .
∎The proof uses separability at one point: the sum of splits coordinate by coordinate. With there is no and the argument breaks exactly where the method fails. The theorem describes where coordinate descent stops; convergence is a further Tseng (2001) result: if with convex , convex lower semicontinuous , compact initial level set, continuous there, and each coordinate subproblem uniquely minimized (technical hypotheses of the theorem), every limit point of exact cyclic coordinate descent minimizes .
Proximal coordinate descent and lasso
The widely used case satisfying the theorem is smooth plus separable penalty, . Each update combines two known ideas: a gradient step in that coordinate and the proximal operator of to handle nonsmoothness exactly.
This is proximal gradient from the proximal-methods lesson applied to one coordinate. For rates, Richtárik and Takáč (2014) prove expected linear rates for the randomized version when is strongly convex, and order in the convex case, like Nesterov’s smooth-case rates.
Lasso
With and (scikit-learn’s scale; the proximal-methods lesson did not divide by and its parameter equals our ), coordinate has constant , and its update follows in four lines.
If columns are standardized with , then and the update is glmnet’s elegant . Otherwise different make the result unit-dependent, so standardize before fitting.
Regularization paths and warm starts
Usually one wants not a single but the path to choose by validation. A natural starting value exists. is optimal iff , i.e. for all . Thus
is the smallest producing an empty model, and the path is traversed downward on a logarithmic grid. The efficiency key is warm starting: the next slightly smaller solution resembles the preceding one, so use it as the starting point. Each then costs a few sweeps rather than a cold start.
Savings are large with loose tolerance and shrink with strict tolerance: warm starts remove each ‘s transient but do not change the subsequent linear convergence rate, which worsens with column correlation. A second trick addresses this: the active-set strategy. After a full sweep most coefficients are zero and will remain so; iterate only on nonzeros (few unless is small) to convergence, then perform a full sweep to check no variable wants to enter. Together with rules screening variables in advance (Tibshirani et al.’s 2012 strong rules), this makes glmnet extraordinarily fast. Implement all this below.
Implementation from scratch
First, the quadratic. Compare exact coordinate descent with maintained rather than recalculated gradient against Gauss-Seidel as a triangular system, and the two-variable factor per sweep.
import numpy as np
def cd_cuadratica(A, b, x0, pasadas):
"""Descenso por coordenadas exacto y cíclico para f(x) = x'Ax/2 - b'x. Devuelve el iterado tras cada pasada."""
x = np.array(x0, dtype=float)
g = A @ x - b # el gradiente se calcula una vez y después se mantiene
historia = [x.copy()]
for _ in range(pasadas):
for i in range(len(x)):
t = -g[i] / A[i, i] # minimiza f(x + t e_i): g_i + t A_ii = 0
x[i] += t
g += t * A[:, i] # actualización incremental del gradiente, O(n)
historia.append(x.copy())
return np.array(historia)
def gauss_seidel(A, b, x0, pasadas):
"""(D + L) x_{k+1} = b - U x_k, resuelto como sistema triangular."""
DL, U = np.tril(A), np.triu(A, 1)
x = np.array(x0, dtype=float)
historia = [x.copy()]
for _ in range(pasadas):
x = np.linalg.solve(DL, b - U @ x)
historia.append(x.copy())
return np.array(historia)
rng = np.random.default_rng(0)
M = rng.normal(size=(8, 8))
A = M @ M.T + 0.5 * np.eye(8) # simétrica definida positiva
b = rng.normal(size=8)
x0 = np.zeros(8)
H_cd = cd_cuadratica(A, b, x0, 10)
H_gs = gauss_seidel(A, b, x0, 10)
print("máx |CD - Gauss-Seidel| tras 10 pasadas:", np.abs(H_cd - H_gs).max())
x_star = np.linalg.solve(A, b)
f = lambda x: 0.5 * x @ A @ x - b @ x
brecha = np.array([f(x) - f(x_star) for x in H_cd])
print("f - f* por pasada:", np.array2string(brecha[:6], precision=3))
print("¿decrece f en cada pasada?", bool(np.all(np.diff(brecha) < 0)))
# dos variables con acoplamiento rho: la teoría dice que f - f* se multiplica por rho^4 en cada pasada
for rho in (0.5, 0.8, 0.95):
A2 = np.array([[1.0, rho], [rho, 1.0]])
H = cd_cuadratica(A2, np.zeros(2), [1.0, -0.3], 8)
fv = np.array([0.5 * x @ A2 @ x for x in H])
print(f"rho = {rho}: factor por pasada medido {fv[7] / fv[6]:.4f} rho^4 = {rho ** 4:.4f}")The implementations agree to roundoff and measured factor is to all digits. Notice g += t * A[:, i]: the quadratic version of an incremental residual. Calculate the gradient once and update in per coordinate. Removing this and recalculating A @ x - b at each coordinate would multiply sweep cost by .
Now compare orders and verify bounds, using the figure’s problem: ten equicorrelated variables with distributed scales , average of 20 random runs.
import numpy as np
def problema(n, rho, dispersion):
"""f(x) = x'Ax/2 con A = D^(1/2) C D^(1/2): C equicorrelada (rho) y L_i = D_ii repartidas entre 1 y `dispersion`."""
C = (1 - rho) * np.eye(n) + rho * np.ones((n, n))
d = np.logspace(0, np.log10(dispersion), n)
return np.sqrt(d)[:, None] * C * np.sqrt(d)[None, :]
def cd(A, x0, orden, K, rng):
"""K actualizaciones exactas (paso 1/L_i). orden: 'ciclico', 'barajado', 'uniforme' o 'importancia'. Devuelve f tras cada una."""
n = len(A)
L = np.diag(A).copy()
x = x0.copy()
g = A @ x
hist = [0.5 * x @ g]
p = L / L.sum()
for k in range(K):
if orden == "ciclico":
i = k % n
elif orden == "barajado":
if k % n == 0:
perm = rng.permutation(n)
i = perm[k % n]
elif orden == "uniforme":
i = rng.integers(n)
else:
i = rng.choice(n, p=p)
t = -g[i] / L[i]
x[i] += t
g += t * A[:, i]
hist.append(0.5 * x @ g)
return np.array(hist)
def experimento(rho, dispersion, K=400, ejecuciones=20, semilla=0):
n = 10
A = problema(n, rho, dispersion)
L = np.diag(A)
mu = np.linalg.eigvalsh(A)[0]
y0 = np.random.default_rng(semilla).normal(size=n)
x0 = y0 / np.sqrt(L) # el arranque se reescala con las unidades
res = {}
for orden in ("ciclico", "barajado", "uniforme", "importancia"):
R = 1 if orden == "ciclico" else ejecuciones
H = np.mean([cd(A, x0, orden, K, np.random.default_rng(100 + s)) for s in range(R)], axis=0)
res[orden] = (H[K] / H[K // 4]) ** (1 / (K - K // 4)) # factor medio por actualización lejos del arranque
cota_unif = 1 - mu / (n * L.max())
cota_imp = 1 - mu / L.sum()
mu_L = np.linalg.eigvalsh(A / np.sqrt(np.outer(L, L)))[0] # fuerte convexidad en la norma ponderada
cota_esc = 1 - mu_L / n
return res, cota_unif, cota_imp, cota_esc
for rho, disp in [(0.5, 1), (0.8, 1), (0.8, 100)]:
res, cu, ci, ce = experimento(rho, disp)
print(f"rho = {rho}, L_max/L_min = {disp:>3}: " + " ".join(f"{k}: {v:.4f}" for k, v in res.items()))
print(f" cota uniforme {cu:.4f} cota importancia {ci:.4f} cota con la norma ponderada {ce:.4f}")Per-update factors confirm the figure. With , cyclic contracts by per update, shuffled by , uniform by : fixed order is several times slower in the exponent. Random rates satisfy their bounds (). Changing spread from 1 to 100 gives cyclic, shuffled and uniform the same numbers, while the uniform bound rises from to and importance sampling worsens from to . The weighted-norm bound remains : only it, like the method, is unit-independent.
Now failure: exact coordinate descent, each one-dimensional minimization solved numerically, on the figure’s two functions.
import numpy as np
from scipy.optimize import minimize_scalar
acoplada = lambda x, y: abs(x - y) + ((x + y) / 2 - 2) ** 2 # |x - y| no es separable
separable = lambda x, y: abs(x) + abs(y) + ((x + y) / 2 - 2) ** 2 # |x| + |y| sí lo es
def cd_exacto(F, p0, pasadas=50):
"""Descenso por coordenadas cíclico; cada coordenada se minimiza de forma exacta (convexa en una variable)."""
x, y = p0
for _ in range(pasadas):
x = minimize_scalar(lambda s: F(s, y), bounds=(-20, 20), method="bounded", options={"xatol": 1e-12}).x
y = minimize_scalar(lambda s: F(x, s), bounds=(-20, 20), method="bounded", options={"xatol": 1e-12}).x
return x, y
arranques = [(4.2, 0.6), (0.5, 3.5), (-1.0, 1.5), (3.0, 4.5), (5.0, 2.2), (1.2, 0.2)]
print("arranque acoplada: punto final f | separable: punto final f")
for p0 in arranques:
a = cd_exacto(acoplada, p0)
s = cd_exacto(separable, p0)
print(f"{str(p0):16s} ({a[0]:6.3f}, {a[1]:6.3f}) {acoplada(*a):7.4f} | ({s[0]:6.3f}, {s[1]:6.3f}) {separable(*s):7.4f}")
# en un punto atascado, las cuatro pendientes sobre los ejes son >= 0, pero a lo largo de la diagonal se baja
p = np.array(cd_exacto(acoplada, (4.2, 0.6)))
h = 1e-7
pend = lambda d: (acoplada(*(p + h * np.array(d))) - acoplada(*p)) / h
print("\npunto atascado:", np.round(p, 4), " f =", round(acoplada(*p), 4), " mínimo global: f(2, 2) =", acoplada(2, 2))
print("pendientes laterales en +e1, -e1, +e2, -e2:", [round(float(pend(d)), 3) for d in ((1, 0), (-1, 0), (0, 1), (0, -1))])
hacia = (np.array([2.0, 2.0]) - p) / np.linalg.norm(np.array([2.0, 2.0]) - p) # dirección hacia el mínimo
print("pendiente hacia (2, 2), a lo largo de la diagonal:", round(float(pend(hacia)), 3))All six starts of the coupled variant end on the diagonal away from , with . At the first, all four one-sided axis slopes are positive while the slope toward is negative. The separable variant always reaches , the minimum, at different points on segment .
Move to lasso, with incremental residual, duality-gap stopping and checks against KKT conditions and scikit-learn. Data comprise 100 examples and 30 correlated variables, 5 with signal.
import numpy as np, time
def umbral(v, t):
"""Umbral suave: el proximal de t|.|."""
return np.sign(v) * np.maximum(np.abs(v) - t, 0.0)
def brecha_lasso(X, y, w, r, lam):
"""Brecha de dualidad del lasso (1/2n)|y - Xw|^2 + lam |w|_1 con el punto dual factible theta = s r."""
n = len(y)
s = min(1.0, n * lam / max(np.abs(X.T @ r).max(), 1e-300))
primal = r @ r / (2 * n) + lam * np.abs(w).sum()
dual = (y @ y - (y - s * r) @ (y - s * r)) / (2 * n)
return primal - dual
def cd_lasso(X, y, lam, w0=None, tol=1e-8, max_pasadas=5000):
"""Descenso por coordenadas cíclico para (1/2n)|y - Xw|^2 + lam |w|_1, con residuo incremental.
Cada actualización cuesta O(n); una pasada, O(np). Para cuando la brecha relativa baja de tol."""
n, p = X.shape
w = np.zeros(p) if w0 is None else np.array(w0, dtype=float)
r = y - X @ w # residuo: se calcula una vez y se mantiene
L = (X ** 2).sum(axis=0) / n # L_j = |X_j|^2 / n
escala = y @ y / (2 * n)
for pasada in range(1, max_pasadas + 1):
for j in range(p):
if L[j] == 0:
continue
xj = X[:, j]
nuevo = umbral(w[j] + xj @ r / (n * L[j]), lam / L[j]) # prox del gradiente parcial con paso 1/L_j
if nuevo != w[j]:
r -= (nuevo - w[j]) * xj # O(n), no O(np)
w[j] = nuevo
if brecha_lasso(X, y, w, r, lam) <= tol * escala:
return w, pasada
return w, max_pasadas
# datos: 100 ejemplos, 30 variables correlacionadas, 5 con señal; columnas estandarizadas
rng = np.random.default_rng(1)
n, p = 100, 30
Z = rng.normal(size=(n, p)) * np.sqrt(0.6) + rng.normal(size=(n, 1)) * np.sqrt(0.4)
X = (Z - Z.mean(0)) / Z.std(0)
w_ver = np.zeros(p); w_ver[:5] = [3, -2, 1.5, 1, -1]
y = X @ w_ver + rng.normal(size=n)
y -= y.mean()
lam_max = np.abs(X.T @ y).max() / n
lam = lam_max / 10
print(f"lambda_max = {lam_max:.4f} lambda = {lam:.4f}")
w, pasadas = cd_lasso(X, y, lam, tol=1e-10)
print("pasadas:", pasadas, " no nulos:", np.count_nonzero(w), " cinco primeros coeficientes:", np.round(w[:5], 3))
# condiciones KKT: g_j = X_j'r/n debe valer lam*sign(w_j) si w_j != 0 y |g_j| <= lam si w_j = 0
g = X.T @ (y - X @ w) / n
kkt = np.where(w != 0, np.abs(g - lam * np.sign(w)), np.maximum(np.abs(g) - lam, 0)).max()
print(f"violación máxima de KKT: {kkt:.1e}")
from sklearn.linear_model import Lasso
sk = Lasso(alpha=lam, fit_intercept=False, tol=1e-12, max_iter=100000).fit(X, y)
print(f"|w - w_sklearn|_inf = {np.abs(w - sk.coef_).max():.1e} (sklearn usa la misma función objetivo y alpha = lam)")
# por qué importa el residuo incremental: la misma pasada recalculando el gradiente completo en cada coordenada
def pasada_ingenua(X, y, w, lam):
n, p = X.shape
L = (X ** 2).sum(axis=0) / n
for j in range(p):
r = y - X @ w # O(np) por coordenada
w[j] = umbral(w[j] + X[:, j] @ r / (n * L[j]), lam / L[j])
return w
def pasada_incremental(X, y, w, lam):
n, p = X.shape
L = (X ** 2).sum(axis=0) / n
r = y - X @ w
for j in range(p):
nuevo = umbral(w[j] + X[:, j] @ r / (n * L[j]), lam / L[j])
r -= (nuevo - w[j]) * X[:, j]
w[j] = nuevo
return w
# la misma pasada, con 3000 ejemplos y 150 variables
rng = np.random.default_rng(2)
XG = rng.normal(size=(3000, 150)); yG = rng.normal(size=3000); lamG = 0.05
w1, w2 = np.zeros(150), np.zeros(150)
t0 = time.perf_counter()
pasada_ingenua(XG, yG, w1, lamG)
t1 = time.perf_counter()
pasada_incremental(XG, yG, w2, lamG)
t2 = time.perf_counter()
print(f"mismo resultado: {np.allclose(w1, w2)}; una pasada: ingenua {1e3 * (t1 - t0):.0f} ms, incremental {1e3 * (t2 - t1):.0f} ms")The solution satisfies KKT to and matches scikit-learn. The last comparison shows the main warning: recalculating the full residual per coordinate gives the same result but costs per coordinate instead of , with the difference growing in .
Now the path with and without warm starts, and coordinate descent versus ISTA and FISTA from proximal methods (one coordinate sweep and one gradient iteration cost the same, ).
def camino(X, y, lams, tol, caliente=True):
"""Camino de regularización: una solución por lambda, de mayor a menor. Devuelve coeficientes y pasadas por lambda."""
w, W, pas = None, [], []
for lam in lams:
w, k = cd_lasso(X, y, lam, w0=w if caliente else None, tol=tol)
W.append(w.copy()); pas.append(k)
return np.array(W), np.array(pas)
lams = lam_max * np.logspace(0, -2, 30) # 30 valores, de lambda_max a lambda_max / 100
for tol in (1e-3, 1e-6):
W_fr, p_fr = camino(X, y, lams, tol, caliente=False)
W_ca, p_ca = camino(X, y, lams, tol, caliente=True)
print(f"tol = {tol:.0e}: pasadas desde cero {p_fr.sum():5d} con arranque en caliente {p_ca.sum():5d} ahorro x{p_fr.sum() / p_ca.sum():.1f}")
# el mismo camino con scikit-learn
from sklearn.linear_model import lasso_path
alfas, W_sk, _ = lasso_path(X, y, alphas=lams, tol=1e-13, max_iter=100000)
print(f"|camino propio - camino de sklearn|_inf = {np.abs(W_ca.T - W_sk).max():.1e} (tol = 1e-6)")
print("variables activas a lo largo del camino:", [int(np.count_nonzero(w)) for w in W_ca[::7]])
# CD frente a ISTA y FISTA en un lambda: una pasada de CD cuesta lo mismo que una iteración de gradiente (O(np))
lam = lams[18]
L = np.linalg.eigvalsh(X.T @ X / n)[-1]
escala = y @ y / (2 * n)
def proximal(X, y, lam, L, acelerado, tol=1e-6, max_it=20000):
n, p = X.shape
w = np.zeros(p); z = w.copy(); t = 1.0
for k in range(1, max_it + 1):
w_nuevo = umbral(z - X.T @ (X @ z - y) / (n * L), lam / L)
if acelerado:
t_nuevo = (1 + np.sqrt(1 + 4 * t * t)) / 2
z = w_nuevo + (t - 1) / t_nuevo * (w_nuevo - w)
t = t_nuevo
else:
z = w_nuevo
w = w_nuevo
if brecha_lasso(X, y, w, y - X @ w, lam) <= tol * escala:
return w, k
return w, max_it
_, k_cd = cd_lasso(X, y, lam, tol=1e-6)
_, k_ista = proximal(X, y, lam, L, acelerado=False)
_, k_fista = proximal(X, y, lam, L, acelerado=True)
print(f"\nlambda = lambda_max / {lam_max / lam:.0f}, brecha relativa 1e-6: CD {k_cd} pasadas ISTA {k_ista} iteraciones FISTA {k_fista} iteraciones")With loose tolerance warm starts save nearly half the sweeps, with strict tolerance much less, as in the figure. The path matches scikit-learn. In this correlated-column lasso, coordinate descent needs about 20 sweeps where ISTA and FISTA need hundreds. Do not overgeneralize: the advantage depends on structure (with nearly diagonal , ISTA would also be fast), and FISTA especially accelerates very ill-conditioned problems, but this behavior made coordinate descent the lasso standard.
The active set remains. With many more variables than examples and a sparse model, this is where it makes the difference.
def cd_lasso_activo(X, y, lam, w0, tol=1e-6):
"""Resolver el lasso restringido a las columnas no nulas (barato) y verificar con UNA pasada completa.
Devuelve w y el número de actualizaciones de coordenada hechas."""
n, p = X.shape
w = np.zeros(p) if w0 is None else np.array(w0, dtype=float)
L = (X ** 2).sum(axis=0) / n
escala = y @ y / (2 * n)
trabajo = 0
while True:
act = np.flatnonzero(w)
if len(act):
w_act, k = cd_lasso(X[:, act], y, lam, w[act], tol) # solo las columnas activas
w[act] = w_act
trabajo += k * len(act)
r = y - X @ w # pasada completa de verificación
for j in range(p):
nuevo = umbral(w[j] + X[:, j] @ r / (n * L[j]), lam / L[j])
if nuevo != w[j]:
r -= (nuevo - w[j]) * X[:, j]; w[j] = nuevo
trabajo += p
if brecha_lasso(X, y, w, r, lam) <= tol * escala:
return w, trabajo
# alta dimensión: 100 ejemplos, 200 variables, 5 con señal
rng = np.random.default_rng(1)
nA, pA = 100, 200
Z = rng.normal(size=(nA, pA)) * np.sqrt(0.6) + rng.normal(size=(nA, 1)) * np.sqrt(0.4)
XA = (Z - Z.mean(0)) / Z.std(0)
wA = np.zeros(pA); wA[:5] = [3, -2, 1.5, 1, -1]
yA = XA @ wA + rng.normal(size=nA)
yA -= yA.mean()
lams_A = (np.abs(XA.T @ yA).max() / nA) * np.logspace(0, -1.3, 25)
W_c, p_c = camino(XA, yA, lams_A, 1e-6, caliente=True)
w, trab = None, 0
W_a = []
for lam_k in lams_A:
w, t = cd_lasso_activo(XA, yA, lam_k, w, 1e-6)
W_a.append(w.copy()); trab += t
print("variables activas a lo largo del camino:", [int(np.count_nonzero(v)) for v in W_c[::4]])
print(f"actualizaciones de coordenada: sin conjunto activo {int(p_c.sum()) * pA}, con conjunto activo {trab} "
f"(x{int(p_c.sum()) * pA / trab:.1f} menos); mismo camino: {np.abs(np.array(W_a) - W_c).max():.1e}")Savings grow with sparsity: when only a few of 200 variables are active, almost every update in a full sweep is wasted work.
Using libraries
Everything above is packaged. sklearn.linear_model.Lasso and ElasticNet are written in Cython with coordinate descent and duality-gap stopping; lasso_path calculates the warm-started path and LassoCV selects by cross-validation over it. Parameter selection='random' samples a coordinate each step instead of cycling, and warm_start=True reuses the same object’s previous fitted solution.
from sklearn.linear_model import Lasso, LassoCV
lam = lams[18]
w_cd, _ = cd_lasso(X, y, lam, tol=1e-12)
for orden in ("cyclic", "random"):
m = Lasso(alpha=lam, fit_intercept=False, tol=1e-10, selection=orden, random_state=0, max_iter=100000).fit(X, y)
print(f"selection='{orden}': pasadas {m.n_iter_:3d} |w - w_nuestro|_inf = {np.abs(m.coef_ - w_cd).max():.1e}")
# arranque en caliente en scikit-learn: el mismo objeto reutiliza su solución anterior
m_fr = Lasso(fit_intercept=False, tol=1e-6, max_iter=100000)
m_ca = Lasso(fit_intercept=False, tol=1e-6, max_iter=100000, warm_start=True)
it_fr, it_ca = [], []
for a in lams:
it_fr.append(m_fr.set_params(alpha=a).fit(X, y).n_iter_)
it_ca.append(m_ca.set_params(alpha=a).fit(X, y).n_iter_)
print(f"pasadas en el camino: desde cero {sum(it_fr)}, warm_start=True {sum(it_ca)}")
# elegir lambda por validación cruzada (usa el camino con arranque en caliente por dentro)
cv = LassoCV(alphas=lams, cv=5, fit_intercept=False, tol=1e-6, max_iter=100000).fit(X, y)
print(f"LassoCV elige lambda = {cv.alpha_:.4f} = lambda_max / {lam_max / cv.alpha_:.1f}, con {np.count_nonzero(cv.coef_)} variables")Two usage details. First, Lasso minimizes , so alpha is exactly this lesson’s . Second, n_iter_ counts full sweeps, not updates, and its stopping criterion differs from ours, so numbers do not match earlier cells even though solutions do. For nonnegative matrix factorization, sklearn.decomposition.NMF defaults to solver='cd': block coordinate descent over entries of and .
Blocks and alternating minimization
When variables form blocks and minimizing an entire block is easy (a linear system, a small convex problem), update one block at a time.
The central example is matrix factorization with missing data, the heart of recommender systems. Given observed only at positions , seek and with on :
is not convex jointly in ( is bilinear), but with fixed it is a strictly convex quadratic in , separable by rows: each solves ridge regression using only observed entries of its row,
and similarly for each with fixed. This is alternating least squares (ALS). Each half comprises (or ) independent problems distributable across machines, making ALS standard in large-scale recommendation.
What guarantees exist? Tseng (2001) shows that if each block subproblem has a unique minimizer and level sets are compact, every block-descent limit point is a stationary point of ; for two blocks compactness suffices (Grippo and Sciandrone, 2000). Theory also limits expectations: global minimization is not guaranteed, blockwise uniqueness is a real hypothesis (without it, Powell’s 1973 examples with three or more blocks cycle without converging), and rate is not generally linear. Concrete structure matters:
- Bad stationary points. , is stationary for and ALS started there does not move: updating either block with the other zero returns zero.
- Symmetry. If is a solution, so is for any orthogonal , with the same . Minimizers are not unique and solutions from different starts should be compared by , not componentwise.
- Slowness. ALS can advance very slowly near the solution when blocks are strongly coupled, the staircase phenomenon again.
import numpy as np
def als(M, mascara, r, lam, U0, V0, iteraciones=40):
"""Mínimos cuadrados alternados para min 1/2 sum_{(i,j) observado} (M_ij - u_i'v_j)^2 + lam/2 (|U|^2 + |V|^2).
Con V fija, cada fila u_i resuelve una regresión ridge con sus entradas observadas (y viceversa)."""
U, V = U0.copy(), V0.copy()
I = lam * np.eye(r)
def objetivo():
E = (M - U @ V.T) * mascara
return 0.5 * (E ** 2).sum() + 0.5 * lam * ((U ** 2).sum() + (V ** 2).sum())
hist = [objetivo()]
for _ in range(iteraciones):
for i in range(M.shape[0]): # bloque U: m problemas independientes de r variables
o = mascara[i] > 0
Vo = V[o]
U[i] = np.linalg.solve(Vo.T @ Vo + I, Vo.T @ M[i, o])
for j in range(M.shape[1]): # bloque V
o = mascara[:, j] > 0
Uo = U[o]
V[j] = np.linalg.solve(Uo.T @ Uo + I, Uo.T @ M[o, j])
hist.append(objetivo())
return U, V, np.array(hist)
rng = np.random.default_rng(0)
m, n, r_ver = 30, 20, 2
M_ver = rng.normal(size=(m, r_ver)) @ rng.normal(size=(n, r_ver)).T
M = M_ver + 0.1 * rng.normal(size=(m, n))
mascara = (rng.random((m, n)) < 0.45).astype(float) # se observa el 45 % de las entradas
prueba = (mascara == 0)
print(f"entradas observadas: {int(mascara.sum())} de {m * n}")
lam = 0.1
en20, finales, rmse = [], [], []
for s in range(6):
R = np.random.default_rng(10 + s)
U, V, h = als(M, mascara, r_ver, lam, R.normal(size=(m, r_ver)), R.normal(size=(n, r_ver)), iteraciones=120)
assert np.all(np.diff(h) <= 1e-9 * h[0]), "el objetivo debe bajar siempre"
en20.append(h[20]); finales.append(h[-1])
rmse.append(np.sqrt(((U @ V.T - M_ver)[prueba] ** 2).mean()))
print("objetivo tras 20 iteraciones, 6 inicializaciones:", np.round(en20, 3))
print("objetivo tras 120 iteraciones: ", np.round(finales, 3))
print("error en entradas no observadas (RMSE):", np.round(rmse, 3), " referencia: std de M =", round(M_ver.std(), 3))
print(f"objetivo al arrancar / tras 1 iteración / tras 120: {h[0]:.1f} / {h[1]:.1f} / {h[-1]:.1f}")
# U = V = 0 es un punto estacionario: ALS no se mueve
U0, V0, h0 = als(M, mascara, r_ver, lam, np.zeros((m, r_ver)), np.zeros((n, r_ver)), iteraciones=5)
print("\narranque en cero: objetivo", np.round(h0[[0, -1]], 3), " |U| =", np.abs(U0).max())
# la solución no es única: (U Q, V Q) con Q ortogonal tiene el mismo objetivo
Q, _ = np.linalg.qr(rng.normal(size=(r_ver, r_ver)))
E1 = 0.5 * (((M - U @ V.T) * mascara) ** 2).sum() + 0.5 * lam * ((U ** 2).sum() + (V ** 2).sum())
U2, V2 = U @ Q, V @ Q
E2 = 0.5 * (((M - U2 @ V2.T) * mascara) ** 2).sum() + 0.5 * lam * ((U2 ** 2).sum() + (V2 ** 2).sum())
print(f"objetivo en (U, V) y en (UQ, VQ): {E1:.6f} {E2:.6f}; |U - UQ| = {np.abs(U - U2).max():.2f}")The objective decreases each iteration, and six initializations, appreciably separated after 20 iterations, end at the same value to three digits. The landscape is benign here, with no guarantee it always is. Zero initialization confirms the bad stationary point: objective stays unchanged and remains zero. The last line shows symmetry: the same objective with different factors.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 4. What bound does (CD) give for with fixed ?
Step 1 of 3. What condition does the exact minimizer of satisfy?
cd_lasso(X, y, lam, tol), returning vector w minimizing with cyclic coordinate descent. Maintain the residual and update it in per coordinate (do not recalculate X @ w inside the coordinate loop). Stop when, after a full sweep, maximum change is tol. Columns are not standardized, and may be zero (their coefficient must be 0). Do not modify X or y.import numpy as np
def cd_lasso(X, y, lam, tol=1e-10, max_pasadas=10000):
"""Devuelve w que minimiza (1/2n)|y - Xw|^2 + lam |w|_1."""
n, p = X.shape
w = np.zeros(p)
# tu código: residuo r = y - Xw que se mantiene, L_j = |X_j|^2 / n,
# y para cada coordenada: umbral suave y actualización de r
return wSummary
glmnet’s lasso); with a term coupling variables it stalls silently.- An exact cyclic sweep on a quadratic is one Gauss-Seidel iteration. In two variables, is multiplied by per sweep, with : one sweep for independent variables, a long staircase for strong coupling.
- With coordinate Lipschitz constants, , and .
- With randomized order, expected decrease is and rate per update (or with ). In partial derivatives, the bound is never worse than gradient descent’s. These are worst-case bounds: cyclic is not covered and can be much slower with correlated variables, and the method is invariant to variable scales although some bounds are not.
- If , a coordinatewise minimum is global and proximal descent converges. With , fused lasso or overlapping norms it stalls away from minima.
- Lasso: update in with incremental residual; ; paths with warm starts and active sets.
- Block methods, in particular ALS, always decrease the objective, but converge to initialization-dependent stationary points (including the origin), with solutions defined up to rotation.