Optimization with Python
Every algorithm in this course needs the same three ingredients: a function to evaluate, its gradient (and sometimes its Hessian), and a loop that updates a point. This lesson sets up those ingredients in NumPy and shows how to check them, so that later lessons can focus on the ideas.
A test function: the Rosenbrock valley
The Rosenbrock function is the classic benchmark for unconstrained methods:
Its minimum is , at the bottom of a long, curved, flat-bottomed valley. Simple methods find the valley quickly and then crawl along it. Its gradient and Hessian are
In code, write each as a function of one NumPy vector:
import numpy as np
def f(p):
x, y = p
return (1 - x)**2 + 100 * (y - x**2)**2
def grad(p):
x, y = p
return np.array([-2 * (1 - x) - 400 * x * (y - x**2), 200 * (y - x**2)])
def hess(p):
x, y = p
return np.array([[2 - 400 * y + 1200 * x**2, -400 * x], [-400 * x, 200.0]])
p = np.array([-1.2, 1.0]) # the traditional starting point
print("f:", round(f(p), 4))
print("grad:", np.round(grad(p), 4))
print("hess eigenvalues:", np.round(np.linalg.eigvalsh(hess(p)), 4))f: 24.2
grad: [-215.6 -88. ]
hess eigenvalues: [ 23.633 1506.367]
Always check your gradient
A wrong gradient is the most common bug in optimization code, and it does not crash: the method just converges slowly or to the wrong point. Compare against central differences, , whose error shrinks like :
import numpy as np
f = lambda p: (1 - p[0])**2 + 100 * (p[1] - p[0]**2)**2
grad = lambda p: np.array([-2 * (1 - p[0]) - 400 * p[0] * (p[1] - p[0]**2), 200 * (p[1] - p[0]**2)])
def num_grad(f, p, h=1e-6):
return np.array([(f(p + h * e) - f(p - h * e)) / (2 * h) for e in np.eye(len(p))])
rng = np.random.default_rng(0)
worst = 0.0
for _ in range(5):
p = rng.uniform(-2, 2, size=2)
g, n = grad(p), num_grad(f, p)
worst = max(worst, np.linalg.norm(g - n) / np.linalg.norm(g))
print(f"largest relative error over 5 random points: {worst:.1e}")largest relative error over 5 random points: 2.2e-10
A relative error around or smaller means the gradient is right; around or larger means a bug.
A reusable loop with a history
Most methods have the shape "compute a direction, choose a step, move, repeat until the gradient is tiny". Keeping a history of values makes convergence visible:
import numpy as np
def minimize(f, grad, x0, step, tol=1e-8, max_iter=10000):
x = np.asarray(x0, dtype=float)
history = [f(x)]
for k in range(max_iter):
g = grad(x)
if np.linalg.norm(g) < tol:
break
x = x - step * g
history.append(f(x))
return x, history
f = lambda p: (p[0] - 3)**2 + 4 * (p[1] + 1)**2
grad = lambda p: np.array([2 * (p[0] - 3), 8 * (p[1] + 1)])
x, hist = minimize(f, grad, [0.0, 0.0], step=0.1)
print("solution:", np.round(x, 6), " iterations:", len(hist) - 1)
print("f after 1, 5, 20 steps:", [float(f"{hist[k]:.3e}") for k in (1, 5, 20)])solution: [ 3. -1.] iterations: 91
f after 1, 5, 20 steps: [5.92, 0.9664, 0.001196]
The production check: scipy.optimize
SciPy's minimize wraps many of the methods in this course behind one interface. We use it to confirm our own results:
import numpy as np
from scipy.optimize import minimize
f = lambda p: (1 - p[0])**2 + 100 * (p[1] - p[0]**2)**2
grad = lambda p: np.array([-2 * (1 - p[0]) - 400 * p[0] * (p[1] - p[0]**2), 200 * (p[1] - p[0]**2)])
for method in ("Nelder-Mead", "CG", "BFGS"):
jac = None if method == "Nelder-Mead" else grad
r = minimize(f, [-1.2, 1.0], jac=jac, method=method, tol=1e-10)
print(f"{method:12s} x = {np.round(r.x, 5)} f evals = {r.nfev}")Nelder-Mead x = [1. 1.] f evals = 249
CG x = [1. 1.] f evals = 80
BFGS x = [1. 1.] f evals = 41
All three reach , but with very different numbers of function evaluations. Why, and when each is the right choice, is what parts 2 and 9 explain.
In software
scipy.optimize.minimize(BFGS, L-BFGS-B, CG, Newton-CG, trust-region methods, Nelder-Mead, SLSQP),linprog(HiGHS) andmilpcover small and medium problems.scipy.optimize.check_graddoes the gradient check above in one call; PyTorch hastorch.autograd.gradcheck.- Automatic differentiation (JAX, PyTorch) removes hand-written gradients, but a numerical check still catches mistakes in custom code.
Exercises
Exercise 1: The minimum of Rosenbrock
Show that for the Rosenbrock function and that .
Answer
At : and , so every term vanishes.
Solution
. Both gradient components contain a factor or , which are zero. Since everywhere, is a global minimum.
Exercise 2: Catch a bug (code)
Someone wrote the second gradient component of Rosenbrock as 100 * (p[1] - p[0]**2) (forgot the factor 2). Use the gradient check to measure the relative error at .
Answer
About 0.35: far too large, so the check flags the bug.
Solution
import numpy as np
f = lambda p: (1 - p[0])**2 + 100 * (p[1] - p[0]**2)**2
bad = lambda p: np.array([-2 * (1 - p[0]) - 400 * p[0] * (p[1] - p[0]**2), 100 * (p[1] - p[0]**2)])
p, h = np.array([0.5, 0.5]), 1e-6
num = np.array([(f(p + h * e) - f(p - h * e)) / (2 * h) for e in np.eye(2)])
print(round(float(np.linalg.norm(bad(p) - num) / np.linalg.norm(num)), 4))0.35
The exact gradient at is , the buggy one is , so the error vector has length 25 against a gradient length of about 71.4.
Exercise 3: Step size too large (code)
Run the minimize loop on with step=0.3. What happens, and why?
Answer
It diverges: the coordinate oscillates with growing amplitude.
Solution
The update is , a factor larger than 1 in size. Gradient descent on a quadratic needs a step below , where is the largest curvature (Smoothness, Strong Convexity and Conditioning), so below 0.25.
y, errors = 0.0, []
for k in range(5):
y = y - 0.3 * 8 * (y + 1)
errors.append(round(y + 1, 4))
print(errors)[-1.4, 1.96, -2.744, 3.8416, -5.3782]
Test yourself
Why compare an analytic gradient with central differences?
- Central differences are faster
- A wrong gradient does not crash; the check finds it
- SciPy requires it
- It makes the function convex
The error of the central difference shrinks like…
- it does not depend on
Where is the minimum of the Rosenbrock function ?