Module contents
Lesson 15 of 27Core 90 min

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, F(w)=12n∥y−Xw∥22+λ∥w∥1F(\vb{w}) = \frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{w}}_2^2 + \lambda\norm{\vb{w}}_1 with X∈Rn×d\mat{X} \in \R^{n \times d}. Computing the smooth-part gradient costs two matrix-vector products, O(nd)\bigO(nd): first residual r=y−Xw\vb{r} = \vb{y} - \mat{X}\vb{w}, then −X⊤r/n-\mat{X}\T\vb{r}/n. But given the residual, one partial derivative is just a dot product,

∂f∂wj=−1n xj⊤r,cost O(n),\pd{f}{w_j} = -\frac{1}{n}\,\vb{x}_j\T\vb{r}, \qquad \text{cost } \bigO(n),

and changing wjw_j by δ\delta updates the residual in another O(n)\bigO(n): r←r−δ xj\vb{r} \leftarrow \vb{r} - \delta\,\vb{x}_j. That is the lesson’s idea. A full gradient costs as much as dd partial derivatives, but dd 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. glmnet and sklearn.linear_model.Lasso solve 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 Ax=b\mat{A}\vb{x} = \vb{b} for symmetric positive definite A\mat{A} 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 f:Rn→Rf: \R^n \to \R be differentiable. Write ∇if(x)=∂f∂xi(x)\nabla_i f(\vb{x}) = \pd{f}{x_i}(\vb{x}) and ei\vb{e}_i for the iith standard basis vector.

The illuminating case is quadratic f(x)=12x⊤Ax−b⊤xf(\vb{x}) = \tfrac12\vb{x}\T\mat{A}\vb{x} - \vb{b}\T\vb{x} with symmetric positive definite A\mat{A}. Minimizing ff in xix_i with others fixed solves a one-variable linear equation: ∇if=(Ax)i−bi=aiixi+∑j≠iaijxj−bi=0\nabla_i f = (\mat{A}\vb{x})_i - b_i = a_{ii}x_i + \sum_{j \neq i} a_{ij}x_j - b_i = 0, i.e.

xi←1aii(bi−∑j≠iaijxj).x_i \leftarrow \frac{1}{a_{ii}}\Big(b_i - \sum_{j \neq i} a_{ij}x_j\Big).

