Module contents
Lesson 10 of 27Core 90 min

Nonsmooth optimization: subgradients

Generalize gradients to convex functions with corners (norms, maxima and hinge loss) using subdifferentials and their calculus. Analyze the subgradient method, which is not a descent method and converges at O(1/√k), and Polyak's step when the optimal value is known.

After this lesson you can

  • Calculate subdifferentials of |x|, ‖x‖₁, ‖x‖₂, maxima of affine functions and hinge loss.
  • Apply subdifferential calculus rules (sum, affine composition, pointwise maximum) and the condition 0 ∈ ∂f(x*).
  • Prove the O(1/√k) subgradient-method rate for the best iterate with suitable steps.
  • Explain why a subgradient is not generally a descent direction and why the rate is optimal for the nonsmooth class.
  • Implement Polyak's step and compare it with decreasing steps.

Before you start

Motivation: frequently solved problems have corners

All algorithms so far assumed a gradient: gradient descent, line search, momentum. But many important machine-learning problems are nondifferentiable by construction, not by oversight:

  • The ℓ1\ell_1 norm (lasso, compressed sensing, sparsity-inducing regularization): ∥x∥1=∑i∣xi∣\norm{\vb{x}}_1 = \sum_i \abs{x_i} has a corner on each axis, and regularized solutions live at those corners, where coordinates vanish.
  • SVM hinge loss max⁡{0, 1−y w⊤x}\max\{0,\, 1 - y\,\vb{w}\T\vb{x}\} and absolute loss ∣w⊤x−y∣\abs{\vb{w}\T\vb{x} - y} in robust regression, estimating medians instead of means.
  • Maxima: worst-case error max⁡ifi(x)\max_i f_i(\vb{x}), Chebyshev approximation, distance to a union of sets, functions in a min-max problem.
  • Networks with ReLU and max-pooling: such a network’s loss is piecewise linear or nearly so, with corners on a measure-zero set traversed constantly in training.

Why not “ignore” corners and apply gradient descent wherever the gradient exists? The optimum often lies at the corner, invisible to the gradient. Consider the smallest case, f(x)=∣x∣f(x) = \abs{x}, with fixed step η=0.3\eta = 0.3 from x0=1x_0 = 1:

xk+1=xk−η sign⁡(xk):1, 0.7, 0.4, 0.1, −0.2, 0.1, −0.2, 0.1, …x_{k+1} = x_k - \eta\,\operatorname{sign}(x_k): \qquad 1,\ 0.7,\ 0.4,\ 0.1,\ -0.2,\ 0.1,\ -0.2,\ 0.1,\ \dots

The method jumps across the minimum forever. The “gradient” is ±1\pm 1 everywhere except 00, where it does not exist: it never vanishes even at the minimum, so ∇f=0\grad f = \vb{0} is neither criterion nor guide. This lesson reconstructs three working pieces: a generalized derivative (subgradient), an optimality condition (0∈∂f0 \in \partial f), and an algorithm (subgradient method), its analysis, O(1/k)\bigO(1/\sqrt{k}) rate, lower bound and Polyak step. We work with convex functions, where theory is clean and nearly all useful results lie.

Intuition: the tangent becomes a fan

For a convex differentiable function, the first-order condition says the tangent at xx lies below the whole graph: f(y)≥f(x)+f′(x)(y−x)f(y) \ge f(x) + f'(x)(y - x). This property, not differentiability, matters for optimization. It remains true at a corner: at the tip of ∣x∣\abs{x} no tangent exists, but lines through the point leave the entire graph above them. In fact many do: all slopes between −1-1 and 11.

InteractiveThe subgradient fan
∂f(x₀)

Slope line: the teal segment is ∂f(x0)\partial f(x_0) and the point is your ss.

  • supporting line
  • line crossing the graph
  • fan of valid slopes
Dimension
Function
0.4
0
x0x_0 and f(x0)f(x_0)0 and 0
∂f(x0)\partial f(x_0)[−1, 1]
slope ss0.4
min. of f(y)−f(x0)−s(y−x0)f(y) - f(x_0) - s(y - x_0)0
At the corner any slope in [−1, 1] gives a supporting line: a fan. The extreme lines are the one-sided slopes of ff.
Drag the blue point on the graph and rotate the line with its handle (or slider). It turns aqua if a supporting line, i.e. below ff everywhere, and red if it crosses the graph (the violating segment is thick). The lower strip is the slope axis: the aqua segment is the set of valid slopes at the point. Move to a corner of ∣x∣\abs{x} and hinge, and to any smooth point: how many slopes work in each case? With x2/2x^2/2 only one; with −∣x∣-\abs{x} none, although the graph is “almost” differentiable. Switch to two variables, choose a norm and move x\vb{x} to the origin: the subgradient region becomes a square, disk or diamond, and for g\vb{g} outside it the figure shows a point y\vb{y} violating the inequality.

Three things the figure shows, formalized in the rest of the lesson:

  1. At a smooth point only one supporting line exists, the tangent. The slope set is a single number.
  2. At a corner there is a slope interval between left and right derivatives. The sharper the corner, the wider the fan.
  3. Without convexity there is no guarantee. At the peak of −∣x∣-\abs{x} no line lies below, and at any other point even the tangent is not a supporting line, because “below” is required globally, not just nearby.

Subgradient and subdifferential

Two reading notes. The inequality is global (for all y\vb{y}), not local: this excludes −∣x∣-\abs{x} and makes the subdifferential a convexity notion, not differential calculus. Geometrically, g\vb{g} is the slope of a supporting hyperplane of the epigraph: vector (g,−1)(\vb{g}, -1) is normal at (x,f(x))(\vb{x}, f(\vb{x})) to a hyperplane leaving the whole epigraph on one side. Hence the supporting hyperplane theorem guarantees existence.

Proof

(1) ∂f(x)=⋂y{g:g⊤(y−x)≤f(y)−f(x)}\partial f(\vb{x}) = \bigcap_{\vb{y}} \{\vb{g} : \vb{g}\T(\vb{y} - \vb{x}) \le f(\vb{y}) - f(\vb{x})\} is an intersection of closed half-spaces.

(2) Nonempty. Epigraph epi⁡f\operatorname{epi} f is convex and (x,f(x))(\vb{x}, f(\vb{x})) lies on its boundary. The supporting hyperplane theorem gives (λ,β)≠0(\vb{\lambda}, \beta) \neq \vb{0} with λ⊤(y−x)+β (t−f(x))≤0\vb{\lambda}\T(\vb{y} - \vb{x}) + \beta\,(t - f(\vb{x})) \le 0 for every (y,t)∈epi⁡f(\vb{y}, t) \in \operatorname{epi} f. Letting t→∞t \to \infty gives β≤0\beta \le 0. If β=0\beta = 0, then λ⊤(y−x)≤0\vb{\lambda}\T(\vb{y} - \vb{x}) \le 0 for every y∈Rn\vb{y} \in \R^n, so λ=0\vb{\lambda} = \vb{0}, impossible. Thus β<0\beta < 0, and with g=λ/(−β)\vb{g} = \vb{\lambda}/(-\beta) and t=f(y)t = f(\vb{y}) we get f(y)≥f(x)+g⊤(y−x)f(\vb{y}) \ge f(\vb{x}) + \vb{g}\T(\vb{y} - \vb{x}). Bounded. If g≠0\vb{g} \neq \vb{0}, take y=x+δ g/∥g∥\vb{y} = \vb{x} + \delta\,\vb{g}/\norm{\vb{g}} for small δ\delta: δ∥g∥≤f(y)−f(x)≤Gδ\delta\norm{\vb{g}} \le f(\vb{y}) - f(\vb{x}) \le G\delta. Closed and bounded implies compact.

(3) If g∈∂f(x)\vb{g} \in \partial f(\vb{x}), for each d\vb{d} and t>0t > 0 we have f(x+td)−f(x)≥t g⊤df(\vb{x} + t\vb{d}) - f(\vb{x}) \ge t\,\vb{g}\T\vb{d}. Divide by tt and let t→0+t \to 0^+: ∇f(x)⊤d≥g⊤d\grad f(\vb{x})\T\vb{d} \ge \vb{g}\T\vb{d} for every d\vb{d}; using d\vb{d} and −d-\vb{d} gives g=∇f(x)\vb{g} = \grad f(\vb{x}). The first-order condition puts ∇f(x)\grad f(\vb{x}) in the subdifferential.

∎

