EVERYTHING AIAI engineering, made visual
0/23 complete
LESSON 18 · MATHEMATICS × AI · BUILD

One bowl, or a
mountain range.

A convex function has a single valley: every downhill walk ends at the same global minimum, and the math can prove it. A non-convex one has many valleys, so the starting point helps pick your ending — and deep learning lives there anyway.

90 MIN · 8 CHAPTERSPREREQ · LESSONS 04, 08
FIG. 18 / ROLLING DOWN, BOWL VS RANGE
ROLLING… global min local min
LESSON 18TYPE · BUILD~90 MINPREREQ · LESSONS 04, 08ORIGINAL LESSON ↗
THE 60-SECOND VERSIONThen show me the bowl ↓
01 / NO HOLES, NO DENTS

Convex sets survive averaging.

A set is convex when the straight segment between any two of its points stays inside. Boxes, balls and half-spaces pass; donuts, crescents and unions fail. Feasible regions built from budget limits are intersections of half-spaces — and intersections of convex sets are always convex.

t·x + (1−t)·y ∈ S for every t in [0, 1]
02 / CHORD ABOVE THE GRAPH

One inequality decides convexity.

Connect any two graph points with a straight chord. Convex means the chord never dips below the curve — equivalently f″ ≥ 0 in 1D, or a positive-semidefinite Hessian in many variables. The same statement is Jensen's inequality: averaging inputs can only undershoot averaging outputs.

f(tx + (1−t)y) ≤ t·f(x) + (1−t)·f(y)
03 / CORNERS CREATE ZEROS

The budget's shape decides sparsity.

L2 regularization constrains weights to a circle: the loss contour kisses it smoothly, so weights shrink but stay nonzero. L1 constrains them to a diamond: the first touch is a corner on an axis, so a weight becomes exactly zero. Same idea, different geometry, different model.

diamond → sparse · circle → small
MENTAL MODEL IN ONE SENTENCE

Convexity is a promise — average in, average out, one valley, every local bottom is the global one — and it holds for anything built from quadratics, norms, log-sum-exp and pointwise maxima. The moment you stack nonlinear layers, the promise is off, the start decides, and the surprise is that noisy descent still finds a good valley.

By the end you will be able to test convexity by chord, derivative or Hessian; explain why a convex model has one answer and where the guarantee breaks; tell positive semidefinite from a saddle; read λ as the price of a constraint; and see why L1 zeros weights while the SVM margin depends only on its support vectors.

CONVEX SETS AND FUNCTIONS

No dents, no holes,
no traps.

Convexity starts with a geometric promise: averaging two allowed points is also allowed, and averaging two outputs never beats averaging the outputs. That promise is what makes a whole class of problems easy.

Before any function, a set. A set S is convex if for any two points x and y in S, the straight segment between them also lies in S. In one line: every blend t·x + (1 − t)·y with t between 0 and 1 is still in S. You can always walk from any point to any other without stepping out.

A line, a plane, a rectangle, a ball and a half-space are all convex. So is the intersection of any number of convex sets — a parking-space region bounded by straight curbs is one big intersection of half-planes. A donut, a crescent, and the union of two separate circles are not: each has a hole or a gap that a straight segment can fall into.

CONVEX SETevery straight path stays inside ✓NOT CONVEXthe path crosses the hole ✗

A convex set has no dents and no holes: pick any two points and the straight segment between them never leaves.

A function f is convex when its domain is convex and the chord between any two graph points lies on or above the graph:

f(t·x + (1 − t)·y) ≤ t·f(x) + (1 − t)·f(y) for every t in [0, 1] plain English: the mixed input is never worth more than the same mix of outputs numeric check: f(x) = x², x = −1, y = 3, t = 0.5 mixed input = 0.5·(−1) + 0.5·3 = 1 f(1) = 1 mix of outputs = 0.5·1 + 0.5·9 = 5 1 ≤ 5 ✓ counterexample: f(x) = x³, x = −2, y = −1, t = 0.5 mixed input = −1.5 f(−1.5) = −3.375 mix of outputs = 0.5·(−8) + 0.5·(−1) = −4.5 −3.375 > −4.5 ✗ the chord dipped below the graph

The usual cast of convex functions, each with its reason: (bends up everywhere), |x| and max(0, x) (V-shape, corner allowed), (its own derivative), −log x for x > 0 (bends up as it dives), and every linear function ax + b — which is both convex and concave, a straight line being the boundary case. Adding convex functions keeps convexity; multiplying them usually does not.

Quick check

Which of these sets is convex?

THE CHORD TEST

A weighted average
can only undershoot.

One inequality decides convexity, and it is checkable by eye: draw a straight line between two points of the graph. If it ever dips below the curve, convexity is broken.

Take two points on a graph and connect them with a straight line — the chord. A function is convex exactly when every chord lies on or above the graph. The same statement in probability language is Jensen’s inequality: for weights that sum to 1, or more generally for an expectation,

