Gradient descent, Newton and quasi-Newton

Part 10 — Optimisation and model fitting

Numerical analysis for biologists

About this lecture

Fitting a model means finding the parameters that make a misfit (a sum of squares, a negative log-likelihood) as small as possible. With more than one parameter we need new tools.

  • The gradient (the slopes in every direction) and the Hessian (the curvatures). Both are Jacobians, which you met in Newton for systems of equations.
  • Steepest descent with a backtracking line search, and why it zig-zags when the Hessian is badly conditioned.
  • Newton’s method for minimisation: fast near the minimum, unreliable far from it.
  • Quasi-Newton (BFGS, L-BFGS): build the curvature from gradients. Nelder–Mead: no derivatives at all.
  • What optim and scipy.optimize.minimize do, and why scaling and starting values matter. One slide on stochastic gradient descent.
  • Biology: fitting a 4-parameter logistic dose–response curve (EC50, Hill slope, top, bottom). We also explain the growth-curve failure from Why numerical analysis?.

A biology problem: a dose–response curve

A reporter assay: 9 doses of an agonist, 2 wells each. The 4-parameter logistic (4PL):

m(c) = b + \frac{t - b}{1 + (\mathrm{EC50}/c)^{h}}

  • b, t: bottom and top plateaus (% of max)
  • \mathrm{EC50}: dose at half response (µM)
  • h: Hill slope
  • Find the 4 numbers that minimise the sum of squared errors \mathrm{SSE}(\mathbf p) = \sum_i (y_i - m(c_i))^2. There is no formula: we must search.

Fitting is minimising

dose <- rep(10^seq(-2, 2, by = 0.5), each = 2)        # µM: 9 doses, 2 wells each
y <- c(12.9, 9.8, 2.9, 0.1, 4.2, 9.7, 17.7, 22.3, 49.7, 42.1,
       67.3, 72.6, 97.4, 91.8, 94.6, 93.3, 92.9, 95.1)  # % of max response
f4 <- function(p, c)                     # p = (bottom, top, EC50, hill)
  p[1] + (p[2] - p[1]) / (1 + (p[3] / c)^p[4])
sse <- function(p) sum((y - f4(p, dose))^2)
p0 <- c(0, 100, 1, 1)                    # a first guess, read off the plot
sse(p0)
# [1] 558.9029
  • sse is an ordinary R function of a vector p of length 4. Every method today only needs to call it (and perhaps its gradient).
  • The best fit has \mathrm{SSE} = 314.924 at \mathbf p^* = (5.39,\ 96.17,\ 1.271,\ 1.240). How do we get there from \mathbf p_0?

What we already have

From Optimisation in one dimension:

  • At a minimum of f(x): f'(x^*) = 0 and f''(x^*) > 0. Newton x - f'/f'' is fast, but only safe with checks: f'' > 0, and f must decrease (else shorten the step).

From Newton for systems of equations:

  • The Jacobian J of \mathbf F: \mathbb R^n \to \mathbb R^m has entries J_{ij} = \partial F_i / \partial x_j (row = output, column = input).
  • Newton for \mathbf F(\mathbf x) = \mathbf 0: solve J\,\boldsymbol\delta = -\mathbf F, set \mathbf x \leftarrow \mathbf x + \boldsymbol\delta. Quadratic convergence near the root.
  • A finite-difference Jacobian costs n+1 evaluations of \mathbf F, step h \approx \sqrt\varepsilon; numDeriv::jacobian does it more accurately.

Today: minimum of f(\mathbf x) = a point where all slopes are zero and the surface curves up in every direction.

The gradient: all slopes at once

For f(x_1, x_2) = x_1^2 + x_1x_2 + 3x_2^2 at (2, 1):

\frac{\partial f}{\partial x_1} = 2x_1 + x_2 = 5, \quad \frac{\partial f}{\partial x_2} = x_1 + 6x_2 = 8

\nabla f(2, 1) = \begin{pmatrix} 5 \\ 8 \end{pmatrix}

  • The gradient \nabla f is the Jacobian of a scalar function: one row, written as a column.
  • It points uphill, perpendicular to the contour lines; -\nabla f is the steepest descent direction.
  • At a minimum: \nabla f(\mathbf x^*) = \mathbf 0.

Arrows: -\nabla \mathrm{SSE} for the 4PL, bottom and top held at their best values.

The gradient of the SSE: the chain rule

\mathrm{SSE}(\mathbf p) = \sum_i r_i^2 with residuals r_i = y_i - m(c_i; \mathbf p), so