In one variable the subdifferential is interval ∂f(x)=[f−′(x), f+′(x)]\partial f(x) = [f'_-(x),\, f'_+(x)] between one-sided derivatives. In several variables it is a convex set that can be a point, segment, polygon or disk, as in the figure.

The directional derivative is the maximum over the subdifferential

All directional information about ff can be recovered from ∂f\partial f, key to understanding why one subgradient can mislead.

Proof

Existence. By convexity quotient q(t)=(f(x+td)−f(x))/tq(t) = (f(\vb{x} + t\vb{d}) - f(\vb{x}))/t is nondecreasing in tt, and bounded below by g⊤d\vb{g}\T\vb{d} for any g∈∂f(x)\vb{g} \in \partial f(\vb{x}) (which exists by the preceding theorem). Its limit as t↓0t \downarrow 0 therefore exists and is finite.

Characterization. Let h(d)=f′(x;d)h(\vb{d}) = f'(\vb{x}; \vb{d}). It is positively homogeneous, convex (a limit of convex functions) and finite. We claim g∈∂f(x)  ⟺  g⊤d≤h(d)\vb{g} \in \partial f(\vb{x}) \iff \vb{g}\T\vb{d} \le h(\vb{d}) for every d\vb{d}. One direction follows by taking limits in f(x+td)−f(x)≥t g⊤df(\vb{x} + t\vb{d}) - f(\vb{x}) \ge t\,\vb{g}\T\vb{d}. Conversely, since qq is nondecreasing, q(1)≥h(d)q(1) \ge h(\vb{d}), i.e. f(y)−f(x)≥h(y−x)≥g⊤(y−x)f(\vb{y}) - f(\vb{x}) \ge h(\vb{y} - \vb{x}) \ge \vb{g}\T(\vb{y} - \vb{x}).

Maximum. We must show h(d0)h(\vb{d}_0) is attained. Since hh is convex and finite, it has a subgradient g\vb{g} at d0\vb{d}_0: h(d)≥h(d0)+g⊤(d−d0)h(\vb{d}) \ge h(\vb{d}_0) + \vb{g}\T(\vb{d} - \vb{d}_0) for every d\vb{d}. With d=0\vb{d} = \vb{0}, g⊤d0≥h(d0)\vb{g}\T\vb{d}_0 \ge h(\vb{d}_0); with d=2d0\vb{d} = 2\vb{d}_0 (homogeneity), g⊤d0≤h(d0)\vb{g}\T\vb{d}_0 \le h(\vb{d}_0). Thus g⊤d0=h(d0)\vb{g}\T\vb{d}_0 = h(\vb{d}_0) and substituting, h(d)≥g⊤dh(\vb{d}) \ge \vb{g}\T\vb{d} for every d\vb{d}: g∈∂f(x)\vb{g} \in \partial f(\vb{x}) attains the value.

∎

Important consequence: d\vb{d} is a descent direction for ff at x\vb{x} when f′(x;d)<0f'(\vb{x}; \vb{d}) < 0, i.e. when g⊤d<0\vb{g}\T\vb{d} < 0 for all g∈∂f(x)\vb{g} \in \partial f(\vb{x}), not just one. Thus −g-\vb{g} for any subgradient g\vb{g} is a descent direction iff g⊤h>0\vb{g}\T\vb{h} > 0 for every h∈∂f(x)\vb{h} \in \partial f(\vb{x}). At a smooth point this always holds (g⊤g>0\vb{g}\T\vb{g} > 0); at a corner it need not. See it live in the figure below.

Examples to know by heart

Absolute value. ∂∣⋅∣(x)={sign⁡(x)}\partial\abs{\cdot}(x) = \{\operatorname{sign}(x)\} if x≠0x \neq 0 and [−1,1][-1, 1] if x=0x = 0.

ℓ1\ell_1 norm. It is a sum of independent single-variable functions, and the subdifferential is computed coordinate by coordinate: ∂∥⋅∥1(x)={g:gi=sign⁡(xi) if xi≠0, gi∈[−1,1] if xi=0}\partial\norm{\cdot}_1(\vb{x}) = \{\vb{g} : g_i = \operatorname{sign}(x_i) \text{ if } x_i \neq 0,\ g_i \in [-1, 1] \text{ if } x_i = 0\}. It is a point when all coordinates are nonzero, a segment when one is zero, and a square when x=0\vb{x} = \vb{0} in the plane. In general, it is a product of intervals.

Any norm. The following result unifies the cases you saw when changing norms in the figure.

Proof

If g\vb{g} is a subgradient, ∥y∥≥∥x∥+g⊤(y−x)\norm{\vb{y}} \ge \norm{\vb{x}} + \vb{g}\T(\vb{y} - \vb{x}) for every y\vb{y}. Taking y=0\vb{y} = \vb{0} gives g⊤x≥∥x∥\vb{g}\T\vb{x} \ge \norm{\vb{x}} and taking y=2x\vb{y} = 2\vb{x} gives g⊤x≤∥x∥\vb{g}\T\vb{x} \le \norm{\vb{x}}: thus g⊤x=∥x∥\vb{g}\T\vb{x} = \norm{\vb{x}} and the inequality reduces to ∥y∥≥g⊤y\norm{\vb{y}} \ge \vb{g}\T\vb{y} for every y\vb{y}, which is exactly ∥g∥∗≤1\norm{\vb{g}}_* \le 1. The converse follows by reversing the same chain.

∎

The three norms in the figure are special cases. The dual of ℓ1\ell_1 is ℓ∞\ell_\infty, so ∂∥⋅∥1(0)\partial\norm{\cdot}_1(\vb{0}) is the square [−1,1]2[-1, 1]^2. The dual of ℓ2\ell_2 is ℓ2\ell_2: at the origin the subdifferential is the unit disk (the answer to the first exercise), and away from the origin the unique unit vector x/∥x∥2\vb{x}/\norm{\vb{x}}_2. The dual of ℓ∞\ell_\infty is ℓ1\ell_1: at the origin it is the diamond {∥g∥1≤1}\{\norm{\vb{g}}_1 \le 1\}, and at a point with a single coordinate of maximum absolute value, the vector sign⁡(xi)ei\operatorname{sign}(x_i)\vb{e}_i.

Maximum of affine functions. If f(x)=max⁡i(ai⊤x+bi)f(\vb{x}) = \max_{i} (\vb{a}_i\T\vb{x} + b_i), the subdifferential is the convex hull of the slopes of the active lines, ∂f(x)=conv⁡{ai:i active at x}\partial f(\vb{x}) = \operatorname{conv}\{\vb{a}_i : i \text{ active at } \vb{x}\}. In the figure, for the maximum of three lines with slopes −2-2, 00 and 1.51.5, the subdifferential at x=−1x = -1 is [−2,0][-2, 0] and at x=1x = 1 is [0,1.5][0, 1.5].

Hinge and ReLU. max⁡{0,1−x}\max\{0, 1 - x\} is the maximum of two affine functions, and its subdifferential at the corner x=1x = 1 is [−1,0][-1, 0]. The function ReLU⁡(x)=max⁡{0,x}\relu(x) = \max\{0, x\} has ∂ReLU⁡(0)=[0,1]\partial\relu(0) = [0, 1]. Any value in [0,1][0, 1] is a legitimate subgradient, and automatic differentiation libraries choose one (we return to this in common mistakes).

Indicator of a convex set. If δC(x)=0\delta_C(\vb{x}) = 0 for x∈C\vb{x} \in C and +∞+\infty otherwise, then ∂δC(x)=NC(x)={g:g⊤(y−x)≤0 ∀y∈C}\partial\delta_C(\vb{x}) = N_C(\vb{x}) = \{\vb{g} : \vb{g}\T(\vb{y} - \vb{x}) \le 0\ \forall\vb{y} \in C\} is the normal cone. This connects to the KKT conditions: a constrained problem is an unconstrained problem with a nondifferentiable function.

Relationship with the conjugate

The subdifferential and the convex conjugate f∗(g)=sup⁡x(g⊤x−f(x))f^*(\vb{g}) = \sup_{\vb{x}}(\vb{g}\T\vb{x} - f(\vb{x})) express the same information from two sides.

Proof