f( Σ pᵢ·xᵢ ) ≤ Σ pᵢ·f(xᵢ) with pᵢ ≥ 0 and Σ pᵢ = 1 f( E[X] ) ≤ E[ f(X) ] plain English: for a convex f, average first then apply f, and you never get more than applying f first and averaging after. The two-point chord definition is Jensen with p₁ = t and p₂ = 1 − t.

The gap between the two sides is real and has a name for squares. With f(x) = x² and a fair coin between 1 and 3:

E[X] = 0.5·1 + 0.5·3 = 2 f(E[X]) = 2² = 4 E[f(X)] = 0.5·1² + 0.5·3² = 5 gap = 5 − 4 = 1 variance = E[X²] − (E[X])² = 5 − 4 = 1 for f(x) = x² the Jensen gap is exactly the variance: the spread of X is what the average-of-squares picks up but the square-of-average ignores.

The chord test

Pick two points on the graph and connect them with a straight chord. Convex means the chord never dips below the curve — at any point along the way, not only the midpoint.

test point: t·x + (1−t)·y = 0.25 f(test point) = 0.0625 t·f(x) + (1−t)·f(y) = 3.125 gap = chord − curve = 3.0625 gap ≥ 0 → inequality holds at this test point worst grid pair: x = -3, y = -3, t = 0.25 smallest (chord − curve) = 0 → no counterexample found: convex on this window

For x³ try both points negative (the graph bends down there); for x⁴ − 3x² the middle hump is the giveaway.

Three tests, from easiest to most rigorous
  1. Definition test. Sample points and check the chord inequality directly. It works even when derivatives do not exist — the source lesson’s convexity checker samples 1,000 random pairs and calls the function convex when it finds no violation with a 10⁻¹⁰ tolerance.
  2. Second derivative (1D). f″(x) ≥ 0 everywhere means the slope never decreases, so the graph always bends upward. Check the cast: x² has f″ = 2 ✓; eˣ has f″ = eˣ > 0 ✓; |x| has f″ = 0 away from the corner, and the corner joins two upward pieces ✓; x³ has f″ = 6x, negative for x < 0 ✗.
  3. Hessian (many variables). The matrix of second partial derivatives must be positive semidefinite at every point. Chapter 04 takes this apart with numbers; the shorthand is that every eigenvalue must be ≥ 0.

All three tests answer the same question. Use the definition when you can only evaluate f, the second derivative when f is smooth in one variable, and the Hessian when there are several variables.

Quick check

Which function fails the chord test somewhere on its domain?

ONE VALLEY, ONE ANSWER

Any local bottom
is the global bottom.

This is the theorem the whole lesson exists for. Without it, training is a search with no guarantees. With it, walking downhill is a proof of optimality.

A local minimum is a point lower than everything nearby; a global minimum is the lowest point anywhere. For a convex function the two definitions collapse: every local minimum is global. Gradient descent cannot be trapped, so it cannot need a restart, a schedule, or a lucky seed. The answer it walks to is the answer.

One valley or many?

Pick a function and a starting point, then run gradient descent. On a convex function every start funnels to the same bottom; on a non-convex one the start decides which valley you keep.

start x₀ = 2.5, f(x₀) = 27.44 after 320 steps: x = 0.95299, f(x) = -0.65802 gradient slope there: f′(x) = 2.7971e-10 settled at a LOCAL minimum that is not global global minimum value: -1.3573 at x = -1.041 stability bound for this function: lr < 2 / max|f″| = 0.01923 ✓ this run is stable

On x⁴ − 2x² + 0.35x, starting left of the hump settles at f ≈ −1.38, starting right of it at f ≈ −0.66 — same function, two different answers, and only one of them is the global minimum. The convex x² always ends at the one bottom, no matter where you start.

Why: a proof you can read

Suppose, for contradiction, that a convex f has a local minimum at x* that is not global. Then some point y has f(y) < f(x*).

  1. Walk from x* toward y: the points x(t) = (1 − t)·x* + t·y, for t between 0 and 1.
  2. Convexity applies: f(x(t)) ≤ (1 − t)·f(x*) + t·f(y).
  3. Because f(y) < f(x*), the right side is strictly less than f(x*), for every t > 0.
  4. That means points arbitrarily close to x* have values below f(x*) — so x* was never a local minimum. Contradiction. ∎
numeric sanity check: f(x) = x², local candidate x* = 0 (global), y = 1 t = 0.1: x(t) = 0.1, f = 0.01 chord bound (1 − 0.1)·f(0) + 0.1·f(1) = 0 + 0.1 = 0.1 0.01 ≤ 0.1 ✓ — and 0.01 < f(0) would have contradicted local minimality, but here f(y) > f(x*), so the walk climbs instead: no contradiction. the theorem needs a y that is strictly lower to trigger.