This is exactly the Gauss-Seidel update for Ax=b\mat{A}\vb{x} = \vb{b}: solve the iith equation using the newest values of other unknowns. Writing A=L+D+U\mat{A} = \mat{L} + \mat{D} + \mat{U} (strictly lower, diagonal and strictly upper parts), one exact cyclic sweep is (D+L)xk+1=b−Uxk(\mat{D} + \mat{L})\vb{x}_{k+1} = \vb{b} - \mat{U}\vb{x}_k. One exercise proves it step by step. What matters is what Gauss-Seidel inherits from coordinate descent: each update decreases ff (exact minimization along a line through the current point), by a measurable amount: updating xix_i by tt decreases ff exactly 12aiit2\tfrac12 a_{ii}t^2. This seeds the proof that Gauss-Seidel converges for every symmetric positive definite A\mat{A} (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.

InteractiveThe coordinate staircase
Contours of ff and paths
x*
f/f0f/f_0 versus partial derivatives evaluated
  • Coordinates
  • Gradient 1/L
  • coordinates (exact)
  • gradient, step 1/L1/L
  • minimum x⋆\vb{x}^\star
35°
7.9
Method
30 updates
Coupling ρ2=a122/(a11a22)\rho^2 = a_{12}^2/(a_{11}a_{22})0.573
f/f0f/f_0, coordinates5.25·10⁻⁹
f/f0f/f_0, gradient (same cost)7.09·10⁻⁷
Factor per sweep, coordinates0.328
Factor per step, gradient0.764
Partial derivatives to f/f0≤10−6f/f_0 \le 10^{-6}, coordinates21
Partial derivatives to f/f0≤10−6f/f_0 \le 10^{-6}, gradient28
The variables are strongly coupled (ρ2=0.57\rho^2 = 0.57): each axis step nearly undoes the previous one and the staircase lengthens. Per sweep, ff is reduced only by factor ρ4=0.328\rho^4 = 0.328.
f(x)=12x⊤Axf(\vb{x}) = \tfrac12\vb{x}\T\mat{A}\vb{x} with A=Rθ diag⁡(1,1/κ) Rθ⊤\mat{A} = \mat{R}_\theta\,\diag(1, 1/\kappa)\,\mat{R}_\theta\T: elliptical contours of eccentricity κ\kappa, rotated by θ\theta. Left, exact coordinate descent (orange) draws a staircase and gradient descent with step 1/L1/L (blue) a curve. Right, compare at equal cost, counting evaluated partial derivatives (one per coordinate update, two per gradient step). Align the ellipse with axes (θ=0°\theta = 0° or 90°90°): two updates suffice. Rotate to 45°45° and increase κ\kappa: the staircase lengthens. Compare the measured per-sweep factor with ρ4\rho^4.

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 e=x−x⋆\vb{e} = \vb{x} - \vb{x}^\star, one sweep transforms x1x_1‘s error into ρ2\rho^2 times its previous value, where

ρ2=a122a11 a22∈[0,1)\rho^2 = \frac{a_{12}^2}{a_{11}\,a_{22}} \in [0, 1)

is the normalized coupling between the variables. Indeed, after updating x2x_2, e2=−(a12/a22) e1e_2 = -(a_{12}/a_{22})\,e_1; the next sweep yields e1′=−(a12/a11) e2=ρ2e1e_1' = -(a_{12}/a_{11})\,e_2 = \rho^2 e_1 and restores e2e_2 to its conditional optimum, so f−f⋆=12(a11−a122/a22) e12f - f^\star = \tfrac12(a_{11} - a_{12}^2/a_{22})\,e_1^2 is multiplied by ρ4\rho^4 each sweep. With independent variables (a12=0a_{12} = 0), ρ=0\rho = 0 and one sweep suffices; with ρ\rho near 1, each axis step undoes nearly everything done by the previous one.

For A=Rθdiag⁡(1,1/κ)Rθ⊤\mat{A} = \mat{R}_\theta\diag(1, 1/\kappa)\mat{R}_\theta\T, coupling depends on rotation: zero with aligned axes (θ=0°\theta = 0° or 90°90°), maximal at 45°45°, where ρ=(κ−1)/(κ+1)\rho = (\kappa - 1)/(\kappa + 1). Two cautions. First: Gauss-Seidel contracts error by ρ2\rho^2 per sweep and Jacobi by ρ\rho; for these matrices Gauss-Seidel is twice as fast in the exponent. Thus coordinate descent beats gradient descent with 1/L1/L in the figure even at 45°45°, 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 nn with cheap updates.

Coordinate Lipschitz constants

A gradient step in one coordinate requires knowing how far to move. Global smoothness uses one constant LL for the entire gradient; here one per coordinate suffices.

For the quadratic, Li=aiiL_i = a_{ii}. For linear fitting loss f(w)=1n∑k=1nϕ((Xw)k)f(\vb{w}) = \frac1n\sum_{k=1}^n \phi\big((\mat{X}\vb{w})_k\big) with ∣ϕ′′∣≤c\abs{\phi''} \le c, the Hessian is 1nX⊤diag⁡(ϕ′′((Xw)k))X\frac1n\mat{X}\T\diag\big(\phi''((\mat{X}\vb{w})_k)\big)\mat{X} and diagonal entry ii is at most cn∥xi∥22\frac{c}{n}\norm{\vb{x}_i}_2^2, so Li=cn∥xi∥22L_i = \frac{c}{n}\norm{\vb{x}_i}_2^2, with xi\vb{x}_i the iith column of X\mat{X} (notation throughout). Standardizing columns changes LiL_i and thus the method.

The inequality above gives, as in the global case, the coordinate descent lemma: f(x+t ei)≤f(x)+t ∇if(x)+Li2t2f(\vb{x} + t\,\vb{e}_i) \le f(\vb{x}) + t\,\nabla_i f(\vb{x}) + \frac{L_i}{2}t^2, and minimizing the right side in tt (t=−∇if(x)/Lit = -\nabla_i f(\vb{x})/L_i),

f(x−1Li∇if(x) ei)≤f(x)−12Li(∇if(x))2.(CD)f\Big(\vb{x} - \tfrac{1}{L_i}\nabla_i f(\vb{x})\,\vb{e}_i\Big) \le f(\vb{x}) - \frac{1}{2L_i}\big(\nabla_i f(\vb{x})\big)^2. \tag{CD}

The exact step reduces ff at least as much, so everything proved for 1/Li1/L_i also holds for exact steps.

If ff is convex and twice differentiable, the familiar constants satisfy Li=sup⁡ei⊤∇2f ei≤LL_i = \sup \vb{e}_i\T\hess f\,\vb{e}_i \le L (a quadratic form at a unit vector is at most the largest eigenvalue), L≤∑iLiL \le \sum_i L_i (the largest eigenvalue of a positive semidefinite matrix is at most its trace), hence

Lmax⁡≤L≤S≤n Lmax⁡.L_{\max} \le L \le S \le n\,L_{\max}.

Both extremes occur. With diagonal A\mat{A}, L=Lmax⁡L = L_{\max}: no coupling, and the full gradient is no worse than one coordinate. With A=11⊤\mat{A} = \vb{1}\vb{1}\T (all variables equal), L=nL = n and Lmax⁡=1L_{\max} = 1: global curvature is nn times each coordinate’s. Changing from 1/L1/L to 1/Li1/L_i 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 xk\vb{x}_k, the conditional expectation of f(xk+1)f(\vb{x}_{k+1}) is a finite sum of nn terms, each satisfying (CD). With uniform sampling,

E[f(xk+1)∣xk]≤f(xk)−12n∑i=1n(∇if(xk))2Li≤f(xk)−12nLmax⁡∥∇f(xk)∥22.\E\big[f(\vb{x}_{k+1}) \given \vb{x}_k\big] \le f(\vb{x}_k) - \frac{1}{2n}\sum_{i=1}^n \frac{(\nabla_i f(\vb{x}_k))^2}{L_i} \le f(\vb{x}_k) - \frac{1}{2nL_{\max}}\norm{\nabla f(\vb{x}_k)}_2^2.

With pi=Li/Sp_i = L_i/S, denominator LiL_i cancels the probability’s and leaves f(xk)−12S∥∇f(xk)∥22f(\vb{x}_k) - \frac{1}{2S}\norm{\nabla f(\vb{x}_k)}_2^2. In both cases, in expectation, coordinate descent guarantees the same decrease as the descent lemma for a gradient step with constant M=nLmax⁡M = nL_{\max} or M=SM = S (both ≥L\ge L): 12M∥∇f∥2\tfrac{1}{2M}\norm{\nabla f}^2. To turn this into a rate use the Polyak–Łojasiewicz condition, satisfied by a μ\mu-strongly convex function with constant μ\mu: ∥∇f∥2≥2μ(f−f⋆)\norm{\nabla f}^2 \ge 2\mu(f - f^\star).

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 nn partial derivatives and, at rate 1−μ/L1 - \mu/L, needs order κ=L/μ\kappa = L/\mu steps per factor-ee reduction: nL/μn L/\mu derivatives total. Uniform descent needs nLmax⁡/μnL_{\max}/\mu updates, one derivative each. Since Lmax⁡≤LL_{\max} \le L, the randomized method’s bound is never worse than gradient descent’s, and up to nn times better if L=nLmax⁡L = nL_{\max}, the strongly coupled case.

InteractiveCyclic, randomized and the bound
E[f(xk)]/f(x0)\E[f(\vb{x}_k)]/f(\vb{x}_0) by coordinate updates (logarithmic scale)
  • Cyclic
  • Random permutation
  • Uniform
  • Importance p ∝ L
  • Uniform bound
  • Importance bound
  • Invariant bound
  • cyclic
  • random permutation
  • uniform
  • importance pi∝Lip_i \propto L_i
  • bounds (dashed; grey is unit-invariant)
0.80
1
μ=λmin⁡(A)\mu = \lambda_{\min}(\mat{A})0.2
Uniform bound 1−μ/(nLmax⁡)1 - \mu/(nL_{\max})0.98000
Importance bound 1−μ/∑Li1 - \mu/\sum L_i0.98000
Invariant bound 1−μL/n1 - \mu_L/n0.98000
Factor per update, cyclic0.9894
Factor per update, random permutation0.9558
Factor per update, uniform0.9657
Factor per update, importance p ∝ l0.9657
Updates to f/f0≤10−3f/f_0 \le 10^{-3} (cyclic / shuffled)486 / 127
Updates to f/f0≤10−3f/f_0 \le 10^{-3} (uniform / importance)159 / 159
Bound ratio nLmax⁡/∑LinL_{\max}/\sum L_i1.00
With highly correlated variables, a fixed order is about 4.34.3 times slower per update than reshuffling each sweep. Nesterov’s bounds cover random sampling only.
Ten variables with A=D1/2CD1/2\mat{A} = \mat{D}^{1/2}\mat{C}\mat{D}^{1/2}, where C\mat{C} has 11 on the diagonal and ρ\rho off-diagonal, and D=diag⁡(Li)\mat{D} = \diag(L_i) distributes constants between 11 and the chosen spread (each variable's 'units'). Plot cyclic order, random permutations, uniform and importance sampling (mean of 40 runs) against Nesterov bounds, straight on a logarithmic scale (gray is the scale-independent bound explained below). Raise ρ\rho: which order suffers most? Then increase scale spread: which curves move? And the bounds?

Three things the figure teaches that a bound alone does not:

  1. Bounds are worst-case. Actual curves fall well below theoretical lines.
  2. 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 n2n^2 times more updates than random.
  3. The 1/Li1/L_i method is independent of variable units, but bounds are not. Multiplying variable xix_i by a constant changes LiL_i 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 Lmax⁡L_{\max}, which changes. A scale-insensitive bound replaces μ\mu by strong-convexity constant μL\mu_L measured in weighted norm ∥x∥L2=∑iLixi2\norm{\vb{x}}_L^2 = \sum_i L_i x_i^2 (for the quadratic, μL=λmin⁡(D−1/2AD−1/2)\mu_L = \lambda_{\min}(\mat{D}^{-1/2}\mat{A}\mat{D}^{-1/2})); the uniform bound is 1−μL/n1 - \mu_L/n (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 LiL_i 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 ff was differentiable. Lasso adds a nonsmooth term. Before seeing what works, look at what fails.

Consider f(x,y)=∣x−y∣+(x+y2−2)2f(x, y) = \abs{x - y} + \big(\tfrac{x + y}{2} - 2\big)^2. It is convex, uniquely minimized at (2,2)(2, 2) with f=0f = 0, and its only nonsmooth term ∣x−y∣\abs{x - y} has a corner along diagonal y=xy = x. At diagonal point (t,t)(t, t), moving only xx by ss gives

f(t+s, t)=∣s∣+(t−2+s2)2,f(t + s,\, t) = \abs{s} + \Big(t - 2 + \frac{s}{2}\Big)^2,

whose one-sided derivative at s=0+s = 0^+ is 1+(t−2)1 + (t - 2) and at s=0−s = 0^- is −1+(t−2)-1 + (t - 2). For s=0s = 0 to minimize, 1+(t−2)≥01 + (t - 2) \ge 0 and −1+(t−2)≤0-1 + (t - 2) \le 0, i.e. 1≤t≤31 \le t \le 3. By symmetry the same holds for yy. Thus every (t,t)(t, t) with 1≤t≤31 \le t \le 3 is a coordinatewise minimum, and coordinate descent gets stuck there, although f(t,t)=(t−2)2f(t, t) = (t - 2)^2 vanishes only at t=2t = 2. Along the diagonal, however, f(t+s,t+s)=(t+s−2)2f(t + s, t + s) = (t + s - 2)^2 does decrease when approaching t=2t = 2.

InteractiveStuck on a ridge
Contours of ∣x−y∣+((x+y)/2−2)2\abs{x - y} + ((x + y)/2 - 2)^2
gets stuck here(2, 2)
ff moving only xx (axis 1)
ff moving only yy (axis 2)
ff along the diagonal (1,1)/2(1, 1)/\sqrt{2}
  • coordinate descent
  • stuck points (t,t)(t, t), 1≤t≤31 \le t \le 3
  • section along the diagonal
Nonsmooth term
8 updates
Current point (x,y)(x, y)(1.400, 1.400)
f−f⋆f - f^\star0.3600
Minimum axis slope0.400
Minimum diagonal slope−0.849
Stuck. All four axis slopes are ≥0\ge 0, so no coordinate update can decrease ff. Along the diagonal, however, the slope is −0.85<0−0.85 < 0: descent exists in a direction the method cannot take.
Drag initial point p0p_0 and play exact updates. With ∣x−y∣\abs{x - y}, nearly all starts end on the diagonal (red segment, 1≤t≤31 \le t \le 3), not minimum (2,2)(2, 2). Right, three sections of ff through the current point: on each axis it is a minimum (with a sharp point at zero), but along the diagonal the curve still falls. Readouts give one-sided slopes. Switch to separable ∣x∣+∣y∣\abs{x} + \abs{y}: now all starts end on minimizer segment x+y=2x + y = 2, x,y≥0x, y \ge 0. Enable 'Where 14 starts end' in both cases.

This is not numerical failure. The four directions the method can test, ±e1\pm\vb{e}_1 and ±e2\pm\vb{e}_2, all rise, yet the diagonal descends. Taking it requires moving both variables at once, which a coordinate method never does: the corner of ∣x−y∣\abs{x - y} couples them. With ∣x∣+∣y∣\abs{x} + \abs{y}, each corner affects only its own variable and the problem disappears. The next result formalizes this.

Proof

For each ii, one-variable φi(t)=f(x⋆+t ei)+gi(xi⋆+t)\varphi_i(t) = f(\vb{x}^\star + t\,\vb{e}_i) + g_i(x^\star_i + t) is convex and minimized at 00. Its one-sided directional derivatives at 00 are nonnegative: ∇if(x⋆)+gi′(xi⋆;+1)≥0\nabla_i f(\vb{x}^\star) + g_i'(x^\star_i; +1) \ge 0 and −∇if(x⋆)+gi′(xi⋆;−1)≥0-\nabla_i f(\vb{x}^\star) + g_i'(x^\star_i; -1) \ge 0, where gi′(x;±1)g_i'(x; \pm 1) is a one-sided directional derivative of gig_i. By convexity gi(z)−gi(xi⋆)≥gi′(xi⋆;±1) ∣z−xi⋆∣g_i(z) - g_i(x^\star_i) \ge g_i'(x^\star_i; \pm 1)\,\abs{z - x^\star_i} (with sign according to whether zz lies right or left), so ∇if(x⋆)(z−xi⋆)+gi(z)−gi(xi⋆)≥0\nabla_i f(\vb{x}^\star)(z - x^\star_i) + g_i(z) - g_i(x^\star_i) \ge 0 for all z∈Rz \in \R. For arbitrary y\vb{y}, convexity of ff gives f(y)≥f(x⋆)+∇f(x⋆)⊤(y−x⋆)f(\vb{y}) \ge f(\vb{x}^\star) + \nabla f(\vb{x}^\star)\T(\vb{y} - \vb{x}^\star), and adding the gig_i,

F(y)−F(x⋆)≥∑i=1n[∇if(x⋆)(yi−xi⋆)+gi(yi)−gi(xi⋆)]≥0,F(\vb{y}) - F(\vb{x}^\star) \ge \sum_{i=1}^n \Big[\nabla_i f(\vb{x}^\star)(y_i - x^\star_i) + g_i(y_i) - g_i(x^\star_i)\Big] \ge 0,

because each summand is nonnegative by the above with z=yiz = y_i.

∎

The proof uses separability at one point: the sum of gi(yi)−gi(xi⋆)g_i(y_i) - g_i(x^\star_i) splits coordinate by coordinate. With ∣x−y∣\abs{x - y} there is no g1(x)+g2(y)g_1(x) + g_2(y) and the argument breaks exactly where the method fails. The theorem describes where coordinate descent stops; convergence is a further Tseng (2001) result: if F=f+∑igiF = f + \sum_i g_i with convex C1C^1 ff, convex lower semicontinuous gig_i, compact initial level set, FF continuous there, and each coordinate subproblem uniquely minimized (technical hypotheses of the theorem), every limit point of exact cyclic coordinate descent minimizes FF.

Proximal coordinate descent and lasso

The widely used case satisfying the theorem is smooth plus separable penalty, F(x)=f(x)+∑igi(xi)F(\vb{x}) = f(\vb{x}) + \sum_i g_i(x_i). Each update combines two known ideas: a gradient step in that coordinate and the proximal operator of gig_i 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 ff is strongly convex, and order 1/k1/k in the convex case, like Nesterov’s smooth-case rates.

Lasso

With f(w)=12n∥y−Xw∥2f(\vb{w}) = \frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{w}}^2 and g(w)=λ∥w∥1g(\vb{w}) = \lambda\norm{\vb{w}}_1 (scikit-learn’s scale; the proximal-methods lesson did not divide by nn and its parameter equals our nλn\lambda), coordinate jj has constant Lj=∥xj∥22/nL_j = \norm{\vb{x}_j}_2^2/n, and its update follows in four lines.

min⁡wj 12n∥r−j−wj xj∥22+λ∣wj∣\min_{w_j}\ \frac{1}{2n}\norm{\vb{r}_{-j} - w_j\,\vb{x}_j}_2^2 + \lambda\abs{w_j}
With other variables fixed and partial residual r−j=y−∑k≠jwkxk\vb{r}_{-j} = \vb{y} - \sum_{k \ne j} w_k\vb{x}_k, this is a one-variable function.
1/4

If columns are standardized with ∥xj∥2=n\norm{\vb{x}_j}^2 = n, then Lj=1L_j = 1 and the update is glmnet’s elegant wj←Sλ(1nxj⊤r+wj)w_j \leftarrow S_\lambda\big(\tfrac1n\vb{x}_j\T\vb{r} + w_j\big). Otherwise different LjL_j make the result unit-dependent, so standardize before fitting.

Regularization paths and warm starts

Usually one wants not a single λ\lambda but the path λ↦w^(λ)\lambda \mapsto \hat{\vb{w}}(\lambda) to choose λ\lambda by validation. A natural starting value exists. w=0\vb{w} = \vb{0} is optimal iff 0∈−1nX⊤y+λ ∂∥0∥1\vb{0} \in -\frac1n\mat{X}\T\vb{y} + \lambda\,\partial\norm{\vb{0}}_1, i.e. ∣xj⊤y∣/n≤λ\abs{\vb{x}_j\T\vb{y}}/n \le \lambda for all jj. Thus

λmax⁡=1n∥X⊤y∥∞\lambda_{\max} = \frac1n\norm{\mat{X}\T\vb{y}}_\infty

is the smallest λ\lambda producing an empty model, and the path is traversed downward on a logarithmic grid. The efficiency key is warm starting: the next slightly smaller λ\lambda solution resembles the preceding one, so use it as the starting point. Each λ\lambda then costs a few sweeps rather than a cold start.

InteractiveRegularization paths
Coefficient path w^(λ)\hat{\vb{w}}(\lambda) (the four signal variables in color)
110⁻¹10⁻²10⁻³λ = 1.000 λmax
λ/λmax⁡\lambda/\lambda_{\max} (logarithmic scale, decreasing to the right)
Complete passes needed for each λ\lambda on the path
  • Cold start
  • Warm start
  • cold start at each λ\lambda
  • warm start
  • variables without signal
1 / 50
Correlation between columns
Tolerance (relative gap)
λ no. 1 / 50
λ/λmax⁡\lambda/\lambda_{\max}1.0000
Nonzero variables0 of 12
Passes at this λ\lambda, cold start0
Passes at this λ\lambda, warm start0
Cumulative so far (cold / warm)0 / 0
Full path (cold / warm)769 / 320
320 warm-start passes versus 769 from zero (2.4 times fewer). Peaks in the aqua curve mark values of λ\lambda where a variable enters the model.
Lasso coefficient path for 50 λ\lambda values between λmax⁡\lambda_{\max} and 10−3λmax⁡10^{-3}\lambda_{\max} (synthetic data, n=60n = 60, 12 variables of which 4 carry signal, in color), calculated by coordinate descent. Right, full sweeps needed per λ\lambda: cold start (red) and warm start (teal). Traverse the path with the slider or playback. Change tolerance and column correlation. When does warm starting save most? What happens at λ\lambda values where a variable enters the model?

Savings are large with loose tolerance and shrink with strict tolerance: warm starts remove each λ\lambda‘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 λ\lambda 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 ρ4\rho^4 factor per sweep.

[ ]Exact coordinates and Gauss-Seidel on a quadraticBrowser
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 ρ4\rho^4 to all digits. Notice g += t * A[:, i]: the quadratic version of an incremental residual. Calculate the gradient once and update in O(n)\bigO(n) per coordinate. Removing this and recalculating A @ x - b at each coordinate would multiply sweep cost by nn.

Now compare orders and verify bounds, using the figure’s problem: ten equicorrelated variables with distributed scales LiL_i, average of 20 random runs.

[ ]Cyclic, shuffled, uniform and importanceBrowser
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 ρ=0.8\rho = 0.8, cyclic contracts ff by 0.98890.9889 per update, shuffled by 0.95530.9553, uniform by 0.96480.9648: fixed order is several times slower in the exponent. Random rates satisfy their bounds (0.9648≤0.980.9648 \le 0.98). Changing spread from 1 to 100 gives cyclic, shuffled and uniform the same numbers, while the uniform bound rises from 0.980.98 to 0.99980.9998 and importance sampling worsens from 0.96590.9659 to 0.99470.9947. The weighted-norm bound remains 0.980.98: 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.

[ ]Stuck on the diagonalBrowser
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 (2,2)(2, 2), with f>0f > 0. At the first, all four one-sided axis slopes are positive while the slope toward (2,2)(2, 2) is negative. The separable variant always reaches f=3f = 3, the minimum, at different points on segment x+y=2x + y = 2.

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.

[ ]Coordinate lasso with incremental residualBrowser
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 10−1010^{-10} and matches scikit-learn. The last comparison shows the main warning: recalculating the full residual per coordinate gives the same result but costs O(np)\bigO(np) per coordinate instead of O(n)\bigO(n), with the difference growing in pp.

Now the λ\lambda 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, O(np)\bigO(np)).

[ ]Regularization path and comparison with ISTA and FISTABrowser
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 X⊤X\mat{X}\T\mat{X}, 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.

[ ]Active-set strategyBrowser
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 λ\lambda 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.

[ ]scikit-learn: order, warm start and cross-validationBrowser
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 12n∥y−Xw∥2+α∥w∥1\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{w}}^2 + \alpha\norm{\vb{w}}_1, so alpha is exactly this lesson’s λ\lambda. 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 W\mat{W} and H\mat{H}.