(1)   ⟺  \iff (2). g∈∂f(x)\vb{g} \in \partial f(\vb{x}) is equivalent to g⊤y−f(y)≤g⊤x−f(x)\vb{g}\T\vb{y} - f(\vb{y}) \le \vb{g}\T\vb{x} - f(\vb{x}) for every y\vb{y}, that is, f∗(g)≤g⊤x−f(x)f^*(\vb{g}) \le \vb{g}\T\vb{x} - f(\vb{x}). The reverse inequality, f(x)+f∗(g)≥g⊤xf(\vb{x}) + f^*(\vb{g}) \ge \vb{g}\T\vb{x}, always holds (the Fenchel–Young inequality, by the definition of supremum), so this is equivalent to equality. (2)   ⟺  \iff (3). Apply the above to f∗f^* and use f∗∗=ff^{**} = f: x∈∂f∗(g)  ⟺  f∗(g)+f∗∗(x)=g⊤x\vb{x} \in \partial f^*(\vb{g}) \iff f^*(\vb{g}) + f^{**}(\vb{x}) = \vb{g}\T\vb{x}.

∎

In other words, ∂f\partial f and ∂f∗\partial f^* are inverse relations: ∂f∗=(∂f)−1\partial f^* = (\partial f)^{-1}. A useful example: the conjugate of a norm is the indicator of the dual ball, and therefore ∂∥⋅∥(x)=arg max⁡∥g∥∗≤1g⊤x\partial\norm{\cdot}(\vb{x}) = \argmax_{\norm{\vb{g}}_* \le 1}\vb{g}\T\vb{x}. This “argmax of a linear function over a ball” appears whenever a bounded perturbation is solved: a maximizer of g⊤δ\vb{g}\T\vb{\delta} with ∥δ∥∞≤ε\norm{\vb{\delta}}_\infty \le \eps is εsign⁡(g)∈ε ∂∥⋅∥1(g)\eps\operatorname{sign}(\vb{g}) \in \eps\,\partial\norm{\cdot}_1(\vb{g}), the same mechanism used to analyze sign descent and robustness to bounded perturbations.

Subdifferential calculus

Computing a subdifferential by hand from the definition is cumbersome. Subdifferential calculus is the set of rules that builds it piece by piece, just as ordinary calculus builds derivatives, together with the optimality condition 0∈∂f(x⋆)0 \in \partial f(\vb{x}^\star) we will see later. All the following rules apply to convex functions finite on Rn\R^n.

Proof

All proofs follow from the maximum formula: two compact convex sets are equal iff they have the same support function d↦max⁡gg⊤d\vb{d} \mapsto \max_{\vb{g}}\vb{g}\T\vb{d}, and that support function is the directional derivative.

(1) is immediate. (2) The inclusion ⊇\supseteq follows by adding the two subgradient inequalities. For ⊆\subseteq: (f1+f2)′(x;d)=f1′(x;d)+f2′(x;d)=max⁡∂f1g1⊤d+max⁡∂f2g2⊤d(f_1 + f_2)'(\vb{x};\vb{d}) = f_1'(\vb{x};\vb{d}) + f_2'(\vb{x};\vb{d}) = \max_{\partial f_1}\vb{g}_1\T\vb{d} + \max_{\partial f_2}\vb{g}_2\T\vb{d}, the support function of ∂f1(x)+∂f2(x)\partial f_1(\vb{x}) + \partial f_2(\vb{x}), which is compact and convex.

(3) Directly from the definition of directional derivative, (h∘affine)′(x;d)=h′(Ax+b;Ad)=max⁡g∈∂h(Ax+b)g⊤Ad=max⁡g(A⊤g)⊤d(h\circ\text{affine})'(\vb{x};\vb{d}) = h'(\mat{A}\vb{x} + \vb{b};\mat{A}\vb{d}) = \max_{\vb{g} \in \partial h(\mat{A}\vb{x} + \vb{b})}\vb{g}\T\mat{A}\vb{d} = \max_{\vb{g}}(\mat{A}\T\vb{g})\T\vb{d}, the support function of A⊤∂h(Ax+b)\mat{A}\T\partial h(\mat{A}\vb{x} + \vb{b}), which is compact and convex as the linear image of a compact convex set.

(4) For fixed d\vb{d}, only active indices count in the limit: f′(x;d)=max⁡i∈I(x)fi′(x;d)=max⁡i∈Imax⁡g∈∂fig⊤df'(\vb{x};\vb{d}) = \max_{i \in I(\vb{x})} f_i'(\vb{x};\vb{d}) = \max_{i \in I}\max_{\vb{g} \in \partial f_i}\vb{g}\T\vb{d}, which is the support function of the union of the ∂fi(x)\partial f_i(\vb{x}); the support function of a union coincides with that of its convex hull (compact because the finite union of compact sets is compact).

∎

With these rules, real examples can be calculated in one line.

Optimality: 0∈∂f(x⋆)0 \in \partial f(\vb{x}^\star)

The first-order condition ∇f(x⋆)=0\grad f(\vb{x}^\star) = \vb{0} generalizes without changing its form. The proof takes one line.

Proof

0∈∂f(x⋆)\vb{0} \in \partial f(\vb{x}^\star) means f(y)≥f(x⋆)+0⊤(y−x⋆)=f(x⋆)f(\vb{y}) \ge f(\vb{x}^\star) + \vb{0}\T(\vb{y} - \vb{x}^\star) = f(\vb{x}^\star) for every y\vb{y}, the definition of a global minimizer. The equivalence is literal: convexity is not needed for it, although without convexity the subdifferential may be empty even at a local minimum.

∎

Two practical consequences. First: the optimum of a function with corners is typically a point where the subdifferential is large and contains zero, not a point with a small subgradient. Second: there is no “small ∥g∥\norm{\vb{g}}” stopping criterion. For ∣x∣\abs{x}, every subgradient at x≠0x \neq 0 has norm 1, however close to the minimum. What matters is whether zero is in the subdifferential.

With the sum and composition rules, lasso optimality follows in two lines. For F(x)=12∥Ax−b∥22+λ∥x∥1F(\vb{x}) = \frac12\norm{\mat{A}\vb{x} - \vb{b}}_2^2 + \lambda\norm{\vb{x}}_1, the quadratic part is differentiable and

∂F(x)=A⊤(Ax−b)+λ ∂∥x∥1,\partial F(\vb{x}) = \mat{A}\T(\mat{A}\vb{x} - \vb{b}) + \lambda\,\partial\norm{\vb{x}}_1,

so x⋆\vb{x}^\star is optimal iff, with c=A⊤(Ax⋆−b)\vb{c} = \mat{A}\T(\mat{A}\vb{x}^\star - \vb{b}), each coordinate satisfies

ci=−λsign⁡(xi⋆)  if xi⋆≠0,∣ci∣≤λ  if xi⋆=0.c_i = -\lambda\operatorname{sign}(x_i^\star) \ \text{ if } x_i^\star \neq 0, \qquad \abs{c_i} \le \lambda \ \text{ if } x_i^\star = 0.

Read the second condition: a coordinate becomes zero when its column’s correlation with the residual does not exceed λ\lambda. This is the exact mechanism behind sparsity. A direct corollary: x⋆=0\vb{x}^\star = \vb{0} is a solution iff ∥A⊤b∥∞≤λ\norm{\mat{A}\T\vb{b}}_\infty \le \lambda, so λmax⁡=∥A⊤b∥∞\lambda_{\max} = \norm{\mat{A}\T\vb{b}}_\infty is the regularization value above which lasso zeros everything. In the scalar case, min⁡x12(x−a)2+λ∣x∣\min_x\frac12(x - a)^2 + \lambda\abs{x} is solved with 0∈x−a+λ∂∣x∣0 \in x - a + \lambda\partial\abs{x}, giving soft thresholding x⋆=sign⁡(a)max⁡{∣a∣−λ,0}x^\star = \operatorname{sign}(a)\max\{\abs{a} - \lambda, 0\}, the basic building block of the proximal gradient method in the next lesson.

The subgradient method

We have the generalized derivative and the optimality condition. We still need an algorithm. The simplest copies gradient descent, replacing the gradient with any subgradient.

It is not a descent method

The maximum formula tells you when −g-\vb{g} is a descent direction and that it may not be one at a corner. Consider the minimal example, f(x,y)=∣x∣+2∣y∣f(x, y) = \abs{x} + 2\abs{y}, with optimum x⋆=0\vb{x}^\star = \vb{0} and f⋆=0f^\star = 0. At point (3,0)(3, 0) on the horizontal axis the subdifferential is the segment {1}×[−2,2]\{1\} \times [-2, 2]. Choose g=(1,2)\vb{g} = (1, 2) and step with η=0.6\eta = 0.6:

x1=(3,0)−0.6 (1,2)=(2.4,−1.2),f(x1)=2.4+2(1.2)=4.8>3=f(x0).\vb{x}_1 = (3, 0) - 0.6\,(1, 2) = (2.4, -1.2), \qquad f(\vb{x}_1) = 2.4 + 2(1.2) = 4.8 > 3 = f(\vb{x}_0).

The function rises. But distance to the optimum falls: ∥x1∥2=2.42+1.22=7.2<9=∥x0∥2\norm{\vb{x}_1}^2 = 2.4^2 + 1.2^2 = 7.2 < 9 = \norm{\vb{x}_0}^2. The method is improving something, and that something is not ff.

InteractiveA subgradient that increases the function
f = f(xₖ)
k = 0
  • f(xk)/f(x0)f(\vb{x}_k)/f(\vb{x}_0)
  • ∥xk−x⋆∥2/∥x0−x⋆∥2\norm{\vb{x}_k - \vb{x}^\star}^2/\norm{\vb{x}_0 - \vb{x}^\star}^2

The orange curve rises from the first step; blue falls while η\eta stays below the limit. The analysis concerns the blue curve. With a fixed step, the limit shrinks near the optimum and both bounce; with Polyak the blue curve always falls.

  • level set {f≤f(xk)}\{f \le f(\vb{x}_k)\}
  • ball ∥y∥≤∥xk∥\norm{\vb{y}} \le \norm{\vb{x}_k} (distance to optimum)
  • hyperplane gk⊤(y−xk)=0\vb{g}_k\T(\vb{y} - \vb{x}_k) = 0
0.6
1
iteration kk0
xk\vb{x}_k(3, 0)
subgradient gk\vb{g}_k(1, 2)
step ηk\eta_k0.6
f(xk+1)−f(xk)f(\vb{x}_{k+1}) - f(\vb{x}_k)1.8
∥xk+1∥2−∥xk∥2\norm{\vb{x}_{k+1}}^2 - \norm{\vb{x}_k}^2−1.8
limit 2(f−f⋆)/∥gk∥22(f - f^\star)/\norm{\vb{g}_k}^21.2
ff increases by 1.8, but squared distance to the optimum decreases by 1.8: the subgradient is not a descent direction yet the step approaches x⋆\vb{x}^\star.
The orange diamond is the level set {f≤f(xk)}\{f \le f(\vb{x}_k)\}; the dashed blue circle is the ball centered at the optimum passing through xk\vb{x}_k; the gray line is the hyperplane perpendicular to the subgradient. The light blue strip contains possible destinations xk−η g\vb{x}_k - \eta\,\vb{g} with g∈∂f(xk)\vb{g} \in \partial f(\vb{x}_k) (a segment with fixed step, an arc with Polyak): drag its point to choose a subgradient g=(1,2t)\vb{g} = (1, 2t). With t=1t = 1 the step lands outside the diamond (the function rises) and inside the circle (distance falls). Play the iterations and compare the curves: orange, f(xk)f(\vb{x}_k), rises from the first step; blue, squared distance, falls while the step stays below the readout's limit, and with fixed step eventually bounces near the optimum, where that limit shrinks. Try ∣t∣<1/4\abs{t} < 1/4 (the step does decrease ff), a large η\eta (the step no longer moves closer), and the Polyak step (distance always decreases).

The figure answers in two ways, one algebraic and one geometric. Geometrically: the hyperplane {y:g⊤(y−x)=0}\{\vb{y} : \vb{g}\T(\vb{y} - \vb{x}) = 0\} leaves the entire level set {f≤f(x)}\{f \le f(\vb{x})\}, including the optimum, on one side, because for y\vb{y} in it g⊤(y−x)≤f(y)−f(x)≤0\vb{g}\T(\vb{y} - \vb{x}) \le f(\vb{y}) - f(\vb{x}) \le 0. Moving in direction −g-\vb{g} approaches every point in that half-space if the step is short enough, although not necessarily points “lower” than x\vb{x} along the direction. Algebraically, calculating distance gives the lemma underlying the whole analysis.

Proof

Expand the square: ∥xk+1−x⋆∥2=∥xk−x⋆∥2−2ηkgk⊤(xk−x⋆)+ηk2∥gk∥2\norm{\vb{x}_{k+1} - \vb{x}^\star}^2 = \norm{\vb{x}_k - \vb{x}^\star}^2 - 2\eta_k\vb{g}_k\T(\vb{x}_k - \vb{x}^\star) + \eta_k^2\norm{\vb{g}_k}^2. By the subgradient definition with y=x⋆\vb{y} = \vb{x}^\star, f⋆≥f(xk)+gk⊤(x⋆−xk)f^\star \ge f(\vb{x}_k) + \vb{g}_k\T(\vb{x}^\star - \vb{x}_k), i.e. gk⊤(xk−x⋆)≥f(xk)−f⋆\vb{g}_k\T(\vb{x}_k - \vb{x}^\star) \ge f(\vb{x}_k) - f^\star. Substitute.

∎

Read the lemma as a balance between two terms. The negative one, −2ηk(f(xk)−f⋆)-2\eta_k(f(\vb{x}_k) - f^\star), is progress: the worse xk\vb{x}_k is, the more it moves closer. The positive one, ηk2∥gk∥2\eta_k^2\norm{\vb{g}_k}^2, is finite-step noise: it grows with the square of the step and does not depend on proximity. As long as progress wins, distance falls and the method advances, even if ff rises. It also reveals the step limit for getting closer: distance falls if ηk<2(f(xk)−f⋆)/∥gk∥2\eta_k < 2(f(\vb{x}_k) - f^\star)/\norm{\vb{g}_k}^2. With f(x0)=3f(\vb{x}_0) = 3, f⋆=0f^\star = 0 and ∥g∥2=5\norm{\vb{g}}^2 = 5 in the example, that limit is 1.21.2, as shown in the figure’s readout. Distance to the optimum, not the value of ff, is the method’s Lyapunov function.

The O(1/k)\bigO(1/\sqrt{k}) bound

Summing the lemma from i=0i = 0 to kk telescopes the ∥xi−x⋆∥2\norm{\vb{x}_{i} - \vb{x}^\star}^2 term.

Proof

Apply the lemma for i=0,…,ki = 0, \dots, k and sum; the left-hand side telescopes:

0≤∥xk+1−x⋆∥2≤R2−2∑i=0kηi(f(xi)−f⋆)+∑i=0kηi2∥gi∥2.0 \le \norm{\vb{x}_{k+1} - \vb{x}^\star}^2 \le R^2 - 2\sum_{i=0}^{k}\eta_i\big(f(\vb{x}_i) - f^\star\big) + \sum_{i=0}^{k}\eta_i^2\norm{\vb{g}_i}^2.

Rearranging, 2∑iηi(f(xi)−f⋆)≤R2+G2∑iηi22\sum_i\eta_i(f(\vb{x}_i) - f^\star) \le R^2 + G^2\sum_i\eta_i^2. The left side is at least 2(∑iηi)(min⁡if(xi)−f⋆)2\big(\sum_i\eta_i\big)\big(\min_i f(\vb{x}_i) - f^\star\big), because every f(xi)−f⋆≥min⁡if(xi)−f⋆f(\vb{x}_i) - f^\star \ge \min_i f(\vb{x}_i) - f^\star and steps are positive. Divide by 2∑iηi2\sum_i\eta_i to obtain the bound. For the average: convexity of ff (Jensen’s inequality) gives f(xˉk)−f⋆≤∑iηi(f(xi)−f⋆)/∑iηif(\bar{\vb{x}}_k) - f^\star \le \sum_i\eta_i(f(\vb{x}_i) - f^\star)/\sum_i\eta_i, which the same inequality bounds by the same ratio.

∎

Each step rule now follows directly from this result.

  • Constant step η\eta. The bound is R22η(k+1)+G2η2\dfrac{R^2}{2\eta(k+1)} + \dfrac{G^2\eta}{2}. The first term tends to zero; the second is a floor: the method guarantees reaching an error proportional to η\eta, and does not improve beyond that (as in the figure below). For fixed horizon N=k+1N = k + 1, the best η\eta equalizes the terms: η=R/(GN)\eta = R/(G\sqrt{N}), giving bound RGN\dfrac{RG}{\sqrt{N}}.
  • Decreasing step c/i+1c/\sqrt{i+1}. Since ∑ηi∼2ck\sum\eta_i \sim 2c\sqrt{k} and ∑ηi2∼c2ln⁡k\sum\eta_i^2 \sim c^2\ln k, the bound is O(ln⁡k/k)\bigO(\ln k/\sqrt{k}): it converges without knowing the horizon, at the cost of a logarithmic factor.
  • Square-summable but nonsummable step c/(i+1)c/(i+1). Here ∑ηi2<∞\sum\eta_i^2 < \infty and ∑ηi=∞\sum\eta_i = \infty, so the bound tends to zero… but since ∑ηi∼cln⁡k\sum\eta_i \sim c\ln k, the guarantee improves only logarithmically. This classic convergence-proof rule is often very slow or very sensitive to cc in practice.