The fine print. Neural networks are not convex. A network with a hidden layer and a nonlinearity like ReLU has a landscape full of peaks, valleys and saddles, and the value you reach depends on the initialization. The surprise is that this is not fatal:

  • Saddles, not valleys, are the obstacle. A critical point is a spot where the gradient is zero. In n dimensions the chance that all n curvature directions point up — making it a true local minimum — is roughly 2⁻ⁿ. For n = 20 that is about one in a million; for a network with thousands of parameters it is astronomically small, so nearly every critical point is a saddle that a little noise can slide off.
  • The minima that exist are close to optimal. In high-dimensional overparameterized models, bad isolated valleys are rare and the good ones are plentiful and connected.
  • Noise helps. Mini-batch SGD adds randomness that kicks the optimizer off saddle points and out of sharp valleys, biasing it toward flat regions that generalize better.
Quick check

A non-convex loss has two local minima, one with loss 2.0 and one with loss 2.1. What does gradient descent from a random start guarantee?

TANGENTS, HESSIANS, NEWTON

The tangent below.
The Hessian decides.

Convexity has two calculus fingerprints: every tangent plane lies below the graph, and every Hessian is positive semidefinite. The second one is also a roadmap for a much faster optimizer.

First-order condition. For a differentiable f, convexity is equivalent to this: at every point x, the tangent line (or plane) sits on or below the graph.

f(y) ≥ f(x) + ∇f(x)ᵀ(y − x) for all x and y plain English: the linear prediction from the local slope always under-promises. Numeric check with f(x) = x²: x = 2, slope f′(2) = 4, y = 3 tangent value = 4 + 4·(3 − 2) = 8 f(3) = 9 9 ≥ 8 ✓ flip the sign, f(x) = −x² (concave): tangent value = −4 − 4·(3 − 2) = −8 f(3) = −9 −9 ≥ −8 ✗

Second-order condition. In one variable, f″(x) ≥ 0 everywhere. In several variables the collection of second derivatives is a matrix — the Hessian — and it must be positive semidefinite (PSD) everywhere: all eigenvalues ≥ 0. For a symmetric 2×2 matrix [[a, b], [b, d]] there is a three-check shortcut: a ≥ 0, d ≥ 0, and a·d − b² ≥ 0.

worked example: f(x, y) = x² + 3xy + y² ∂²f/∂x² = 2 ∂²f/∂x∂y = 3 ∂²f/∂y² = 2 H = [[2, 3], [3, 2]] a·d − b² = 4 − 9 = −5 < 0 → NOT PSD eigenvalues: trace = 4, det = −5, so λ² − 4λ − 5 = 0 → λ = 5 and λ = −1 the function bends up along (1, 1): f(1, 1) = 1 + 3 + 1 = 5 and down along (1, −1): f(1, −1) = 1 − 3 + 1 = −1 one bad direction is enough: the origin is a saddle, so f is not convex — even though x² and y² alone are. The cross term did it.

Hessian curvature checker

The Hessian is the matrix of second derivatives. Move the evaluation point and watch the local quadratic model: ellipses mean curvature up both ways, hyperbola-like curves mean a saddle.

H(0.5, 0.5) = [[2, 3], [3, 2]] eigenvalues: 5 and -1 2×2 PSD test: a = 2 ≥ 0? ✓ d = 2 ≥ 0? ✓ a·d − b² = -5 ≥ 0? ✗ verdict: indefinite · up in one direction, down in another (saddle) constant Hessian, cross term makes one eigenvalue negative. To be CONVEX the Hessian must pass this test at every point, not just here.

Try the quartic at (0, 0) — one eigenvalue is negative, so the origin is a saddle — then at (1, 0), where the local model is only semidefinite. Convexity needs PSD everywhere: one bad point is enough to break it.

Newton’s method turns the Hessian into an optimizer. Gradient descent takes a step proportional to the slope; Newton fits the local quadratic bowl and jumps straight to its bottom:

gradient descent: x ← x − lr · ∇f(x) one number to tune Newton's method: x ← x − H(x)⁻¹ · ∇f(x) no learning rate, exact curvature price: H is n×n — O(n²) memory to store and O(n³) work per step. for n = 1,000,000 weights that is 10¹² numbers and about 10¹⁸ operations, which is why deep learning replaces H with cheap surrogates: L-BFGS (curvature from recent gradients), Adam (a diagonal guess), or Hessian-free methods (Hessian-vector products without forming H).
Newton is exact on quadratics; gradient descent is not

Take f(x, y) = 5x² + y², gradient (10x, 2y), Hessian diag(10, 2).

Newton from (10, 10): x ← 10 − (10·10)/10 = 0 y ← 10 − (2·10)/2 = 0 one step, done — from anywhere. In 1D the same algebra: for f = ax² + bx + c, x − f′/f″ = x − (2ax + b)/(2a) = −b/(2a), the vertex. gradient descent at lr = 0.1: x ← (1 − 10·0.1)·x = 0·x x is exact after one step y ← (1 − 2·0.1)·y = 0.8·y y shrinks by 20% per step from y = 10, reaching y < 10⁻⁵ (loss < 10⁻¹⁰) needs n = ln(10⁻⁶)/ln(0.8) ≈ 61.9 → 62 steps. Pushing to 10⁻¹¹ takes 114. why so uneven? the Hessian eigenvalues 10 and 2 differ by 5 — the condition number κ = 10/2 = 5. The larger it is, the more the steep direction caps the learning rate while the shallow direction crawls. Newton divides by curvature, so it does not care.

