TExcelTAD
Home › Optimization › Optimization with Python

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:

f(x,y)=(1−x)2+100 (y−x2)2f(x, y) = (1 - x)^2 + 100\,(y - x^2)^2

Its minimum is f(1,1)=0f(1, 1) = 0, 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

∇f=[−2(1−x)−400x(y−x2)200(y−x2)],∇2f=[2−400y+1200x2−400x−400x200]\nabla f = \begin{bmatrix} -2(1 - x) - 400x(y - x^2) \\ 200(y - x^2) \end{bmatrix}, \qquad \nabla^2 f = \begin{bmatrix} 2 - 400y + 1200x^2 & -400x \\ -400x & 200 \end{bmatrix}

In code, write each as a function of one NumPy vector:

python · try it yourself
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, ∂f∂xi≈f(x+hei)−f(x−hei)2h\frac{\partial f}{\partial x_i} \approx \frac{f(\mathbf{x} + h\mathbf{e}_i) - f(\mathbf{x} - h\mathbf{e}_i)}{2h}, whose error shrinks like h2h^2:

python · try it yourself
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 10−810^{-8} or smaller means the gradient is right; around 10−210^{-2} 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 ff values makes convergence visible:

python · try it yourself
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:

python · try it yourself
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 (1,1)(1, 1), 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) and milp cover small and medium problems.
  • scipy.optimize.check_grad does the gradient check above in one call; PyTorch has torch.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 ∇f(1,1)=0\nabla f(1, 1) = \mathbf{0} for the Rosenbrock function and that f(1,1)=0f(1, 1) = 0.

Answer

At (1,1)(1, 1): 1−x=01 - x = 0 and y−x2=0y - x^2 = 0, so every term vanishes.

Solution

f(1,1)=02+100⋅02=0f(1, 1) = 0^2 + 100 \cdot 0^2 = 0. Both gradient components contain a factor (1−x)(1 - x) or (y−x2)(y - x^2), which are zero. Since f≥0f \ge 0 everywhere, (1,1)(1, 1) 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 (0.5,0.5)(0.5, 0.5).

Answer

About 0.35: far too large, so the check flags the bug.

Solution
python · try it yourself
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 (0.5,0.5)(0.5, 0.5) is (−51,50)(-51, 50), the buggy one is (−51,25)(-51, 25), 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 f(x,y)=(x−3)2+4(y+1)2f(x, y) = (x - 3)^2 + 4(y + 1)^2 with step=0.3. What happens, and why?

Answer

It diverges: the yy coordinate oscillates with growing amplitude.

Solution

The yy update is y+1←(1−8⋅0.3)(y+1)=−1.4 (y+1)y + 1 \leftarrow (1 - 8 \cdot 0.3)(y + 1) = -1.4\,(y + 1), a factor larger than 1 in size. Gradient descent on a quadratic needs a step below 2/L2/L, where L=8L = 8 is the largest curvature (Smoothness, Strong Convexity and Conditioning), so below 0.25.

python · try it yourself
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?

  1. Central differences are faster
  2. A wrong gradient does not crash; the check finds it
  3. SciPy requires it
  4. It makes the function convex

The error of the central difference f(x+h)−f(x−h)2h\frac{f(x + h) - f(x - h)}{2h} shrinks like…

  1. hh
  2. h2h^2
  3. h3h^3
  4. it does not depend on hh

Where is the minimum of the Rosenbrock function (1−x)2+100(y−x2)2(1 - x)^2 + 100(y - x^2)^2?

  1. (0,0)(0, 0)
  2. (1,1)(1, 1)
  3. (−1,1)(-1, 1)
  4. (1,100)(1, 100)