AI Knowledge Tree

Convex functions and their tests

Define convex functions and test convexity with the first- and second-order conditions.

A convex function is one whose graph never dips below its chords. This single shape property has an outsized payoff: for a convex objective, every stationary point is a global minimum and gradient descent cannot get trapped. This lesson defines convexity and gives the two practical tests for it.

Definition

A function f:Rn→Rf: \mathbb{R}^n \to \mathbb{R} (with convex domain) is convex if for all x,yx, y and θ∈[0,1]\theta \in [0, 1],

f(θx+(1−θ)y)≤θf(x)+(1−θ)f(y).f(\theta x + (1-\theta)y) \le \theta f(x) + (1-\theta) f(y). [1]

The left side is the function at a point on the segment; the right side is the corresponding point on the chord. Convexity says the function lies on or below every chord. It is strictly convex if the inequality is strict for x≠yx \neq y and θ∈(0,1)\theta \in (0,1). A function is concave if −f-f is convex.

A useful equivalent: ff is convex if and only if its epigraph {(x,t):t≥f(x)}\{(x, t) : t \ge f(x)\}, the region above the graph, is a convex set. This links function convexity back to the previous lesson's set convexity.

The chord test: for a convex function (left) every chord lies above the graph; a nonconvex function (right) has a chord the graph rises above.
The chord test: for a convex function (left) every chord lies above the graph; a nonconvex function (right) has a chord the graph rises above.

First-order condition

If ff is differentiable, convexity is equivalent to the graph lying above all its tangent planes:

f(y)≥f(x)+∇f(x)⊤(y−x)for all x,y.f(y) \ge f(x) + \nabla f(x)^\top (y - x) \quad \text{for all } x, y.

The right side is the first-order Taylor approximation at xx. Convexity says this linear underestimate is a global lower bound, never an overestimate.

Why this makes optimization easy. If ∇f(x⋆)=0\nabla f(x^\star) = 0, the bound becomes f(y)≥f(x⋆)f(y) \ge f(x^\star) for all yy: the stationary point is a global minimum. For convex functions, the necessary first-order condition is also sufficient, and local minima are global.

Second-order condition

If ff is twice differentiable, convexity is equivalent to a positive semidefinite Hessian everywhere:

∇2f(x)⪰0for all x.\nabla^2 f(x) \succeq 0 \quad \text{for all } x. [2]

Using the definiteness tests from quadratic forms, this is checkable: all eigenvalues of the Hessian are nonnegative at every point. Strict positive definiteness (∇2f≻0\nabla^2 f \succ 0) gives strict convexity. The Hessian being PSD is the curvature restatement of "curves upward in every direction".

Example. A quadratic f(x)=12x⊤Ax+b⊤xf(x) = \tfrac{1}{2}x^\top A x + b^\top x has Hessian AA, so it is convex if and only if A⪰0A \succeq 0. The least-squares objective ∥Ax−b∥2\lVert Ax - b\rVert^2 has Hessian 2A⊤A⪰02A^\top A \succeq 0, hence is always convex.

Operations that preserve convexity

Convex functions are built from a small toolbox:

  • Nonnegative weighted sums: αf+βg\alpha f + \beta g is convex for α,β≥0\alpha, \beta \ge 0.
  • Pointwise maximum: max⁡(f,g)\max(f, g) is convex (the epigraph is an intersection).
  • Affine composition: f(Ax+b)f(Ax + b) is convex if ff is.

These rules certify convexity of composite objectives (a convex loss plus a convex regularizer stays convex) without returning to the definition.

Check it on arrays

python · numpy
import numpy as np

rng = np.random.default_rng(1)

# Chord test: f(theta x + (1-theta) y) <= theta f(x) + (1-theta) f(y)
def chord_holds(f, dim, trials=200_000):
    x = rng.normal(size=(trials, dim))
    y = rng.normal(size=(trials, dim))
    th = rng.random((trials, 1))
    lhs = f(th * x + (1 - th) * y)
    rhs = th.ravel() * f(x) + (1 - th).ravel() * f(y)
    return np.all(lhs <= rhs + 1e-9)

f_quad = lambda X: np.sum(X**2, axis=1)          # convex
f_exp  = lambda X: np.exp(X[:, 0])               # convex
f_cos  = lambda X: np.cos(X[:, 0])               # not convex
print("||x||^2 convex:", chord_holds(f_quad, 3))
print("exp(x) convex: ", chord_holds(f_exp, 1))
print("cos(x) convex: ", chord_holds(f_cos, 1))

# Second-order test on a quadratic: Hessian = A, PSD <-> convex
A = np.array([[2.0, 0.5], [0.5, 1.0]])           # symmetric
print("eig(A):", np.linalg.eigvalsh(A), "-> all >= 0 -> convex")
A_indef = np.array([[1.0, 0.0], [0.0, -1.0]])
print("eig(A_indef):", np.linalg.eigvalsh(A_indef), "-> mixed -> not convex")

The chord test confirms the square and exponential are convex while the cosine is not, and the Hessian eigenvalue signs agree.