Rosenbrock check (and a correction). The classic test function f = (1 − x)² + 100(y − x²)² has Hessian [[2 + 1200x² − 400y, −400x], [−400x, 200]]. At the minimum (1, 1): [[802, −400], [−400, 200]], with eigenvalues ≈ 1001.6 and 0.4 — κ ≈ 2508, a valley 2,500 times narrower than it is long, which is why first-order methods zigzag there. The reference notebook’s answer to this exercise says (−1, 1) has a negative eigenvalue; recomputing gives [[802, 400], [400, 200]] there with eigenvalues 1001.6 and 0.4, both positive. A true saddle point on this surface is (0, 2), where the Hessian is [[−798, 0], [0, 200]] with eigenvalues −798 and 200 — one direction up, one down.

Build it · convexity checker + 2-D Newtonpython
import random

def is_convex(f, dim, trials=1000, bounds=(-5, 5)):
    """Empirical chord test: return the first counterexample, if any."""
    for _ in range(trials):
        x = [random.uniform(*bounds) for _ in range(dim)]
        y = [random.uniform(*bounds) for _ in range(dim)]
        t = random.random()
        mid = [t * a + (1 - t) * b for a, b in zip(x, y)]
        if f(mid) > t * f(x) + (1 - t) * f(y) + 1e-10:
            return False, (x, y, t)
    return True, None

def newton_2d(grad, hess, x, steps=20):
    """x <- x - H^-1 g, using the 2x2 inverse from Lesson 02."""
    for _ in range(steps):
        g = grad(x)
        (a, b), (c, d) = hess(x)
        det = a * d - b * c
        if abs(det) < 1e-15:
            break
        dx = [(d * g[0] - b * g[1]) / det,
              (-c * g[0] + a * g[1]) / det]
        x = [x[0] - dx[0], x[1] - dx[1]]
        if g[0] ** 2 + g[1] ** 2 < 1e-12:
            break
    return x

# f = 5x^2 + y^2: grad (10x, 2y), hess [[10, 0], [0, 2]]
print(newton_2d(lambda v: [10 * v[0], 2 * v[1]],
                lambda v: [[10, 0], [0, 2]], [10, 10]))  # -> [0.0, 0.0]
Both routines print numbers this chapter asks you to verify: chord violations on a candidate function, and a Newton step that lands on the exact minimum of a quadratic.
CONVEX IN THE WILD

The losses you meet
before the neural net.

Most classical ML models are convex on purpose: least squares, ridge, LASSO, logistic regression and the SVM. Each one is built from quadratics, norms, log-sum-exp or a maximum of linear functions — pieces that preserve convexity.

Quadratics: least squares. Fitting a line means minimizing f(w) = ‖Xw − y‖², whose gradient is 2Xᵀ(Xw − y) and whose Hessian is 2XᵀX. That Hessian is always PSD, and the reason is a one-liner: for any direction z, zᵀXᵀXz = (Xz)ᵀ(Xz) = ‖Xz‖² ≥ 0 — a squared length cannot be negative. Least squares is convex no matter what data you feed it.

numeric check: X = [[1, 1], [2, 1]], direction z = (1, −1) Xz = [1·1 + 1·(−1), 2·1 + 1·(−1)] = [0, 1] ‖Xz‖² = 0² + 1² = 1 XᵀX = [[5, 3], [3, 2]] zᵀ(XᵀX)z = 5 − 3 − 3 + 2 = 1 ✓ matches ‖Xz‖² exactly. the same quadratic in disguise: ridge regression adds λ‖w‖², and XᵀX + λI stays PSD, so the answer is still unique for any λ > 0.

Norms. ‖w‖₁ and ‖w‖₂ are convex because they obey the triangle inequality ‖a + b‖ ≤ ‖a‖ + ‖b‖ and scale positively. Check it with w = (1, 2) and z = (2, −1): ‖w + z‖₁ = ‖(3, 1)‖₁ = 4, while ‖w‖₁ + ‖z‖₁ = 3 + 3 = 6, so 4 ≤ 6 ✓. Penalties built from norms therefore keep a loss convex while pulling weights toward zero.

Log-sum-exp: the soft maximum. Define LSE(x) = log(Σᵢ e^(xᵢ)). It is convex, it lies between the maximum and the maximum plus log n, and its gradient is the softmax function — so it is also the piece that makes cross-entropy well-behaved.

x = (1, 2), n = 2 max(x) = 2 LSE = log(e¹ + e²) = log(2.718 + 7.389) = log(10.107) = 2.313 max + log n = 2 + 0.693 = 2.693 2 ≤ 2.313 ≤ 2.693 ✓ softmax(x) = (e¹, e²)/(e¹ + e²) = (0.269, 0.731) — the gradient of LSE. it spreads its weight smoothly instead of picking the winner, which is exactly what a differentiable maximum has to do.

