AI-210 · Lesson 11 of 12 · 36 min
Convexity and optimization basics
Every machine learning model is trained by solving an optimization problem: choose parameters that minimize a loss. Whether that problem is easy or hard depends largely on one property, convexity. For convex problems, any local minimum is the global minimum, gradient descent provably finds it, and the rate at which it does so can be predicted from the curvature of the loss. Linear and logistic regression, support vector machines and ridge regression are all convex. Deep neural networks are not, yet the same tools, used with care, train them successfully, and understanding the convex case is the best guide to why.
This chapter defines convex sets and functions, shows how to test for convexity, works through gradient descent on a quadratic to show how the learning rate and the condition number govern convergence, introduces Newton's method, and solves constrained problems with Lagrange multipliers. It closes with what changes for the non-convex losses of deep learning, a bridge to AI-310.
Convex sets and functions
A set is convex if the straight line between any two of its points stays inside it. Balls, half-spaces, boxes and the set of probability distributions are convex; a ring or a crescent is not.
A function \(f\) is convex if its graph lies on or below every chord: for any two points and any \(t \in [0, 1]\),
Intuitively, a convex function is bowl-shaped: it never curves downward. Two equivalent tests are easier to apply when the function is differentiable:
- First-order: the function lies above all its tangents, \(f(\mathbf{y}) \ge f(\mathbf{x}) + \nabla f(\mathbf{x})^\top(\mathbf{y} - \mathbf{x})\).
- Second-order: the Hessian is positive semidefinite everywhere (for one variable, \(f\prime\prime(x) \ge 0\)). If it is positive definite everywhere, the function is strictly convex and has at most one minimizer.
Why convexity matters
The first-order condition has a powerful consequence: if \(\nabla f(\mathbf{x}^*) = 0\) at some point, then \(f(\mathbf{y}) \ge f(\mathbf{x}^*)\) for every \(\mathbf{y}\). For a convex function, every stationary point is a global minimum, and there are no local minima to get stuck in. Convexity is also preserved by useful operations, which makes it easy to recognize: non-negative weighted sums of convex functions are convex; the composition of a convex function with a linear map is convex; and the maximum of convex functions is convex.
Common convex functions in machine learning include: squared error \(\|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2\); any norm, such as \(\|\mathbf{w}\|_1\) or \(\|\mathbf{w}\|_2^2\); the logistic loss \(\log(1 + e^{-y\,\mathbf{w}^\top\mathbf{x}})\); the hinge loss \(\max(0, 1 - y\,\mathbf{w}^\top\mathbf{x})\) of support vector machines; the log-sum-exp function behind softmax cross-entropy; and the negative log-likelihood of any exponential-family model with linear parameters. So regularized linear regression, logistic regression and SVMs are all convex problems with a unique global optimum.
Worked problem
Testing convexity
Which of these are convex? (a) \(f(x) = e^x\); (b) \(f(x) = x^3\); (c) \(f(x_1, x_2) = x_1^2 + x_1x_2 + x_2^2\); (d) \(f(x_1, x_2) = x_1^2 + 3x_1x_2 + 2x_2^2\).
Show solution
- (a) \(f\prime\prime = e^x > 0\): strictly convex.
- (b) \(f\prime\prime = 6x\), negative for \(x < 0\): not convex.
- (c) Hessian \(\begin{bmatrix} 2 & 1 \ 1 & 2 \end{bmatrix}\), eigenvalues 1 and 3 (Lesson 1), both positive: strictly convex.
- (d) Hessian \(\begin{bmatrix} 2 & 3 \ 3 & 4 \end{bmatrix}\), determinant −1, so one negative eigenvalue: not convex (Lesson 4 found its saddle point).
Answer: (a) and (c) are convex; (b) and (d) are not. A small change in a cross term can turn a bowl into a saddle.
Gradient descent on a quadratic
Gradient descent repeatedly steps against the gradient, \(\mathbf{x}_{k+1} = \mathbf{x}_k - \eta\nabla f(\mathbf{x}_k)\). A quadratic is the right model problem: near any minimum, a smooth function looks like one, with the Hessian supplying the curvature. Take \(f(\mathbf{x}) = \tfrac12\mathbf{x}^\top\mathbf{A}\mathbf{x}\) with \(\mathbf{A}\) symmetric positive definite, eigenvalues \(\lambda_{\min}\) to \(\lambda_{\max}\), and minimum at the origin. The gradient is \(\mathbf{A}\mathbf{x}\), so each step multiplies \(\mathbf{x}\) by \(\mathbf{I} - \eta\mathbf{A}\). Along each eigenvector the error is multiplied by \(1 - \eta\lambda_i\) per step. Two conclusions follow:
- Stability: the iteration converges only if \(|1 - \eta\lambda_i| < 1\) for all \(i\), which requires \(\eta < 2/\lambda_{\max}\). A learning rate above this diverges, however small it is compared with the other directions.
- Speed: the slowest direction is the one with the smallest curvature, which shrinks by \(1 - \eta\lambda_{\min}\) per step. The best fixed step, \(\eta = 2/(\lambda_{\min} + \lambda_{\max})\), gives a convergence factor of \((\kappa - 1)/(\kappa + 1)\) per step, where \(\kappa = \lambda_{\max}/\lambda_{\min}\) is the condition number.
An ill-conditioned problem (large \(\kappa\)), a long narrow valley, forces a small step to stay stable in the steep direction, so progress along the shallow direction is painfully slow, and the iterates zigzag across the valley.
import numpy as np
A = np.diag([1.0, 10.0]) # f(x) = 0.5 x^T A x, minimum at the origin
f = lambda x: 0.5 * x @ A @ x
x0 = np.array([10.0, 1.0])
for lr in (0.05, 0.15, 0.19, 0.21):
x = x0.copy()
for _ in range(100):
x = x - lr * (A @ x) # gradient of f is A x
print(f"learning rate {lr:.2f}: f after 100 steps = {f(x):.3e}")learning rate 0.05: f after 100 steps = 1.753e-03 learning rate 0.15: f after 100 steps = 3.826e-13 learning rate 0.19: f after 100 steps = 3.528e-09 learning rate 0.21: f after 100 steps = 9.495e+08
Worked problem
Explaining the results
For \(\mathbf{A} = \operatorname{diag}(1, 10)\), compute the per-step factors \(|1 - \eta\lambda|\) for each learning rate in the program, and the optimal learning rate.
Show solution
- \(\eta = 0.05\): factors 0.95 and 0.5. The shallow direction (0.95) is slow.
- \(\eta = 0.15\): factors 0.85 and 0.5. Faster.
- \(\eta = 0.19\): factors 0.81 and 0.9. Now the steep direction oscillates (\(1 - 1.9 = -0.9\)) and limits progress.
- \(\eta = 0.21\): factor \(|1 - 2.1| = 1.1 > 1\) in the steep direction: divergence, since \(0.21 > 2/10\).
- Optimal: \(\eta = 2/(1 + 10) = 0.182\), giving factor \((10 - 1)/(10 + 1) = 0.818\) in both directions.
Answer: The best step balances the two directions. The limit \(\eta < 2/\lambda_{\max}\) is sharp: 0.19 converges, 0.21 explodes. Training runs that "blow up" with a NaN loss have usually crossed this kind of limit somewhere in the loss landscape.
Practical remedies for ill-conditioning include standardizing input features (which can dramatically reduce \(\kappa\) for linear models), momentum, which accumulates velocity along consistent directions and damps oscillation, and adaptive methods such as Adam, which scale each parameter's step by an estimate of its gradient magnitude. AI-310 develops these in detail.
Newton's method
Gradient descent uses only the slope. Newton's method also uses the curvature: it fits the quadratic approximation from Lesson 4 at the current point and jumps to its minimum:
On a quadratic it reaches the exact minimum in one step, whatever the condition number, because multiplying by \(\mathbf{H}^{-1}\) undoes the uneven curvature. Near the minimum of a smooth function it converges quadratically: the number of correct digits roughly doubles each step. Its drawback is cost: forming and solving with the Hessian takes \(O(n^2)\) memory and roughly \(O(n^3)\) time for \(n\) parameters, which is impossible for a model with millions of weights. Quasi-Newton methods such as L-BFGS build a cheap approximation to \(\mathbf{H}^{-1}\) from recent gradients and work well for medium-sized convex problems; deep learning relies on first-order methods.
Worked problem
One Newton step
Apply one Newton step to \(f(\mathbf{x}) = \tfrac12\mathbf{x}^\top\mathbf{A}\mathbf{x}\) with \(\mathbf{A} = \operatorname{diag}(1, 10)\), starting at (10, 1).
Show solution
- Gradient: \(\mathbf{A}\mathbf{x} = (10, 10)\). Hessian: \(\mathbf{A}\), with inverse \(\operatorname{diag}(1, 0.1)\).
- Step: \(\mathbf{x} - \mathbf{A}^{-1}\mathbf{A}\mathbf{x} = (10, 1) - (10, 1) = (0, 0)\).
Answer: The exact minimum in one step, where gradient descent needed about 100 steps to get close. That is the value of curvature information.
Ridge regression: a convex problem solved two ways
Ridge regression minimizes \(\|\mathbf{X}\mathbf{w} - \mathbf{y}\|^2 + \lambda\|\mathbf{w}\|^2\). Its Hessian, \(2(\mathbf{X}^\top\mathbf{X} + \lambda\mathbf{I})\), is positive definite for any \(\lambda > 0\), so the problem is strictly convex with a unique solution, \(\mathbf{w}^* = (\mathbf{X}^\top\mathbf{X} + \lambda\mathbf{I})^{-1}\mathbf{X}^\top\mathbf{y}\). Regularization also improves conditioning: adding \(\lambda\) to every eigenvalue raises the smallest one most in relative terms.
import numpy as np
rng = np.random.default_rng(5)
X = rng.normal(size=(40, 5)); y = X @ rng.normal(size=5) + 0.5 * rng.normal(size=40)
lam = 2.0
w_closed = np.linalg.solve(X.T @ X + lam * np.eye(5), X.T @ y) # ridge, closed form
H = 2 * (X.T @ X + lam * np.eye(5)) # Hessian of ||Xw - y||^2 + lam ||w||^2
eig = np.linalg.eigvalsh(H)
print(f"Hessian eigenvalues from {eig.min():.1f} to {eig.max():.1f}: convex, condition number {eig.max() / eig.min():.1f}")
w = np.zeros(5); lr = 1.0 / eig.max() # a safe step size
for step in range(300):
w -= lr * (2 * X.T @ (X @ w - y) + 2 * lam * w)
print("gradient descent matches closed form:", np.allclose(w, w_closed, atol=1e-6))
print("weights:", w_closed.round(3))Hessian eigenvalues from 49.6 to 116.0: convex, condition number 2.3 gradient descent matches closed form: True weights: [-0.618 -2.021 -0.674 -0.066 1.025]
Constrained optimization and Lagrange multipliers
Many problems have constraints: probabilities must sum to one, a budget limits spending, a model's weights must stay within a norm ball. For an equality constraint \(g(\mathbf{x}) = 0\), the method of Lagrange multipliers says that at a constrained optimum the gradient of the objective is parallel to the gradient of the constraint, \(\nabla f = \lambda\nabla g\). In practice, form the Lagrangian \(\mathcal{L}(\mathbf{x}, \lambda) = f(\mathbf{x}) - \lambda g(\mathbf{x})\) and set all its partial derivatives to zero.
Worked problem
Closest point on a line
Minimize \(x^2 + y^2\) subject to \(x + y = 1\).
Show solution
- \(\mathcal{L} = x^2 + y^2 - \lambda(x + y - 1)\).
- \(\partial\mathcal{L}/\partial x = 2x - \lambda = 0\); \(\partial\mathcal{L}/\partial y = 2y - \lambda = 0\); so \(x = y = \lambda/2\).
- Constraint: \(x + y = \lambda = 1\), so \(x = y = 0.5\), with \(f = 0.5\).
Answer: The point (0.5, 0.5), the point on the line closest to the origin. The multiplier \(\lambda = 1\) is the rate at which the optimal value changes as the constraint is relaxed: its "shadow price".
Worked problem
Maximum entropy
Which distribution over \(K\) outcomes has the largest entropy?
Show solution
- Maximize \(-\sum_k p_k\ln p_k\) subject to \(\sum_k p_k = 1\).
- \(\mathcal{L} = -\sum p_k\ln p_k - \lambda(\sum p_k - 1)\); \(\partial\mathcal{L}/\partial p_k = -\ln p_k - 1 - \lambda = 0\).
- So \(\ln p_k = -1 - \lambda\) is the same for every \(k\): all \(p_k\) are equal, \(p_k = 1/K\).
Answer: The uniform distribution, with entropy \(\log K\), confirming the result stated in Lesson 9. Adding constraints on the mean leads instead to exponential-family distributions, which is one route to deriving softmax.
Inequality constraints, \(h(\mathbf{x}) \le 0\), are handled by the Karush–Kuhn–Tucker (KKT) conditions, which add the requirement that each multiplier is non-negative and is zero unless its constraint is active (tight). Support vector machines are derived this way: only the training points whose constraints are active, the support vectors, determine the solution. Convex problems with convex constraints keep the guarantee that a local optimum is global, and specialized solvers handle them reliably.
Beyond convexity: deep learning
Lesson 8 discusses why non-convex, over-parameterized models can still generalize, and Lesson 12 trains one from scratch.
The loss of a neural network, as a function of its weights, is not convex. It has symmetries (swapping two hidden units gives an identical network), many saddle points and, in principle, local minima. Yet gradient-based training works remarkably well. Several observations, partly theoretical and partly empirical, explain why:
- In very high dimensions, most stationary points are saddle points rather than local minima, and the noise in stochastic gradient descent helps escape them.
- Large, overparameterized networks tend to have many good minima connected by low-loss paths, so most reasonable starting points lead somewhere good.
- Careful initialization, normalization layers, residual connections and adaptive optimizers keep the local landscape reasonably well conditioned.
- The quadratic analysis still applies locally: near a minimum the Hessian sets the stable learning rate, and learning-rate warm-up and schedules (AI-310) manage the changing curvature during training.
Convex analysis remains the foundation. It provides the guarantees for linear models, the intuition for step sizes and conditioning, and the vocabulary in which the behaviour of deep networks is studied.
Common mistakes
MistakeAssuming a found minimum is global for any loss.
InsteadOnly for convex functions; check convexity with the Hessian or by recognizing convex building blocks.
MistakeChoosing a learning rate from the average curvature.
InsteadStability is limited by the largest curvature: \(\eta < 2/\lambda_{\max}\).
MistakeLeaving features unscaled when training with gradient descent.
InsteadStandardize features; poor scaling inflates the condition number and slows convergence.
MistakeUsing Newton's method on a model with millions of parameters.
InsteadThe Hessian is too large to form or invert; use first-order or quasi-Newton methods.
MistakeForgetting to apply the constraint after setting the Lagrangian's derivatives to zero.
InsteadThe multiplier is found by substituting back into the constraint.
Summary and key terms
- A convex function lies below its chords and above its tangents; its Hessian is positive semidefinite.
- For convex functions every stationary point is a global minimum.
- Squared error, norms, logistic and hinge losses and log-sum-exp are convex; so are sums and linear compositions of them.
- On a quadratic, gradient descent multiplies the error along eigenvector \(i\) by \(1 - \eta\lambda_i\) per step; it needs \(\eta < 2/\lambda_{\max}\).
- Convergence slows with the condition number \(\kappa = \lambda_{\max}/\lambda_{\min}\); the best fixed rate is \((\kappa - 1)/(\kappa + 1)\).
- Newton's method uses the Hessian and solves quadratics in one step but is too costly for large models.
- Lagrange multipliers solve equality-constrained problems; KKT conditions extend them to inequalities.
- Deep learning losses are non-convex, but saddle points, overparameterization and good conditioning make gradient methods work.
- Convex set
- A set containing the line segment between any two of its points.
- Convex function
- A function whose graph lies on or below every chord.
- Strictly convex
- Convex with strict inequality, giving at most one minimizer.
- Global minimum
- The lowest value of a function over its entire domain.
- Local minimum
- A point lower than all nearby points but not necessarily lowest overall.
- Learning rate
- The step size \(\eta\) in gradient descent.
- Condition number
- The ratio of the largest to smallest Hessian eigenvalue, measuring how elongated a minimum is.
- Momentum
- A gradient method that accumulates past gradients to speed progress and damp oscillation.
- Newton's method
- An optimization method that steps using the inverse Hessian times the gradient.
- Quasi-Newton method
- A method, such as L-BFGS, that approximates the inverse Hessian from gradients.
- Lagrange multiplier
- A variable introduced to enforce an equality constraint; it measures the sensitivity of the optimum to the constraint.
- Lagrangian
- The objective combined with multiplier-weighted constraints.
- KKT conditions
- Optimality conditions for problems with inequality constraints.
- Support vector
- A training point whose constraint is active in a support vector machine solution.
- Overparameterization
- Having more parameters than needed to fit the training data, common in deep networks.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Is \(f(x) = |x|\) convex? Is \(f(x) = \sqrt{|x|}\)?
Show answer
|x| is convex (it is a norm). √|x| is not: on [0, 1], the chord from (0, 0) to (1, 1) has height 0.25 at x = 0.25, but √0.25 = 0.5 lies above it.
Show that \(f(x) = \log(1 + e^x)\) is convex.
Show answer
f′ = σ(x) (the sigmoid) and f″ = σ(x)(1 − σ(x)) > 0 for all x.
For \(f(\mathbf{x}) = \tfrac12\mathbf{x}^\top\mathbf{A}\mathbf{x}\) with eigenvalues 2 and 50, what is the largest stable learning rate and the condition number?
Show answer
η < 2/50 = 0.04; κ = 25.
For the same problem, what is the optimal fixed learning rate and its per-step convergence factor?
Show answer
η = 2/(2 + 50) = 0.0385; factor (25 − 1)/(25 + 1) = 0.923.
Roughly how many steps does a factor of 0.923 per step need to reduce the error by a factor of 1000?
Show answer
ln(1000)/(−ln 0.923) = 6.91/0.080 ≈ 86 steps.
One feature is measured in metres (values about 1) and another in millimetres (about 1000). Why does this slow gradient descent for linear regression, and what fixes it?
Show answer
The Hessian XᵀX has curvature about a million times larger in the millimetre direction, a huge condition number; standardizing the features fixes it.
Apply one Newton step to \(f(x) = x^4\) from \(x = 1\).
Show answer
f′ = 4, f″ = 12; x₁ = 1 − 4/12 = 0.667 (Newton converges, but only linearly here because f″ = 0 at the minimum).
Minimize \(x^2 + 2y^2\) subject to \(x + y = 3\).
Show answer
2x = λ, 4y = λ, so x = 2y; x + y = 3 gives y = 1, x = 2; f = 4 + 2 = 6.
Why does adding L2 regularization make the least-squares problem strictly convex even when \(\mathbf{X}^\top\mathbf{X}\) is singular?
Show answer
The Hessian becomes 2(XᵀX + λI); every eigenvalue increases by 2λ > 0, so it is positive definite.
Give two reasons gradient descent works well on non-convex neural network losses.
Show answer
Any two: most stationary points in high dimensions are saddles that SGD noise escapes; overparameterized networks have many good, connected minima; initialization, normalization and residual connections keep the landscape well conditioned.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.