The Polyak step

The lemma suggests choosing the step without looking at the horizon: minimize its right side, a quadratic polynomial, in ηk\eta_k.

With it, the lemma becomes ∥xk+1−x⋆∥2≤∥xk−x⋆∥2−(f(xk)−f⋆)2∥gk∥2\norm{\vb{x}_{k+1} - \vb{x}^\star}^2 \le \norm{\vb{x}_k - \vb{x}^\star}^2 - \dfrac{(f(\vb{x}_k) - f^\star)^2}{\norm{\vb{g}_k}^2}: distance to the optimum never increases (the sequence is Fejér monotone), and summing, ∑i(f(xi)−f⋆)2≤G2R2\sum_i(f(\vb{x}_i) - f^\star)^2 \le G^2R^2, whence min⁡i≤kf(xi)−f⋆≤GR/k+1\min_{i \le k}f(\vb{x}_i) - f^\star \le GR/\sqrt{k+1}: the same rate as the best constant step, without choosing any constant or knowing RR. In the figure’s example, the initial step is exactly η0=3/5=0.6\eta_0 = 3/5 = 0.6, the one we used.

A bonus explains why the method works so well in ℓ1\ell_1 regression. If the minimum is sharp, i.e. f(x)−f⋆≥α∥x−x⋆∥f(\vb{x}) - f^\star \ge \alpha\norm{\vb{x} - \vb{x}^\star} for some α>0\alpha > 0 (as in ∣x∣\abs{x}, ∥x∥1\norm{\vb{x}}_1 and every polyhedral function with its minimum at a vertex), then f(xk)−f⋆≥α∥xk−x⋆∥f(\vb{x}_k) - f^\star \ge \alpha\norm{\vb{x}_k - \vb{x}^\star} and the Polyak step gives

∥xk+1−x⋆∥2≤(1−α2G2)∥xk−x⋆∥2,\norm{\vb{x}_{k+1} - \vb{x}^\star}^2 \le \Big(1 - \frac{\alpha^2}{G^2}\Big)\norm{\vb{x}_k - \vb{x}^\star}^2,

linear convergence for a nonsmooth function. The rate O(1/k)\bigO(1/\sqrt{k}) is worst-case, and sharp minima are far from that case.

The price is knowing f⋆f^\star. In some problems it is known: f⋆=0f^\star = 0 when seeking a point in an intersection of convex sets with f(x)=max⁡idist⁡(x,Ci)f(\vb{x}) = \max_i\operatorname{dist}(\vb{x}, C_i), or in models interpolating the data. Otherwise an estimate f^⋆\hat f^\star is used, and the next figure shows what happens if it is wrong: with f^⋆<f⋆\hat f^\star < f^\star steps are too long and the method oscillates without converging; with f^⋆>f⋆\hat f^\star > f^\star the step, truncated at zero, vanishes when f(xk)≤f^⋆f(\vb{x}_k) \le \hat f^\star and the method stops short.

InteractiveStep-rule race
startoptimum

Each point (a,b)(a, b) represents a line y=ax+by = a x + b. The contours of ff are nearly polygonal and the minimum is a vertex.

  • constant step η\eta
  • c/k+1c/\sqrt{k+1}
  • c/(k+1)c/(k+1)
  • Polyak
  • worst-case bound RG/kRG/\sqrt{k}