\nabla \mathrm{SSE} = -2\, J^\mathsf{T} \mathbf r, \qquad J_{ij} = \frac{\partial m(c_i)}{\partial p_j} \quad (18 \times 4)

grad_sse <- function(p) {
  u <- (p[3] / dose)^p[4];  D <- 1 + u
  J <- cbind(u / D,                                       # dm/d bottom
             1 / D,                                       # dm/d top
             -(p[2] - p[1]) * p[4] * u / (p[3] * D^2),    # dm/d EC50
             -(p[2] - p[1]) * u * log(p[3] / dose) / D^2) # dm/d hill
  -2 * drop(t(J) %*% (y - f4(p, dose)))
}
grad_sse(p0)
# [1]    -1.729861    48.929861 -1125.637873    59.964774
library(numDeriv);  grad(sse, p0)             # check with finite differences
# [1]    -1.729861    48.929861 -1125.637873    59.964774

The Hessian: the Jacobian of the gradient

The gradient is a vector function of \mathbf x, so it has a Jacobian: the Hessian, H_{ij} = \dfrac{\partial^2 f}{\partial x_i\,\partial x_j}.

For f = x_1^2 + x_1x_2 + 3x_2^2: \nabla f = (2x_1 + x_2,\ x_1 + 6x_2), so H = \begin{pmatrix} 2 & 1 \\ 1 & 6 \end{pmatrix} (symmetric).

Quadratic model (Taylor in several variables):

f(\mathbf x + \mathbf s) \approx f(\mathbf x) + \nabla f^\mathsf{T}\mathbf s + \tfrac12\, \mathbf s^\mathsf{T} H\, \mathbf s

Test for a minimum: \nabla f = \mathbf 0 and H positive definite (all eigenvalues > 0): the surface curves up in every direction.

  • Here: eigenvalues 4 \pm \sqrt5 = 6.24,\ 1.76, both positive. One positive, one negative: a saddle. Both negative: a maximum.

The Hessian at the 4PL minimum

hess <- function(p) jacobian(grad_sse, p)      # Jacobian of the gradient
H <- hess(pstar);  round(H, 1)                 # pstar = best fit
#        [,1]   [,2]   [,3]   [,4]
# [1,]   16.0    2.8 -123.8 -100.8
# [2,]    2.8   14.4 -123.6   99.6
# [3,] -123.8 -123.6 3611.5   12.5
# [4,] -100.8   99.6   12.5 3701.6
ev <- eigen(H, symmetric = TRUE)$values;  ev
# [1] 3708.824707 3618.223881    9.741189    6.737673
max(ev) / min(ev)
# [1] 550.4608
  • All four eigenvalues positive: a true minimum.
  • Curvature differs by a factor 550 between directions: the valley is long and narrow. This is the condition number \kappa(H) from Pivoting, norms and conditioning.

Steepest descent with a fixed step

Go downhill: \mathbf x_{k+1} = \mathbf x_k - \alpha\, \nabla f(\mathbf x_k), with a fixed step size \alpha.

x <- p0
for (k in 1:5000) x <- x - 1e-4 * grad_sse(x)
sse(x)
# [1] 315.1635                            # 5000 steps, still not at 314.924
x <- p0
for (k in 1:20) x <- x - 6e-4 * grad_sse(x)
sse(x)
# [1] NaN                                 # overshoots: EC50 < 0 after 10 steps
  • Too small: slow. Too large: each step overshoots the valley and the iteration blows up.
  • On a quadratic, steepest descent is stable only for \alpha < 2/\lambda_{\max}; here 2/3709 = 5.4\times10^{-4}. Nobody knows \lambda_{\max} in advance.

Backtracking line search (Armijo)

Try \alpha = 1; halve it until the step decreases f enough: f(\mathbf x - \alpha \mathbf g) \le f(\mathbf x) - c\,\alpha\, \|\mathbf g\|^2, with c = 10^{-4}.

sd_armijo <- function(f, g, x, tol = 1e-4, maxit = 1e4) {
  for (k in 1:maxit) {
    gk <- g(x)
    if (sqrt(sum(gk^2)) < tol) break           # gradient ~ 0: stop
    a <- 1
    while (!isTRUE(f(x - a * gk) <= f(x) - 1e-4 * a * sum(gk^2)))
      a <- a / 2                                # backtrack
    x <- x - a * gk
  }
  list(par = x, steps = k - 1)
}
sd_armijo(sse, grad_sse, p0)$steps
# [1] 3453
  • isTRUE also rejects a step that gives NaN. Never diverges; but 3453 steps.

