Prove the classical gradient-descent rates: O(1/k) for L-smooth convex functions, linear for strongly convex functions, and O(1/k) for squared gradient norm in nonconvex functions. Introduce the Polyak-Łojasiewicz condition, giving linear convergence without convexity and helping explain training of overparameterized models.
After this lesson you can
Distinguish sublinear, linear, superlinear and quadratic rates and translate them into iterations for precision ε.
Prove the descent lemma and use it to bound decrease per iteration.
Prove the GD rate f(x_k) − f* ≤ L‖x₀ − x*‖²/(2k) for L-smooth convex functions.
Prove linear convergence with factor (1 − μ/L) under strong convexity or the PL condition.
Prove that for nonconvex L-smooth functions min‖∇f(xᵢ)‖² decreases as O(1/k) and explain what reaching a stationary point means.
Motivation: a loss curve is a falsifiable prediction
You launch training and loss decreases. The useful question is not “does it decrease?” but “how fast, and how much remains?” A convergence theorem answers with explicit assumptions: “if f is L-smooth and convex, then f(xk)−f⋆≤L∥x0−x⋆∥2/(2k)”. It is a prediction you can falsify by plotting: if actual loss exceeds the bound, your code has an error or an assumption fails.
Three situations where this interpretation saves hours:
Budget. If the curve is a straight line on a semilog scale with slope logρ, you know iterations remaining to accuracy ε without running them: k≈ln(1/ε)/ln(1/ρ). If instead it is a log-log line of slope −1, each extra decimal digit costs ten times the previous iterations.
Diagnosis. Logistic regression with ℓ2 regularization converges linearly; without it, on separable data, only as 1/k. Poorly conditioned ridge converges linearly but with ρ near 1. Curve shape reveals which assumption fails or which constant dominates.
Design. Step η, choosing GD or an accelerated method, and the value of a preconditioner follow from constants L, μ and κ in the rates. In overparameterized networks where nothing is convex, training curves still fall as straight semilog lines: this lesson’s Polyak-Łojasiewicz condition explains why.
This lesson proves four basic gradient-descent rates with step η=1/L and compares them with reality in each figure. The map:
Assumption on f
GD guarantee with η=1/L
Iterations for accuracy ε
convex and L-smooth
f(xk)−f⋆≤2kL∥x0−x⋆∥2
O(1/ε)
μ-strongly convex and L-smooth
f(xk)−f⋆≤(1−Lμ)k(f(x0)−f⋆)
O(κlog(1/ε))
only L-smooth and bounded below
mini<k∥∇f(xi)∥2≤k2L(f(x0)−f⋆)
O(1/ε2) for ∥∇f∥≤ε
L-smooth and μ-PL (without convexity)
same linear rate as row 2
O(κlog(1/ε))
Convergence orders: what “fast” means
Comparing algorithms needs vocabulary. Let ek>0 measure error at iteration k, e.g. f(xk)−f⋆ or ∥xk−x⋆∥, with ek→0.
The names come from graphs. If ek+1=ρek, then logek=loge0+klogρ is a straight line in k (semilog scale): “linear”. Slope reveals constant ρ: each iteration gains −log10ρ decimal digits. But the same sequence is far from a line on log-log. Conversely, if ek=Ck−p, then logek=logC−plogk is a straight line in logk (log-log) of slope −p, and a flattening curve on semilog.
What about higher orders? If ek+1=Cekq, taking logarithms gives logek+1=qlogek+logC: plotting logek+1 against logek gives a line of slope q. This measures order without knowing the method. For quadratic convergence, logek≈−c2k: correct digits double each step, and on semilog the curve plunges ever faster.
In iterations to reach accuracy ε (with e0≈1):
Type
Model
Iterations for ε
With ε=10−6
sublinear, p=1/2
ek≈k−1/2
ε−2
1012
sublinear, p=1
ek≈k−1
ε−1
106
sublinear, p=2
ek≈k−2
ε−1/2
103
linear, ρ=0.9
ek≈0.9k
ln(1/ε)/ln(1/ρ)
132
linear, ρ=0.99
ek≈0.99k
same
1375
linear, ρ=0.999
ek≈0.999k
same
13809
quadratic, e0=1/2
ek+1=ek2
log2log1/2ε
5
Two things stand out. First, a linear rate with ρ very near 1 can be practically worse than a sublinear one with large p: 0.999k needs 13809 steps for six digits, versus only a thousand for k−2. Second, for ρ near 1, ln(1/ρ)≈1−ρ, and linear cost is ≈ln(1/ε)/(1−ρ). With ρ=1−1/κ this becomes κln(1/ε): the preceding lesson’s condition number.
The first interactive is a detective game. Seven actual error sequences (gradient descent on different problems, bisection, Newton, secant) are unlabeled: decide their type from the curve alone.
InteractiveRate detective
error sequence
Scale
My diagnosis
R2 on semilog1.0000
R2 on log-log0.9862
ρ^ (semilog slope)0.9344
p^ (log-log slope)9.00
q^ (order)1.00
Correct0 of 0
On a linear scale most curves look alike: they fall quickly and then hug the axis, making their rates hard to distinguish.
Choose a case and explore four scales. In “Linear” nearly all curves look alike: they decrease and hug the axis. In “Semilog” a line reveals linear rate; in “Log-log”, sublinear; in “Order”, plot logek+1 against logek and the slope is order q (the dotted diagonal is q=1). Readings calculate three least-squares fits over the window chosen with “Fit from”: compare both R2 values and decide. Then press “Check”. Move the window in case 1 to separate transient from asymptotic rate, and inspect case 7 on log-log: does it look sublinear? Is it?
What you should have seen:
Linear scale distinguishes nothing. Often used for loss curves, it is least informative: every converging sequence resembles a flattening exponential.
Each type has its scale. Linear sequences (cases 1, 5 and 7) are semilog lines, with ρ^ equal to the theoretical constant. Sublinear ones (2 and 4) are log-log lines with p^≈1 and p^≈2. Newton and secant plunge on semilog, with q^≈2 and q^≈1.6.
Order separates sublinear and linear from superlinear. In the (logek,logek+1) plane, linear and sublinear sequences parallel the diagonal (q=1); only superlinear ones separate. Secant order q^≈1.6 is the golden ratio (1+5)/2.
A line in one window is not proof. In case 7 (ρ=0.996 per step), the log-log curve looks “almost straight”: a short window of a slow exponential resembles a power. Case 1’s transient shows the reverse: before the slowest mode dominates, apparent slope exceeds the asymptotic slope. A rate is asymptotic behavior, read at the curve’s end.
The descent lemma: what one step guarantees
All rates in this lesson follow from a one-line inequality. Recall the smoothness assumption: ∇f is L-Lipschitz, ∥∇f(x)−∇f(y)∥≤L∥x−y∥.
The descent lemma does not require convexity. Part (a) is the quadratic upper bound of lesson 3, reconstructed step by step in the first exercise. Part (b) is a substitution.
Function η↦η(1−Lη/2) is a parabola maximized at η=1/L, where it equals 1/(2L). ■
∎
Two everyday observations. First, descent is guaranteed iff η<2/L, because factor 1−Lη/2 is positive exactly in that range, with maximum guarantee at η=1/L. Bound 2/L is tight: for f(x)=2Lx2 with η=2/L, each step is x+=−x and value does not decrease. Second, inequality (b) concerns the next iterate, not the minimum: it holds anywhere, including far from a minimum and in nonconvex regions.
InteractiveThe descent lemma, step by step
k = 0
f
parabola Qk with curvature L
tangent at xk
Function value by iteration and cumulative bound f(x0)−∑i<kη(1−Lη/2)f′(xi)2
actual f(xk)
cumulative bound
minf
f(xk)16.629
f′(xk)2116.546
Guaranteed decrease7.2841
Actual decrease9.1923
actual / guaranteed1.26
Bound at x+holds
η=1/L: the next iterate is exactly the minimum of the parabola. This step maximizes the guaranteed decrease, ∥∇f∥2/(2L).
Each iteration draws the red curvature-L parabola tangent to f at xk. The next iterate x+ lies on the parabola axis and the red bar measures its guaranteed decrease, η(1−Lη/2)f′(xk)2; blue measures actual decrease of f (at least as much while L is true). With η=1/L, x+ minimizes the parabola. Raise ηL toward 2 and see the guarantee vanish; pass 2 and GD may increase. Lower “Assumed L” below 1: the parabola crosses f and stops bounding it. Choose nonconvex functions: the lemma still holds each step. Below, the sum of guaranteed decreases is always bounded by f(x0)−minf.
The figure’s lower graph anticipates the next argument. Sum inequality (b) over iterations and the left side telescopes: f(xk)≤f(x0)−∑i<kη(1−Lη/2)∥∇f(xi)∥2. Since f≥f⋆, total guaranteed decreases cannot exceed f(x0)−f⋆. That observation alone, without convexity, proves the nonconvex result. Convexity and a little more algebra yield rate 1/k.
Convex and L-smooth functions: rate O(1/k)
Add convexity. Now error f(x)−f⋆ relates to the gradient via the first-order conditionf(x⋆)≥f(x)+∇f(x)⊤(x⋆−x), i.e.
f(x)−f⋆≤∇f(x)⊤(x−x⋆).
The O(1/k) rate of GD on convex functions requires knowing L but neither μ nor dimension: it is independent of n.
Proof
Write gi=∇f(xi), so xi+1=xi−gi/L. There are four steps.
1. Combine descent and convexity. The descent lemma gives f(xi+1)≤f(xi)−2L1∥gi∥2, and convexity gives f(xi)−f⋆≤gi⊤(xi−x⋆). Subtract f⋆ from the first and substitute the second:
f(xi+1)−f⋆≤gi⊤(xi−x⋆)−2L1∥gi∥2.
2. Complete the square. With a=xi−x⋆, ∥a−gi/L∥2=∥a∥2−L2gi⊤a+L21∥gi∥2, so
4. Monotonicity. The descent lemma guarantees f(xi) does not increase, so f(xk)≤f(xi+1) for every i≤k−1; the step-3 sum has k terms, each ≥f(xk)−f⋆. Thus k(f(xk)−f⋆)≤2L∥x0−x⋆∥2. ■
∎
Four comments on what has and has not been proved.
Iterates remain in a ball. Monotonicity of ∥xk−x⋆∥ (step 2) avoids assuming bounded sublevel sets: the proof itself keeps iterates within B(x⋆,∥x0−x⋆∥).
Shorter steps. With η≤1/L the same argument gives f(xk)−f⋆≤∥x0−x⋆∥2/(2ηk). Reducing the step worsens the constant proportionally.
No minimizer. If f does not attain its infimum (e.g. logistic regression with separable data and no ℓ2), the argument holds with any comparison point z instead of x⋆: f(xk)≤f(z)+L∥x0−z∥2/(2k). Check this in the lab.
This is GD’s limit. Worst-case analysis (Drori and Teboulle, 2014; Taylor, Hendrickx and Glineur, 2017) shows that with η=1/L the exact constant is L∥x0−x⋆∥2/(4k+2), slightly less than half the proved bound, but the exponent of k does not improve. Exceeding 1/k requires another method: Nesterov accelerated gradient reaches O(1/k2), and lower bounds show that is optimal for first-order methods.
How closely does the bound match reality? We need a family of problems with tiny but known μ>0. A quadratic with eigenvalues λi=(i/n)q works: a spectrum with many nearly zero eigenvalues, so f(xk)−f⋆=21∑iλix0,i2(1−ηλi)2k can be evaluated in closed form.
InteractiveThe 1/k bound versus reality
actual f(xk)−f⋆
proven bound
k axis
μ=λmin (tiny)2.8e−4
k with f−f⋆≤10−4, real85
k guaranteed by the bound5000
bound / actual58.8×
The bound R2/(2ηk) is a line with slope −1 on a log-log plot and the actual curve lies below it. While k≪1/(ημ), GD does not yet detect μ>0; later the curve bends downward (linear convergence).
A convex quadratic with L=1 and spectrum λi=(i/n)q with n=60: blue is exact f(xk)−f⋆ and dashed red is theorem bound R2/(2ηk) (log-log line of slope −1). Raise “Spectrum” to accumulate tiny eigenvalues: the actual curve stays closer to the bound longer. The vertical line marks k≈1/(ημ), when GD “discovers” μ>0 and the curve breaks downward linearly. For steps above 1/L the bound is no longer proved.
Strongly convex functions: linear convergence
If f is also μ-strongly convex, error does more than decrease: it is multiplied by a constant below 1 each step. The key inequality from lesson 3 is f(x)−f⋆≤∥∇f(x)∥2/(2μ): a large gradient certifies a large error, so the lemma’s guaranteed decrease is proportional to error.
The linear GD rate on strongly convex functions depends only on κ: the condition number fixes the contraction factor.
Proof
By the descent lemma with η=1/L, f(xk+1)−f⋆≤f(xk)−f⋆−2L1∥∇f(xk)∥2. From lesson 3, ∥∇f(xk)∥2≥2μ(f(xk)−f⋆). Substitution gives
f(xk+1)−f⋆≤(1−Lμ)(f(xk)−f⋆),
and induction gives the first bound. For the second, 2μ∥xk−x⋆∥2≤f(xk)−f⋆. Finally (1−1/κ)k≤e−k/κ, which is ≤ε/(f(x0)−f⋆) when k≥κln((f(x0)−f⋆)/ε). ■
∎
Notice how little was needed: strong convexity enters only through ∥∇f∥2≥2μ(f−f⋆). This observation becomes the PL condition’s definition and lets us remove convexity below.
The step need not be 1/L. With any η∈(0,2/L) the same calculation gives factor
1−ημ(2−Lη),
equal to 1−μ/L at η=1/L (its minimum, the best guarantee) and tending to 1 as η→0 and η→2/L. With η=2/(L+μ) on quadratics, distance contracts as (κ+1κ−1)k, seen last lesson.
The proved bound is not exactly reality. On a quadratic, error in f is multiplied each step by at most maxi(1−ηλi)2 (and asymptotically exactly that factor), the square of distance contraction. With η=1/L this is (1−μ/L)2, while the theorem bound is only 1−μ/L: conservative by factor 2 in the exponent. The figure lets you measure the difference and see what happens as η approaches 2/L.
InteractiveThe linear bound versus reality
actual f(xk)−f⋆
proven bound
k axis
κ=L/μ100
proven per-step factor 1−ημ(2−Lη)0.99000
actual per-step factor (quadratic)0.98010
k for f−f⋆≤10−6f(x0), real371
k guaranteed by the bound1375
With κ=100 and η=1/L the bound requires on the order of κln(106)≈1382 steps; actual GD arrives earlier because only part of the spectrum is close to μ. For quadratics the actual contraction is the square of the proven factor, because the theorem bounds f using the PL inequality and the quadratic contracts distance by 1−ημ.
The quadratic spectrum is logarithmically spaced between μ=1/κ and L=1. Blue is exact f(xk)−f⋆ and dashed red is bound (1−ημ(2−Lη))k(f(x0)−f⋆). Move κ: both semilog slopes change like log(1−1/κ), and readings give actual and guaranteed steps for six digits. With η=1/L and κ=1000 the bound requires 13809 steps and GD reaches it in about 2700: the bound covers worst case, and this spectrum is not it. Move ηL near 2: the guarantee vanishes. Change the k axis to logarithmic and the bound's line curves: linear convergence is not a line on log-log.
Nonconvex functions: stationary points
Without convexity there is no minimizer to approach nor f(x)−f⋆≤∇f⊤(x−x⋆). Even so, the descent lemma and telescoping yield a real, more modest guarantee: the gradient becomes small.
Proof
The descent lemma with η=1/L gives for each i, 2L1∥∇f(xi)∥2≤f(xi)−f(xi+1). Sum for i=0,…,k−1: the right side telescopes and
2L1i=0∑k−1∥∇f(xi)∥2≤f(x0)−f(xk)≤f(x0)−f⋆.
The minimum of k terms cannot exceed their mean: mini<k∥∇f(xi)∥2≤k1∑i<k∥∇f(xi)∥2≤2L(f(x0)−f⋆)/k. For the second claim require the bound ≤ε2. ■
∎
This is GD’s nonconvex stationarity result: an ε-stationary point (∥∇f∥≤ε) in O(1/ε2) iterations. Compare the convex case, where f−f⋆≤ε cost O(1/ε): here the gradient is measured, and ∥∇f∥ is the square root of what decreases as 1/k, so norm decreases as 1/k. Dependence ε−2 cannot be improved for GD in this class (Cartis, Gould and Toint, 2010).
What the theorem does not say matters as much as what it does:
It concerns the best iterate, not the last. Without convexity, ∥∇f(xk)∥ may rise and fall. In practice this does not matter: stopping as soon as ∥∇f∥≤ε finds the first satisfying iterate.
Stationary is not minimum. A point with ∇f=0 can be a local minimum, maximum or saddle. The theorem does not distinguish them, and f(xk) can be far from f⋆.
Nor does it say where you go. A small ∇f need not put xk near anything in particular.
These are more than theoretical cautions: consider f(x,y)=sinxsiny, which is 1-smooth, bounded (f⋆=−1), has global minima at (±2π,∓2π) and saddles at multiples of π. Along diagonal x=y it equals sin2x and GD, which by symmetry stays there, falls exactly onto saddle(0,0) with ∇f→0 and f−f⋆→1.
InteractiveStationary is not minimum
∥∇f(xk)∥2
minimum through k
proven bound
k axis
f(xk)−f⋆ at the end1.000
∥∇f(xk)∥2 at the end0.0e0
mini<k∥∇f(xi)∥20.0e0
bound at k8.1e−3
the final iterate issaddle
The gradient is almost zero, but the function remains far from its minimum (f−f⋆≈1): GD stopped at a saddle. Without convexity, ∥∇f∥→0 means only a stationary point, not a minimum.
Level curves of sinxsiny (blue: negative values; orange: positive). Filled circles are minima and hollow circles saddles. Drag x0. Below are ∥∇f(xk)∥2 (pale blue), its minimum through k (green), and proved bound 2L(f(x0)−f⋆)/(kηL(2−ηL)) (dashed red); green always stays below. Start on the diagonal: the gradient nearly vanishes but f−f⋆≈1 and the reading says “saddle”. Press “Diagonal + 0.001”: the small deviation grows as (1+η)k along the unstable direction and, with η=1/L, GD leaves the saddle for a minimum in about ten steps. Shorter steps take longer.
There is good news outside the theorem. Initial points falling exactly on a saddle’s stable manifold form a measure-zero set: with random initialization and η<1/L, GD almost surely does not converge to a “strict” saddle, one with a negative Hessian eigenvalue. If all saddles are strict and GD converges, it converges to a local minimum (Lee, Simchowitz, Jordan and Recht, 2016). This returns with the strict saddle property and escaping saddles.
The Polyak-Łojasiewicz condition: linear without convexity
The linear proof used one property: ∥∇f(x)∥2≥2μ(f(x)−f⋆). Keep only that.
Read it as a ratio: f(x)−f⋆21∥∇f(x)∥2≥μ everywhere. The gradient never dies while error remains: there can be no plateaus or stationary points outside the minimizer set. An immediate consequence: every stationary point is a global minimum (if ∇f(x)=0, then 0≥μ(f(x)−f⋆), so f(x)=f⋆).
Proof
This is literally the strongly convex proof. The descent lemma gives f(xk+1)−f⋆≤f(xk)−f⋆−2L1∥∇f(xk)∥2 and PL gives ∥∇f(xk)∥2≥2μ(f(xk)−f⋆). Thus f(xk+1)−f⋆≤(1−μ/L)(f(xk)−f⋆). ■
∎
The relationship to the preceding result is a strict implication. Every μ-strongly convex function is μ-PL (inequality f−f⋆≤∥∇f∥2/(2μ) from lesson 3, reconstructed in exercise 3), but PL does not require convexity, a unique minimizer, or even a convex minimizer set. It does not need L-smoothness to exist, only for the theorem to apply. It does imply (without proof here) quadratic growth relative to minimizer set X⋆, f(x)−f⋆≥2μdist(x,X⋆)2 (Karimi, Nutini and Schmidt, 2016, who also place PL in the hierarchy of “error bound” conditions).
Three families of examples show the condition is not arbitrary.
Two instructive counterexamples. f(x)=x4 is convex with a unique minimizer but not PL: 21f′(x)2/f(x)=8x2→0 near the minimum, so GD converges as 1/k2, not linearly (detective case 4). And the ring 41(x2+y2−1)2 has the unit circle as its minimizer set, but at the origin its gradient vanishes with f=41: the PL ratio is 0.
The figure brings together three landscapes. Click to launch GD from several points and observe in the center panel the PL ratio along each trajectory, always above μ; below, the straight semilog line.
InteractiveNonconvex PL functions
PL ratio 21∥∇f(xk)∥2/(f(xk)−f⋆) per iteration
Error f(xk)−f⋆ (log scale) and bound (1−ημ(2−Lη))kf(x0) of the last trajectory
GD trajectories (in start order)
PL bound
Landscape
μ (min. of 21∥∇f∥2/(f−f⋆))0.1755
L (sup. de ∥∇2f∥)8.00
proven per-step factor0.9816
observed per-step factor0.1603
minimum observed PL ratio0.1756
f(x)=x2+3sin2x is not convex (f′′=2+6cos2x reaches −4) but satisfies 21f′(x)2≥μf(x) con μ≈0.1755 (minimum ratio on a grid, at x≈±2.20). All trajectories, from any start, decrease linearly to the unique minimum.
Three landscapes: x2+3sin2x; a curved valley 21(y−asinx)2 whose minimizer set is the green curve (with a>0 it is nonconvex and each start ends at a different point on it, but PL ratio is always 1+a2cos2x≥1); and the ring, which is not PL. Click the landscape to launch GD (up to five trajectories). The middle panel plots 21∥∇f(xk)∥2/(f(xk)−f⋆) per iteration against μ (numerically calculated), and the bottom panel plots semilog error against bound (1−ημ(2−Lη))k. On the ring start GD near the origin: the ratio falls to zero, the trajectory takes time to escape and there is no linear bound.
Implementation from scratch: a rates lab
Build the full toolkit: GD, three problems, rate fitting and comparison with bounds. The problems are a quadratic with κ=100, ℓ2-regularized logistic regression (strongly convex), and unregularized logistic regression on separable data (convex, no minimizer). For regularized logistic use lesson 3’s constants, L=λ+∥X∥22/(4n) and μ=λ, and calculate w⋆ with a few Newton steps solely for exact error measurement.
[ ]GD and three problemsBrowser
import numpy as np
def gd(grad, x0, eta, n):
"""n + 1 iterados de x <- x - eta * grad(x)."""
xs = [np.array(x0, dtype=float)]
for _ in range(n):
xs.append(xs[-1] - eta * grad(xs[-1]))
return np.array(xs)
rng = np.random.default_rng(0)
# 1) cuadrática con kappa = 100: f(x) = ½ xᵀAx, minimizador x* = 0
d = 20
lam = np.logspace(0, 2, d)
Q, _ = np.linalg.qr(rng.standard_normal((d, d)))
A = Q @ np.diag(lam) @ Q.T
quad = dict(f=lambda x: 0.5 * x @ A @ x, grad=lambda x: A @ x, L=lam.max(), mu=lam.min(),
xstar=np.zeros(d), fstar=0.0, x0=rng.standard_normal(d))
# 2) regresión logística con etiquetas ruidosas (no separables) y regularización ℓ2
n, p = 200, 5
X = rng.standard_normal((n, p))
w_true = rng.standard_normal(p)
y = np.where(X @ w_true + 0.8 * rng.standard_normal(n) > 0, 1.0, -1.0)
def logistic(X, y, l2):
n = len(y)
f = lambda w: np.mean(np.logaddexp(0.0, -y * (X @ w))) + 0.5 * l2 * w @ w
grad = lambda w: -(X.T @ (y / (1.0 + np.exp(y * (X @ w))))) / n + l2 * w
L = l2 + np.linalg.norm(X, 2) ** 2 / (4 * n) # constante de la lección 3
return f, grad, L
l2 = 0.005
f_r, g_r, L_r = logistic(X, y, l2)
def hess_r(w):
s = 1.0 / (1.0 + np.exp(-y * (X @ w)))
return (X.T * (s * (1 - s))) @ X / n + l2 * np.eye(p)
w = np.zeros(p)
for _ in range(30): # Newton: solo para obtener w* a precisión de máquina
w = w - np.linalg.solve(hess_r(w), g_r(w))
logreg = dict(f=f_r, grad=g_r, L=L_r, mu=l2, xstar=w, fstar=f_r(w), x0=np.zeros(p))
# 3) datos separables con margen, sin ℓ2: no hay minimizador, inf f = 0
Xs = rng.standard_normal((800, p))
Xs = Xs[np.abs(Xs @ w_true) > 0.18 * np.linalg.norm(w_true)][:200]
ys = np.sign(Xs @ w_true)
f_s, g_s, L_s = logistic(Xs, ys, 0.0)
sep = dict(f=f_s, grad=g_s, L=L_s, x0=np.zeros(p), fstar=0.0)
print(f"cuadrática: L = {quad['L']:.0f}, mu = {quad['mu']:.0f}, kappa = {quad['L'] / quad['mu']:.0f}")
print(f"logística con l2: L = {L_r:.4f}, mu = {l2}, kappa = {L_r / l2:.1f}, f* = {logreg['fstar']:.6f}")
print(f"logística separable: L = {L_s:.4f}, mu = 0")
def errores(prob, n_iter):
xs = gd(prob["grad"], prob["x0"], 1.0 / prob["L"], n_iter) # paso eta = 1/L
return np.array([prob["f"](x) - prob["fstar"] for x in xs]), xs
e_quad, xs_quad = errores(quad, 1500)
e_log, xs_log = errores(logreg, 3000)
e_sep, xs_sep = errores(sep, 8000)
print("error final:", f"{e_quad[-1]:.1e}", f"{e_log[-1]:.1e}", f"{e_sep[-1]:.1e}")
The three errors end very differently: the quadratic and regularized logistic reach machine precision (logistic error stays at rounding noise, so may be zero or negative), while separable remains at 6⋅10−4. Now the detective in code. Fit the interactive’s two lines over the second half of each curve (past the transient), keeping the part where error remains above rounding noise:
[ ]Fitting rates: semilog versus log-logBrowser
def r2(y, yhat):
return 1 - np.sum((y - yhat) ** 2) / np.sum((y - np.mean(y)) ** 2)
def tramo(e, piso=1e-12):
"""Longitud del prefijo en que el error está por encima del ruido de redondeo."""
return np.flatnonzero(e > piso)[-1] + 1
def ajuste_semilog(e):
"""e_k ≈ C rho^k sobre la segunda mitad: devuelve (rho, R²)."""
n = tramo(e); k = np.arange(n); a = n // 2
s, b = np.polyfit(k[a:], np.log(e[a:n]), 1)
return np.exp(s), r2(np.log(e[a:n]), s * k[a:] + b)
def ajuste_loglog(e):
"""e_k ≈ C k^(-p) sobre la segunda mitad: devuelve (p, R²)."""
n = tramo(e); k = np.arange(n); a = n // 2
s, b = np.polyfit(np.log(k[a:]), np.log(e[a:n]), 1)
return -s, r2(np.log(e[a:n]), s * np.log(k[a:]) + b)
for nombre, e in [("cuadrática kappa=100", e_quad), ("logística con l2", e_log), ("logística separable", e_sep)]:
rho, rs = ajuste_semilog(e)
pp, rl = ajuste_loglog(e)
print(f"{nombre:22s} semilog: rho = {rho:.5f}, R2 = {rs:.5f} | log-log: p = {pp:.3f}, R2 = {rl:.5f}")
print("(1 - mu/L)^2 en la cuadrática:", (1 - quad["mu"] / quad["L"]) ** 2)
Quadratic and regularized logistic are straight lines in semilog (R2≈1), while separable is a line in log-log, with slope p^≈0.9: it converges like 1/k. For the quadratic, observed factor 0.9799 matches theory’s value for f, (1−μ/L)2=0.9801, not the theorem’s guaranteed 1−μ/L=0.99. Most surprising is regularized logistic: proved bound is 1−μ/L=0.984 and observed factor 0.79. The next cell compares bounds to data, checking with actual numbers that theorems are never violated:
[ ]Bounds versus realityBrowser
for nombre, prob, e, xs in [("cuadrática kappa=100", quad, e_quad, xs_quad), ("logística con l2", logreg, e_log, xs_log)]:
R2 = np.sum((xs[0] - prob["xstar"]) ** 2) # ‖x₀ − x*‖²
ks = np.arange(1, len(e))
cota_conv = prob["L"] * R2 / (2 * ks) # teorema convexo
cota_lin = (1 - prob["mu"] / prob["L"]) ** ks * e[0] # teorema fuertemente convexo
vivos = e[1:] > 1e-12 # por debajo, f − f* es ruido
print(f"{nombre}: ¿e_k <= L R²/(2k) siempre? {np.all(e[1:] <= cota_conv)} ¿e_k <= (1-mu/L)^k f0? {np.all(e[1:][vivos] <= cota_lin[vivos])}")
for k in (10, 100, 1000):
print(f" k = {k:4d} real {e[k]:9.2e} L R²/(2k) {prob['L'] * R2 / (2 * k):9.2e} (1-mu/L)^k f0 {(1 - prob['mu'] / prob['L']) ** k * e[0]:9.2e}")
# datos separables: no hay x*, pero la cota vale con cualquier comparador z = s·u (x₀ = 0)
u = w_true / np.linalg.norm(w_true)
ss = np.linspace(0, 60, 601)
f_z = np.array([f_s(s * u) for s in ss])
for k in (100, 1000, 5000):
cota = np.min(f_z + L_s * ss ** 2 / (2 * k)) # min_z [ f(z) + L‖x₀ − z‖²/(2k) ]
print(f"separable k = {k:5d} real {e_sep[k]:.2e} cota con comparador libre {cota:.2e} k·real = {k * e_sep[k]:.2f}")
Both bounds always hold; neither approaches reality when the problem is easy. The last line shows sublinear rate is order 1/k up to slow factors: product k⋅ek only increases from 2.6 to 4.9 when k is multiplied by 50 (hence p^≈0.92, not exactly 1), and the much more pessimistic free-comparator bound still holds. Now turn to PL: nonconvex x2+3sin2x and least squares with more unknowns than equations.
[ ]PL without convexityBrowser
g = lambda x: x ** 2 + 3 * np.sin(x) ** 2 # g'' = 2 + 6 cos 2x llega a −4: no convexa
dg = lambda x: 2 * x + 3 * np.sin(2 * x)
xs_ = np.linspace(-20, 20, 400001)
xs_ = xs_[np.abs(xs_) > 1e-6]
mu_g = np.min(0.5 * dg(xs_) ** 2 / g(xs_)) # constante PL en esa rejilla
L_g = 8.0
print(f"g: mu_PL = {mu_g:.4f}, L = {L_g}, kappa_PL = {L_g / mu_g:.1f}")
for c in (1.0, 0.5):
eta = c / L_g
xs = gd(dg, 3.9, eta, 400)
eg = g(xs)
factor = 1 - eta * mu_g * (2 - L_g * eta)
k = np.arange(1, len(eg))
vivos = eg[1:] > 1e-250
print(f"eta = {c}/L: ¿g(x_k) <= factor^k g(x_0)? {np.all(eg[1:][vivos] <= factor ** k[vivos] * eg[0])} (factor {factor:.4f}) g(x_400) = {eg[-1]:.1e}")
# mínimos cuadrados sobreparametrizados: 30 ecuaciones, 100 incógnitas
rng = np.random.default_rng(1)
m, dd = 30, 100
Xw = rng.standard_normal((m, dd))
yw = Xw @ rng.standard_normal(dd)
sv = np.linalg.svd(Xw, compute_uv=False)
mu_w, L_w = sv.min() ** 2, sv.max() ** 2 # mu = sigma_min(X)², L = sigma_max(X)²
fw = lambda w: 0.5 * np.sum((Xw @ w - yw) ** 2)
ws = gd(lambda w: Xw.T @ (Xw @ w - yw), np.zeros(dd), 1 / L_w, 400)
fv = np.array([fw(w) for w in ws])
k = np.arange(1, 401)
print(f"mínimos cuadrados d > m: mu = {mu_w:.2f}, L = {L_w:.1f}, kappa = {L_w / mu_w:.1f}, rango de la hessiana = {np.linalg.matrix_rank(Xw.T @ Xw)} de {dd}")
print("¿f(w_k) <= (1 - mu/L)^k f(w_0)?", np.all(fv[1:] <= (1 - mu_w / L_w) ** k * fv[0] * (1 + 1e-9)), f" f(w_400) = {fv[-1]:.1e}")
Observe the first result: with η=1/L and f′′(0)=2+6=8=L, the local quadratic matches the majorizer, the step’s linear term cancels and GD converges cubically near 0 (floating-point arithmetic reaches exact 0 in a few steps), making the linear bound extremely conservative. In least squares the Hessian has rank 30 of 100 (not strongly convex at all), yet error falls by factor ≤1−μ/L per step, as the example claims. Finally the general nonconvex case checks stationarity and displays the saddle:
[ ]Stationarity in nonconvex functionsBrowser
f2 = lambda V: np.sin(V[..., 0]) * np.sin(V[..., 1])
g2 = lambda V: np.stack([np.cos(V[..., 0]) * np.sin(V[..., 1]), np.sin(V[..., 0]) * np.cos(V[..., 1])], axis=-1)
rng = np.random.default_rng(3)
V = rng.uniform(-3, 3, (500, 2)) # 500 inicios a la vez; L = 1, f* = −1, eta = 1/L
f0 = f2(V) + 1
min_g2 = np.full(len(V), np.inf)
peor = 0.0
for k in range(1, 301):
min_g2 = np.minimum(min_g2, np.sum(g2(V) ** 2, axis=1)) # min_{i<k} ‖∇f(x_i)‖²
peor = max(peor, np.max(min_g2 / (2 * f0 / k)))
V = V - g2(V)
print(f"max de (min ‖∇f‖²) / (2L(f0 - f*)/k) sobre 500 inicios y 300 pasos: {peor:.3f} (el teorema dice <= 1)")
print(f"inicios que acaban en un mínimo (f < -0.99): {np.mean(f2(V) < -0.99):.3f}")
for nombre, v0 in [("sobre la diagonal", [0.9, 0.9]), ("diagonal + 0.001", [0.9, 0.901])]:
v = np.array(v0)
for _ in range(600):
v = v - g2(v)
print(f"{nombre:18s}: f = {f2(v):+.4f} ‖∇f‖ = {np.linalg.norm(g2(v)):.1e}")
The theorem’s bound is never violated (ratio below 1), and all 500 random starts end at a minimum: landing on a saddle requires starting in a measure-zero set. But starting on the diagonal ends with ∥∇f∥=0 to machine precision and f=0: a perfect stationary point that is not a minimum (with η=1/L and curvature 1=L along the diagonal, GD reaches the saddle cubically). The same start displaced by a thousandth ends at f=−1. Finally, the synthesis plot with bounds:
[ ]Curves with boundsBrowser
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 3, figsize=(11, 3.4))
# (a) fuertemente convexas: rectas en semilog
for nombre, prob, e, c in [("cuadrática kappa=100", quad, e_quad, "C0"), ("logística con l2", logreg, e_log, "C1")]:
n_ = tramo(e); k = np.arange(n_)
axs[0].semilogy(k, e[:n_], color=c, label=nombre)
axs[0].semilogy(k, (1 - prob["mu"] / prob["L"]) ** k * e[0], "--", color=c, alpha=0.7)
axs[0].set_ylim(1e-12, 1e3); axs[0].set_title("lineal: real y cota (discontinua)", fontsize=10)
axs[0].set_xlabel("k"); axs[0].legend(fontsize=8)
# (b) separable: recta de pendiente −1 en log-log
k = np.arange(1, len(e_sep))
axs[1].loglog(k, e_sep[1:], label="logística separable")
axs[1].loglog(k, e_sep[-1] * (len(e_sep) - 1) / k, "--", label="C/k")
axs[1].set_title("sublineal: pendiente −1", fontsize=10); axs[1].set_xlabel("k"); axs[1].legend(fontsize=8)
# (c) PL no convexas
xs = gd(dg, 3.9, 0.5 / L_g, 400)
axs[2].semilogy(g(xs)[:60], label="x² + 3 sin² x")
axs[2].semilogy(fv[:200], label="mínimos cuadrados d > m")
axs[2].semilogy(np.arange(200), (1 - mu_w / L_w) ** np.arange(200) * fv[0], "--", color="C1", alpha=0.7)
axs[2].set_ylim(1e-25, 1e4); axs[2].set_title("PL: lineal sin convexidad", fontsize=10); axs[2].set_xlabel("k"); axs[2].legend(fontsize=8)
plt.tight_layout()
plt.show()
The professional version
In a real project you do not write fitting by hand: scipy provides regression with standard errors, nonlinear fitting and reference minimizers. The important lesson here is why regularized logistic’s observed rate (0.79) is far from the proved one (0.984). The theorem uses global constants (μ=λ bounds curvature everywhere, but the Hessian approaches it only as ∥w∥→∞), while the curve’s tail is governed by local curvature at w⋆.
[ ]Local constants and fits with scipyBrowser
from scipy import linalg, optimize, stats
# 1) curvatura local en w*: autovalores de la hessiana y factor asintótico esperado de f
ev = linalg.eigvalsh(hess_r(logreg["xstar"]))
eta = 1 / L_r
print(f"hessiana en w*: lambda_min = {ev[0]:.4f}, lambda_max = {ev[-1]:.4f} (globales: mu = {l2}, L = {L_r:.4f})")
print(f"factor local esperado de f por paso, (1 - eta lambda_min)²: {(1 - eta * ev[0]) ** 2:.4f} | observado: {ajuste_semilog(e_log)[0]:.4f}")
# 2) comprobar f* con un optimizador de referencia
res = optimize.minimize(logreg["f"], np.zeros(p), jac=logreg["grad"], method="L-BFGS-B", tol=1e-14)
print(f"L-BFGS-B: f - f* = {res.fun - logreg['fstar']:.1e} en {res.nit} iteraciones (GD necesita ~100 para llegar a 1e-12)")
# 3) regresión lineal con errores típicos (semilog) y ajuste no lineal de una potencia (log-log)
n_ = tramo(e_quad); k = np.arange(n_)
lr = stats.linregress(k[n_ // 2:], np.log(e_quad[n_ // 2:n_]))
print(f"linregress en la cuadrática: rho = {np.exp(lr.slope):.5f}, R2 = {lr.rvalue ** 2:.6f}")
kk = np.arange(1, len(e_sep))
mitad = slice(len(kk) // 2, None)
(C, pot), cov = optimize.curve_fit(lambda k, C, p_: C * k ** (-p_), kk[mitad], e_sep[1:][mitad], p0=(1.0, 1.0))
print(f"curve_fit en la separable: error ≈ {C:.2f}·k^(-{pot:.3f}) (error típico del exponente {np.sqrt(cov[1, 1]):.1e})")
The first line is key: the Hessian-predicted factor at w⋆ matches observation to four digits, and smallest local eigenvalue (0.035) is seven times μ=λ=0.005, because data add curvature that the theorem deliberately does not count. Theorems give guarantees for the whole class; a particular problem’s rate is set by its local spectrum. That does not make them useless: the global bound alone holds without calculating w⋆.
Common mistakes
Exercises
ProofThe quadratic upper bound
Prove: If ∇f is L-Lipschitz, then f(y)≤f(x)+∇f(x)⊤(y−x)+2L∥y−x∥2 for every x,y.
0
Fix x and y and consider φ(t)=f(x+t(y−x)) for t∈[0,1].
Step 1 of 3. How do you express f(y)−f(x)−∇f(x)⊤(y−x) as an integral?
ProofThe $1/k$ GD rate for convex functions
Prove: If f is convex and L-smooth and xi+1=xi−L1∇f(xi), then f(xk)−f⋆≤2kL∥x0−x⋆∥2.
0
Write gi=∇f(xi) and ai=xi−x⋆. You have the descent lemma and f(x)−f⋆≤∇f(x)⊤(x−x⋆).
Step 1 of 4. Combine the inequalities to bound f(xi+1)−f⋆.
ProofStrong convexity implies PL
Prove: If f is differentiable and μ-strongly convex with minimizer x⋆, then 21∥∇f(x)∥2≥μ(f(x)−f⋆) for every x.
0
Start with lesson 3's quadratic lower bound.
Step 1 of 4. What inequality holds at any point x?
NumericSix digits with κ = 1000
A μ-strongly convex L-smooth function has κ=1000. With η=1/L, what is the smallest integer iteration count k for which proved bound f(xk)−f⋆≤(1−1/κ)k(f(x0)−f⋆) guarantees reducing f−f⋆ by factor 106?
NumericThe factor for an arbitrary step
An L-smooth μ-PL function has L=10 and μ=1. Apply GD with η=0.15. What per-step factor 1−ημ(2−Lη) does the theorem guarantee for f(xk)−f⋆?
NumericA gradient of $10^{-3}$
A nonconvex L-smooth function has L=4 and f(x0)−f⋆=2.5. With η=1/L, how many iterations does the stationarity theorem guarantee to find an iterate with ∥∇f(xi)∥≤10−3?
QuizWhat does this curve say?
Plot training error f(xk)−f⋆. On semilog the curve falls and flattens increasingly (concave upward, not straight). On log-log it is a line of slope −2. What follows?
QuizWhich satisfy PL?
Select all functions f that are PL (with some constant μ>0 and attained minimum f⋆):
More than one answer may be correct.
QuizA tiny gradient
GD with η=1/L on a nonconvex, L-smooth, bounded-below function runs until ∥∇f(xk)∥=10−9. What can you assert without further assumptions?
CodeA rate classifier
Implement estimate_rate(errors). It receives a positive error sequence decreasing to zero and returns a pair (tipo, valor), where tipo is one of sublineal (error ≈Ck−p, and valor=p), lineal (error ≈Cρk, and valor=ρ) or superlineal (order exceeds 1, and valor is order q of ek+1≈Cekq). Write the type exactly as shown, lowercase without accents or spaces. Work on the second half of the sequence to leave the transient behind. Design hint: order is the slope of logek+1 versus logek; between linear and sublinear decide which fit, semilog or log-log, gives a better line.
A convergence rate is a prediction falsifiable by a plot: linear is a semilog line (slope logρ, ρ≈1−1/κ), sublinear a log-log line, and superlinear curves downward in semilog. Everything follows from the descent lemma f(x+)≤f(x)−2L1∥∇f(x)∥2: summing and telescoping gives 1/k with convexity, (1−μ/L)k with strong convexity or PL, and min∥∇f∥2≤2L(f0−f⋆)/k without convexity.
Orders. Sublinear (ek≈k−p), linear (ek+1≤ρek), superlinear (ek+1/ek→0), and order q (ek+1≤Cekq). Measure order from slope of logek+1 versus logek. Linear cost is ln(1/ε)/ln(1/ρ)≈κln(1/ε).
Descent lemma. For L-smooth f, f(x−η∇f(x))≤f(x)−η(1−Lη/2)∥∇f(x)∥2: descent is guaranteed iff η<2/L, optimal at η=1/L. GD minimizes the curvature-L quadratic majorizer.
Convex L-smooth.f(xk)−f⋆≤L∥x0−x⋆∥2/(2k) by telescoping and monotonicity; O(1/ε) iterations and iterates remain in a ball.
Strongly convex.f(xk)−f⋆≤(1−μ/L)k(f(x0)−f⋆) and O(κlog(1/ε)) iterations; with tiny μ the sublinear bound dominates.
Nonconvex.mini<k∥∇f(xi)∥2≤2L(f(x0)−f⋆)/k: an ε-stationary point in O(1/ε2) steps. Stationary is not minimum.
PL condition.21∥∇f∥2≥μ(f−f⋆) gives exactly the linear rate without convexity; includes strong convexity, overparameterized least squares and nonlinear residuals with full-rank Jacobian. It forbids saddles and plateaus with positive error.
Theory and practice. Bounds are global and pessimistic; the observed rate is set by local curvature at the optimum, and deviations are useful diagnostics.