104
Step constants
1
1
2
1
Display
f⋆f^\star (exact optimum)0.7122
best error, constante0.00309
best error, c/k+1c/\sqrt{k+1}3.14e-6
best error, c/(k+1)c/(k+1)6.60e-7
best error, Polyak< 10⁻⁹
bound RG/kRG/\sqrt{k} with R=3.76R = 3.76, G=1.45G = 1.450.534
The constant step stalls: the best value stops improving at a level that grows with η\eta (here η=1\eta = 1). Con η\eta a smaller value decreases further but takes longer to get there.
ℓ1\ell_1 regression on 200 points with 40 outliers: each point (a,b)(a, b) in the left plane is a line, and the level sets of ff are nearly polygonal (200 faces) with the minimum at a vertex. Four rules start at the same point. On the right, the best value found minus f⋆f^\star on log-log axes, and worst-case bound RG/kRG/\sqrt{k}. The constant step soon levels off at a value depending on η\eta (well below the bound's worst-case floor G2η/2G^2\eta/2): reduce it and the level falls, but takes longer to reach. Reduce the scale of c/(k+1)c/(k+1) and see that it barely moves; misestimate f⋆f^\star in Polyak below and above 1 and observe how it stalls. Switch to “current value” to see that f(xk)f(\vb{x}_k) does oscillate.

Lower bound: why 1/k1/\sqrt{k} cannot be improved

Is O(1/k)\bigO(1/\sqrt{k}) an artifact of the analysis, or can no first-order method do better on this class? It is a property of the class, proved with a “worst-case” function that resists any method using only subgradients. It is the nonsmooth counterpart of the complexity lower bounds seen for smooth functions.

Proof

Let f(x)=γmax⁡1≤i≤Nxi+μ2∥x∥2f(\vb{x}) = \gamma\max_{1 \le i \le N}x_i + \frac\mu2\norm{\vb{x}}^2, with γ=GN/(1+N)\gamma = G\sqrt{N}/(1 + \sqrt{N}) and μ=G/(R(1+N))\mu = G/\big(R(1 + \sqrt{N})\big). Its subdifferential at x\vb{x} is γconv⁡{ei:i active}+μx\gamma\operatorname{conv}\{\vb{e}_i : i \text{ active}\} + \mu\vb{x}.

The optimum. Let x⋆=−γμN1\vb{x}^\star = -\frac{\gamma}{\mu N}\vb{1}. All NN indices are active and the combination 1N∑iγei+μx⋆=γN1−γN1=0\frac1N\sum_i\gamma\vb{e}_i + \mu\vb{x}^\star = \frac\gamma N\vb{1} - \frac\gamma N\vb{1} = \vb{0} belongs to the subdifferential: 0∈∂f(x⋆)\vb{0} \in \partial f(\vb{x}^\star) and, by optimality, x⋆\vb{x}^\star is a minimizer. Its norm is γ/(μN)=R\gamma/(\mu\sqrt{N}) = R and f⋆=−γ2/(2μN)f^\star = -\gamma^2/(2\mu N). On the ball B(0,R)B(\vb{0}, R), every subgradient satisfies ∥g∥≤γ+μR=G\norm{\vb{g}} \le \gamma + \mu R = G.

The resisting oracle. Ask the oracle to return, at each point, the subgradient with the first active index, g=γei+μx\vb{g} = \gamma\vb{e}_i + \mu\vb{x}. By induction, xj∈span⁡{e1,…,ej}\vb{x}_j \in \spn\{\vb{e}_1, \dots, \vb{e}_j\}: if x\vb{x} has support in the first j<Nj < N coordinates, coordinates j+1,…,Nj+1, \dots, N are zero, the maximum is ≥0\ge 0 and the first active index is ≤j+1\le j + 1, so g∈span⁡{e1,…,ej+1}\vb{g} \in \spn\{\vb{e}_1, \dots, \vb{e}_{j+1}\}.

The value. Thus, for p≤N−1p \le N - 1 the last coordinate of xp\vb{x}_p is zero, max⁡ixi≥0\max_i x_i \ge 0 and f(xp)≥μ2∥xp∥2≥0f(\vb{x}_p) \ge \frac\mu2\norm{\vb{x}_p}^2 \ge 0. Hence f(xp)−f⋆≥−f⋆=γ2/(2μN)=GR/(2(1+N))f(\vb{x}_p) - f^\star \ge -f^\star = \gamma^2/(2\mu N) = GR/(2(1 + \sqrt{N})).

∎

Notice the final step: for this function none of the first N−1N - 1 iterates improves the starting point, f(x0)=0f(\vb{x}_0) = 0. The method can take a thousand reasonable-looking steps without progress, because each subgradient reveals only one new coordinate. You will check this numerically below.

Two important qualifications. The bound requires dimension n≥Nn \ge N: it concerns large-scale problems. In fixed dimension there are methods (cutting planes, center of gravity) with rate e−ck/ne^{-ck/n}, irrelevant at the scale of millions of parameters. It is a bound for the entire class: functions with structure, such as “smooth plus ℓ1\ell_1”, are outside that class, and the proximal methods in the next lesson achieve rates O(1/k)\bigO(1/k) and, when accelerated, O(1/k2)\bigO(1/k^2), exploiting knowledge of the smooth part.

Implementation from scratch

First, the defining property: check by sampling that a vector is a subgradient, without knowing the subdifferential. This is the test you should apply to any subgradient you program.

[ ]Check a subgradient by samplingBrowser
import numpy as np

rng = np.random.default_rng(0)

def es_subgradiente(f, x, g, n=4000, escala=3.0, tol=1e-9):
    """Comprueba f(y) >= f(x) + g.(y-x) en n puntos y aleatorios alrededor de x."""
    Y = x + escala * rng.normal(size=(n, len(x)))
    lado_izq = np.array([f(y) for y in Y])
    lado_der = f(x) + (Y - x) @ g
    return bool(np.all(lado_izq >= lado_der - tol)), float(np.min(lado_izq - lado_der))

relu = lambda x: max(0.0, x[0])
norma2 = lambda x: np.linalg.norm(x)
norma1 = lambda x: np.abs(x).sum()

print("ReLU en 0 (el subdiferencial es [0, 1]):")
for g in (-0.1, 0.0, 0.5, 1.0, 1.1):
    ok, margen = es_subgradiente(relu, np.array([0.0]), np.array([g]))
    print(f"  g = {g:5.2f}  ->  {'subgradiente' if ok else 'NO lo es':13s} (peor margen {margen:+.3f})")

print("||x||_2 en el origen (el subdiferencial es la bola unidad):")
for g in ([0.0, 0.0], [0.6, 0.8], [0.8, 0.8], [1.0, 0.0], [1.2, 0.0]):
    ok, margen = es_subgradiente(norma2, np.zeros(2), np.array(g))
    print(f"  g = {str(g):12s} |g| = {np.linalg.norm(g):.3f}  ->  {'sí' if ok else 'no'}")

print("||x||_1 en (0, 2) (el subdiferencial es [-1, 1] x {1}):")
for g in ([0.0, 1.0], [0.7, 1.0], [1.0, 1.0], [0.0, 0.9], [1.1, 1.0]):
    ok, margen = es_subgradiente(norma1, np.array([0.0, 2.0]), np.array(g))
    print(f"  g = {str(g):12s} ->  {'sí' if ok else 'no'}")

The boundary of the subdifferential sets the limits: g=1.0g = 1.0 is valid and g=1.1g = 1.1 is not; ∥g∥2=1\norm{\vb{g}}_2 = 1 is valid and 1.131.13 is not. Now the ℓ1\ell_1 regression problem, with an exact reference. ℓ1\ell_1 regression is a linear problem: introduce a variable ti≥∣ri∣t_i \ge \abs{r_i} per data point and solve min⁡1m∑ti\min \frac1m\sum t_i with −ti≤ri≤ti-t_i \le r_i \le t_i, an LP solved by scipy.optimize.linprog. It gives f⋆f^\star to measure each step rule’s error and x⋆\vb{x}^\star to calculate RR.

[ ]ℓ1 regression: problem and exact LP solutionBrowser
from scipy.optimize import linprog

rng = np.random.default_rng(0)
m = 200
x = rng.uniform(-2, 2, m)
y = 0.8 * x + 0.5 + 0.18 * rng.normal(size=m)
atip = rng.choice(m, 40, replace=False)
y[atip] += rng.uniform(2, 4, 40)                  # 40 atípicos, todos hacia arriba
X = np.column_stack([x, np.ones(m)])              # w = (pendiente, ordenada)

def f(w):
    return np.mean(np.abs(X @ w - y))

def subgrad(w):
    return X.T @ np.sign(X @ w - y) / m           # un subgradiente (sign(0) = 0 es válido)

# LP: min (1/m) sum t   s.t.  -t <= Xw - y <= t
c = np.r_[np.zeros(2), np.ones(m) / m]
A_ub = np.block([[X, -np.eye(m)], [-X, -np.eye(m)]])
b_ub = np.r_[y, -y]
lp = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=[(None, None)] * 2 + [(0, None)] * m, method="highs")
w_star, f_star = lp.x[:2], lp.fun

G = np.mean(np.linalg.norm(X, axis=1))            # cota de Lipschitz: ||g|| <= media de ||(x_i, 1)||
w0 = np.array([-1.6, -2.4])
R = np.linalg.norm(w0 - w_star)
w_mco = np.linalg.lstsq(X, y, rcond=None)[0]
print(f"LP:   w* = {np.round(w_star, 4)}, f* = {f_star:.5f}   (verdad: pendiente 0.8, ordenada 0.5)")
print(f"MCO:  w  = {np.round(w_mco, 4)}   (los atípicos tiran de la ordenada; la mediana apenas se mueve)")
print(f"R = {R:.3f},  G = {G:.3f},  f(w0) - f* = {f(w0) - f_star:.3f}")

With the problem and reference in place, the method. A single function takes the step rule as an argument and returns the best value up to each iteration as well as the current value: see the lack of descent with your own eyes.

[ ]The subgradient method and four step rulesBrowser
def metodo_subgradiente(f, subgrad, w0, paso, K):
    """w_{k+1} = w_k - eta_k g_k. `paso(k, fk, gk)` devuelve eta_k. Devuelve (mejor hasta k, valor actual)."""
    w = np.array(w0, float)
    mejor, actual, m_ = np.empty(K), np.empty(K), np.inf
    for k in range(K):
        fk, gk = f(w), subgrad(w)
        actual[k], m_ = fk, min(m_, fk)
        mejor[k] = m_
        w = w - paso(k, fk, gk) * gk
    return mejor, actual

reglas = {
    "constante 2.0":      lambda k, fk, gk: 2.0,
    "1/sqrt(k+1)":        lambda k, fk, gk: 1.0 / np.sqrt(k + 1),
    "2/(k+1)":            lambda k, fk, gk: 2.0 / (k + 1),
    "Polyak (f* exacta)": lambda k, fk, gk: (fk - f_star) / (gk @ gk) if gk @ gk > 0 else 0.0,
}
K, marcas = 3000, (10, 100, 1000, 3000)
print(f"{'error del mejor iterado':24s}" + "".join(f"{'k=' + str(k):>11s}" for k in marcas))
corridas = {}
for nombre, regla in reglas.items():
    mejor, actual = metodo_subgradiente(f, subgrad, w0, regla, K)
    corridas[nombre] = (mejor, actual)
    print(f"{nombre:24s}" + "".join(f"{max(mejor[k - 1] - f_star, 0.0):11.2e}" for k in marcas))
print(f"{'cota R G / sqrt(k)':24s}" + "".join(f"{R * G / np.sqrt(k):11.2e}" for k in marcas))

mejor, actual = corridas["constante 2.0"]
sube = int(np.sum(np.diff(actual) > 0))
print(f"\nCon paso constante, f(x_k) sube en {sube} de {K - 1} pasos; el mejor error se estanca en {mejor[-1] - f_star:.1e} "
      f"y el error actual sigue oscilando hasta {np.max(actual[-300:] - f_star):.2f}")

Three readings of this table. The constant step stalls (the bound’s floor); decreasing steps and Polyak reduce the error by several orders of magnitude; and all rows are well below the worst-case bound because this problem has a sharp minimum. Note also that 2/(k+1)2/(k+1) beats 1/k+11/\sqrt{k+1} here despite a worse guarantee: with c=2c = 2 the sum of steps reaches the distance to the optimum in a few iterations and, near a sharp vertex, rapidly shrinking steps are just what is needed. With cc ten times smaller it would not reach it (see the figure). Now the complete theoretical result: the bound with arbitrary steps, not just RG/kRG/\sqrt{k}.