Logistic regression: convex where it matters. For a single example with score z = wᵀx and label y in {0, 1}, the negative log-likelihood collapses to log(1 + eᶻ) − y·z. Its second derivative in z is σ(z)·(1 − σ(z)) with σ(z) = 1/(1 + e^(−z)) — a product of two positive numbers, so ≥ 0. Composing with the linear score z = wᵀx keeps it convex in the weights.

numeric check: z = 2, y = 1 σ(2) = 1/(1 + e⁻²) = 1/(1 + 0.1353) = 0.8808 loss = −log(σ(2)) = −log(0.8808) = 0.1269 other form: log(1 + e²) − 1·2 = log(8.389) − 2 = 2.1269 − 2 = 0.1269 ✓ curvature: σ·(1 − σ) = 0.8808·0.1192 = 0.105 > 0 confident and wrong is expensive: z = −2, y = 1 gives loss = −log(σ(−2)) = −log(0.1192) = 2.1269 — over 16× bigger.
f″ ≥ 0 · convex|x|f″ ≥ 0 · convexf″ ≥ 0 · convex−log xf″ ≥ 0 · convexmax(0, x)f″ ≥ 0 · convex

The working convex vocabulary: quadratic, absolute value, exponential, negative log, and max(0, x). Corners are fine — a kink joins two upward pieces, so convexity survives.

ProblemConvex?Why
Linear regression (MSE)YesLoss is quadratic in the weights
Logistic regression (log-loss)Yeslog(1 + eᶻ) is convex in the linear score
SVM (hinge loss)YesMaximum of linear functions
LASSO (L1) and ridge (L2)YesConvex loss + convex penalty
Neural network, any depthNoNonlinear activations between layers
k-meansNoDiscrete assignment step
Matrix factorizationNoProduct of two unknowns
The four rules that build convex functions (with checks)
  1. Sum. f + g is convex. Check: x² has f″ = 2, and |x| has a kink at 0 joining slopes −1 and +1. Their sum still has a slope that never decreases, so x² + |x| is a bowl with a corner.
  2. Nonnegative scaling. a·f is convex for a ≥ 0; negative a flips it concave. Check: 3x² stays a bowl; −3x² becomes a cap.
  3. Affine composition. f(Ax + b) is convex whenever f is. Check: (2x − 1)² is x² with a shift and stretch, still a bowl. This is why logistic regression is convex in w: it is a convex function of the linear score z = wᵀx.
  4. Pointwise maximum. max(f, g) is convex. Check: max(x, 0) is ReLU, which opens upward on both pieces; the hinge loss max(0, 1 − y·z) is the same trick with a tilt.

Turn each rule around and it becomes a warning: a difference of convex functions, a product of two unknowns, or a composition through a non-linear non-convex function can all destroy the guarantee. That is exactly the line neural networks cross.

LAGRANGE & KKT

Every limit
has a price.

Real problems come with budgets, and a budget bends the answer. Lagrange multipliers turn the boundary into a number, and the KKT conditions tell you exactly which limits are actually doing work.

An unconstrained problem says “go as low as you can”. A constrained problem adds a rule: minimize f(x) subject to g(x) = 0 (equality) or gᵢ(x) ≤ 0 (inequality). The set of points that satisfy the rules is the feasible set, and the answer is the lowest point inside it.

Lagrange multipliers. For an equality constraint, bundle the rule into the objective with a new variable λ:

minimize f(x) subject to g(x) = 0 ↓ Lagrangian: L(x, λ) = f(x) + λ·g(x) stationarity: ∂L/∂x = ∇f + λ·∇g = 0 and ∂L/∂λ = g(x) = 0 plain English: at the constrained bottom you cannot slide along the constraint to improve f — which happens exactly when ∇f and ∇g point along the same line. λ measures the exchange rate between f and g.

Lagrange geometry: parallel gradients

The circles are level sets of f; the line is the constraint. The constrained minimum is the point where a circle first touches the line — and there the two gradients point along the same line.

constraint: 0.454·x + 0.891·y = 4 constrained minimum: (2.984, 2.969) f at that point = 0.0012244 ∇f = (-0.03177, -0.06235) ∇g = (0.454, 0.891) λ = 0.06998 (∇f + λ·∇g = 0) ∇f × ∇g = 0 → parallel ✓

Drag the line and the circle centre: the touch point slides until the two arrows line up. λ is the exchange rate — how much f would drop per unit of extra constraint budget.

Two worked problems, fully checked

Problem A (the lesson example). Minimize f(x, y) = x² + y² on the line x + y = 1.

L = x² + y² + λ(x + y − 1) ∂L/∂x = 2x + λ = 0 → x = −λ/2 ∂L/∂y = 2y + λ = 0 → y = −λ/2 so x = y ∂L/∂λ = x + y − 1 = 0 → 2x = 1 → x = y = 0.5, λ = −1 check: ∇f = (2x, 2y) = (1, 1) at the solution, ∇g = (1, 1): parallel ✓ the point (0.5, 0.5) is the foot of the perpendicular from the origin to the line, and f = 0.25 + 0.25 = 0.5.