Blocks and alternating minimization

When variables form blocks x=(x1,…,xm)\vb{x} = (\vb{x}_1, \dots, \vb{x}_m) 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 M∈Rm×n\mat{M} \in \R^{m \times n} observed only at positions Ω\Omega, seek U∈Rm×r\mat{U} \in \R^{m \times r} and V∈Rn×r\mat{V} \in \R^{n \times r} with M≈UV⊤\mat{M} \approx \mat{U}\mat{V}\T on Ω\Omega:

F(U,V)=12∑(i,j)∈Ω(Mij−ui⊤vj)2+λ2(∥U∥F2+∥V∥F2).F(\mat{U}, \mat{V}) = \frac12\sum_{(i,j) \in \Omega}\big(M_{ij} - \vb{u}_i\T\vb{v}_j\big)^2 + \frac{\lambda}{2}\big(\norm{\mat{U}}_F^2 + \norm{\mat{V}}_F^2\big).

FF is not convex jointly in (U,V)(\mat{U}, \mat{V}) (ui⊤vj\vb{u}_i\T\vb{v}_j is bilinear), but with V\mat{V} fixed it is a strictly convex quadratic in U\mat{U}, separable by rows: each ui\vb{u}_i solves ridge regression using only observed entries of its M\mat{M} row,