[ ]Check the bound (R² + G² Σ η²) / (2 Σ η)Browser
for nombre in ("constante 2.0", "1/sqrt(k+1)", "2/(k+1)"):
    regla = reglas[nombre]
    mejor, _ = corridas[nombre]
    etas = np.array([regla(k, 0.0, 0.0) for k in range(K)])
    peor = 0.0
    for k in (1, 10, 100, 1000, 3000):
        cota = (R**2 + G**2 * np.sum(etas[:k] ** 2)) / (2 * np.sum(etas[:k]))
        gap = mejor[k - 1] - f_star
        assert gap <= cota, (nombre, k, gap, cota)
        peor = max(peor, gap / cota)
    print(f"{nombre:16s} la cota se cumple en todos los k; el mayor cociente gap/cota es {peor:.2f}")

Now the lower bound in action. We construct the theorem’s Nesterov function with N=100N = 100, R=G=1R = G = 1, and minimize it with three step rules, including Polyak with exact f⋆f^\star.

[ ]The worst-case function: no progress before N stepsBrowser
def instancia_peor_caso(N, R, G):
    """f(x) = gamma * max_i x_i + (mu/2)||x||^2 en R^N (Nesterov, 2018, teorema 3.2.1)."""
    gamma = G * np.sqrt(N) / (1 + np.sqrt(N))
    mu = G / (R * (1 + np.sqrt(N)))
    f = lambda x: gamma * x.max() + 0.5 * mu * x @ x
    def subgrad(x):
        g = mu * x
        g[np.argmax(x)] += gamma                  # argmax devuelve el primer índice activo
        return g
    return f, subgrad, -gamma**2 / (2 * mu * N), np.full(N, -gamma / (mu * N))

