11 / 16 · Optimization
Convex sets and functions
When local information certifies a global minimum: convex sets and functions, the tangent and Hessian tests, operations that keep convexity, strong convexity and smoothness, and which machine learning losses are convex.
On this page 10
Run gradient descent with step on the function
Started at , it stops at with . Started at , it stops at with . Both runs report convergence, and at both end points the derivative is zero and the second derivative is positive:
| Stationary point | |||
|---|---|---|---|
A test that looks only at the point, as the gradient and the Hessian of the calculus section do, cannot tell the global minimum from the other one. For a function of one variable we can list the stationary points and compare them; for the loss of a model with millions of weights we cannot.
The way out is to restrict the class of functions until the local test becomes a global one. That class is the convex functions, and the restriction costs less than it seems: least squares, logistic regression, the support vector machine and the lasso all have convex losses.
Convex sets#
A set is convex if it contains the segment between any two of its points. For and in , the segment is the set of points with :
A convex set, a non-convex set and a convex hull
A half-space is convex, because the constraint is linear. If and , then
A linear classifier splits the space into two half-spaces. Other convex sets met throughout machine learning:
- norm balls , for every norm, so the L1 ball of the lasso too: by the triangle inequality and homogeneity, ;
- the probability simplex , the set of distributions on outcomes and the range of the softmax: a weighted average of non-negative vectors is non-negative, and its entries sum to ;
- the positive semidefinite matrices, since and give ; covariance and kernel matrices live here.
A ring is not convex: it contains and but not their midpoint, the origin. Neither is the union of two disjoint discs, for the same reason with one point in each disc.
New convex sets come from old ones. If and lie in every of a family of convex sets, the segment between them does too, so any intersection of convex sets is convex. A finite intersection of half-spaces, , is a polyhedron; the feasible sets of linear programs and of the SVM are polyhedra. The image of a convex set under an affine map is convex, and so is its preimage (Boyd and Vandenberghe, EE364a, lecture 2). Both follow from one identity: the map sends to , the same combination of the images. An ellipsoid, for example, is the image of a ball. Unions do not preserve convexity, as the two discs show.
A convex combination of points is a weighted average with and . The convex hull is the set of all convex combinations. It is the smallest convex set containing the points: a convex set that contains them contains every convex combination, by induction on . For the induction step writes
a two-point combination of and a combination of points, whose weights again sum to 1. For finitely many points in the plane it is the polygon a rubber band would form around them.
Is in the convex hull of , and ? The weights must satisfy , and , so all three are , non-negative, and the answer is yes. For the same equations give . The three equations have exactly one solution, since the matrix with columns , and has determinant 9, so no non-negative weights exist and is outside. The probability simplex is the convex hull of the standard basis vectors, and the duality note shows that the hard-margin SVM looks for the two nearest points of the convex hulls of its two classes.
Convex functions#
A function on a convex set is convex if every chord lies on or above its graph:
for all , and . It is strictly convex if the inequality is strict whenever and , and concave if is convex. Equivalently, the region above the graph, the epigraph , is a convex set. If and , the chord inequality gives ; conversely, the points and lie in the epigraph, and convexity of the epigraph is the chord inequality. The sublevel sets of a convex function are convex as well: if and , the chord bounds on the segment by . Convex sublevel sets do not make a function convex: has intervals as sublevel sets, yet its chord from 0 to 1 passes below the graph at , where .
By induction the inequality extends from two points to any convex combination, , which is Jensen’s inequality: the step splits off the last point as for the convex hull, applies the two-point inequality, then the inequality for points. With the weights read as probabilities it says for an with finitely many values. The same holds for integrals and general expectations whenever they exist (Boyd and Vandenberghe, 2004, Section 3.1.8). The VAE note bounds a log-likelihood with it; the logarithm is concave, so there the inequality flips.
For the gap between chord and graph is
The middle line uses and .
It is never negative, so is convex, and it is positive whenever and , so is strictly convex. For , and the chord is at and the graph at . Every norm is convex, by the triangle inequality and homogeneity, as for the balls above.
Checking chords pair by pair is impractical in many dimensions. For differentiable functions two tests use the derivatives instead.
The first-order condition: the tangent lies below#
For a convex function the chord from towards lies above the graph. As the chord shrinks to a point it turns into the tangent, so the tangent at any point lies below the whole graph. For a differentiable on an open convex set:
The tangent of a convex function lies below the graph
Fix and and take . Convexity with the weights and bounds at the point of the segment; subtracting and dividing by gives a difference quotient:
As the left side tends to the directional derivative , by the chain rule for at , and the inequality survives the limit. The converse is as short. Put , write the tangent bound at once towards and once towards , multiply the two inequalities by and , and add. The gradient terms cancel, because , and what remains is .
At , has the tangent , so the bound says for every : at , . The opening function fails the test. At its local minimum the tangent is the horizontal line at height , and at the graph is below it.
The bound is why convexity matters. Put into it, and it reads for every . For a differentiable convex function, a point with zero gradient is a global minimum.
The second-order condition: a positive semidefinite Hessian#
A function is convex exactly when it is convex along every line, because chords along a line are chords of . Restrict to the line through in direction , . Its derivatives come from the chain rule:
In one variable, is convex exactly when . If , then never decreases, and the gap to the tangent at , , is non-negative on both sides of : the tangent bound. Conversely, the tangent bound written at and at and added gives , so is nondecreasing, and its derivative , a limit of non-negative difference quotients, is . Requiring at every point and in every direction is exactly the condition on the Hessian. For a twice differentiable on an open convex set:
Here means that the symmetric matrix is positive semidefinite, for all , as in the symmetric matrices note. If (positive definite) everywhere, is strictly convex: then , is strictly increasing, the gap integral above is positive for , and the converse argument of the tangent test, run with strict inequalities, gives strict chords. The converse fails: has , yet its derivative is strictly increasing, so the same argument makes it strictly convex.
The quadratic with symmetric has the constant Hessian , so it is convex exactly when . For with rows and the eigenvalues are 1 and 3: convex. For rows and they are 3 and , and the direction , with , exposes it. With , , while the midpoint has , above the chord.
The log-sum-exp , the normalizer of the softmax, has gradient and Hessian , the Jacobian of ; both are derived in the matrix calculus note. For any ,
because the right side is the variance of a random variable that takes the value with probability . For , , and the Hessian has eigenvalues , and ; for both sides equal . The zero eigenvalue belongs to : adding a constant to every logit changes nothing, so lse is convex but not strictly.
Operations that preserve convexity#
Most losses are not checked from scratch. They are built from convex pieces by operations that keep convexity, each a line of algebra from the chord definition (Boyd and Vandenberghe, EE364a, lecture 3):
- a non-negative weighted sum of convex functions is convex: add their chord inequalities with the weights . An average loss over training examples plus a convex penalty is convex;
- a composition with an affine map is convex, because the affine map sends a segment to a segment. A convex loss of a linear model’s prediction is convex in the weights;
- a pointwise maximum of convex functions is convex: its epigraph is the intersection of their epigraphs. The hinge is the maximum of two affine functions, and for symmetric , (the Rayleigh quotient), a maximum of functions linear in , is convex in . The epigraph argument works for any family, finite or not.
A convex nondecreasing function of a convex function is convex. If is convex and is convex and nondecreasing, then
The first step uses that is nondecreasing, the second that is convex. So is convex whenever is.
A product, a difference, or a composition in the wrong order need not be convex. The functions and are convex, but their product is not, and , the squared error of the product of two weights, is the counterexample of the section on losses below.
Why every local minimum is global#
A point is a local minimum if for all in some ball with . For a convex on a convex set , a local minimum is a global one: for every .
Suppose some had . Walk a small fraction of the way from towards , to . Since , any with puts inside the ball. The point is in because is convex, and
So is inside the ball and strictly lower than , which contradicts local minimality. The same chord gives two more facts. The set of minimizers is convex: if and both attain the minimum value, the chord keeps at or below it on the segment. And a strictly convex function has at most one minimizer, since two distinct ones would make the midpoint strictly lower than both.
Least squares with two identical feature columns shows both. For a target of 1 and a feature equal to 1, the loss is convex, and its minimizers form the whole line , a convex set; gradient descent stops somewhere on it, always at the minimum value 0. Its gradient never changes , and with the step the sum moves to in one step. The penalty adds to the Hessian, which has rows and , and so makes it positive definite and the loss strictly convex. Setting both partial derivatives to zero forces with , so the one minimizer is , which is for .
Strong convexity and smoothness#
Convexity says the function lies above its tangents. Two quantitative versions say by how much, at least and at most, and they set the speed of every algorithm in the next note.
A differentiable is -strongly convex, with , if it lies above each tangent by at least a parabola:
Equivalently, is convex. Its gradient is , and its tangent test, after moving the terms to the right, adds to the tangent of . For twice differentiable the Hessian test for reads everywhere: every eigenvalue of the Hessian is at least .
A differentiable is -smooth if its gradient is -Lipschitz, ; for twice continuously differentiable this means . One way, is the limit of , whose norm is at most , so every eigenvalue lies in . The other way, , and a symmetric matrix with eigenvalues in stretches no vector by more than . The gradient cannot change faster than per unit of distance, so the function cannot rise above its tangent faster than a parabola of curvature :
To prove it, let , , and write for the gap between the function and its tangent:
- The fundamental theorem of calculus for , whose derivative is ; the constant integrates to itself.
- The Cauchy–Schwarz inequality.
- The Lipschitz gradient, with .
This is the route of Bubeck (2015), Lemma 3.4. A function that is both strongly convex and smooth is squeezed between two parabolas around every tangent, of curvatures and . Their ratio is the condition number of . For a quadratic it is , the condition number of the matrix that the conditioning note studies from the numerical side.
For with of rows and , , and . From to the tangent is 0, , and the two parabolas give .
How far from the minimum?#
Strong convexity turns a small gradient into a guarantee. Write the lower parabola at towards the minimizer , with . A value is at least the minimum over all points, and the parabola is smallest where its gradient vanishes, at . There it equals :
Rearranged, . This is the Polyak–Łojasiewicz inequality, and the next note turns it into the linear convergence rate of gradient descent. For the quadratic above at , and , and the bound is . The inequality can hold without convexity: Merkulov (2024) shows , whose second derivative dips to . Karimi, Nutini and Schmidt (2016) state that it satisfies the inequality with (Section 2.2) and build linear-rate proofs on the inequality alone (Theorem 1).
The ridge penalty adds to any Hessian, so a convex loss plus ridge is -strongly convex. The regularization note uses the penalty for statistics; it also fixes the geometry. The logistic loss has Hessian with , from the matrix calculus note. Since , we get , so the loss is -smooth with . Far from the origin the predictions saturate: along every with tends to 0 as , so the smallest Hessian eigenvalue tends to 0, and without a penalty no works everywhere.
Which machine learning losses are convex#
The tests above settle the standard losses of linear models, all in the weights for fixed data:
| Loss | Why it is convex | Strongly convex? |
|---|---|---|
| least squares | Hessian (least squares) | if has full column rank: for |
| logistic | convex function of an affine map (logistic regression) | no, only with a penalty |
| softmax cross-entropy | lse of an affine map minus a linear term | no: shifting all logits is flat |
| hinge | maximum of affine functions (SVM) | no; not differentiable either |
| ridge , lasso | a squared norm, a norm | ridge yes (), lasso no |
A neural network composes linear maps with nonlinear activations, and its loss as a function of all the weights is not convex. The smallest example is a “network” with one hidden unit and no activation, , fitted to one example :
Both and fit exactly, with loss 0, but their midpoint has loss 1, above the chord. The Hessian there has eigenvalues and : the origin is a saddle point with zero gradient. The same sign symmetry, and the permutation symmetry of hidden units, holds in every network, as the deep learning course works out. Matrix factorization, -means and mixture models are non-convex for the same reason: a model with interchangeable parts has several equivalent minimizers and worse points between them. For these, the guarantees of the next note shrink to “the gradient becomes small”, and the starting point matters.
Where it breaks#
Convexity does not promise that a minimum exists. Logistic regression on one point with label has the loss , convex and decreasing towards 0, a value no attains. Gradient descent with step 1 never stops moving:
| Steps | ||
|---|---|---|
| 10 | ||
| 100 | ||
| 1,000 | ||
| 10,000 |
The weight grows like and the loss falls like , as the fold derives. The same happens on any linearly separable data set: if for every , each term decreases as grows, so scaling up a separating always lowers the loss, which stays positive. A ridge penalty restores a minimizer. The penalized loss is at least , so outside a large enough ball it exceeds its value at ; on that closed ball a continuous function attains its minimum.
Derivation: why the weight grows like log k
The step is . Put , so and . The weight only grows, so and the exponent lies in . From , the tangent bound and the mean value theorem:
So : is up to a bounded term, and the loss , which lies between and because and , falls like .
Convexity also says nothing about speed: a convex function can be very flat or badly conditioned, and the next note shows that the number of gradient steps grows with . And the hinge and the L1 norm are convex but not differentiable at their kinks. There the tangent bound becomes a family of supporting lines, the subgradients, and gradient methods need their non-smooth variants.
What you should remember#
- Convex set: contains every chord. Convex function: every chord lies above the graph.
- Equivalent tests: the tangent lies below, ; or everywhere.
- Sums, affine substitutions, maxima and convex nondecreasing outer functions keep convexity.
- For a convex , every local minimum is global, and certifies it.
- , , and .
- Linear models with standard losses are convex; neural networks, factorizations and mixtures are not.
Code#
The opening function, the chord test on three convex losses and one non-convex one, the tangent and Hessian tests, the parabola sandwich, the Polyak–Łojasiewicz bound, and logistic regression without a minimizer, with NumPy. Exact digits can differ slightly across platforms and library versions.
import numpy as np
rng = np.random.default_rng(0)
# the opening function f(x) = x^4 - 2x^2 + x/2 has two local minima; gradient descent finds the one near its start
f = lambda x: x**4 - 2 * x**2 + 0.5 * x
df = lambda x: 4 * x**3 - 4 * x + 0.5
crit = np.sort(np.roots([4, 0, -4, 0.5]).real)
print(crit.round(3), f(crit).round(3), (12 * crit**2 - 4).round(2)) # stationary points, values, f''
for x in (1.5, -1.5):
x0 = x
for _ in range(2000):
x -= 0.05 * df(x)
print(x0, round(x, 3), round(f(x), 3))
# [-1.057 0.127 0.93 ] [-1.515 0.032 -0.517] [ 9.42 -3.81 6.39]
# 1.5 0.93 -0.517 | -1.5 -1.057 -1.515
# the chord test f(t u + (1 - t) v) <= t f(u) + (1 - t) f(v) on 10,000 random pairs
X = rng.normal(size=(50, 3)); y = np.sign(rng.normal(size=50))
losses = {
'least squares': lambda w: np.mean((X @ w - y) ** 2),
'logistic': lambda w: np.mean(np.logaddexp(0, -y * (X @ w))),
'hinge': lambda w: np.mean(np.maximum(0, 1 - y * (X @ w))),
'(ab - 1)^2': lambda w: (w[0] * w[1] - 1) ** 2,
}
for name, L in losses.items():
bad = 0
for _ in range(10_000):
u, v, t = rng.normal(size=3) * 2, rng.normal(size=3) * 2, rng.uniform()
bad += L(t * u + (1 - t) * v) > t * L(u) + (1 - t) * L(v) + 1e-12
print(name, bad)
# least squares 0 | logistic 0 | hinge 0 | (ab - 1)^2 1779
# (ab - 1)^2: two minimizers, a worse midpoint, and an indefinite Hessian there
g = losses['(ab - 1)^2']
print(g(np.array([1., 1, 0])), g(np.array([-1., -1, 0])), g(np.zeros(3)), np.linalg.eigvalsh([[0, -2], [-2, 0]]))
# 0.0 0.0 1.0 [-2. 2.]
# the tangent lies below: e^y >= 1 + y; at the local minimum of the opening function the flat tangent does not
print(np.exp(1.0) - 2, f(crit[0]) - f(crit[2]))
# 0.7182818284590451 -0.9980051329904565
# the Hessian of log-sum-exp is diag(p) - p p^T, a covariance matrix
z = np.array([1., 2, 3]); p = np.exp(z) / np.exp(z).sum()
H = np.diag(p) - np.outer(p, p); v = np.array([1., 0, -1])
print(p.round(4), np.linalg.eigvalsh(H).round(4), round(v @ H @ v, 4), round(p @ v**2 - (p @ v) ** 2, 4))
# [0.09 0.2447 0.6652] [-0. 0.1186 0.3709] 0.4244 0.4244
# mu and L of a quadratic, and the sandwich mu/2 |d|^2 <= f(x + d) - f(x) - grad^T d <= L/2 |d|^2
A = np.array([[2., 1], [1, 2]]); mu, L = np.linalg.eigvalsh(A)
q = lambda x: 0.5 * x @ A @ x
ok = 0
for _ in range(10_000):
x, d = rng.normal(size=2), rng.normal(size=2)
gap = q(x + d) - q(x) - (A @ x) @ d
ok += mu / 2 * d @ d - 1e-12 <= gap <= L / 2 * d @ d + 1e-12
print(mu, L, L / mu, ok)
# 1.0 3.0 3.0 10000
# the Polyak-Lojasiewicz bound f(w) - f* <= |grad f(w)|^2 / (2 mu) for logistic loss + (lam/2)|w|^2, mu = lam
lam = 0.1
F = lambda w: np.mean(np.logaddexp(0, -y * (X @ w))) + lam / 2 * w @ w
G = lambda w: -X.T @ (y / (1 + np.exp(y * (X @ w)))) / len(y) + lam * w
w = np.zeros(3)
for _ in range(20): # Newton's method finds the minimizer to machine precision
p_ = 1 / (1 + np.exp(-(X @ w)))
w -= np.linalg.solve((X.T * (p_ * (1 - p_))) @ X / len(y) + lam * np.eye(3), G(w))
Fs = F(w)
ratios = [(F(u) - Fs) / (G(u) @ G(u) / (2 * lam)) for u in rng.normal(size=(1000, 3)) * 3]
print(round(max(ratios), 3)) # at most 1: the bound holds at every sampled point
# 0.9
# a non-convex function with the PL property: x^2 + 3 sin^2 x
t = np.linspace(-20, 20, 400_001); t = t[np.abs(t) > 1e-3]
print(round((2 + 6 * np.cos(2 * t)).min(), 3), round(((2 * t + 3 * np.sin(2 * t)) ** 2 / (2 * (t**2 + 3 * np.sin(t) ** 2))).min(), 3))
# -4.0 0.176: f'' dips to -4, yet f'^2 >= 2 * 0.176 * (f - f*) on the whole range
# the convex hull of (0,0), (3,0), (0,3): weights of (1,1) and of (2,2)
P = np.array([[0., 3, 0], [0, 0, 3], [1, 1, 1]]) # columns: the points, with a row of ones for sum = 1
print(np.linalg.solve(P, [1, 1, 1]).round(3), np.linalg.solve(P, [2, 2, 1]).round(3))
# [0.333 0.333 0.333] [-0.333 0.667 0.667]
# no minimizer: logistic loss log(1 + e^-w) on one separable point, gradient descent with step 1
w = 0.0
for k in range(1, 10_001):
w += 1 / (1 + np.exp(w))
if k in (10, 100, 1000, 10_000):
print(k, round(w, 2), f'{np.log1p(np.exp(-w)):.1e}', end=' | ')
print()
# 10 2.26 9.9e-02 | 100 4.59 1.0e-02 | 1000 6.91 1.0e-03 | 10000 9.21 1.0e-04
Next#
Convexity says that the bottom of the bowl can be recognized. It does not say how to get there, or how many steps it takes. The next note proves how fast gradient descent converges on smooth and on strongly convex functions, with the condition number setting the speed, and derives Newton’s method from the quadratic model, which removes at the price of solving a linear system per step.
References#
- S. Boyd, L. Vandenberghe. Convex Optimization. Cambridge University Press, 2004. Section 3.1.8 (Jensen’s inequality for integrals and expectations). Lecture slides of Stanford EE364a: lecture 2 (convex sets, operations that preserve convexity), lecture 3 (convex functions, restriction to a line, first- and second-order conditions, log-sum-exp, Jensen’s inequality, operations that preserve convexity).
- D. Merkulov. Optimization for ML, HSE University, 2024. Lecture 4: convex sets and functions; lecture 5: strong convexity, the Polyak–Łojasiewicz condition, convexity in machine learning.
- S. Bubeck. Convex optimization: algorithms and complexity. Foundations and Trends in Machine Learning, 8(3–4), 2015. Section 3.2, Lemma 3.4 (the quadratic upper bound of a smooth function).
- H. Karimi, J. Nutini, M. Schmidt. Linear convergence of gradient and proximal-gradient methods under the Polyak–Łojasiewicz condition. ECML PKDD, 2016. Theorem 1 (linear rate under the inequality), Section 2.2 ( with ).