ui←(∑j∈Ωivjvj⊤+λIr)−1∑j∈ΩiMij vj,\vb{u}_i \leftarrow \Big(\sum_{j \in \Omega_i}\vb{v}_j\vb{v}_j\T + \lambda\mat{I}_r\Big)^{-1}\sum_{j \in \Omega_i} M_{ij}\,\vb{v}_j,

and similarly for each vj\vb{v}_j with U\mat{U} fixed. This is alternating least squares (ALS). Each half comprises mm (or nn) independent r×rr \times r 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 FF; 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. U=0\mat{U} = \mat{0}, V=0\mat{V} = \mat{0} is stationary for FF and ALS started there does not move: updating either block with the other zero returns zero.
  • Symmetry. If (U,V)(\mat{U}, \mat{V}) is a solution, so is (UQ,VQ)(\mat{U}\mat{Q}, \mat{V}\mat{Q}) for any orthogonal Q\mat{Q}, with the same FF. Minimizers are not unique and solutions from different starts should be compared by UV⊤\mat{U}\mat{V}\T, not componentwise.
  • Slowness. ALS can advance very slowly near the solution when blocks are strongly coupled, the staircase phenomenon again.
[ ]ALS with missing dataBrowser
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 U\mat{U} remains zero. The last line shows symmetry: the same objective with different factors.