R_, G_, N = 1.0, 1.0, 100
fw, sw, fw_star, xw_star = instancia_peor_caso(N, R_, G_)
cota_inf = G_ * R_ / (2 * (1 + np.sqrt(N)))
print(f"f* = {fw_star:.4f},  ||x*|| = {np.linalg.norm(xw_star):.3f},  f(x0) = {fw(np.zeros(N)):.1f},  cota inferior = {cota_inf:.4f}")
pasos = (N // 2, N - 1, N, 2 * N, 10 * N)
print(f"{'error del mejor iterado':26s}" + "".join(f"{'k=' + str(k):>10s}" for k in pasos))
reglas_w = {
    "constante R/(G sqrt(N))": lambda i, fi, gi: R_ / (G_ * np.sqrt(N)),
    "1/sqrt(i+1)":             lambda i, fi, gi: 1.0 / np.sqrt(i + 1),
    "Polyak (f* exacta)":      lambda i, fi, gi: (fi - fw_star) / (gi @ gi),
}
for nombre, regla in reglas_w.items():
    xk, mejor_v, fila = np.zeros(N), np.inf, []
    for i in range(max(pasos) + 1):
        fi, gi = fw(xk), sw(xk)
        mejor_v = min(mejor_v, fi)
        if i in pasos:
            fila.append(mejor_v - fw_star)
        xk = xk - regla(i, fi, gi) * gi
    assert all(v >= cota_inf - 1e-12 for v in fila[:2])
    print(f"{nombre:26s}" + "".join(f"{v:10.4f}" for v in fila))

Through k=N−1=99k = N - 1 = 99 all three rules, including Polyak with the exact optimum, leave the error at 0.0455=−f⋆0.0455 = -f^\star, exactly the lower bound: the best value seen is still f(x0)=0f(\vb{x}_0) = 0. Only from k=Nk = N onward is there progress. Now the primal linear SVM: the vectorized subgradient, and training with decreasing steps and iterate averaging.

[ ]Primal linear SVM with subgradientsBrowser
rng = np.random.default_rng(3)
n, d = 400, 5
ys = np.where(rng.random(n) < 0.5, -1.0, 1.0)
mu_c = np.array([1.0, 0.8, 0.0, 0.0, 0.0])
Xs = rng.normal(size=(n, d)) + 0.9 * ys[:, None] * mu_c
lam = 0.02

def F(w):
    return 0.5 * lam * w @ w + np.mean(np.maximum(0.0, 1.0 - ys * (Xs @ w)))

def hinge_subgradient(w, X, y, lam):
    """Un subgradiente de F(w) = lam/2 |w|^2 + media(max(0, 1 - y x.w)), sin bucles."""
    activo = y * (X @ w) < 1                      # margen < 1; con margen = 1 se elige 0 (también válido)
    return lam * w - (y[activo, None] * X[activo]).sum(axis=0) / len(y)

def entrenar_svm(X, y, lam, K, eta0=0.5):
    w, w_prom, S = np.zeros(X.shape[1]), np.zeros(X.shape[1]), 0.0
    for k in range(K):
        eta = eta0 / np.sqrt(k + 1)               # paso decreciente
        w_prom += eta * w                         # promedio ponderado de iterados (el teorema)
        S += eta
        w = w - eta * hinge_subgradient(w, X, y, lam)
    return w, w_prom / S

w_ult, w_prom = entrenar_svm(Xs, ys, lam, 3000)
print(f"F(0) = {F(np.zeros(d)):.4f}   F(último iterado) = {F(w_ult):.4f}   F(promedio) = {F(w_prom):.4f}")
print(f"exactitud (promedio): {np.mean(np.sign(Xs @ w_prom) == ys):.3f}")

The library version

In practice no one programs the subgradient method for a structured problem: ℓ1\ell_1 regression is an LP (or quantile regression) and SVMs have specialized solvers. Nevertheless it is useful to compare our implementation with scikit-learn. QuantileRegressor with quantile=0.5 solves ℓ1\ell_1 regression exactly via an LP, and LinearSVC(loss="hinge") minimizes 12∥w∥2+C∑imax⁡{0,1−yiw⊤xi}\frac12\norm{\vb{w}}^2 + C\sum_i\max\{0, 1 - y_i\vb{w}\T\vb{x}_i\}, which matches our FF for C=1/(nλ)C = 1/(n\lambda).

[ ]Against scikit-learnBrowser
from sklearn.linear_model import QuantileRegressor
from sklearn.svm import LinearSVC

qr = QuantileRegressor(quantile=0.5, alpha=0.0, fit_intercept=False, solver="highs").fit(X, y)
print(f"regresión l1:  QuantileRegressor f = {f(qr.coef_):.5f}   LP propio f* = {f_star:.5f}   "
      f"|w - w*| = {np.linalg.norm(qr.coef_ - w_star):.1e}")

svc = LinearSVC(loss="hinge", C=1 / (n * lam), fit_intercept=False, max_iter=200000, tol=1e-10).fit(Xs, ys)
F_svc = F(svc.coef_.ravel())
print(f"SVM primal:    LinearSVC F = {F_svc:.5f}   subgradiente (promedio) F = {F(w_prom):.5f}   "
      f"diferencia = {F(w_prom) - F_svc:.1e}")

Regression matches our LP exactly (it is the same problem) and the SVM matches the iterate average with an FF difference of about five ten-thousandths. What changes is cost: the LP and LinearSVC duality exploit structure and reach machine precision; the subgradient method is the tool when the problem is too large for a specialized solver, as in online learning or with millions of examples. Then the gradient is estimated with a minibatch (SGD), adding noise but not changing the form of the bound (which now holds in expectation, with G2G^2 bounding the estimated subgradient’s second moment), and iterate averaging restores stability.

Common mistakes

Exercises

QuizThe subdifferential of the Euclidean norm
Let f(x)=∥x∥2f(\vb{x}) = \norm{\vb{x}}_2 on Rn\R^n with n≥2n \ge 2. What is ∂f(0)\partial f(\vb{0})?
QuizWhat does autograd return at the corner?
An automatic differentiation library returns 00 as the derivative of ReLU⁡\relu at x=0x = 0. Which statements are true?

More than one answer may be correct.

NumericA subdifferential with affine composition
Let f(x1,x2)=∣x1∣+2∣x2−x1∣f(x_1, x_2) = \abs{x_1} + 2\abs{x_2 - x_1}. Among all subgradients g∈∂f(0)\vb{g} \in \partial f(\vb{0}), what is the largest possible value of the first component g1g_1?
NumericThe threshold above which lasso zeros everything
For F(x)=12∥Ax−b∥22+λ∥x∥1F(\vb{x}) = \frac12\norm{\mat{A}\vb{x} - \vb{b}}_2^2 + \lambda\norm{\vb{x}}_1 with A=[2100131−11]\mat{A} = \begin{bmatrix} 2 & 1 & 0 \\ 0 & 1 & 3 \\ 1 & -1 & 1 \end{bmatrix} and b=(1,2,−1)⊤\vb{b} = (1, 2, -1)\T, calculate the smallest λ\lambda for which x=0\vb{x} = \vb{0} is a solution.
NumericA Polyak step that increases f
For f(x,y)=∣x∣+2∣y∣f(x, y) = \abs{x} + 2\abs{y} at (3,0)(3, 0), choose subgradient g=(1,2)\vb{g} = (1, 2) and a Polyak step with f⋆=0f^\star = 0. What is ff at the new iterate?
NumericHow many iterations does the bound guarantee?
With R=1R = 1 and G=1G = 1, using the optimal constant step for NN iterations, η=R/(GN)\eta = R/(G\sqrt{N}), the guaranteed error is RG/NRG/\sqrt{N}. How many iterations NN are needed to guarantee error at most 0.010.01?
NumericThe constant-step floor
With constant step η=0.1\eta = 0.1 and G=3G = 3, the method's bound is R2/(2ηN)+G2η/2R^2/(2\eta N) + G^2\eta/2. What value does it approach as N→∞N \to \infty?
QuizPolyak with a poorly estimated f*
You apply the Polyak step with an estimate f^⋆\hat f^\star of the optimal value, ηk=max⁡{f(xk)−f^⋆, 0}/∥gk∥2\eta_k = \max\{f(\vb{x}_k) - \hat f^\star,\, 0\}/\norm{\vb{g}_k}^2, to a convex function with a sharp minimum. What happens?
QuizWhat not to expect from the method
You run the subgradient method on f(x)=∥Ax−b∥1f(\vb{x}) = \norm{\mat{A}\vb{x} - \vb{b}}_1 with step ηk=c/k+1\eta_k = c/\sqrt{k+1}. Which statements are true?

More than one answer may be correct.

ProofMinimizer iff 0 belongs to the subdifferential
Prove: Let f:Rn→R∪{+∞}f : \R^n \to \R \cup \{+\infty\} be convex and x⋆∈dom⁡f\vb{x}^\star \in \dom f. Then x⋆\vb{x}^\star minimizes ff iff 0∈∂f(x⋆)\vb{0} \in \partial f(\vb{x}^\star).
0
Start from the definition of subgradient: g∈∂f(x)\vb{g} \in \partial f(\vb{x}) if f(y)≥f(x)+g⊤(y−x)f(\vb{y}) \ge f(\vb{x}) + \vb{g}\T(\vb{y} - \vb{x}) for all y\vb{y}.

Step 1 of 3. Assume 0∈∂f(x⋆)\vb{0} \in \partial f(\vb{x}^\star). What do you write?

ProofThe subgradient method bound
Prove: Let ff be convex with minimizer x⋆\vb{x}^\star, R=∥x0−x⋆∥R = \norm{\vb{x}_0 - \vb{x}^\star} and ∥gi∥≤G\norm{\vb{g}_i} \le G. For xi+1=xi−ηigi\vb{x}_{i+1} = \vb{x}_i - \eta_i\vb{g}_i with gi∈∂f(xi)\vb{g}_i \in \partial f(\vb{x}_i), we have min⁡0≤i≤kf(xi)−f⋆≤R2+G2∑i=0kηi22∑i=0kηi\displaystyle\min_{0 \le i \le k}f(\vb{x}_i) - f^\star \le \frac{R^2 + G^2\sum_{i=0}^{k}\eta_i^2}{2\sum_{i=0}^{k}\eta_i}.
0
Expand distance to the optimum after one step and use the subgradient definition with y=x⋆\vb{y} = \vb{x}^\star.

Step 1 of 4. How do you express ∥xi+1−x⋆∥2\norm{\vb{x}_{i+1} - \vb{x}^\star}^2?

CodeLinear SVM with subgradients
Implement hinge_subgradient(w, X, y, lam) (vectorized, without loops over examples), returning a subgradient of F(w)=λ2∥w∥2+1n∑imax⁡{0, 1−yiw⊤xi}F(\vb{w}) = \frac\lambda2\norm{\vb{w}}^2 + \frac1n\sum_i\max\{0,\ 1 - y_i\vb{w}\T\vb{x}_i\}, and train_svm(X, y, lam, K), which runs KK steps of the method with ηk=0.5/k+1\eta_k = 0.5/\sqrt{k+1} and returns the weighted average of iterates ∑kηkwk/∑kηk\sum_k\eta_k\vb{w}_k/\sum_k\eta_k (with w0=0\vb{w}_0 = \vb{0}). Labels are ±1\pm 1.
import numpy as np

def hinge_subgradient(w, X, y, lam):
  """Un subgradiente de F(w) = lam/2 |w|^2 + media(max(0, 1 - y_i w.x_i)). Sin bucles."""
  # tu código
  return np.zeros_like(w)

def train_svm(X, y, lam, K):
  """K pasos con eta_k = 0.5/sqrt(k+1); devuelve el promedio ponderado de los iterados w_0, ..., w_{K-1}."""
  w = np.zeros(X.shape[1])
  # tu código
  return w
Shift+Enter to run

Summary

Key idea
A subgradient is the slope of a hyperplane touching the function and leaving it above; at a corner there is an entire fan of them, the subdifferential. With it, 0∈∂f(x⋆)0 \in \partial f(\vb{x}^\star) characterizes the optimum, and the subgradient method advances by distance to the optimum, not descent of ff: it converges at O(1/k)\bigO(1/\sqrt{k}) for the best iterate, and this rate cannot be improved in the Lipschitz class.
  • ∂f(x)={g:f(y)≥f(x)+g⊤(y−x) ∀y}\partial f(\vb{x}) = \{\vb{g} : f(\vb{y}) \ge f(\vb{x}) + \vb{g}\T(\vb{y} - \vb{x})\ \forall\vb{y}\} is convex, compact and nonempty in the interior of the domain; if ff is differentiable, it is the gradient. The directional derivative is f′(x;d)=max⁡g∈∂f(x)g⊤df'(\vb{x};\vb{d}) = \max_{\vb{g} \in \partial f(\vb{x})}\vb{g}\T\vb{d}.
  • It is calculated by rules: sum and affine composition, and the maximum is the convex hull of active subdifferentials. ∂∥⋅∥\partial\norm{\cdot} is the face of the dual ball where g⊤x=∥x∥\vb{g}\T\vb{x} = \norm{\vb{x}}, and that of the indicator of a convex set is its normal cone.
  • Optimality: 0∈∂f(x⋆)0 \in \partial f(\vb{x}^\star). For lasso: ∣ci∣≤λ\abs{c_i} \le \lambda where xi⋆=0x_i^\star = 0 and ci=−λsign⁡(xi⋆)c_i = -\lambda\operatorname{sign}(x_i^\star) elsewhere; hence soft thresholding and λmax⁡=∥A⊤b∥∞\lambda_{\max} = \norm{\mat{A}\T\vb{b}}_\infty.
  • xk+1=xk−ηkgk\vb{x}_{k+1} = \vb{x}_k - \eta_k\vb{g}_k is not a descent method. The lemma ∥xk+1−x⋆∥2≤∥xk−x⋆∥2−2ηk(f(xk)−f⋆)+ηk2∥gk∥2\norm{\vb{x}_{k+1} - \vb{x}^\star}^2 \le \norm{\vb{x}_k - \vb{x}^\star}^2 - 2\eta_k(f(\vb{x}_k) - f^\star) + \eta_k^2\norm{\vb{g}_k}^2 gives bound (R2+G2∑ηi2)/(2∑ηi)(R^2 + G^2\sum\eta_i^2)/(2\sum\eta_i) for the best iterate and average: constant step, floor G2η/2G^2\eta/2; optimal step R/(GN)R/(G\sqrt{N}), error RG/NRG/\sqrt{N}.
  • The Polyak step ηk=(f(xk)−f⋆)/∥gk∥2\eta_k = (f(\vb{x}_k) - f^\star)/\norm{\vb{g}_k}^2 minimizes the lemma, makes distance nonincreasing and converges linearly for a sharp minimum; with a poor estimate of f⋆f^\star it stalls or oscillates.
  • Nesterov’s function γmax⁡ixi+μ2∥x∥2\gamma\max_i x_i + \frac\mu2\norm{\vb{x}}^2 proves lower bound GR/(2(1+k+1))GR/(2(1 + \sqrt{k+1})): O(1/k)\bigO(1/\sqrt{k}) is optimal in high dimension. With structure (smooth plus ℓ1\ell_1), proximal methods do better.