Why steepest descent zig-zags

  • On a long narrow valley, -\nabla f points across the valley, not along it. Each step overshoots to the other side.
  • With exact line search the error shrinks per step by about \dfrac{\kappa - 1}{\kappa + 1}. For the 4PL, \kappa = 550: 0.9964 per step, about 3800 steps per 6 digits.

Newton’s method for minimisation

Minimum \Rightarrow \nabla f = \mathbf 0: a system of n equations. Apply Newton for systems with \mathbf F = \nabla f and J = H:

H(\mathbf x_k)\, \mathbf s = -\nabla f(\mathbf x_k), \qquad \mathbf x_{k+1} = \mathbf x_k + \mathbf s

Newton for systems Newton for minimisation
\mathbf F(\mathbf x) = \mathbf 0 \nabla f(\mathbf x) = \mathbf 0
Jacobian J Hessian H (= Jacobian of \nabla f)
solve(J, -F) solve(H, -g)
  • Same step = the minimum of the quadratic model. On a quadratic f, one step is exact. Toy example from (2, 1): \mathbf s = -H^{-1}(5, 8)^\mathsf{T} = (-2, -1), straight to (0, 0).
  • Quadratic convergence near the minimum. The condition number does not slow it down.

Newton in R

newton_min <- function(f, g, H, x, tol = 1e-4, maxit = 50) {
  for (k in 1:maxit) {
    gk <- g(x)
    if (sqrt(sum(gk^2)) < tol) break
    s <- solve(H(x), -gk)                      # Newton direction
    a <- 1                                     # line search, as before
    while (!isTRUE(f(x + a * s) <= f(x) + 1e-4 * a * sum(gk * s))) a <- a / 2
    x <- x + a * s
  }
  list(par = x, steps = k - 1)
}
newton_min(sse, grad_sse, hess, p0)$steps
# [1] 5
step 0 1 2 3 4 5
SSE 558.90 395.01 315.68 314.92418 314.92395944 314.92395944
\lVert\nabla \mathrm{SSE}\rVert 1128 218 11.6 0.735 1.4\times10^{-4} 2.2\times10^{-11}

Three methods on the same fit

  • Newton: 5 steps. BFGS (in a few slides): 13 steps, gradients only. Steepest descent: a straight line on a log axis, linear convergence, slope set by \kappa.

When Newton fails

Start from a worse guess, \mathrm{EC50} = 10 µM: \mathbf p = (0, 100, 10, 1).

eigen(hess(c(0, 100, 10, 1)), symmetric = TRUE)$values
# [1]   115.27332    13.13729   -42.62776 -2422.74914
  • Two negative eigenvalues: the quadratic model has no minimum (a saddle). Pure Newton steps head for any point with \nabla f = 0; after 20 steps: EC50 = 86, hill = 16, \mathrm{SSE} = 21188.
  • Check: eigenvalues of H, or \nabla f^\mathsf{T}\mathbf s < 0 (a descent direction); a line search only helps if \mathbf s goes downhill.
  • Fixes: make H positive definite (add \mu I; 9 steps to the minimum from here), a trust region, or quasi-Newton.

Quasi-Newton: learn the curvature from gradients

The secant idea from Newton and secant methods: replace f'' by a slope of f' between two points. In n dimensions, with step \mathbf s_k = \mathbf x_{k+1} - \mathbf x_k and gradient change \mathbf y_k = \nabla f_{k+1} - \nabla f_k:

\textbf{secant condition:}\quad B_{k+1}\,\mathbf y_k = \mathbf s_k \qquad (B \approx H^{-1})

BFGS (Broyden, Fletcher, Goldfarb, Shanno, 1970) picks the update closest to B_k that satisfies it:

B_{k+1} = V^\mathsf{T} B_k V + \rho\, \mathbf s_k \mathbf s_k^\mathsf{T}, \qquad V = I - \rho\, \mathbf y_k \mathbf s_k^\mathsf{T}, \quad \rho = 1/(\mathbf y_k^\mathsf{T}\mathbf s_k)

  • Start from B_0 = I (first step = steepest descent). Direction -B_k \nabla f_k: no Hessian, no linear solve.
  • If \mathbf y_k^\mathsf{T}\mathbf s_k > 0, B stays positive definite: every direction goes downhill.

BFGS in R