Common mistakes

Exercises

NumericAn exact cyclic sweep
Let f(x)=12x⊤Axf(\vb{x}) = \tfrac12\vb{x}\T\mat{A}\vb{x} with A=[2112]\mat{A} = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix}. Starting at (1,1)(1, 1), make one exact cyclic sweep (first x1x_1, then x2x_2) and give the resulting second component.
NumericThe per-sweep factor
For f(x)=12x⊤Axf(\vb{x}) = \tfrac12\vb{x}\T\mat{A}\vb{x} with A=[10.80.81]\mat{A} = \begin{bmatrix} 1 & 0.8 \\ 0.8 & 1 \end{bmatrix}, exact cyclic coordinate descent reduces f−f⋆f - f^\star by a constant factor each complete sweep from the second onward (the first depends on the start). What is the factor?
NumericUniform versus importance sampling
A μ\mu-strongly convex function of n=3n = 3 variables has coordinate constants L=(1,1,8)L = (1, 1, 8). How many times fewer updates does importance bound 1−μ/S1 - \mu/S guarantee than uniform bound 1−μ/(nLmax⁡)1 - \mu/(nL_{\max}) for a given reduction factor in f−f⋆f - f^\star? (Use the exponent ratio, valid for small μ\mu.)
NumericThe first $\lambda$ on the path
With n=4n = 4, X=[12−111−2−1−1]\mat{X} = \begin{bmatrix} 1 & 2 \\ -1 & 1 \\ 1 & -2 \\ -1 & -1 \end{bmatrix} and y=(3,−1,2,0)⊤\vb{y} = (3, -1, 2, 0)\T, what is the smallest λ\lambda for which w=0\vb{w} = \vb{0} solves lasso 12n∥y−Xw∥2+λ∥w∥1\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{w}}^2 + \lambda\norm{\vb{w}}_1?
NumericHow many updates are guaranteed?
A μ\mu-strongly convex function with μ=0.05\mu = 0.05 and Lmax⁡=4L_{\max} = 4 has n=100n = 100 variables. For uniform randomized descent, what is the smallest kk for which Nesterov's bound guarantees E[f(xk)]−f⋆≤10−6 (f(x0)−f⋆)\E[f(\vb{x}_k)] - f^\star \le 10^{-6}\,(f(\vb{x}_0) - f^\star)?
QuizWhich ones converge?
For which convex problems with a nonsmooth term does exact coordinate descent (under Tseng's hypotheses) guarantee reaching a minimizer?

More than one answer may be correct.

QuizChanging a variable's units
Multiply variable x3x_3's unit by 100100 (use x~3=x3/100\tilde{x}_3 = x_3/100 as the new variable) in a quadratic, then rerun exact cyclic and uniform coordinate descent. What happens?
QuizWhat holds for ALS?
For ALS applied to F(U,V)=12∑Ω(Mij−ui⊤vj)2+λ2(∥U∥F2+∥V∥F2)F(\mat{U}, \mat{V}) = \frac12\sum_{\Omega}(M_{ij} - \vb{u}_i\T\vb{v}_j)^2 + \frac\lambda2(\norm{\mat{U}}_F^2 + \norm{\mat{V}}_F^2) with λ>0\lambda > 0, which statements are true?

More than one answer may be correct.

ProofThe randomized descent rate
Prove: Let ff be μ\mu-strongly convex with coordinate constants LiL_i and minimum f⋆f^\star, and let x+=x−1Li∇if(x)ei\vb{x}^+ = \vb{x} - \frac{1}{L_i}\nabla_i f(\vb{x})\vb{e}_i with ii uniform on {1,…,n}\{1, \dots, n\}. Then E[f(x+)]−f⋆≤(1−μnLmax⁡)(f(x)−f⋆)\E[f(\vb{x}^+)] - f^\star \le \big(1 - \tfrac{\mu}{nL_{\max}}\big)\big(f(\vb{x}) - f^\star\big), hence E[f(xk)]−f⋆≤(1−μnLmax⁡)k(f(x0)−f⋆)\E[f(\vb{x}_k)] - f^\star \le \big(1 - \tfrac{\mu}{nL_{\max}}\big)^k\big(f(\vb{x}_0) - f^\star\big).
0
Start with the lesson's inequality (CD) for a fixed coordinate ii.

Step 1 of 4. What bound does (CD) give for f(x+)f(\vb{x}^+) with fixed ii?

ProofCyclic coordinate descent is Gauss-Seidel
Prove: Let A\mat{A} be symmetric with positive diagonal, f(x)=12x⊤Ax−b⊤xf(\vb{x}) = \tfrac12\vb{x}\T\mat{A}\vb{x} - \vb{b}\T\vb{x} and A=L+D+U\mat{A} = \mat{L} + \mat{D} + \mat{U} (strictly lower, diagonal, strictly upper). One exact cyclic sweep of x1,…,xnx_1, \dots, x_n from x\vb{x} gives x+\vb{x}^+ satisfying (D+L)x+=b−Ux(\mat{D} + \mat{L})\vb{x}^+ = \vb{b} - \mat{U}\vb{x}.
0
Fix coordinate ii during the sweep: coordinates 1,…,i−11, \dots, i-1 already equal xj+x_j^+ and i+1,…,ni+1, \dots, n still equal xjx_j.

Step 1 of 3. What condition does the exact minimizer of t↦f(z+t ei)t \mapsto f(\vb{z} + t\,\vb{e}_i) satisfy?

CodeLasso by coordinates
Implement cd_lasso(X, y, lam, tol), returning vector w minimizing 12n∥y−Xw∥22+λ∥w∥1\frac{1}{2n}\norm{\vb{y} - \mat{X}\vb{w}}_2^2 + \lambda\norm{\vb{w}}_1 with cyclic coordinate descent. Maintain the residual and update it in O(n)\bigO(n) per coordinate (do not recalculate X @ w inside the coordinate loop). Stop when, after a full sweep, maximum change max⁡j∣Δwj∣\max_j\abs{\Delta w_j} is ≤\le 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 w
Shift+Enter to run

Summary

Key idea
When inspecting or changing one variable is much cheaper than inspecting all, coordinate descent with a maintained residual or gradient turns nn updates into the cost of one gradient, each using fresher information. With a separable nonsmooth term it converges (coordinatewise soft thresholding is 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, f−f⋆f - f^\star is multiplied by ρ4\rho^4 per sweep, with ρ2=a122/(a11a22)\rho^2 = a_{12}^2/(a_{11}a_{22}): one sweep for independent variables, a long staircase for strong coupling.
  • With coordinate Lipschitz constants, f(x−1Li∇if ei)≤f(x)−12Li(∇if)2f(\vb{x} - \frac{1}{L_i}\nabla_i f\,\vb{e}_i) \le f(\vb{x}) - \frac{1}{2L_i}(\nabla_i f)^2, and Lmax⁡≤L≤S≤nLmax⁡L_{\max} \le L \le S \le nL_{\max}.
  • With randomized order, expected decrease is 12n∑i(∇if)2/Li\frac{1}{2n}\sum_i(\nabla_i f)^2/L_i and rate 1−μ/(nLmax⁡)1 - \mu/(nL_{\max}) per update (or 1−μ/S1 - \mu/S with pi∝Lip_i \propto L_i). 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 F=f+∑igi(xi)F = f + \sum_i g_i(x_i), a coordinatewise minimum is global and proximal descent xi←prox⁡gi/Li(xi−∇if/Li)x_i \leftarrow \operatorname{prox}_{g_i/L_i}(x_i - \nabla_i f/L_i) converges. With ∣x−y∣\abs{x - y}, fused lasso or overlapping norms it stalls away from minima.
  • Lasso: update wj←Sλ(xj⊤r/n+Ljwj)/Ljw_j \leftarrow S_\lambda(\vb{x}_j\T\vb{r}/n + L_jw_j)/L_j in O(n)\bigO(n) with incremental residual; λmax⁡=∥X⊤y∥∞/n\lambda_{\max} = \norm{\mat{X}\T\vb{y}}_\infty/n; λ\lambda 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.