Problem B (exercise 3). Minimize f(x, y) = (x − 3)² + (y − 3)² subject to x + 2y = 4 — the offset bowl from the lab.

∂L/∂x = 2(x − 3) + λ = 0 → x = 3 − λ/2 ∂L/∂y = 2(y − 3) + 2λ = 0 → y = 3 − λ constraint: (3 − λ/2) + 2(3 − λ) = 4 → 9 − 5λ/2 = 4 → λ = 2 so (x, y) = (2, 1) and f = 1² + 2² = 5 gradient check: ∇f = (2(2−3), 2(1−3)) = (−2, −4) = −2·(1, 2) = −2·∇g ✓ nearby feasible point (2.4, 0.8): f = 0.36 + 4.84 = 5.2 > 5 ✓ the free minimum (3, 3) is not feasible at all: 3 + 2·3 = 9 ≠ 4.

KKT conditions. Inequality constraints gᵢ(x) ≤ 0 add a fourth rule. A point is optimal (under mild conditions) when:

1. Stationarity: ∇f(x) + Σᵢ λᵢ·∇gᵢ(x) = 0 2. Primal feasibility: gᵢ(x) ≤ 0 for every i 3. Dual feasibility: λᵢ ≥ 0 for every i 4. Complementary slackness: λᵢ·gᵢ(x) = 0 for every i rule 4 is the interesting one. Each constraint is either active (gᵢ = 0, the solution sits on the boundary, λᵢ may be positive) or slack (gᵢ < 0, the constraint is irrelevant and λᵢ must be 0). Never both.
toy check: minimize (x − 2)² subject to x ≤ 1 unconstrained minimum: x = 2, but 2 > 1 → infeasible stationarity: 2(x − 2) + λ = 0 with x = 1 → λ = 2 ≥ 0 ✓ active constraint toy check 2: same objective subject to x ≤ 5 x = 2 is feasible, λ = 0, g(2) = 2 − 5 = −3 < 0 → slack λ·g = 0·(−3) = 0 ✓ and the constraint never touched the answer. in an SVM the active constraints are the support vectors. Every other point has λᵢ = 0 and can move around without changing the boundary.
Quick check

At the optimum of a KKT problem, a constraint has g(x) = −4 and λ = 6. What must be true?

DIAMONDS, CIRCLES, MARGINS

The shape of the budget
decides what you learn.

Regularization is constrained optimization in disguise, and the shape of the constraint explains sparsity: a diamond has corners on the axes, a circle does not. The same geometry gives the SVM its margin.

Penalty or budget, same problem. “Minimize loss + λ·‖w‖²” and “minimize loss subject to ‖w‖² ≤ t” describe the same family of answers — λ is the Lagrange multiplier of the budget, and choosing one pins down the other. In two dimensions the L2 budget is a circle and the L1 budget is a diamond (a square standing on a corner). The solution is where the smallest loss contour first touches the shape.

Why the diamond makes zeros

The shaded region is the budget; the circles are loss contours. Watch where the smallest contour touches: the diamond at a corner on an axis, the circle at a smooth point with both weights alive.

free minimum: (3, 2) constraint |w₁| + |w₂| ≤ 1 solution w* = (1, 0) loss at w* = 8 zero coordinates: 1 → sparse! the first loss contour touches at a diamond corner, where one weight is exactly 0 — that is LASSO.

Both penalties shrink the weights; only L1 can switch a feature off. The corner is the whole story: it is the only place on a diamond where a coordinate can be exactly zero while still touching the boundary.