bfgs <- function(f, g, x, tol = 1e-4, maxit = 200) {
  n <- length(x); B <- diag(n); gk <- g(x)     # B ~ inverse Hessian
  for (k in 1:maxit) {
    if (sqrt(sum(gk^2)) < tol) break
    s <- -drop(B %*% gk);  a <- 1
    while (!isTRUE(f(x + a*s) <= f(x) + 1e-4 * a * sum(gk*s))) a <- a / 2
    s <- a * s;  x <- x + s;  gn <- g(x);  yv <- gn - gk;  gk <- gn
    if ((sy <- sum(yv * s)) > 0) {             # curvature check
      V <- diag(n) - outer(yv, s) / sy
      B <- t(V) %*% B %*% V + outer(s, s) / sy }
  }
  list(par = x, steps = k - 1)
}
bfgs(sse, grad_sse, p0)$steps
# [1] 13
  • 13 steps, one gradient each, plus backtracking. Superlinear convergence; no second derivatives.

L-BFGS: when there are many parameters

  • BFGS stores an n \times n matrix. For n = 10^6 parameters (an image, a genome-wide model, a neural network) that is 8 \times 10^{12} bytes.
  • L-BFGS (limited-memory BFGS) never forms B. It keeps the last m pairs (\mathbf s_k, \mathbf y_k), typically m = 5 to 20, and computes -B\nabla f from them in O(mn) operations.
  • Each step costs about as much as a steepest-descent step, but converges almost as fast as BFGS.
  • In R: optim(method = "L-BFGS-B") (the B is for bounds, e.g. lower = 0). In Python: minimize(method="L-BFGS-B"), the default when bounds are given.

Nelder–Mead: no derivatives at all

  • Keep n + 1 points (a simplex: a triangle in 2-D). Replace the worst by its reflection through the others; expand if that was very good, contract if bad, shrink if nothing helps.
  • Needs only f: works for noisy or non-smooth functions. optim’s default. Slow, and it can stop at a non-minimum, especially in many dimensions.

Try it: an optimiser race

What optim, minimize and argmin do

R optim Python minimize Rust argmin method
"Nelder-Mead" (default) "Nelder-Mead" NelderMead simplex, no derivatives
"BFGS" "BFGS" (default without bounds) BFGS quasi-Newton
"L-BFGS-B" "L-BFGS-B" (default with bounds) LBFGS limited memory, bounds
"CG" "CG" NonlinearConjugateGradient conjugate gradients
nlm "trust-exact", "Newton-CG" Newton, TrustRegion Newton-type
  • No gradient given → finite differences: R’s optim uses central differences with ndeps = 1e-3 (an absolute step!); scipy uses forward differences with h \approx \sqrt\varepsilon\max(1, |x|).
  • Stopping: relative change in f below reltol \approx 1.5\times10^{-8} (R), gradient norm below gtol = 10^{-5} (scipy BFGS). maxit = 500 for Nelder–Mead, 100 for BFGS in R.
  • convergence = 0 means “a stopping rule was met”, not “this is the minimum”.

The 4PL with optim

for (m in c("Nelder-Mead", "BFGS", "CG", "L-BFGS-B")) {
  o <- optim(p0, sse, method = m)
  cat(sprintf("%-11s  SSE %.4f  EC50 %.4f  fn %3d  gr %3s  conv %d\n",
              m, o$value, o$par[3], o$counts[1], o$counts[2], o$convergence))
}
# Nelder-Mead  SSE 314.9240  EC50 1.2711  fn 335  gr  NA  conv 0
# BFGS         SSE 314.9240  EC50 1.2711  fn  40  gr  11  conv 0
# CG           SSE 321.2024  EC50 1.2765  fn 333  gr 101  conv 1
# L-BFGS-B     SSE 314.9240  EC50 1.2710  fn  36  gr  36  conv 0
  • fn, gr: calls of sse and of the (finite-difference) gradient; each gr costs 8 more sse calls.
  • Conjugate gradients hit maxit = 100 (conv 1): another victim of \kappa = 550.
  • Passing the analytic gradient, optim(p0, sse, grad_sse, method = "BFGS"), saves the finite-difference calls.

Scaling: the same data in nM

dose_nM <- dose * 1000
sse_nM <- function(p) sum((y - f4(p, dose_nM))^2)
o <- optim(c(0, 100, 1, 1), sse_nM, method = "BFGS")
round(o$par, 2); o$value; o$convergence
# [1]  48.69 127.67   2.24 -13.82
# [1] 25807.26
# [1] 0
  • “EC50 is about 1” is now 1000 times too small. The curve sits left of every dose; BFGS slides to a flat line at the mean (hill = -13.8) and reports success.
  • Even from a good start (EC50 = 1000), \kappa(H) = 1.9\times10^{6} and BFGS stops early: SSE 314.9246, 109 calls. With control = list(parscale = c(1, 100, 1000, 1)): 314.9240, 36 calls.

