Module contents
Lesson 3 of 27Core 100 min

Convex functions, strong convexity and smoothness

Characterize convexity, strong convexity and smoothness and their consequences for optimization.

After this lesson you can

  • Prove equivalence of the chord definition and first- and second-order conditions for differentiable functions.
  • Prove convexity of composite functions including log-sum-exp, norms, maxima of affine functions and minus log determinant using composition rules.
  • Prove that every local minimum of a convex function is global and the minimizer set is convex.
  • State quadratic lower and upper bounds defining μ-strong convexity and L-smoothness.
  • Calculate μ and L for quadratics and regularized logistic loss from the Hessian spectrum.

Before you start

Motivation: from a gradient to a global guarantee

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: 12∥Xw−y∥22+λ2∥w∥22\tfrac12\norm{\mat{X}\vb{w} - \vb{y}}_2^2 + \tfrac{\lambda}{2}\norm{\vb{w}}_2^2 is quadratic with Hessian X⊤X+λI\mat{X}\T\mat{X} + \lambda\mat{I}.
  • Regularized logistic regression: 1n∑ilog⁡(1+e−yixi⊤w)+λ2∥w∥2\frac1n\sum_i\log(1 + e^{-y_i\vb{x}_i\T\vb{w}}) + \frac\lambda2\norm{\vb{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 μ\mu (minimum curvature) and smoothness LL (maximum curvature), sandwich the function between two parabolas, and their ratio κ=L/μ\kappa = L/\mu 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))(\vb{x}, f(\vb{x})) and (y,f(y))(\vb{y}, f(\vb{y})), chord value at intermediate point θx+(1−θ)y\theta\vb{x} + (1 - \theta)\vb{y} is θf(x)+(1−θ)f(y)\theta f(\vb{x}) + (1 - \theta) f(\vb{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 ff is convex and (x,s),(y,t)∈epi⁡f(\vb{x}, s), (\vb{y}, t) \in \operatorname{epi} f, then f(θx+(1−θ)y)≤θf(x)+(1−θ)f(y)≤θs+(1−θ)tf(\theta\vb{x} + (1 - \theta)\vb{y}) \le \theta f(\vb{x}) + (1 - \theta) f(\vb{y}) \le \theta s + (1 - \theta) t, so the points’ convex combination lies in the epigraph. Conversely, if the epigraph is convex, (x,f(x))(\vb{x}, f(\vb{x})) and (y,f(y))(\vb{y}, f(\vb{y})) lie in it, hence so does (θx+(1−θ)y, θf(x)+(1−θ)f(y))(\theta\vb{x} + (1 - \theta)\vb{y},\ \theta f(\vb{x}) + (1 - \theta) f(\vb{y})), exactly the inequality. A sublevel is the epigraph intersected with hyperplane {t=α}\{t = \alpha\} and projected onto Rn\R^n; convex intersections and projections are convex.

∎

The converse of the second statement is false: f(x)=x3f(x) = x^3 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:

  1. Chords (definition): the segment joining two graph points lies above it.
  2. Tangents (first order): if ff is differentiable, the tangent line (hyperplane) at any point lies below the graph everywhere.
  3. Curvature (second order): if ff is twice differentiable, f′′≥0f'' \ge 0 (in several variables, ∇2f⪰0\hess f \succeq \mat{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 aa and bb on either side of the central maximum and inspect the violation. Switch to tangent and drag cc 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′′<0f'' < 0 in (−1,1)(-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
  • ff (drag the gray nodes)
  • chord
  • violation
Curvature f′′(x)f''(x): blue where nonnegative, red where negative
Where each test fails (red = fails): the negative curvature region lies inside the other two
negative curvaturetangent at that point lies abovea chord starts there and lies below
Test
0.50
θf(a)+(1−θ)f(b)\theta f(a) + (1-\theta) f(b)−0.899
f(θa+(1−θ)b)f(\theta a + (1-\theta) b)0.000
Chord minus function−0.899
Chords: all passno
Tangents: all passno
f′′≥0f'' \ge 0 throughout the intervalno
All three tests fail. f′′<0f'' < 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 aa, bb and slider θ\theta: the chord must lie above ff; red marks where it does not. Tangent: drag cc: the tangent must lie below ff everywhere (reading min⁡x[f(x)−Tc(x)]\min_x[f(x) - T_c(x)] must be ≥0\ge 0). Curvature: drag cc and read f′′(c)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/8f(x) = x^4/8, f′′(0)=0f''(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)=0f''(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 kk; k=2k = 2 is the definition. If θk=1\theta_k = 1 there is nothing to prove. Otherwise ∑iθixi=(1−θk)q+θkxk\sum_i\theta_i\vb{x}_i = (1 - \theta_k)\vb{q} + \theta_k\vb{x}_k with q=∑i<kθi1−θkxi\vb{q} = \sum_{i<k}\frac{\theta_i}{1 - \theta_k}\vb{x}_i a convex combination of k−1k - 1 points. Applying the definition then the induction hypothesis to q\vb{q},

f(∑i≤kθixi)≤(1−θk)f(q)+θkf(xk)≤(1−θk)∑i<kθi1−θkf(xi)+θkf(xk)=∑i≤kθif(xi).■f\Big(\sum_{i\le k}\theta_i\vb{x}_i\Big) \le (1 - \theta_k) f(\vb{q}) + \theta_k f(\vb{x}_k) \le (1 - \theta_k)\sum_{i<k}\frac{\theta_i}{1 - \theta_k}f(\vb{x}_i) + \theta_k f(\vb{x}_k) = \sum_{i \le k}\theta_i f(\vb{x}_i). \qquad\blacksquare∎

Weights θi\theta_i form a probability distribution on kk points, and the inequality says f(E[X])≤E[f(X)]f(\E[X]) \le \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

(⇒\Rightarrow) For θ∈(0,1]\theta \in (0, 1], convexity gives f(x+θ(y−x))≤(1−θ)f(x)+θf(y)f(\vb{x} + \theta(\vb{y} - \vb{x})) \le (1 - \theta) f(\vb{x}) + \theta f(\vb{y}), i.e.

f(x+θ(y−x))−f(x)θ≤f(y)−f(x).\frac{f(\vb{x} + \theta(\vb{y} - \vb{x})) - f(\vb{x})}{\theta} \le f(\vb{y}) - f(\vb{x}).

As θ→0+\theta \to 0^+ the left side tends to directional derivative ∇f(x)⊤(y−x)\grad f(\vb{x})\T(\vb{y} - \vb{x}), leaving ∇f(x)⊤(y−x)≤f(y)−f(x)\grad f(\vb{x})\T(\vb{y} - \vb{x}) \le f(\vb{y}) - f(\vb{x}).

(⇐\Leftarrow) This is the lesson’s first proof exercise: apply the condition at intermediate point z=θx+(1−θ)y\vb{z} = \theta\vb{x} + (1 - \theta)\vb{y} toward x\vb{x} and y\vb{y} and combine both inequalities with weights θ\theta and 1−θ1 - \theta.

∎

The first half has a geometric interpretation: a convex function’s difference quotient is nondecreasing in θ\theta, so tangent slope (the limit as θ→0+\theta \to 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)(\vb{x}, \vb{y}) and (y,x)(\vb{y}, \vb{x}) gives gradient monotonicity, (∇f(x)−∇f(y))⊤(x−y)≥0(\grad f(\vb{x}) - \grad f(\vb{y}))\T(\vb{x} - \vb{y}) \ge 0: in one variable, f′f' is nondecreasing.
  • If ∇f(x⋆)=0\grad f(\vb{x}^\star) = \vb{0}, the lower bound is constant f(x⋆)f(\vb{x}^\star), so f(y)≥f(x⋆)f(\vb{y}) \ge f(\vb{x}^\star) for every y\vb{y}: a stationary point of a convex function is a global minimum.
  • For the same reason, to minimize ff over convex KK (with ff convex and differentiable on an open set containing KK), x⋆∈K\vb{x}^\star \in K is optimal if and only if ∇f(x⋆)⊤(y−x⋆)≥0\grad f(\vb{x}^\star)\T(\vb{y} - \vb{x}^\star) \ge 0 for every y∈K\vb{y} \in K. Lesson 1’s necessary condition becomes sufficient. (Lesson 2’s projection onto a convex set is the case f(y)=12∥y−v∥2f(\vb{y}) = \tfrac12\norm{\vb{y} - \vb{v}}^2, and its variational inequality is exactly this.)

Local and global minima

Proof

(1) Let x⋆\vb{x}^\star be a local minimum and suppose some y\vb{y} has f(y)<f(x⋆)f(\vb{y}) < f(\vb{x}^\star). For small θ\theta, point xθ=θy+(1−θ)x⋆\vb{x}_\theta = \theta\vb{y} + (1 - \theta)\vb{x}^\star is arbitrarily close to x⋆\vb{x}^\star, and f(xθ)≤θf(y)+(1−θ)f(x⋆)<f(x⋆)f(\vb{x}_\theta) \le \theta f(\vb{y}) + (1 - \theta) f(\vb{x}^\star) < f(\vb{x}^\star), contradicting local minimality. (2) The minimizer set is {x:f(x)≤f⋆}\{\vb{x} : f(\vb{x}) \le f^\star\}, a sublevel, convex by the preceding theorem. (3) If distinct x1≠x2\vb{x}_1 \ne \vb{x}_2 were minimizers, their midpoint would give f<f⋆f < f^\star. (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\vb{x} \in C and v∈Rn\vb{v} \in \R^n define restriction to a line g(t)=f(x+tv)g(t) = f(\vb{x} + t\vb{v}), with derivatives g′(t)=∇f(x+tv)⊤vg'(t) = \grad f(\vb{x} + t\vb{v})\T\vb{v} and g′′(t)=v⊤∇2f(x+tv)vg''(t) = \vb{v}\T\hess f(\vb{x} + t\vb{v})\vb{v}. Convexity of ff is equivalent to convexity of every such restriction because the definition concerns segments.

(⇒\Rightarrow) If gg is convex, the first-order condition at s<ts < t gives g′(s)(t−s)≤g(t)−g(s)≤g′(t)(t−s)g'(s)(t - s) \le g(t) - g(s) \le g'(t)(t - s), so g′g' is nondecreasing and g′′(0)≥0g''(0) \ge 0. Since CC is open, this holds in every direction v\vb{v} and v⊤∇2f(x)v≥0\vb{v}\T\hess f(\vb{x})\vb{v} \ge 0.

(⇐\Leftarrow) Let x,y∈C\vb{x}, \vb{y} \in C and v=y−x\vb{v} = \vb{y} - \vb{x}. Taylor’s formula with remainder for gg gives g(1)=g(0)+g′(0)+12g′′(ξ)g(1) = g(0) + g'(0) + \tfrac12 g''(\xi) for some ξ∈(0,1)\xi \in (0, 1), i.e.

f(y)=f(x)+∇f(x)⊤(y−x)+12(y−x)⊤∇2f(z)(y−x)with z∈[x,y].f(\vb{y}) = f(\vb{x}) + \grad f(\vb{x})\T(\vb{y} - \vb{x}) + \tfrac12(\vb{y} - \vb{x})\T\hess f(\vb{z})(\vb{y} - \vb{x}) \quad\text{with } \vb{z} \in [\vb{x}, \vb{y}].

If the Hessian is positive semidefinite, the last term is nonnegative and the first-order condition holds. If positive definite and x≠y\vb{x} \ne \vb{y}, it is strictly positive: the tangent lies strictly below, and repeating the first-order theorem’s (⇐\Leftarrow) argument with strict inequalities yields strict convexity. ■\blacksquare

∎

The converse of the last statement is false: f(x)=x4f(x) = x^4 is strictly convex and f′′(0)=0f''(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.

FunctionDomainWhy convex
12x⊤Ax+b⊤x+c\tfrac12\vb{x}\T\mat{A}\vb{x} + \vb{b}\T\vb{x} + cRn\R^n∇2f=A\hess f = \mat{A}; convex iff A⪰0\mat{A} \succeq \mat{0}
eaxe^{ax}, −log⁡x-\log x, xlog⁡xx\log x, ∣x∣p\abs{x}^p with p≥1p \ge 1R\R, R++\R_{++}, R++\R_{++}, R\Rsecond derivatives a2eaxa^2e^{ax}, 1/x21/x^2, 1/x1/x; for ∣x∣p\abs{x}^p, not C2C^2 at 00 if p<2p < 2, derivative p∣x∣p−1sgn⁡xp\abs{x}^{p-1}\operatorname{sgn}x (outside 00 if p=1p = 1) is nondecreasing
Any norm ∥x∥\norm{\vb{x}}Rn\R^ntriangle inequality and homogeneity: ∥θx+(1−θ)y∥≤θ∥x∥+(1−θ)∥y∥\norm{\theta\vb{x} + (1-\theta)\vb{y}} \le \theta\norm{\vb{x}} + (1-\theta)\norm{\vb{y}}
max⁡(x1,…,xn)\max(x_1, \dots, x_n)Rn\R^nmaximum of linear functions (see convexity calculus)
lse⁡(x)=log⁡∑iexi\operatorname{lse}(\vb{x}) = \log\sum_i e^{x_i}Rn\R^n∇2f=diag⁡(p)−pp⊤\hess f = \operatorname{diag}(\vb{p}) - \vb{p}\vb{p}\T with p=softmax⁡(x)\vb{p} = \softmax(\vb{x}), positive semidefinite (exercise)
∑ixilog⁡xi\sum_i x_i\log x_i (negative entropy)R++n\R^n_{++}∇2f=diag⁡(1/xi)≻0\hess f = \operatorname{diag}(1/x_i) \succ \mat{0}
−log⁡det⁡X-\log\det\mat{X}S++n\mathbb{S}^n_{++}restriction to lines, below
∥x∥2/t\norm{\vb{x}}^2/t (quadratic-over-linear)Rn×R++\R^n \times \R_{++}supremum of linear functions, in convexity calculus

Three rows deserve comment. First, lse⁡\operatorname{lse} is a smooth maximum, max⁡ixi≤lse⁡(x)≤max⁡ixi+log⁡n\max_i x_i \le \operatorname{lse}(\vb{x}) \le \max_i x_i + \log n (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)=−log⁡det⁡(X+tV)g(t) = -\log\det(\mat{X} + t\mat{V}) is convex in tt for X≻0\mat{X} \succ \mat{0} and symmetric V\mat{V}, on the interval where X+tV≻0\mat{X} + t\mat{V} \succ \mat{0}. Let X−1/2VX−1/2=Qdiag⁡(λ1,…,λn)Q⊤\mat{X}^{-1/2}\mat{V}\mat{X}^{-1/2} = \mat{Q}\operatorname{diag}(\lambda_1, \dots, \lambda_n)\mat{Q}\T be its eigendecomposition (spectral theorem). Then

g(t)=−log⁡det⁡(X1/2(I+tX−1/2VX−1/2)X1/2)=−log⁡det⁡X−∑i=1nlog⁡(1+tλi),g(t) = -\log\det\big(\mat{X}^{1/2}(\mat{I} + t\mat{X}^{-1/2}\mat{V}\mat{X}^{-1/2})\mat{X}^{1/2}\big) = -\log\det\mat{X} - \sum_{i=1}^{n}\log(1 + t\lambda_i),

and each −log⁡(1+tλi)-\log(1 + t\lambda_i) is convex in tt (composition of −log⁡-\log with an affine function). ■\blacksquare

∎

Finally, a reminder of what convexity is not: f(x1,x2)=x1x2f(x_1, x_2) = x_1x_2 is convex in each variable separately but not jointly convex, because Hessian [0110]\begin{bmatrix}0 & 1\\ 1 & 0\end{bmatrix} has eigenvalues ±1\pm 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 α\alpha, fα(θx+(1−θ)y)≤θfα(x)+(1−θ)fα(y)≤θsup⁡αfα(x)+(1−θ)sup⁡αfα(y)f_\alpha(\theta\vb{x} + (1-\theta)\vb{y}) \le \theta f_\alpha(\vb{x}) + (1-\theta)f_\alpha(\vb{y}) \le \theta\sup_\alpha f_\alpha(\vb{x}) + (1-\theta)\sup_\alpha f_\alpha(\vb{y}); take the supremum on the left. (This reflects that the epigraph of a supremum is the intersection of epigraphs.) (4) For convex gg and convex nondecreasing hh, h(g(θx+(1−θ)y))≤h(θg(x)+(1−θ)g(y))h(g(\theta\vb{x} + (1-\theta)\vb{y})) \le h(\theta g(\vb{x}) + (1-\theta)g(\vb{y})) by monotonicity of hh, which is ≤θh(g(x))+(1−θ)h(g(y))\le \theta h(g(\vb{x})) + (1-\theta)h(g(\vb{y})) by convexity. Other cases are symmetric. (5) Given ε>0\eps > 0 and y1,y2∈D\vb{y}_1, \vb{y}_2 \in D with f(xi,yi)≤inf⁡yf(xi,y)+εf(\vb{x}_i, \vb{y}_i) \le \inf_{\vb{y}} f(\vb{x}_i, \vb{y}) + \eps, joint convexity in (x,y)(\vb{x}, \vb{y}) gives

inf⁡yf(θx1+(1−θ)x2,y)≤f(θ(x1,y1)+(1−θ)(x2,y2))≤θinf⁡yf(x1,y)+(1−θ)inf⁡yf(x2,y)+ε,\inf_{\vb{y}} f(\theta\vb{x}_1 + (1-\theta)\vb{x}_2, \vb{y}) \le f\big(\theta(\vb{x}_1, \vb{y}_1) + (1-\theta)(\vb{x}_2, \vb{y}_2)\big) \le \theta\inf_{\vb{y}} f(\vb{x}_1, \vb{y}) + (1-\theta)\inf_{\vb{y}} f(\vb{x}_2, \vb{y}) + \eps,

and take ε→0\eps \to 0.

∎

These rules generate almost the whole catalog. Norm ∥x∥2=sup⁡∥u∥≤1u⊤x\norm{\vb{x}}_2 = \sup_{\norm{\vb{u}} \le 1}\vb{u}\T\vb{x} and coordinate maximum are suprema of linear functions (rule 3). Logistic loss log⁡(1+e−yx⊤w)=lse⁡(0,−yx⊤w)\log(1 + e^{-y\vb{x}\T\vb{w}}) = \operatorname{lse}(0, -y\vb{x}\T\vb{w}) composes an affine map with lse (rule 2), so logistic regression with ℓ2\ell_2 regularization is a nonnegative sum (rule 1) of convex functions. By rule 5, distance to a convex set, dist⁡(x,C)=inf⁡y∈C∥x−y∥\operatorname{dist}(\vb{x}, C) = \inf_{\vb{y} \in C}\norm{\vb{x} - \vb{y}}, is convex. Quadratic-over-linear ∥x∥2/t\norm{\vb{x}}^2/t is the supremum over u\vb{u} of functions linear in (x,t)(\vb{x}, t) given by 2u⊤x−t∥u∥22\vb{u}\T\vb{x} - t\norm{\vb{u}}^2 (the maximum is attained at u=x/t\vb{u} = \vb{x}/t and equals ∥x∥2/t\norm{\vb{x}}^2/t), so ∥x∥2/(1⊤x)\norm{\vb{x}}^2/(\vb{1}\T\vb{x}) is convex on the positive orthant: it composes that function with affine map x↦(x,1⊤x)\vb{x} \mapsto (\vb{x}, \vb{1}\T\vb{x}).

In the figure build an expression from blocks and watch rules propagate from leaves to root.

InteractiveConvex function builder
f(x)=e−x2f(x) = e^{-x^{2}}
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][-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][-3, 3] reports the truth. Try exp⁡(x2)\exp(x^2) (certified), exp⁡(−x2)\exp(-x^2) (uncertified: exp⁡\exp is increasing but −x2-x^2 is concave, and the function is indeed nonconvex), and x2+1\sqrt{x^2 + 1} built with ⋅\sqrt{\cdot} and ++ (uncertified yet convex), against block ⋅2+1\sqrt{\cdot^2 + 1} (certified: a norm of (x,1)(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\sqrt{x^2 + 1} = \norm{(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∥2g(\vb{x}) = f(\vb{x}) - \frac\mu2\norm{\vb{x}}^2, so ∇g(x)=∇f(x)−μx\grad g(\vb{x}) = \grad f(\vb{x}) - \mu\vb{x}. By the first-order condition, gg is convex if and only if g(y)≥g(x)+∇g(x)⊤(y−x)g(\vb{y}) \ge g(\vb{x}) + \grad g(\vb{x})\T(\vb{y} - \vb{x}). Expanding,

f(y)−μ2∥y∥2≥f(x)−μ2∥x∥2+∇f(x)⊤(y−x)−μx⊤(y−x),f(\vb{y}) - \tfrac\mu2\norm{\vb{y}}^2 \ge f(\vb{x}) - \tfrac\mu2\norm{\vb{x}}^2 + \grad f(\vb{x})\T(\vb{y} - \vb{x}) - \mu\vb{x}\T(\vb{y} - \vb{x}),

and moving the parabolas to the other side and using ∥y∥2−∥x∥2−2x⊤(y−x)=∥y−x∥2\norm{\vb{y}}^2 - \norm{\vb{x}}^2 - 2\vb{x}\T(\vb{y} - \vb{x}) = \norm{\vb{y} - \vb{x}}^2 yields (2). Each step is an equivalence. For C2C^2, ∇2g=∇2f−μI⪰0\hess g = \hess f - \mu\mat{I} \succeq \mat{0} is the second-order condition for gg. Strong monotonicity follows by adding (2) for (x,y)(\vb{x}, \vb{y}) and (y,x)(\vb{y}, \vb{x}). ■\blacksquare

∎

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∥2T_{\vb{x}}(\vb{y}) + \frac\mu2\norm{\vb{y} - \vb{x}}^2. Thus a parabola of curvature μ\mu fits between a tangent and the function. For a quadratic 12x⊤Ax\tfrac12\vb{x}\T\mat{A}\vb{x}, the best value is the smallest eigenvalue, μ=λmin⁡(A)\mu = \lambda_{\min}(\mat{A}), by the Rayleigh quotient.

Two consequences justify the name “strong”. If x⋆\vb{x}^\star is the minimizer, the quadratic bound reveals the error f(x)−f⋆f(\vb{x}) - f^\star and the gradient.

Proof

Existence. Bound (2) with x=0\vb{x} = \vb{0} gives f(y)≥f(0)−∥∇f(0)∥∥y∥+μ2∥y∥2→∞f(\vb{y}) \ge f(\vb{0}) - \norm{\grad f(\vb{0})}\norm{\vb{y}} + \frac\mu2\norm{\vb{y}}^2 \to \infty as ∥y∥→∞\norm{\vb{y}} \to \infty: ff is coercive and continuous, so it attains its minimum (existence of minimizers). Uniqueness. ff is strictly convex because μ2∥⋅∥2\frac\mu2\norm{\cdot}^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⋆\vb{x} = \vb{x}^\star in (2) and using ∇f(x⋆)=0\grad f(\vb{x}^\star) = \vb{0} gives the first inequality. For the second, minimize the right-hand side of (2) over y\vb{y}: the parabola y↦f(x)+∇f(x)⊤(y−x)+μ2∥y−x∥2\vb{y} \mapsto f(\vb{x}) + \grad f(\vb{x})\T(\vb{y} - \vb{x}) + \frac\mu2\norm{\vb{y} - \vb{x}}^2 attains its minimum at y=x−∇f(x)/μ\vb{y} = \vb{x} - \grad f(\vb{x})/\mu with value f(x)−∥∇f(x)∥2/(2μ)f(\vb{x}) - \norm{\grad f(\vb{x})}^2/(2\mu), and since f(y)≥f(\vb{y}) \ge this for every y\vb{y}, also at x⋆\vb{x}^\star: f⋆≥f(x)−∥∇f(x)∥2/(2μ)f^\star \ge f(\vb{x}) - \norm{\grad f(\vb{x})}^2/(2\mu). Finally, strong monotonicity with y=x⋆\vb{y} = \vb{x}^\star and Cauchy-Schwarz yield μ∥x−x⋆∥2≤∇f(x)⊤(x−x⋆)≤∥∇f(x)∥∥x−x⋆∥\mu\norm{\vb{x} - \vb{x}^\star}^2 \le \grad f(\vb{x})\T(\vb{x} - \vb{x}^\star) \le \norm{\grad f(\vb{x})}\norm{\vb{x} - \vb{x}^\star}. ■\blacksquare

∎

The second inequality, f(x)−f⋆≤∥∇f(x)∥2/(2μ)f(\vb{x}) - f^\star \le \norm{\grad f(\vb{x})}^2/(2\mu), 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 12x⊤Ax\tfrac12\vb{x}\T\mat{A}\vb{x} with A≻0\mat{A} \succ \mat{0} is λmin⁡(A)\lambda_{\min}(\mat{A})-strongly convex. Adding ℓ2\ell_2 regularization to any convex function ff makes it λ\lambda-strongly convex: f+λ2∥⋅∥2f + \frac\lambda2\norm{\cdot}^2 has ∇2⪰λI\hess \succeq \lambda\mat{I}. This is one reason ridge is much more stable than ordinary least squares: it adds λ\lambda to every eigenvalue of X⊤X\mat{X}\T\mat{X} (the smallest goes from zero to λ\lambda when X⊤X\mat{X}\T\mat{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))t \mapsto f(\vb{x} + t(\vb{y} - \vb{x})),

f(y)−f(x)−∇f(x)⊤(y−x)=∫01(∇f(x+t(y−x))−∇f(x))⊤(y−x) ⁣dt,f(\vb{y}) - f(\vb{x}) - \grad f(\vb{x})\T(\vb{y} - \vb{x}) = \int_0^1\big(\grad f(\vb{x} + t(\vb{y} - \vb{x})) - \grad f(\vb{x})\big)\T(\vb{y} - \vb{x})\dd t,

the integrand’s absolute value is bounded by Lt∥y−x∥2Lt\norm{\vb{y} - \vb{x}}^2 (Cauchy-Schwarz and the assumption), whose integral is L2∥y−x∥2\frac L2\norm{\vb{y} - \vb{x}}^2. For the C2C^2 characterization: if ∇f\grad f is LL-Lipschitz, ∇2f(x)v=lim⁡t→0∇f(x+tv)−∇f(x)t\hess f(\vb{x})\vb{v} = \lim_{t \to 0}\frac{\grad f(\vb{x} + t\vb{v}) - \grad f(\vb{x})}{t} has norm ≤L∥v∥\le L\norm{\vb{v}}, so the operator norm (operator norm) of ∇2f\hess f is ≤L\le L. Conversely, the mean value inequality gives ∥∇f(y)−∇f(x)∥≤sup⁡z∥∇2f(z)∥2 ∥y−x∥\norm{\grad f(\vb{y}) - \grad f(\vb{x})} \le \sup_{\vb{z}}\norm{\hess f(\vb{z})}_2\,\norm{\vb{y} - \vb{x}}. Since ∇2f\hess f is symmetric, ∥∇2f∥2=max⁡∣λi∣\norm{\hess f}_2 = \max\abs{\lambda_i} and the condition is equivalent to −LI⪯∇2f⪯LI-L\mat{I} \preceq \hess f \preceq L\mat{I}. ■\blacksquare

∎

Thus a parabola of curvature LL fits above between ff and its tangent, just as one of curvature μ\mu fits below. Together they form the sandwich: for a μ\mu-strongly convex and LL-smooth function,

f(x)+∇f(x)⊤(y−x)+μ2∥y−x∥2  ≤  f(y)  ≤  f(x)+∇f(x)⊤(y−x)+L2∥y−x∥2,f(\vb{x}) + \grad f(\vb{x})\T(\vb{y} - \vb{x}) + \tfrac\mu2\norm{\vb{y} - \vb{x}}^2 \;\le\; f(\vb{y}) \;\le\; f(\vb{x}) + \grad f(\vb{x})\T(\vb{y} - \vb{x}) + \tfrac L2\norm{\vb{y} - \vb{x}}^2,

and, if ff is C2C^2, in Hessian terms, μI⪯∇2f(x)⪯LI\mu\mat{I} \preceq \hess f(\vb{x}) \preceq L\mat{I}. The best constants are μ=inf⁡xλmin⁡(∇2f(x))\mu = \inf_{\vb{x}}\lambda_{\min}(\hess f(\vb{x})) and L=sup⁡xλmax⁡(∇2f(x))L = \sup_{\vb{x}}\lambda_{\max}(\hess f(\vb{x})). For a quadratic 12x⊤Ax\tfrac12\vb{x}\T\mat{A}\vb{x} they do not depend on the point: they are λmin⁡(A)\lambda_{\min}(\mat{A}) and λmax⁡(A)\lambda_{\max}(\mat{A}), by the Courant-Fischer theorem.

The figure shows the sandwich for functions of one variable. Drag x0x_0 and check that the two parabolas tangent at x0x_0 enclose ff throughout the window. The limiting cases are instructive: the quartic is convex but has μ=0\mu = 0 (no lower curvature bound) and its LL grows with the window (no global bound); absolute value is convex but not smooth (L=∞L = \infty, the gradient jumps at zero); regularized logistic has both constants; and the nonconvex function has μ<0\mu < 0, so no convex parabola fits underneath.

InteractiveThe μ-L sandwich
  • ff
  • lower parabola (curvature μ\mu)
  • upper parabola (curvature LL)
  • tangent
Curvature f′′(x)f''(x) between μ\mu and LL
3.0
Constants
μ=inf⁡f′′\mu = \inf f''0.145
L=sup⁡f′′L = \sup f''0.350
κ=L/μ\kappa = L/\mu2.41
f′(x0)f'(x_0)0.889
Lower bound at x0x_0holds
Upper bound at x0x_0holds
f(x)=log⁡(1+ex)+λ2x2f(x) = \log(1 + e^x) + \tfrac{\lambda}{2}x^2 with λ=0.1\lambda = 0.1: f′′∈(λ, λ+1/4]f'' \in (\lambda,\ \lambda + 1/4] on the whole line.
For each function, parabolas tangent at x0x_0 with curvatures μ\mu (below) and LL (above) enclose ff. “Optimal” computes μ=inf⁡f′′\mu = \inf f'' and L=sup⁡f′′L = \sup f'' in the visible window. In “Manual”, raise μ\mu above inf⁡f′′\inf f'' or lower LL below sup⁡f′′\sup f'' 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 x0x_0 or x0x_0 must be moved to see it. Choose x4/8x^4/8: μ=0\mu = 0 and LL depends on the window. Choose ∣x∣\abs{x}: no finite LL exists. Try regularized logistic: f′′=σ(1−σ)+λf'' = \sigma(1-\sigma) + \lambda stays between λ\lambda and λ+1/4\lambda + 1/4, and the ratio κ=L/μ\kappa = L/\mu is shown live.

What LL does: the step limit

The upper bound lets us take a step with guarantees. If ff is LL-smooth and you take a descent step x+=x−η∇f(x)\vb{x}^+ = \vb{x} - \eta\grad f(\vb{x}), the quadratic upper bound gives

f(x+)≤f(x)−η(1−Lη2)∥∇f(x)∥2.f(\vb{x}^+) \le f(\vb{x}) - \eta\Big(1 - \frac{L\eta}{2}\Big)\norm{\grad f(\vb{x})}^2.

While η<2/L\eta < 2/L the value decreases (even if ff is not convex), and with η=1/L\eta = 1/L it decreases as much as the bound guarantees, by 12L∥∇f(x)∥2\frac{1}{2L}\norm{\grad f(\vb{x})}^2. This is the descent lemma of lesson 8, and its 2/L2/L bound is tight: for f(x)=L2x2f(x) = \frac L2x^2 a step η>2/L\eta > 2/L amplifies the error at each iteration, since x+=(1−ηL)x\vb{x}^+ = (1 - \eta L)\vb{x} with ∣1−ηL∣>1\abs{1 - \eta L} > 1.

For convex functions, smoothness says more than the upper bound. The gradient is cocoercive.

Proof

Fix x\vb{x} and define φ(z)=f(z)−∇f(x)⊤z\varphi(\vb{z}) = f(\vb{z}) - \grad f(\vb{x})\T\vb{z}, convex and LL-smooth, with ∇φ(x)=0\grad\varphi(\vb{x}) = \vb{0}, so x\vb{x} minimizes φ\varphi by convexity. Applying the upper bound for φ\varphi at y\vb{y} with step y−1L∇φ(y)\vb{y} - \frac1L\grad\varphi(\vb{y}):

φ(x)≤φ(y−1L∇φ(y))≤φ(y)−12L∥∇φ(y)∥2.\varphi(\vb{x}) \le \varphi\big(\vb{y} - \tfrac1L\grad\varphi(\vb{y})\big) \le \varphi(\vb{y}) - \frac{1}{2L}\norm{\grad\varphi(\vb{y})}^2.

Substituting φ\varphi and ∇φ(y)=∇f(y)−∇f(x)\grad\varphi(\vb{y}) = \grad f(\vb{y}) - \grad f(\vb{x}) yields the first inequality. The second follows by adding it to the inequality obtained by exchanging x\vb{x} and y\vb{y}. ■\blacksquare

∎

Notice the change in roles: monotonicity says ⟨Δ∇,Δx⟩≥0\inner{\Delta\grad}{\Delta\vb{x}} \ge 0 (convexity) or ≥μ∥Δx∥2\ge \mu\norm{\Delta\vb{x}}^2 (strong convexity); cocoercivity says ≥1L∥Δ∇∥2\ge \frac1L\norm{\Delta\grad}^2 (smooth and convex). Convexity plus smoothness is the assumption under which gradient descent converges with η<2/L\eta < 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\ell_2 regularization. Given X∈Rn×d\mat{X} \in \R^{n \times d} with rows xi⊤\vb{x}_i\T, labels yi∈{−1,+1}y_i \in \{-1, +1\} and λ>0\lambda > 0,

f(w)=1n∑i=1nlog⁡(1+e−yixi⊤w)+λ2∥w∥2,∇2f(w)=1nX⊤D(w)X+λI,f(\vb{w}) = \frac1n\sum_{i=1}^{n}\log\big(1 + e^{-y_i\vb{x}_i\T\vb{w}}\big) + \frac\lambda2\norm{\vb{w}}^2, \qquad \hess f(\vb{w}) = \frac1n\mat{X}\T\mat{D}(\vb{w})\mat{X} + \lambda\mat{I},

where D(w)=diag⁡(σ(zi)(1−σ(zi)))\mat{D}(\vb{w}) = \operatorname{diag}\big(\sigma(z_i)(1 - \sigma(z_i))\big) and zi=yixi⊤wz_i = y_i\vb{x}_i\T\vb{w} (the second derivative of log⁡(1+e−z)\log(1 + e^{-z}) is σ(z)(1−σ(z))\sigma(z)(1 - \sigma(z)) and does not depend on the sign of yiy_i because yi2=1y_i^2 = 1).

Proof

Since 0<σ(z)(1−σ(z))≤140 < \sigma(z)(1 - \sigma(z)) \le \frac14, we have 0⪯D⪯14I\mat{0} \preceq \mat{D} \preceq \frac14\mat{I} and hence 0⪯1nX⊤DX⪯14nX⊤X\mat{0} \preceq \frac1n\mat{X}\T\mat{D}\mat{X} \preceq \frac{1}{4n}\mat{X}\T\mat{X}, whose largest eigenvalue is ∥X∥22/(4n)\norm{\mat{X}}_2^2/(4n). Adding λI\lambda\mat{I} gives the sandwich λI⪯∇2f⪯(λ+∥X∥22/4n)I\lambda\mat{I} \preceq \hess f \preceq (\lambda + \norm{\mat{X}}_2^2/4n)\mat{I}. At w=0\vb{w} = \vb{0}, D=14I\mat{D} = \frac14\mat{I} and the upper bound is an equality; with w=tv\vb{w} = t\vb{v} and t→∞t \to \infty, D→0\mat{D} \to \mat{0} and ∇2f→λI\hess f \to \lambda\mat{I}. ■\blacksquare

∎

Two messages. The data do not enter μ\mu: regularization fixes it. Without it (λ=0\lambda = 0), μ=0\mu = 0 and with linearly separable data the minimizer does not even exist (the loss tends to zero as ∥w∥→∞\norm{\vb{w}} \to \infty). And LL grows with the data scale, ∥X∥22\norm{\mat{X}}_2^2: this is why features are normalized before training, otherwise the step must be reduced.

The condition number

The two constants, μ\mu and LL, 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\propto 1/\sqrt{\lambda_i}, so the ratio of long to short axis is κ\sqrt\kappa. With κ=1\kappa = 1 they are circles and the gradient points directly to the minimum; with large κ\kappa they are narrow ellipses, the gradient points almost perpendicular to the valley, and gradient descent zigzags. When κ=1\kappa = 1 a single step with η=1/L\eta = 1/L reaches the minimum. The larger κ\kappa, the more steps are needed, linearly, and the figure measures this with an actual count (not a formula).

InteractiveBowls and condition number
  • contours of ff
  • gradient descent
  • starting point x0\vb{x}_0
1.00
9.0
30°
Step
20
κ=L/μ\kappa = L/\mu9.00
λmax⁡(A)/λmin⁡(A)\lambda_{\max}(\mat{A}) / \lambda_{\min}(\mat{A}) from entries9.00
A\mat{A}[7.00, 3.46; 3.46, 3.00]
Semiaxis ratio κ\sqrt{\kappa}3.00
Steps until f≤10−6f(x0)f \le 10^{-6} f(\vb{x}_0)55
Theoretical factor per step for f−f⋆f - f^\star0.8889
Rotate the bowl: the entries of A\mat{A} change, but its eigenvalues and κ\kappa do not. Increase LL and watch the valley narrow.
A quadratic f(x)=12x⊤Axf(\vb{x}) = \frac12\vb{x}\T\mat{A}\vb{x} whose eigenvalues μ\mu and LL you control with sliders. Level curves change from circles (κ=1\kappa = 1) to elongated ellipses. Axis rotation: rotate the bowl; A\mat{A} changes entries but κ\kappa does not, as confirmed by the ratio λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\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)f \le 10^{-6}f(\vb{x}_0) changes. With η=1/L\eta = 1/L the general guarantee is that f−f⋆f - f^\star is multiplied by at most 1−1/κ1 - 1/\kappa at each step, and with η=2/(L+μ)\eta = 2/(L + \mu) the distance to the minimum is multiplied by (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1).

Two properties are visible directly in the figure. κ\kappa does not depend on rotation of the axes: A\mat{A} and QAQ⊤\mat{Q}\mat{A}\mat{Q}\T have the same spectrum, and gradient descent, which is rotation invariant, behaves identically. And κ\kappa does depend on the relative scale of variables: if you change the units of one coordinate (a change of variables x=Sz\vb{x} = \mat{S}\vb{z} with diagonal S\mat{S}) the function z↦f(Sz)\vb{z} \mapsto f(\mat{S}\vb{z}) has Hessian SAS\mat{S}\mat{A}\mat{S} and a different κ\kappa. Choosing S\mat{S} to reduce κ\kappa is preconditioning, and the lessons on Adam and adaptive methods catalog ways to do it.

Why does κ\kappa control speed? The quadratic shows it in one line. Gradient descent xk+1=xk−ηAxk\vb{x}_{k+1} = \vb{x}_k - \eta\mat{A}\vb{x}_k satisfies xk+1−x⋆=(I−ηA)(xk−x⋆)\vb{x}_{k+1} - \vb{x}^\star = (\mat{I} - \eta\mat{A})(\vb{x}_k - \vb{x}^\star), and the eigenvalues of I−ηA\mat{I} - \eta\mat{A} lie in [1−ηL,1−ημ][1 - \eta L, 1 - \eta\mu]. With η=2/(L+μ)\eta = 2/(L + \mu) that interval is [−κ−1κ+1,κ−1κ+1][-\frac{\kappa - 1}{\kappa + 1}, \frac{\kappa - 1}{\kappa + 1}] and therefore

∥xk−x⋆∥≤(κ−1κ+1)k∥x0−x⋆∥.\norm{\vb{x}_k - \vb{x}^\star} \le \Big(\frac{\kappa - 1}{\kappa + 1}\Big)^k\norm{\vb{x}_0 - \vb{x}^\star}.

To reduce the distance by a factor of 10−610^{-6}, k=ln⁡106/ln⁡κ+1κ−1k = \ln 10^6/\ln\frac{\kappa + 1}{\kappa - 1} steps suffice: 12.612.6 with κ=2\kappa = 2, 68.868.8 with κ=10\kappa = 10, 690.8690.8 with κ=100\kappa = 100 and 6907.86907.8 with κ=1000\kappa = 1000. As ln⁡κ+1κ−1≈2/κ\ln\frac{\kappa + 1}{\kappa - 1} \approx 2/\kappa for large κ\kappa, this is k≈κ2ln⁡106≈6.9 κk \approx \frac\kappa2\ln 10^6 \approx 6.9\,\kappa: linear in κ\kappa. 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≤α}\{f \le \alpha\} are convex (equivalent to f(θx+(1−θ)y)≤max⁡(f(x),f(y))f(\theta\vb{x} + (1-\theta)\vb{y}) \le \max(f(\vb{x}), f(\vb{y}))). Every convex function is quasiconvex, as are x3x^3 and ∣x∣\sqrt{\abs{x}}, although neither is convex. What is lost is essential: x3x^3 has f′(0)=0f'(0) = 0 but no minimum at 00. The first-order condition is no longer sufficient.

A density p≥0p \ge 0 is log-concave if log⁡p\log p is concave (with convention log⁡0=−∞\log 0 = -\infty, making its support convex), that is, if −log⁡p-\log p is convex. The Gaussian is log-concave: −log⁡p(x)=12(x−m)⊤Σ−1(x−m)+const-\log p(\vb{x}) = \frac12(\vb{x} - \vb{m})\T\mat{\Sigma}\inv(\vb{x} - \vb{m}) + \text{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\eta = 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.

[ ]A convexity falsifierBrowser
import numpy as np
rng = np.random.default_rng(0)

def lse(x):
    m = x.max(axis=-1, keepdims=True)
    return (m + np.log(np.exp(x - m).sum(axis=-1, keepdims=True)))[..., 0]

A = rng.normal(size=(4, 3)); b = rng.normal(size=4)
# cada entrada: (nombre, f, gradiente, muestreador, ¿es convexa?)
casos = {
    "||Ax - b||_2": (lambda x: np.linalg.norm(x @ A.T - b, axis=-1),
                     lambda x: ((x @ A.T - b) / np.linalg.norm(x @ A.T - b, axis=-1, keepdims=True)) @ A,
                     lambda n: rng.normal(size=(n, 3)) * 2, True),
    "log-sum-exp":  (lse, lambda x: np.exp(x - lse(x)[..., None]),
                     lambda n: rng.normal(size=(n, 3)) * 3, True),
    "x1^2 / x2 (x2>0)": (lambda x: x[..., 0] ** 2 / x[..., 1],
                         lambda x: np.stack([2 * x[..., 0] / x[..., 1], -x[..., 0] ** 2 / x[..., 1] ** 2], -1),
                         lambda n: np.column_stack([rng.normal(size=n) * 2, rng.uniform(0.3, 3, n)]), True),
    "x1 * x2":      (lambda x: x[..., 0] * x[..., 1],
                     lambda x: np.stack([x[..., 1], x[..., 0]], -1),
                     lambda n: rng.normal(size=(n, 2)) * 2, False),
    "exp(-||x||^2)": (lambda x: np.exp(-(x ** 2).sum(-1)),
                      lambda x: -2 * x * np.exp(-(x ** 2).sum(-1, keepdims=True)),
                      lambda n: rng.normal(size=(n, 2)), False),
    "||x||^2/2 + 1.2 cos(2 x1)": (lambda x: 0.5 * (x ** 2).sum(-1) + 1.2 * np.cos(2 * x[..., 0]),
                                  lambda x: x + np.stack([-2.4 * np.sin(2 * x[..., 0]), 0 * x[..., 0]], -1),
                                  lambda n: rng.normal(size=(n, 2)) * 2, False),
}

def falsa(f, grad, sample, n=20000):
    """Devuelve (fracción de cuerdas violadas, peor violación de cuerda, fracción de tangentes violadas)."""
    x, y = sample(n), sample(n)
    theta = rng.uniform(size=(n, 1))
    cuerda = theta[:, 0] * f(x) + (1 - theta[:, 0]) * f(y) - f(theta * x + (1 - theta) * y)   # debe ser >= 0
    tangente = f(y) - f(x) - (grad(x) * (y - x)).sum(-1)                                      # debe ser >= 0
    return (cuerda < -1e-9).mean(), min(cuerda.min(), 0.0), (tangente < -1e-9).mean()

print(f"{'función':28s}{'cuerdas rotas':>15s}{'peor violación':>16s}{'tangentes rotas':>17s}")
for nombre, (f, g, s, convexa) in casos.items():
    c, peor, t = falsa(f, g, s)
    print(f"{nombre:28s}{c:15.3f}{peor:16.4f}{t:17.3f}   (convexa: {convexa})")

The three convex functions yield 0.0000.000 on both tests, and the three nonconvex ones violate both with clearly positive percentages: 50 %50\,\% of pairs for x1x2x_1x_2, 74 %74\,\% for e−∥x∥2e^{-\norm{\vb{x}}^2}, and 13 %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 μ\mu and LL for regularized logistic loss. The Hessian is 1nX⊤DX+λI\frac1n\mat{X}\T\mat{D}\mat{X} + \lambda\mat{I} and the theorem says its spectrum lives in [λ, λ+∥X∥22/(4n)][\lambda,\ \lambda + \norm{\mat{X}}_2^2/(4n)]. We sample many points w\vb{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 00 (only point w=0\vb{w} = \vb{0}), λmax⁡\lambda_{\max} matches the analytic bound LL: logistic’s second derivative is maximal there, 14\frac14. But the measured λmin⁡\lambda_{\min} is greater than λ\lambda and only approaches it as the radius grows, because σ(1−σ)→0\sigma(1-\sigma) \to 0 far from the origin. An estimator of μ\mu sampling near the origin overestimates μ\mu, and one for LL sampling far from the origin underestimates LL. This asymmetry motivates the last common error in the lesson.

The third piece is the LL estimator from the exercises: ratios ∥∇f(x)−∇f(y)∥/∥x−y∥\norm{\grad f(\vb{x}) - \grad f(\vb{y})}/\norm{\vb{x} - \vb{y}} over random pairs. By definition of LL 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^\eta = 1/\hat 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 LL from below with few pairs; ratios taken far from the origin never see the high-curvature region and give an L^\hat L near λ\lambda. The resulting step 1/L^≈8.51/\hat L \approx 8.5 exceeds 2/L≈5.02/L \approx 5.0, so descent ceases to be monotonic and after 6060 steps is worse than with the correct step (f≈1.10f \approx 1.10 versus 0.450.45), whereas with 1/L≈2.51/L \approx 2.5 the value decreases at each iteration. The lesson: sampling-based estimation of LL 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 <= L

x = cp.Variable(3)
print(cp.log_sum_exp(x).is_convex())    # True
print(cp.exp(-cp.sum_squares(x)).is_convex())   # False: la regla de composición no se cumple
print(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))\lambda_{\min}(\hess f(\vb{w})) heads towards λ\lambda, 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 ff be differentiable on an open convex set CC. Prove that ff is convex if and only if f(y)≥f(x)+∇f(x)⊤(y−x)f(\vb{y}) \ge f(\vb{x}) + \grad f(\vb{x})\T(\vb{y} - \vb{x}) for all x,y∈C\vb{x}, \vb{y} \in 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 (⇒\Rightarrow), what is the first step?

Prooflog-sum-exp is convex
Prove: Prove that lse⁡(x)=log⁡∑i=1nexi\operatorname{lse}(\vb{x}) = \log\sum_{i=1}^n e^{x_i} is convex on Rn\R^n by calculating its Hessian.
0
With p=softmax⁡(x)\vb{p} = \softmax(\vb{x}), that is, pi=exi/∑jexjp_i = e^{x_i}/\sum_je^{x_j}, calculate the gradient and then the Hessian, and prove it is positive semidefinite.

Step 1 of 3. What is the gradient of lse⁡\operatorname{lse}?

NumericCondition number of a quadratic
Calculate the condition number κ\kappa of f(x)=12x⊤Axf(\vb{x}) = \tfrac12\vb{x}\T\mat{A}\vb{x} with A=[10221]\mat{A} = \begin{bmatrix}10 & 2\\ 2 & 1\end{bmatrix}.
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)=12∥Ax−b∥22+λ2∥x∥22f(\vb{x}) = \tfrac12\norm{\mat{A}\vb{x} - \vb{b}}_2^2 + \tfrac\lambda2\norm{\vb{x}}_2^2 with A=[201101]\mat{A} = \begin{bmatrix}2 & 0\\ 1 & 1\\ 0 & 1\end{bmatrix} and λ=0.5\lambda = 0.5, calculate the condition number κ=L/μ\kappa = L/\mu.
NumericThe maximum guaranteed step
For regularized logistic loss with one data point, n=1n = 1, x1=(3)\vb{x}_1 = (3) (a scalar, d=1d = 1) and λ=0.2\lambda = 0.2, calculate 2/L2/L, the largest step for which gradient descent decreases ff 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\norm{\grad f(\vb{x}) - \grad f(\vb{y})}_2 / \norm{\vb{x} - \vb{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 (μ\mu) and smoothness (LL) quantify curvature below and above, sandwich the function between two parabolas and fix the step limit (η<2/L\eta < 2/L); their ratio κ=L/μ\kappa = L/\mu measures landscape elongation and governs the speed of first-order methods.