In the first lesson you saw that zero gradient is a necessary condition for a minimum and generally says little else: it may be a local minimum, maximum or saddle, and a local minimum may lie far above the global one. A gradient is information at one point. For that information to say something about the whole domain requires an assumption connecting distant points, and the most useful is convexity: the function curves downward nowhere.
Almost everything we can solve with guarantees is convex or sufficiently similar to something convex that theory guides practice:
Least squares and ridge: 21∥Xw−y∥22+2λ∥w∥22 is quadratic with Hessian X⊤X+λI.
Regularized logistic regression: n1∑ilog(1+e−yixi⊤w)+2λ∥w∥2, with no closed form but a unique minimum reachable by gradient descent.
SVM, lasso, robust regression (Huber): convex, sometimes nondifferentiable losses.
Any local neural-network problem solved “in the linear limit” (last layer, fine-tuning a linear head): the convex portion of an overall nonconvex problem.
This lesson supplies the module’s analytical vocabulary in two halves. First, convexity: its chord definition, equivalence to the first-order condition (the tangent is a global lower bound) and second-order condition (the Hessian is positive semidefinite), calculus for recognizing convex functions without differentiating, and the theorem justifying the effort: for a convex function, every local minimum is global. Second, quantification: convexity is yes or no, but algorithms need numbers. Two constants, strong convexityμ (minimum curvature) and smoothnessL (maximum curvature), sandwich the function between two parabolas, and their ratio κ=L/μ governs speed of the first-order methods in lessons 7–9.
Convexity: the chord lies above
A convex function of one variable does not curve downward: joining two points of its graph with a segment puts that segment above the graph. This makes sense in any dimension because it refers only to segments between domain points, so the domain must be convex (convex set).
The definition says that on the line joining (x,f(x)) and (y,f(y)), chord value at intermediate point θx+(1−θ)y is θf(x)+(1−θ)f(y), and the function does not exceed it. An affine function always has equality: it is both convex and concave, and these are the only functions with both properties.
Proof
If f is convex and (x,s),(y,t)∈epif, then f(θx+(1−θ)y)≤θf(x)+(1−θ)f(y)≤θs+(1−θ)t, so the points’ convex combination lies in the epigraph. Conversely, if the epigraph is convex, (x,f(x)) and (y,f(y)) lie in it, hence so does (θx+(1−θ)y,θf(x)+(1−θ)f(y)), exactly the inequality. A sublevel is the epigraph intersected with hyperplane {t=α} and projected onto Rn; convex intersections and projections are convex.
∎
The converse of the second statement is false: f(x)=x3 has convex sublevels (rays) and is not convex. We return to this at the end, because functions with convex sublevels have their own name and weaker properties. Throughout the rest of the module, convexity means the chord inequality.
Three tests for one property
The chord inequality is the definition, but not the convenient working form. Two other more useful forms will be proved next:
Chords (definition): the segment joining two graph points lies above it.
Tangents (first order): if f is differentiable, the tangent line (hyperplane) at any point lies below the graph everywhere.
Curvature (second order): if f is twice differentiable, f′′≥0 (in several variables, ∇2f⪰0).
The figure lets you test all three on the same one-variable function, reshaped by dragging gray nodes. Start with the nonconvex double well: in the chord test choose a and b on either side of the central maximum and inspect the violation. Switch to tangent and drag c over the central hump: the tangent passes above the graph. Above all, inspect the three lower tracks: if one test fails somewhere, all three fail. They do not fail at the same location, which is informative: curvature pinpoints the hump (f′′<0 in (−1,1)), while a tangent or chord may start outside the hump and still intersect it, so failure regions are wider and contain it.
InteractiveThree faces of convexity
f (drag the gray nodes)
chord
violation
Curvature f′′(x): blue where nonnegative, red where negative
Where each test fails (red = fails): the negative curvature region lies inside the other two
Test
θf(a)+(1−θ)f(b)−0.899
f(θa+(1−θ)b)0.000
Chord minus function−0.899
Chords: all passno
Tangents: all passno
f′′≥0 throughout the intervalno
All three tests fail. f′′<0 on [−1.0, 1.0]; tangents and chords fail in a wider region containing it (tracks below).
One function under three tests. Chord: drag a, b and slider θ: the chord must lie above f; red marks where it does not. Tangent: drag c: the tangent must lie below f everywhere (reading minx[f(x)−Tc(x)] must be ≥0). Curvature: drag c and read f′′(c) and the osculating parabola. For the double well and cubic all three tests fail; the negative-curvature region is narrowest and lies inside tangent and chord failure regions. For quartic f(x)=x4/8, f′′(0)=0 yet the function is convex: zero curvature breaks nothing. Reshape the function by dragging gray nodes and find the ugliest shape that remains convex.
Two observations. First, the tangent is local (uses one point and its derivative) but its verdict is global (lying below everywhere). This is the module’s key, proved shortly. Second, for the quartic f′′(0)=0 and the function is convex, but curvature vanishes at the origin. The distinction between “convex” and “curved with a positive lower bound” separates convexity from strong convexity, discussed below.
Jensen’s inequality
The definition addresses two points but extends to any number, just as with convex sets.
Proof
Induct on k; k=2 is the definition. If θk=1 there is nothing to prove. Otherwise ∑iθixi=(1−θk)q+θkxk with q=∑i<k1−θkθixi a convex combination of k−1 points. Applying the definition then the induction hypothesis to q,
Weights θi form a probability distribution on k points, and the inequality says f(E[X])≤E[f(X)]. The general version for any random variable with finite expectation is proved in the probability lesson and underlies the evidence lower bound (ELBO), KL divergence nonnegativity and the arithmetic–geometric mean inequality.
First-order condition: the tangent is a global lower bound
Proof
(⇒) For θ∈(0,1], convexity gives f(x+θ(y−x))≤(1−θ)f(x)+θf(y), i.e.
θf(x+θ(y−x))−f(x)≤f(y)−f(x).
As θ→0+ the left side tends to directional derivative ∇f(x)⊤(y−x), leaving ∇f(x)⊤(y−x)≤f(y)−f(x).
(⇐) This is the lesson’s first proof exercise: apply the condition at intermediate point z=θx+(1−θ)y toward x and y and combine both inequalities with weights θ and 1−θ.
∎
The first half has a geometric interpretation: a convex function’s difference quotient is nondecreasing in θ, so tangent slope (the limit as θ→0+) is the smallest slope among chords leaving the point. Every chord lies above the tangent, and therefore so does the graph.
The first-order condition converts a property involving two points and a parameter into one involving a point and its derivative, with immediate consequences:
Adding the condition at (x,y) and (y,x) gives gradient monotonicity, (∇f(x)−∇f(y))⊤(x−y)≥0: in one variable, f′ is nondecreasing.
If ∇f(x⋆)=0, the lower bound is constant f(x⋆), so f(y)≥f(x⋆) for every y: a stationary point of a convex function is a global minimum.
For the same reason, to minimize f over convex K (with f convex and differentiable on an open set containing K), x⋆∈K is optimal if and only if ∇f(x⋆)⊤(y−x⋆)≥0 for every y∈K. Lesson 1’s necessary condition becomes sufficient. (Lesson 2’s projection onto a convex set is the case f(y)=21∥y−v∥2, and its variational inequality is exactly this.)
Local and global minima
Proof
(1) Let x⋆ be a local minimum and suppose some y has f(y)<f(x⋆). For small θ, point xθ=θy+(1−θ)x⋆ is arbitrarily close to x⋆, and f(xθ)≤θf(y)+(1−θ)f(x⋆)<f(x⋆), contradicting local minimality. (2) The minimizer set is {x:f(x)≤f⋆}, a sublevel, convex by the preceding theorem. (3) If distinct x1=x2 were minimizers, their midpoint would give f<f⋆. (4) This is the first-order consequence just seen.
∎
Point (1) saves the most work: no need to worry about a bad local minimum, so “finding a local minimum” and “solving the problem” are equivalent, and any descent algorithm converging to a stationary point is done. Point (4) also says optimality can be certified with one vector, the gradient, without comparison to any other point. The next lessons build on these statements.
Second-order condition
Proof
For x∈C and v∈Rn define restriction to a line g(t)=f(x+tv), with derivatives g′(t)=∇f(x+tv)⊤v and g′′(t)=v⊤∇2f(x+tv)v. Convexity of f is equivalent to convexity of every such restriction because the definition concerns segments.
(⇒) If g is convex, the first-order condition at s<t gives g′(s)(t−s)≤g(t)−g(s)≤g′(t)(t−s), so g′ is nondecreasing and g′′(0)≥0. Since C is open, this holds in every direction v and v⊤∇2f(x)v≥0.
If the Hessian is positive semidefinite, the last term is nonnegative and the first-order condition holds. If positive definite and x=y, it is strictly positive: the tangent lies strictly below, and repeating the first-order theorem’s (⇐) argument with strict inequalities yields strict convexity. ■
∎
The converse of the last statement is false: f(x)=x4 is strictly convex and f′′(0)=0. Thus positive definiteness is sufficient but not necessary for strict convexity. In practice calculate the Hessian, study its sign (with the Rayleigh quadratic form or spectrum), and conclude.
A catalog of convex functions
These examples recur throughout the course. Almost all can be checked with one of the two conditions.
Function
Domain
Why convex
21x⊤Ax+b⊤x+c
Rn
∇2f=A; convex iff A⪰0
eax, −logx, xlogx, ∣x∣p with p≥1
R, R++, R++, R
second derivatives a2eax, 1/x2, 1/x; for ∣x∣p, not C2 at 0 if p<2, derivative p∣x∣p−1sgnx (outside 0 if p=1) is nondecreasing
Any norm ∥x∥
Rn
triangle inequality and homogeneity: ∥θx+(1−θ)y∥≤θ∥x∥+(1−θ)∥y∥
max(x1,…,xn)
Rn
maximum of linear functions (see convexity calculus)
lse(x)=log∑iexi
Rn
∇2f=diag(p)−pp⊤ with p=softmax(x), positive semidefinite (exercise)
∑ixilogxi (negative entropy)
R++n
∇2f=diag(1/xi)≻0
−logdetX
S++n
restriction to lines, below
∥x∥2/t (quadratic-over-linear)
Rn×R++
supremum of linear functions, in convexity calculus
Three rows deserve comment. First, lse is a smooth maximum, maxixi≤lse(x)≤maxixi+logn (log-sum-exp), and its gradient is softmax. Second, negative entropy makes KL divergence convex in the distribution. Third, the matrix case:
Proof
By the preceding proof’s discussion, it suffices to show g(t)=−logdet(X+tV) is convex in t for X≻0 and symmetric V, on the interval where X+tV≻0. Let X−1/2VX−1/2=Qdiag(λ1,…,λn)Q⊤ be its eigendecomposition (spectral theorem). Then
and each −log(1+tλi) is convex in t (composition of −log with an affine function). ■
∎
Finally, a reminder of what convexity is not: f(x1,x2)=x1x2 is convex in each variable separately but not jointly convex, because Hessian [0110] has eigenvalues ±1. Convexity is a joint property.
Convexity calculus
Rarely do we check the definition or calculate a Hessian: we recognize a function as built from convex pieces and convexity-preserving operations. Convex programming modeling languages do this (“disciplined convex programming” in lesson 4), and it is the fastest way to check, for example, whether a loss is convex before training.
Proof
(1) and (2) follow in one line from the definition. (3) For each α, fα(θx+(1−θ)y)≤θfα(x)+(1−θ)fα(y)≤θsupαfα(x)+(1−θ)supαfα(y); take the supremum on the left. (This reflects that the epigraph of a supremum is the intersection of epigraphs.) (4) For convex g and convex nondecreasing h, h(g(θx+(1−θ)y))≤h(θg(x)+(1−θ)g(y)) by monotonicity of h, which is ≤θh(g(x))+(1−θ)h(g(y)) by convexity. Other cases are symmetric. (5) Given ε>0 and y1,y2∈D with f(xi,yi)≤infyf(xi,y)+ε, joint convexity in (x,y) gives
These rules generate almost the whole catalog. Norm ∥x∥2=sup∥u∥≤1u⊤x and coordinate maximum are suprema of linear functions (rule 3). Logistic loss log(1+e−yx⊤w)=lse(0,−yx⊤w) composes an affine map with lse (rule 2), so logistic regression with ℓ2 regularization is a nonnegative sum (rule 1) of convex functions. By rule 5, distance to a convex set, dist(x,C)=infy∈C∥x−y∥, is convex. Quadratic-over-linear ∥x∥2/t is the supremum over u of functions linear in (x,t) given by 2u⊤x−t∥u∥2 (the maximum is attained at u=x/t and equals ∥x∥2/t), so ∥x∥2/(1⊤x) is convex on the positive orthant: it composes that function with affine map x↦(x,1⊤x).
In the figure build an expression from blocks and watch rules propagate from leaves to root.
InteractiveConvex function builder
f(x)=e−x2
uncertified· ≥ 0
exp is increasing but its argument is concave: the rule is inconclusive (exp(−x²) is not convex).
concave
Changing sign exchanges convex and concave.
convex· ≥ 0
t² is convex and the argument is affine: affine composition preserves convexity.
affine
The variable is affine.
nonnegative second difference
negative second difference (nonconvex here)
Certified by the rulesuncertified
Numerical checkneither
Valid domain in [−3,3]100 %
Uncertified, as the plot confirms: neither convex nor concave. See the red areas, where the second difference is negative.
Compose an expression by choosing a block for each slot (up to depth 3). Each node shows certified curvature (convex, concave, affine or “uncertified”) and the rule used, propagating monotonicity and signs as in disciplined convex programming. Beside it, a numerical check on [−3,3] reports the truth. Try exp(x2) (certified), exp(−x2) (uncertified: exp is increasing but −x2 is concave, and the function is indeed nonconvex), and x2+1 built with ⋅ and + (uncertified yet convex), against block ⋅2+1 (certified: a norm of (x,1)). Rules are sufficient, not necessary.
The last example is the builder’s lesson: rules certify convexity when composition can be written with appropriate monotonicity; otherwise they are silent, not equivalent to “nonconvex.” A modeling program failing to certify your expression says “I cannot prove it using my rules,” and sometimes the right rewrite, e.g. x2+1=∥(x,1)∥2, a norm applied to an affine map, turns rejection into proof.
Strong convexity: a lower bound on curvature
Convexity only requires nonnegative curvature. To know how much, we need a bound. The natural idea is to subtract a parabola and still require convexity.
Proof
Let g(x)=f(x)−2μ∥x∥2, so ∇g(x)=∇f(x)−μx. By the first-order condition, g is convex if and only if g(y)≥g(x)+∇g(x)⊤(y−x). Expanding,
f(y)−2μ∥y∥2≥f(x)−2μ∥x∥2+∇f(x)⊤(y−x)−μx⊤(y−x),
and moving the parabolas to the other side and using ∥y∥2−∥x∥2−2x⊤(y−x)=∥y−x∥2 yields (2). Each step is an equivalence. For C2, ∇2g=∇2f−μI⪰0 is the second-order condition for g. Strong monotonicity follows by adding (2) for (x,y) and (y,x). ■
∎
Condition (2) is the tangent condition with a margin: the graph lies not only above the tangent, but above the parabola Tx(y)+2μ∥y−x∥2. Thus a parabola of curvature μ fits between a tangent and the function. For a quadratic 21x⊤Ax, the best value is the smallest eigenvalue, μ=λmin(A), by the Rayleigh quotient.
Two consequences justify the name “strong”. If x⋆ is the minimizer, the quadratic bound reveals the error f(x)−f⋆ and the gradient.
Proof
Existence. Bound (2) with x=0 gives f(y)≥f(0)−∥∇f(0)∥∥y∥+2μ∥y∥2→∞ as ∥y∥→∞: f is coercive and continuous, so it attains its minimum (existence of minimizers). Uniqueness.f is strictly convex because 2μ∥⋅∥2 is strictly convex and the sum of a convex and a strictly convex function is strictly convex; the preceding theorem applies.
Bounds. Putting x=x⋆ in (2) and using ∇f(x⋆)=0 gives the first inequality. For the second, minimize the right-hand side of (2) over y: the parabola y↦f(x)+∇f(x)⊤(y−x)+2μ∥y−x∥2 attains its minimum at y=x−∇f(x)/μ with value f(x)−∥∇f(x)∥2/(2μ), and since f(y)≥ this for every y, also at x⋆: f⋆≥f(x)−∥∇f(x)∥2/(2μ). Finally, strong monotonicity with y=x⋆ and Cauchy-Schwarz yield μ∥x−x⋆∥2≤∇f(x)⊤(x−x⋆)≤∥∇f(x)∥∥x−x⋆∥. ■
∎
The second inequality, f(x)−f⋆≤∥∇f(x)∥2/(2μ), is a stopping certificate: if the gradient is small, the value error is small. This is the Polyak-Łojasiewicz inequality, seen in lesson 8 as an assumption weaker than strong convexity and sufficient for linear convergence; it reappears in overparameterized networks.
Two sources of strong convexity appear repeatedly. A quadratic 21x⊤Ax with A≻0 is λmin(A)-strongly convex. Adding ℓ2 regularization to any convex function f makes it λ-strongly convex: f+2λ∥⋅∥2 has ∇2⪰λI. This is one reason ridge is much more stable than ordinary least squares: it adds λ to every eigenvalue of X⊤X (the smallest goes from zero to λ when X⊤X is singular, for example with more variables than data), turning the problem from “one minimum, or a valley of minima” into “one unique minimum”.
Smoothness: an upper bound on curvature
Strong convexity bounds curvature from below. Smoothness bounds it from above, and that bound tells us how far we can move in one step without overshooting.
Proof
By the fundamental theorem of calculus applied to t↦f(x+t(y−x)),
the integrand’s absolute value is bounded by Lt∥y−x∥2 (Cauchy-Schwarz and the assumption), whose integral is 2L∥y−x∥2. For the C2 characterization: if ∇f is L-Lipschitz, ∇2f(x)v=limt→0t∇f(x+tv)−∇f(x) has norm ≤L∥v∥, so the operator norm (operator norm) of ∇2f is ≤L. Conversely, the mean value inequality gives ∥∇f(y)−∇f(x)∥≤supz∇2f(z)2∥y−x∥. Since ∇2f is symmetric, ∇2f2=max∣λi∣ and the condition is equivalent to −LI⪯∇2f⪯LI. ■
∎
Thus a parabola of curvature L fits above between f and its tangent, just as one of curvature μ fits below. Together they form the sandwich: for a μ-strongly convex and L-smooth function,
and, if f is C2, in Hessian terms, μI⪯∇2f(x)⪯LI. The best constants are μ=infxλmin(∇2f(x)) and L=supxλmax(∇2f(x)). For a quadratic 21x⊤Ax they do not depend on the point: they are λmin(A) and λmax(A), by the Courant-Fischer theorem.
The figure shows the sandwich for functions of one variable. Drag x0 and check that the two parabolas tangent at x0 enclose f throughout the window. The limiting cases are instructive: the quartic is convex but has μ=0 (no lower curvature bound) and its L grows with the window (no global bound); absolute value is convex but not smooth (L=∞, the gradient jumps at zero); regularized logistic has both constants; and the nonconvex function has μ<0, so no convex parabola fits underneath.
InteractiveThe μ-L sandwich
f
lower parabola (curvature μ)
upper parabola (curvature L)
tangent
Curvature f′′(x) between μ and L
Constants
μ=inff′′0.145
L=supf′′0.350
κ=L/μ2.41
f′(x0)0.889
Lower bound at x0holds
Upper bound at x0holds
f(x)=log(1+ex)+2λx2 with λ=0.1: f′′∈(λ,λ+1/4] on the whole line.
For each function, parabolas tangent at x0 with curvatures μ (below) and L (above) enclose f. “Optimal” computes μ=inff′′ and L=supf′′ in the visible window. In “Manual”, raise μ above inff′′ or lower L below supf′′ and watch the parabola cross the function: the warning says which constant fails, and the readings show whether the bound is violated at the current x0 or x0 must be moved to see it. Choose x4/8: μ=0 and L depends on the window. Choose ∣x∣: no finite L exists. Try regularized logistic: f′′=σ(1−σ)+λ stays between λ and λ+1/4, and the ratio κ=L/μ is shown live.
What L does: the step limit
The upper bound lets us take a step with guarantees. If f is L-smooth and you take a descent step x+=x−η∇f(x), the quadratic upper bound gives
f(x+)≤f(x)−η(1−2Lη)∥∇f(x)∥2.
While η<2/L the value decreases (even if f is not convex), and with η=1/L it decreases as much as the bound guarantees, by 2L1∥∇f(x)∥2. This is the descent lemma of lesson 8, and its 2/L bound is tight: for f(x)=2Lx2 a step η>2/L amplifies the error at each iteration, since x+=(1−ηL)x with ∣1−ηL∣>1.
For convex functions, smoothness says more than the upper bound. The gradient is cocoercive.
Proof
Fix x and define φ(z)=f(z)−∇f(x)⊤z, convex and L-smooth, with ∇φ(x)=0, so x minimizes φ by convexity. Applying the upper bound for φ at y with step y−L1∇φ(y):
φ(x)≤φ(y−L1∇φ(y))≤φ(y)−2L1∥∇φ(y)∥2.
Substituting φ and ∇φ(y)=∇f(y)−∇f(x) yields the first inequality. The second follows by adding it to the inequality obtained by exchanging x and y. ■
∎
Notice the change in roles: monotonicity says ⟨Δ∇,Δx⟩≥0 (convexity) or ≥μ∥Δx∥2 (strong convexity); cocoercivity says ≥L1∥Δ∇∥2 (smooth and convex). Convexity plus smoothness is the assumption under which gradient descent converges with η<2/L and under which Nesterov proves its optimal rate.
Constants for regularized logistic loss
The case you will use most in practice is logistic regression with ℓ2 regularization. Given X∈Rn×d with rows xi⊤, labels yi∈{−1,+1} and λ>0,
where D(w)=diag(σ(zi)(1−σ(zi))) and zi=yixi⊤w (the second derivative of log(1+e−z) is σ(z)(1−σ(z)) and does not depend on the sign of yi because yi2=1).
Proof
Since 0<σ(z)(1−σ(z))≤41, we have 0⪯D⪯41I and hence 0⪯n1X⊤DX⪯4n1X⊤X, whose largest eigenvalue is ∥X∥22/(4n). Adding λI gives the sandwich λI⪯∇2f⪯(λ+∥X∥22/4n)I. At w=0, D=41I and the upper bound is an equality; with w=tv and t→∞, D→0 and ∇2f→λI. ■
∎
Two messages. The data do not enter μ: regularization fixes it. Without it (λ=0), μ=0 and with linearly separable data the minimizer does not even exist (the loss tends to zero as ∥w∥→∞). And L grows with the data scale, ∥X∥22: this is why features are normalized before training, otherwise the step must be reduced.
The condition number
The two constants, μ and L, enter all convergence results in the same way: through their ratio.
It measures the landscape’s elongation. Level curves of a quadratic are ellipses with semiaxes ∝1/λi, so the ratio of long to short axis is κ. With κ=1 they are circles and the gradient points directly to the minimum; with large κ they are narrow ellipses, the gradient points almost perpendicular to the valley, and gradient descent zigzags. When κ=1 a single step with η=1/L reaches the minimum. The larger κ, the more steps are needed, linearly, and the figure measures this with an actual count (not a formula).
InteractiveBowls and condition number
contours of f
gradient descent
starting point x0
Step
κ=L/μ9.00
λmax(A)/λmin(A) from entries9.00
A[7.00, 3.46; 3.46, 3.00]
Semiaxis ratio κ3.00
Steps until f≤10−6f(x0)55
Theoretical factor per step for f−f⋆0.8889
Rotate the bowl: the entries of A change, but its eigenvalues and κ do not. Increase L and watch the valley narrow.
A quadratic f(x)=21x⊤Ax whose eigenvalues μ and L you control with sliders. Level curves change from circles (κ=1) to elongated ellipses. Axis rotation: rotate the bowl; A changes entries but κ does not, as confirmed by the ratio λmax/λmin calculated from the entries. Drag the gradient descent starting point, choose the step rule and see how the step count to f≤10−6f(x0) changes. With η=1/L the general guarantee is that f−f⋆ is multiplied by at most 1−1/κ at each step, and with η=2/(L+μ) the distance to the minimum is multiplied by (κ−1)/(κ+1).
Two properties are visible directly in the figure. κdoes not depend on rotation of the axes: A and QAQ⊤ have the same spectrum, and gradient descent, which is rotation invariant, behaves identically. And κdoes depend on the relative scale of variables: if you change the units of one coordinate (a change of variables x=Sz with diagonal S) the function z↦f(Sz) has Hessian SAS and a different κ. Choosing S to reduce κ is preconditioning, and the lessons on Adam and adaptive methods catalog ways to do it.
Why does κ control speed? The quadratic shows it in one line. Gradient descent xk+1=xk−ηAxk satisfies xk+1−x⋆=(I−ηA)(xk−x⋆), and the eigenvalues of I−ηA lie in [1−ηL,1−ημ]. With η=2/(L+μ) that interval is [−κ+1κ−1,κ+1κ−1] and therefore
∥xk−x⋆∥≤(κ+1κ−1)k∥x0−x⋆∥.
To reduce the distance by a factor of 10−6, k=ln106/lnκ−1κ+1 steps suffice: 12.6 with κ=2, 68.8 with κ=10, 690.8 with κ=100 and 6907.8 with κ=1000. As lnκ−1κ+1≈2/κ for large κ, this is k≈2κln106≈6.9κ: linear in κ. The result for every strongly convex and smooth function, not just quadratics, is the subject of lesson 8.
Extensions: quasiconvexity and log-concavity
Two generalizations appear in probability and economics; it helps to know what they preserve and what they lose.
A function is quasiconvex if all its sublevel sets {f≤α} are convex (equivalent to f(θx+(1−θ)y)≤max(f(x),f(y))). Every convex function is quasiconvex, as are x3 and ∣x∣, although neither is convex. What is lost is essential: x3 has f′(0)=0 but no minimum at 0. The first-order condition is no longer sufficient.
A density p≥0 is log-concave if logp is concave (with convention log0=−∞, making its support convex), that is, if −logp is convex. The Gaussian is log-concave: −logp(x)=21(x−m)⊤Σ−1(x−m)+const. So are uniform densities on a convex set, the exponential and logistic densities. The most useful consequence: if a model is log-concave in its parameter, the negative log-likelihood is convex and maximum likelihood estimation is a convex problem, as in logistic regression and Gaussian linear regression. (A Gaussian mixture’s likelihood, on the other hand, is not log-concave in its parameters, starting with the means, so its negative log-likelihood has local minima.)
Implementation from scratch
Before trusting a bound, or using a step η=1/L, it helps to measure. We start with a convexity falsifier that tests both inequalities, the chord and tangent inequalities, on random pairs. As in the preceding lesson, a violation refutes convexity, while no violations only says we have not found one.
The three convex functions yield 0.000 on both tests, and the three nonconvex ones violate both with clearly positive percentages: 50% of pairs for x1x2, 74% for e−∥x∥2, and 13% for the cosine function. The two tests are equivalent for differentiable functions and fail almost as often (not exactly: each looks at a different region of pairs). The tangent test has the advantage of comparing a point with its gradient, without choosing a third intermediate point.
Now we measure the constants μ and L for regularized logistic loss. The Hessian is n1X⊤DX+λI and the theorem says its spectrum lives in [λ,λ+∥X∥22/(4n)]. We sample many points w at different scales and record the smallest and largest eigenvalues.
[ ]μ and L for regularized logistic lossBrowser
import numpy as np
rng = np.random.default_rng(1)
n, d, lam = 200, 5, 0.1
X = rng.normal(size=(n, d))
y = np.where(X @ rng.normal(size=d) + 0.5 * rng.normal(size=n) > 0, 1.0, -1.0)
def sigma(z): return 1 / (1 + np.exp(-z))
def f(w): return np.mean(np.logaddexp(0.0, -y * (X @ w))) + 0.5 * lam * w @ w
def grad(w): return -(X.T @ (y * sigma(-y * (X @ w)))) / n + lam * w
def hess(w):
s = sigma(X @ w)
return (X.T * (s * (1 - s))) @ X / n + lam * np.eye(d)
mu_teo, L_teo = lam, lam + np.linalg.norm(X, 2) ** 2 / (4 * n)
print(f"cotas analíticas: mu = lambda = {mu_teo:.4f}, L = lambda + ||X||^2/(4n) = {L_teo:.4f}, kappa = {L_teo / mu_teo:.2f}")
print(f"{'radio de muestreo':>18s}{'min lambda_min':>16s}{'max lambda_max':>16s}")
for r in (0.0, 0.5, 2.0, 10.0, 50.0, 200.0):
ws = rng.normal(size=(2000, d)) * r / np.sqrt(d)
espectros = np.array([np.linalg.eigvalsh(hess(w)) for w in ws])
print(f"{r:18.1f}{espectros[:, 0].min():16.4f}{espectros[:, -1].max():16.4f}")
The output tells an important story. At radius 0 (only point w=0), λmax matches the analytic bound L: logistic’s second derivative is maximal there, 41. But the measured λmin is greater than λ and only approaches it as the radius grows, because σ(1−σ)→0 far from the origin. An estimator of μ sampling near the origin overestimates μ, and one for L sampling far from the origin underestimatesL. This asymmetry motivates the last common error in the lesson.
The third piece is the L estimator from the exercises: ratios ∥∇f(x)−∇f(y)∥/∥x−y∥ over random pairs. By definition of L as a supremum, any ratio is a lower bound, and the maximum of many ratios is also a lower bound that grows with the number of pairs. With it we construct the step η=1/L^ and compare it with the true one.
[ ]Estimating L from pairs and the risk of an estimated 1/L stepBrowser
import numpy as np
rng = np.random.default_rng(2)
n, d, lam = 200, 5, 0.1
X = rng.normal(size=(n, d))
y = np.where(X @ rng.normal(size=d) + 0.5 * rng.normal(size=n) > 0, 1.0, -1.0)
sigma = lambda z: 1 / (1 + np.exp(-z))
f = lambda w: np.mean(np.logaddexp(0.0, -y * (X @ w))) + 0.5 * lam * w @ w
grad = lambda w: -(X.T @ (y * sigma(-y * (X @ w)))) / n + lam * w
L_true = lam + np.linalg.norm(X, 2) ** 2 / (4 * n)
def estimate_lipschitz_lower(grad, sampler, n_pairs):
"""Máximo de ||grad f(x) - grad f(y)|| / ||x - y|| en n_pairs pares.
Es solo una cota INFERIOR de L, que es un supremo sobre TODOS los pares: no vemos los pares no muestreados."""
best = 0.0
for _ in range(n_pairs):
a, b = sampler(), sampler()
best = max(best, np.linalg.norm(grad(a) - grad(b)) / np.linalg.norm(a - b))
return best
def gd(eta, steps=60):
w = np.ones(d) * 3.0
vals = [f(w)]
for _ in range(steps):
w = w - eta * grad(w)
vals.append(f(w))
return vals
print(f"L verdadera = {L_true:.4f}")
for escala, etiqueta in ((0.1, "cerca de 0"), (20.0, "lejos de 0")):
sampler = lambda: rng.normal(size=d) * escala
for n_pairs in (5, 50, 500):
print(f"pares {etiqueta:11s} n={n_pairs:4d}: L_hat = {estimate_lipschitz_lower(grad, sampler, n_pairs):.4f}")
L_hat = estimate_lipschitz_lower(grad, lambda: rng.normal(size=d) * 20.0, 200)
for nombre, eta in (("1/L verdadera", 1 / L_true), ("1/L_hat (pares lejanos)", 1 / L_hat)):
v = gd(eta)
print(f"{nombre:26s} eta = {eta:7.3f} f_final = {v[-1]:.3e} ¿monótona?: {all(b <= a + 1e-12 for a, b in zip(v, v[1:]))}")
Ratios near the origin approach L from below with few pairs; ratios taken far from the origin never see the high-curvature region and give an L^ near λ. The resulting step 1/L^≈8.5 exceeds 2/L≈5.0, so descent ceases to be monotonic and after 60 steps is worse than with the correct step (f≈1.10 versus 0.45), whereas with 1/L≈2.5 the value decreases at each iteration. The lesson: sampling-based estimation of L is a starting heuristic (for example to choose the first step), not a guarantee; practical algorithms supplement it with line search (lesson 7).
The library version
With a library we can calculate the exact Hessian without writing derivatives and study its spectrum. In PyTorch, torch.autograd.functional.hessian(f, w) and, in JAX, jax.hessian(f)(w) each take one line. For convex functions, cvxpy implements the convexity calculus in this topic: expr.is_convex() applies the rules (“disciplined convex programming”) and returns False when it cannot certify, like the figure’s builder.
import numpy as np, torch, cvxpy as cp# Hessiano exacto de la pérdida logística, sin escribirlo a mano# (loss, X, y, lam y w0 como en las celdas anteriores, pero con tensores de torch)H = torch.autograd.functional.hessian(lambda w: loss(w, X, y, lam), w0)print(torch.linalg.eigvalsh(H)) # mu <= lambda_min, lambda_max <= Lx = cp.Variable(3)print(cp.log_sum_exp(x).is_convex()) # Trueprint(cp.exp(-cp.sum_squares(x)).is_convex()) # False: la regla de composición no se cumpleprint(cp.sqrt(cp.sum_squares(x) + 1).is_convex()) # False, pero cp.norm(cp.hstack([x, np.ones(1)])) sí es convexa
In the browser, with scipy and sympy, we can check two things using an independent library: that lse’s symbolic Hessian is as stated in the exercise, and that a general optimizer minimizingλmin(∇2f(w)) heads towards λ, the unattained infimum.
[ ]With sympy and scipy: symbolic lse and the infimum of lambda_minBrowser
import numpy as np, sympy as sp
from scipy.optimize import minimize
# 1) Hessiano simbólico de lse en R^3 frente a diag(p) - p p^T
x = sp.symbols("x1 x2 x3")
lse = sp.log(sum(sp.exp(xi) for xi in x))
H = sp.hessian(lse, x)
p = [sp.exp(xi) / sum(sp.exp(xj) for xj in x) for xi in x]
P = sp.Matrix(3, 3, lambda i, j: (p[i] if i == j else 0) - p[i] * p[j])
print("Hessiano simbólico = diag(p) - p p^T:", sp.simplify(H - P) == sp.zeros(3, 3))
# 2) Autovalor mínimo del Hessiano logístico a lo largo de un rayo w = t v
rng = np.random.default_rng(3)
n, d, lam = 100, 4, 0.1
X = rng.normal(size=(n, d))
sigma = lambda z: 1 / (1 + np.exp(-z))
def lmin(w):
s = sigma(X @ w)
return np.linalg.eigvalsh((X.T * (s * (1 - s))) @ X / n + lam * np.eye(d))[0]
res = minimize(lmin, rng.normal(size=d), method="Nelder-Mead", options={"xatol": 1e-9, "fatol": 1e-12, "maxiter": 4000})
print(f"min lambda_min encontrado = {res.fun:.6f} en ||w|| = {np.linalg.norm(res.x):.1f} (lambda = {lam})")
Common mistakes
Exercises
ProofConvexity and tangents
Prove: Let f be differentiable on an open convex set C. Prove that f is convex if and only if f(y)≥f(x)+∇f(x)⊤(y−x) for all x,y∈C.
0
The two implications use different ideas: one uses a limit of difference quotients and the other chooses carefully where to apply the inequality.
Step 1 of 4. For (⇒), what is the first step?
Prooflog-sum-exp is convex
Prove: Prove that lse(x)=log∑i=1nexi is convex on Rn by calculating its Hessian.
0
With p=softmax(x), that is, pi=exi/∑jexj, calculate the gradient and then the Hessian, and prove it is positive semidefinite.
Step 1 of 3. What is the gradient of lse?
NumericCondition number of a quadratic
Calculate the condition number κ of f(x)=21x⊤Ax with A=[10221].
QuizWhich are convex?
Which of these functions are convex on the indicated domain?
More than one answer may be correct.
QuizStrict, strong, smooth
Which of these statements are true?
More than one answer may be correct.
Numericκ for ridge least squares
For f(x)=21∥Ax−b∥22+2λ∥x∥22 with A=210011 and λ=0.5, calculate the condition number κ=L/μ.
NumericThe maximum guaranteed step
For regularized logistic loss with one data point, n=1, x1=(3) (a scalar, d=1) and λ=0.2, calculate 2/L, the largest step for which gradient descent decreases f at each iteration according to the quadratic upper bound.
CodeEstimate L from below
Implement estimate_lipschitz_lower(grad, sampler, n_pairs): take n_pairs pairs of points with sampler() and return the maximum of ∥∇f(x)−∇f(y)∥2/∥x−y∥2. Add a comment explaining why the result is only a lower bound on $L$. If the two points in a pair coincide, discard the pair.
import numpy as np
def estimate_lipschitz_lower(grad, sampler, n_pairs):
"""Máximo de ||grad(x) - grad(y)|| / ||x - y|| sobre n_pairs pares aleatorios."""
# tu código: bucle sobre los pares, calcula el cociente y quédate con el mayor.
# Comentario obligatorio: ¿por qué esto es solo una cota inferior de L?
return 0.0
Shift+Enter to run
Summary
Key idea
A function is convex if its chords lie above it, equivalent to its tangents lying below it (first order) and its Hessian being positive semidefinite (second order): every local minimum is therefore global and a zero gradient certifies the optimum. Strong convexity (μ) and smoothness (L) quantify curvature below and above, sandwich the function between two parabolas and fix the step limit (η<2/L); their ratio κ=L/μ measures landscape elongation and governs the speed of first-order methods.