Exercises

Exercise 1. Use the second-order condition to decide whether f(x,y)=2x2+3y2+2xyf(x, y) = 2x^2 + 3y^2 + 2xy is convex. Compute the Hessian and check its eigenvalues by hand.

Solution

Step 1. The Hessian of a quadratic f=12z⊤Hzf = \tfrac12 z^\top H z is constant. Here the second partials are fxx=4f_{xx} = 4, fyy=6f_{yy} = 6, fxy=2f_{xy} = 2, so

∇2f=[4226].\nabla^2 f = \begin{bmatrix} 4 & 2 \\ 2 & 6 \end{bmatrix}.

Step 2. Check positive semidefiniteness by the eigenvalues, the roots of det⁡(∇2f−λI)=(4−λ)(6−λ)−4=0\det(\nabla^2 f - \lambda I) = (4 - \lambda)(6 - \lambda) - 4 = 0, that is λ2−10λ+20=0\lambda^2 - 10\lambda + 20 = 0:

λ=10±100−802=5±5≈7.236, 2.764.\lambda = \frac{10 \pm \sqrt{100 - 80}}{2} = 5 \pm \sqrt 5 \approx 7.236,\ 2.764.

Step 3. Both eigenvalues are positive, so ∇2f≻0\nabla^2 f \succ 0 everywhere. The function is strictly convex. (A faster route: a 2×22\times 2 symmetric matrix is positive definite when the diagonal entries and the determinant are positive; here 4>04 > 0, 6>06 > 0, and det⁡=24−4=20>0\det = 24 - 4 = 20 > 0.)

Exercise 2. Prove that a nonnegative weighted sum of convex functions is convex: if f,gf, g are convex and α,β≥0\alpha, \beta \ge 0, then h=αf+βgh = \alpha f + \beta g is convex. Use the chord definition.

Solution

Step 1. Fix x,yx, y and θ∈[0,1]\theta \in [0, 1]. Apply the convexity inequality to ff and to gg separately:

f(θx+(1−θ)y)≤θf(x)+(1−θ)f(y),g(θx+(1−θ)y)≤θg(x)+(1−θ)g(y).f(\theta x + (1-\theta)y) \le \theta f(x) + (1-\theta)f(y), \qquad g(\theta x + (1-\theta)y) \le \theta g(x) + (1-\theta)g(y).

Step 2. Multiply the first by α≥0\alpha \ge 0 and the second by β≥0\beta \ge 0. The inequality directions are preserved because the multipliers are nonnegative. Add the two:

αf(⋅)+βg(⋅)≤θ(αf(x)+βg(x))+(1−θ)(αf(y)+βg(y)).\alpha f(\cdot) + \beta g(\cdot) \le \theta(\alpha f(x) + \beta g(x)) + (1-\theta)(\alpha f(y) + \beta g(y)).

Step 3. The left side is h(θx+(1−θ)y)h(\theta x + (1-\theta)y) and the right side is θh(x)+(1−θ)h(y)\theta h(x) + (1-\theta)h(y), the chord condition for hh. So hh is convex. Nonnegativity of α,β\alpha, \beta is essential: a negative weight flips an inequality and can destroy convexity.

Exercise 3 (code). The softplus f(x)=log⁡(1+ex)f(x) = \log(1 + e^x) is claimed convex. Verify it two ways in numpy: the chord test on random pairs, and a finite-difference second derivative that stays nonnegative on a grid.

Solution
python · numpy
import numpy as np

rng = np.random.default_rng(0)
softplus = lambda x: np.log1p(np.exp(x))

# Chord test on random scalar pairs
x = rng.normal(size=200_000)
y = rng.normal(size=200_000)
th = rng.random(200_000)
lhs = softplus(th * x + (1 - th) * y)
rhs = th * softplus(x) + (1 - th) * softplus(y)
assert np.all(lhs <= rhs + 1e-9)

# Finite-difference second derivative on a grid: f'' >= 0 means convex
g = np.linspace(-8, 8, 4001)
h = g[1] - g[0]
f2 = (softplus(g[2:]) - 2 * softplus(g[1:-1]) + softplus(g[:-2])) / h**2
assert f2.min() >= -1e-8
print("min finite-diff f'':", round(f2.min(), 8),
      " (sigmoid(0) =", round(float(1 / (1 + np.exp(0))) * (1 - 1/(1+np.exp(0))), 4), ")")

The chord never rises above the function and the numerical second derivative stays at or above zero, the curvature signature of a convex function. (Its true second derivative is the sigmoid times one minus the sigmoid, peaking at 0.250.25 at x=0x = 0.)

The next lesson uses these convexity guarantees to analyze the first optimization algorithm: gradient descent.


References

  1. [1]Boyd, S., & Vandenberghe, L. (2004). Convex Optimization, §3.1. Cambridge University Press. The definition of a convex function and the epigraph characterization.↩
  2. [2]Boyd, S., & Vandenberghe, L. (2004). Convex Optimization, §3.1.3-3.2. Cambridge University Press. The first- and second-order conditions and convexity-preserving operations.↩