numeric check (the lesson's exercise): minimize (w₁ − 3)² + (w₂ − 2)² subject to |w₁| + |w₂| ≤ 1. The free minimum (3, 2) has |3| + |2| = 5 > 1. corner (1, 0): (1−3)² + (0−2)² = 4 + 4 = 8 ← best corner (0, 1): (0−3)² + (1−2)² = 9 + 1 = 10 corner (−1, 0): (−1−3)² + (0−2)² = 16 + 4 = 20 corner (0, −1): (0−3)² + (−1−2)² = 9 + 9 = 18 edge point (0.8, 0.2): 2.2² + 1.8² = 4.84 + 3.24 = 8.08 > 8 ✓ so w* = (1, 0): one coordinate exactly zero — sparsity, not smallness. circle version, ‖w‖₂ ≤ 1: closest point to (3, 2) is (3, 2)/√13 ≈ (0.83, 0.55), both coordinates nonzero. The constraint's corners are what create zeros.

SVM margins. A support vector machine looks for the separating line (or hyperplane) with the widest possible buffer. For a unit direction w and offset b, the constraints are yᵢ·(wᵀxᵢ + b) ≥ 1; the band between the two dashed lines has width 2/‖w‖. Maximizing the margin is the same as minimizing ‖w‖², so the SVM is a convex quadratic program — and it is the constrained optimization behind the most famous KKT example in ML.

SVM margin: only the nearest points matter

This dataset has a perfect separating line at angle 0. Tilt or shift it and the margin collapses; put it back and the two ringed support vectors alone are holding the boundary in place.

boundary: 1·x + 0·y + (0) = 0 geometric margin = 2·min slack = 2 points inside the margin band: 0 misclassified: 0 slacks y·(wᵀx + b): +(1, 0) → 1 +(2, 1.5) → 2 +(2.5, -0.5) → 2.5 −(-1, 0) → 1 −(-2, -1.5) → 2 −(-2.5, 0.5) → 2.5 support vectors (slack = min): (1, 0), (-1, 0) the other points could move until they touch the band and nothing changes — λ = 0.

Max-margin at angle 0, b = 0: margin 2, support vectors (1, 0) and (−1, 0). The four handier points have slack ≥ 2 and never appear in the SVM solution — that is complementary slackness in action.

Duality in one paragraph (and why kernels need it)

Every constrained problem has a companion dual: maximize over λ ≥ 0 the minimum over x of the Lagrangian. For convex problems the two optima are equal (strong duality), so you may solve whichever is easier. The SVM dual depends on the data only through dot products xᵢᵀxⱼ, and those dot products can be replaced by a similarity function K(xᵢ, xⱼ). That is the kernel trick: a linear method becomes nonlinear without ever building the high-dimensional feature map, because no coefficient ever needs the map explicitly — only the pairwise similarities.

SVM primal: minimize ½‖w‖² subject to yᵢ(wᵀxᵢ + b) ≥ 1 SVM dual: maximize Σαᵢ − ½ΣΣ αᵢαⱼyᵢyⱼ·(xᵢᵀxⱼ) subject to αᵢ ≥ 0 and Σαᵢyᵢ = 0 support vectors: the points with αᵢ > 0, exactly the active constraints. replace xᵢᵀxⱼ with K(xᵢ, xⱼ) → kernel SVM.
CHECK YOURSELF

Five questions.
Then the terms worth keeping.

Answer before you look. The complementary-slackness and non-convex-SGD questions are the ones that separate remembering the words from knowing what they do.

0 / 5 answered · 0 correct

01What is the defining property of a convex function?

02Which of these ML problems has a convex loss landscape?

03Newton's method converges to the minimum of f(x) = 5x² + 3x + 1 in how many steps?

04In the KKT conditions, what does complementary slackness (λᵢ·gᵢ(x) = 0) mean?

05Why does SGD find good solutions in non-convex neural network landscapes despite the lack of convexity guarantees?

Key terms, demystified

Click a card to swap the lazy description for what it actually means.

Exercises from the lesson

Four problems, all fully worked. The Rosenbrock correction lives in chapter 04; these solutions show every number.

  1. Convexity gallery: test f(x) = x⁴, f(x) = sin x, f(x, y) = x² + y², f(x, y) = x·y and f(x) = max(x, 0). Use the second-derivative/Hessian test and one chord check each, and explain each verdict.
    Show one worked answer

    x⁴: f″ = 12x² ≥ 0 everywhere, so convex (the graph flattens at 0 but never bends down). Chord check x = −1, y = 2, t = 0.5: midpoint 0.5, f = 0.0625; chord = 0.5·1 + 0.5·16 = 8.5; 0.0625 ≤ 8.5 ✓. sin x: f″ = −sin x changes sign, so neither convex nor concave; chord check x = 0, y = π, t = 0.5: midpoint π/2, f = 1, chord = 0.5·0 + 0.5·0 = 0, and 1 > 0 — the chord dips below the graph ✗. x² + y²: Hessian 2I has eigenvalues 2, 2 ≥ 0, so convex. x·y: Hessian [[0, 1], [1, 0]] has eigenvalues +1 and −1 — a saddle; check direction (1, 1): f = 1 > 0, direction (1, −1): f = −1 < 0 around the origin. max(x, 0): the maximum of two linear functions is convex (and ReLU inherits it), even though it has a corner at 0; chord check x = −2, y = 1, t = 0.5: midpoint −0.5, f = 0; chord = 0.5·0 + 0.5·1 = 0.5, and 0 ≤ 0.5 ✓.

  2. Newton vs gradient descent race: run both on f(x, y) = 50x² + y² from (10, 10). How many steps does each need for the loss to fall below 10⁻¹⁰? What happens as the condition number grows?
    Show one worked answer

    Newton: ∇f = (100x, 2y) and H = diag(100, 2), so one step x ← x − H⁻¹∇f maps (10, 10) to (0, 0) exactly; the loss is 0 after step 1 because the model is the function. Gradient descent: x ← (1 − 100·lr)·x and y ← (1 − 2·lr)·y, stable only for lr < 0.02. Take lr = 0.015: the x factor is −0.5, so |x| halves each step, while the y factor is 0.97. The y coordinate dominates the loss: 10·0.97ⁿ < 10⁻⁵ needs n = ln(10⁻⁶)/ln(0.97) ≈ 453.6, so about 454 steps — roughly 454× more work than Newton. The Hessian eigenvalues are 100 and 2, so the condition number κ = 50; the number of descent steps grows roughly in proportion to κ, while Newton does not care. At lr = 0.02 or above the x update has |factor| ≥ 1 and the run diverges.

  3. Lagrange multiplier geometry: minimize f(x, y) = (x − 3)² + (y − 3)² subject to x + 2y = 4. Solve it, then verify that ∇f is parallel to ∇g at the answer and that no nearby feasible point beats it.
    Show one worked answer

    Form L = (x − 3)² + (y − 3)² + λ(x + 2y − 4). Stationarity: ∂L/∂x = 2(x − 3) + λ = 0 → x = 3 − λ/2; ∂L/∂y = 2(y − 3) + 2λ = 0 → y = 3 − λ. The constraint gives (3 − λ/2) + 2(3 − λ) = 4 → 9 − 5λ/2 = 4 → λ = 2, so (x, y) = (2, 1). Checks: 2 + 2·1 = 4 ✓; f(2, 1) = 1 + 4 = 5; ∇f = (2(2 − 3), 2(1 − 3)) = (−2, −4) and ∇g = (1, 2), so ∇f = −2·∇g — parallel with λ = 2 ✓. A nearby feasible point (2.4, 0.8): f = (−0.6)² + (−2.2)² = 0.36 + 4.84 = 5.2 > 5, confirming the minimum; the unconstrained minimizer (3, 3) is not on the line at all (3 + 6 = 9 ≠ 4).

  4. Regularization constraint: minimize f(x, y) = (x − 3)² + (y − 2)² subject to |x| + |y| ≤ 1. Show that the solution has one coordinate exactly zero, and explain why the diamond does this while a circle would not.
    Show one worked answer

    The unconstrained minimizer (3, 2) has |3| + |2| = 5 > 1, so the solution sits on the diamond's boundary. Check the four corners: (1, 0) → 4 + 4 = 8; (0, 1) → 9 + 1 = 10; (−1, 0) → 16 + 4 = 20; (0, −1) → 9 + 9 = 18. A generic edge point (0.8, 0.2) gives 2.2² + 1.8² = 4.84 + 3.24 = 8.08 > 8, so the corner (1, 0) wins, with f = 8 and y = 0 exactly. At (1, 0) the constraint x + y ≤ 1 is active, ∇f = (−4, −4) is parallel to ∇g = (1, 1) (λ = 4), and complementary slackness holds. The diamond's corners lie on the axes, and the loss contours — circles around (3, 2) — reach the constraint set first at that corner. A circle constraint has no corners, so the tangency point is generally smooth with both coordinates nonzero: for ‖w‖₂ ≤ 1 the closest point to (3, 2) is (3, 2)/√13 ≈ (0.83, 0.55) and neither weight is zero. Sparsity is a property of the constraint's shape, not of the penalty constant.

Terms this lesson borrows from later lessons (or outside)

You do not need to master these here. Each one gets a proper treatment in its own lesson; the one-line meaning is enough to keep reading. Orange dotted underlines in the prose point back to this list.

  • logistic regressionLinear score followed by a sigmoid, used to predict the probability of a yes/no outcome. Its negative log-likelihood is convex. (Lesson 07)
  • generalizationHow well a model performs on new data it did not train on. Flat minima found by noisy SGD tend to generalize better. (Lesson 15)
  • initializationThe random starting values of the weights before training. On a non-convex landscape the start helps decide which minimum you reach. (Lesson 08)
  • eigenvalueNumbers λ with Av = λv: directions a matrix only stretches. Positive semidefinite means all eigenvalues ≥ 0. (Lesson 03)
  • gradientThe vector of partial derivatives, pointing uphill. Convexity says the tangent plane built from it lies below the graph. (Lesson 04)
  • regularizationAdding a penalty to the loss to keep weights small. L1 and L2 penalties are Lagrange multipliers of constraint budgets. (Lesson 14)
  • kernel trickReplacing dot products xᵢᵀxⱼ with a similarity function K(xᵢ, xⱼ) so a linear method becomes nonlinear without building the high-dimensional map. The SVM dual is the classic home of this trick (outside this lesson).
KEEP GOING

A picture is a start.
Practice is the rest.

This lesson is a port of an open course. Everything here traces back to it — and the next step is running the code yourself.

Lesson text adapted from AI Engineering from Scratch (Phase 01, Lesson 18) and the Math Foundations Notebook reference build. The rolling-bowl hero, chord test, landscape explorer, Hessian checker, Lagrange geometry, L1-vs-L2 and SVM-margin labs are original to this page, as are the convexity gallery, the extra numeric checks inside every derivation, and the correction to the reference notebook's Rosenbrock eigenvalue claim (the saddle used here is (0, 2), not (−1, 1)). Every displayed number is computed in your browser from the values shown. All labs run in your browser.