Back to the growth curve

Why numerical analysis?: logistic fit, time in minutes, start r = 0.5 (“per hour” by habit).

grad(sse_min, c(r = 0.5, K = 1, N0 = 0.05))      # time in minutes
# [1] 0.000 3.940 0.098
optim(c(r = 0.5, K = 1, N0 = 0.05), sse_min, method = "BFGS")$par
#            r            K           N0
# 0.5000000000 0.8358333304 0.0009999665
optim(c(r = 0.5, K = 1, N0 = 0.05), sse_h)$par   # time in hours
#         r         K        N0
# 0.5241071 1.1913604 0.0165278
  • At r = 0.5/min the model reaches K within minutes, long before the first reading: \partial\,\mathrm{SSE}/\partial r \approx 4\times10^{-23}. BFGS never moves r; Nelder–Mead wanders on the plateau until its corner values agree (to r = 0.68, SSE 2.23, as in the intro).
  • In hours the natural guess is right, and \kappa drops from 1.2\times10^4 to 1.0\times10^3. Choose units so parameters are near 1.

Starting values and multistart

  • Start from the data: bottom ≈ min(y), top ≈ max(y), EC50 ≈ dose where y crosses halfway, hill ≈ 1. R’s SSfpl self-start model for nls does this for you.
  • Multistart: run from many starts, keep the best, and look at how many agree.
starts <- expand.grid(EC50 = 10^(-2:2), hill = c(0.5, 1, 3))   # 15 starts
nm <- apply(starts, 1, function(s) optim(c(0, 100, s), sse)$value)
table(round(nm, 1))
#  314.9 1344.4 1557.2 1926.8 2453.2
#     10      2      1      1      1
  • Nelder–Mead from 15 starts: 5 end far from the minimum, 4 of them with convergence = 0. BFGS with the analytic gradient finds 314.9 from all 15.

Stochastic gradient descent, in one slide

When the objective is a sum over many data points, f(\mathbf p) = \sum_{i=1}^N f_i(\mathbf p), with N in the millions (images, sequences, cells):

\mathbf p_{k+1} = \mathbf p_k - \alpha_k \sum_{i \in \text{batch}_k} \nabla f_i(\mathbf p_k)

  • Each step uses the gradient of a small random minibatch (say 32 points): a noisy but cheap estimate of \nabla f.
  • No line search: the learning rate \alpha_k is set by hand and decreased over time; variants (momentum, Adam) adapt it per parameter, a cheap form of scaling.
  • This is how neural networks are trained (gradients by automatic differentiation). For an 18-point dose–response curve, use BFGS.

Checklist for a fit

  • Check the gradient against numDeriv::grad before using it (agreement to ~10^{-6} relative, not ~1).
  • Look at the convergence code and the counts; maxit reached means “not finished”.
  • Plot the fitted curve over the data. A flat line or a step is a degenerate fit.
  • Units and scale: parameters near 1 (µM, hours, log EC50), or parscale.
  • Start from the data, and multistart: do the answers agree?
  • At the answer: gradient near 0 and Hessian eigenvalues all positive (a minimum, not a saddle or plateau). A huge \kappa warns of poorly determined parameters.
  • Method: smooth with gradient → BFGS (L-BFGS for many parameters); noisy or non-smooth → Nelder–Mead; sum of squares → Nonlinear least squares and ODE fitting.

Summary

  • Gradient \nabla f: Jacobian of a scalar function, points uphill. Hessian H: Jacobian of the gradient. Minimum: \nabla f = \mathbf 0, H positive definite.
  • Steepest descent + backtracking (Armijo): always goes downhill, but converges linearly at a rate set by \kappa(H); it zig-zags in narrow valleys.
  • Newton: solve H\mathbf s = -\nabla f. Quadratic convergence near the minimum; can head for saddles when H is not positive definite.
  • BFGS builds H^{-1} from gradient differences; L-BFGS stores only a few of them. Nelder–Mead uses only f.
  • optim (default Nelder–Mead) and minimize (default BFGS) report “converged” when a stopping rule is met. Scale the parameters, start from the data, multistart, check.

Next: Nonlinear least squares and ODE fitting: Gauss–Newton and Levenberg–Marquardt use the structure of a sum of squares.