General numerical optimization
A numerical optimizer returns coefficient estimates and reports that it has stopped. Before using those estimates, a researcher needs to know whether the calculation has reached a suitable solution. In a regression for grouped success counts, for example, the negative log likelihood may still decrease when the slope changes. More generally, the shape of the function and the permitted parameter values determine where a search can move and what a returned value means. Assessing the solution therefore requires evidence from the function near that value, beyond the stopping message alone. Using the LOGIT3 counts and standard test functions, the chapter builds descent, quasi-Newton, derivative-free and trust-region methods, then turns to restricted parameters, standard errors and the question of whether a returned value is a solution at all.
3.1 Numerical gradients, Hessians, and derivative checks
Fix the intercept at $a$ and write $f(b)=-\ell(a,b)$ for the negative log likelihood of the three LOGIT3 counts from Chapter 2 as a function of the slope $b$. Its derivative is the negative of the slope component of the score vector. To estimate it from function values, choose $h>0$ so that the function is defined and finite at both $b-h$ and $b+h$. The slope in this logistic regression can take any real value. If $f$ has four continuous derivatives near $b$, the two Taylor expansions about $b$ are
Subtract the second expansion from the first. The even powers cancel. With five continuous derivatives, division by $2h$ gives the central difference
\[D_h f(b)=\frac{f(b+h)-f(b-h)}{2h}=f'(b)+\tfrac16 h^2 f'''(b)+O(h^4).\]The surviving cubic terms thus contribute an error of order $h^2$. The same calculation gives one component of a gradient when only that coordinate varies.
Halving $h$ reduces a nonzero leading truncation error by a factor of four. Yet the two numbers being subtracted have already been rounded by the computer. In R’s double precision, .Machine$double.eps gives the gap between 1 and its immediate successor, $\epsilon=2^{-52}\approx2.220446\times10^{-16}$. If each function evaluation has relative error of order $\epsilon$ and both values have magnitude near $\vert f(b)\vert $, division by $2h$ gives a rounding error of order $\epsilon \vert f(b)\vert /h$. With the coordinate and function suitably scaled, balancing $h^2$ with $\epsilon/h$ gives a relative step of order $\epsilon^{1/3}\approx6.06\times10^{-6}$. Multiplying by the coordinate magnitude adapts the increment to its units. Near zero a positive minimum scale is needed for the two trial points to differ.
Adding the two expansions instead eliminates the first derivative. Subtract twice the central value and divide by $h^2$ to estimate a diagonal entry of the Hessian, the matrix of second partial derivatives. For a vector $x$ and the $i$th unit vector $e_i$, this gives
\[H_{ii}(x)\approx\frac{f(x+h e_i)-2f(x)+f(x-h e_i)}{h^2}.\]For $i\ne j$, take the central difference in direction $i$ at each of $x+h e_j$ and $x-h e_j$, then difference those results in direction $j$. The numerator now uses four corners and the denominator is $4h^2$. Both formulas have truncation error of order $h^2$ when the required fourth partial derivatives are continuous near $x$. Rounding in the numerator now contributes an error of order $\epsilon \vert f(x)\vert /h^2$. The balance gives a larger relative step, $\epsilon^{1/4}\approx1.22\times10^{-4}$. With an analytic gradient $g$, each column of the Hessian can instead be estimated as $[g(x+h e_i)-g(x-h e_i)]/(2h)$. Each component of this quotient has the error orders of a first derivative.
Several steps can remove a leading truncation term before rounding becomes appreciable. Write a central approximation as $D(h)=T+c_2h^2+c_4h^4+\cdots$, where $T$ is the derivative sought. At half the step the quadratic term is one quarter as large, so Richardson extrapolation gives
\[\frac{4D(h/2)-D(h)}{3}=T+O(h^4).\]Starting with $h,h/2,h/4,h/8$ gives three such estimates. Combining adjacent estimates with weights $16$ and $-1$ and dividing by 15 cancels the fourth-order term. Weights $64$ and $-1$ with divisor 63 cancel the sixth-order term in the final pair. This permits a larger first increment for the gradient and the Hessian calculated from function values.
Numerical derivative functions
The following functions implement these differences and the extrapolation. From the book directory, construct the grouped LOGIT3 model and two test functions with known derivatives. The model’s fn, gr and he evaluate its negative log likelihood, gradient and Hessian. The test functions are a quadratic with different second derivatives along its coordinate axes and Rosenbrock’s function with its curved valley.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/logit.R")
source("code/lib/newton.R")
source("code/lib/glm.R")
source("code/lib/simulation.R")
LOGIT3 <- read.csv("data/source/LOGIT3.csv")
logit_model <- make_glm(cbind(intercept = 1, x = LOGIT3$x),
LOGIT3$successes, "binomial", LOGIT3$trials)
quadratic <- function(x) 0.5 * sum(c(1, 100) * x^2)
quadratic_gr <- function(x) c(1, 100) * x
quadratic_he <- function(x) diag(c(1, 100))
rosenbrock <- function(x) 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2
rosenbrock_gr <- function(x) c(-400 * x[1] * (x[2] - x[1]^2) + 2 * (x[1] - 1),
200 * (x[2] - x[1]^2))
rosenbrock_he <- function(x) matrix(c(1200 * x[1]^2 - 400 * x[2] + 2,
-400 * x[1], -400 * x[1], 200), 2)
rosen_start <- c(-1.2, 1)
print(c(relative_step = 1e-4, near_zero_increment = 1e-4, step_sizes = 4,
hessian_relative_step = 0.1, gradient_difference_step = 1e-3))
1
2
3
4
relative_step near_zero_increment step_sizes hessian_relative_step
1e-04 1e-04 4e+00 1e-01
gradient_difference_step
1e-03
The first gradient increment for coordinate $i$ is $10^{-4}\vert x_i\vert $, plus $10^{-4}$ if $\vert x_i\vert <\sqrt{\epsilon/(7\times10^{-7})}$. Three halvings give four increments. For the Hessian calculated directly from function values, the initial relative step rises to 0.1. A supplied gradient is differenced at one absolute increment of 0.001.
Begin with num_grad() for numerical first derivatives, then use num_hess() for second derivatives and check_grad() to compare analytic and numerical components. In num_grad(), fn is the scalar function, par the point and step an optional absolute increment. With a supplied step, hh displaces just coordinate i. Each evaluation through f adds one to the count.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
num_grad <- function(fn, par, step = NULL) {
stopifnot(is.numeric(par), is.null(dim(par)), length(par) > 0L, all(is.finite(par)))
n <- length(par)
evaluations <- 0L
f <- function(x) { evaluations <<- evaluations + 1L; fn(x) }
if (!is.null(step)) {
stopifnot(length(step) == 1L, is.finite(step), step > 0)
gradient <- numeric(n)
for (i in seq_len(n)) {
hh <- rep(0, n); hh[i] <- step
gradient[i] <- (f(par + hh) - f(par - hh)) / (2 * step)
}
return(list(gradient = gradient, steps = rep(step, n), evaluations = evaluations,
reason = if (all(is.finite(gradient))) "evaluated" else "nonfinite_derivative"))
}
With the default steps, row k of est contains the estimates before the next halving. For a scalar function of several coordinates, each call of one_coordinate() varies one coordinate. A missing difference makes the gradient unavailable. The code also sets a later difference to zero if the preceding magnitude was below $10^{-20}$.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Default: four central differences, the step halved between them, then Richardson rounds.
tiny <- sqrt(.Machine$double.eps / 7e-7); n_est <- 4; shrink <- 2
f0 <- f(par)
elementwise <- n == length(f0)
est <- matrix(NA, n_est, n)
h <- abs(1e-4 * par) + 1e-4 * (abs(par) < tiny)
h0 <- h
one_coordinate <- function(i, h)
(f(par + h * (seq_len(n) == i)) - f(par - h * (seq_len(n) == i))) / (2 * h[i])
# Form a row of central differences at the current increments.
for (k in seq_len(n_est)) {
est[k, ] <- if (elementwise) (f(par + h) - f(par - h)) / (2 * h) else
vapply(seq_len(n), function(i)
if (k > 1 && abs(est[k - 1, i]) < 1e-20) 0 else one_coordinate(i, h), 0)
if (anyNA(est[k, ])) {
return(list(gradient = rep(NA_real_, n), steps = h0, evaluations = evaluations,
reason = "nonfinite_derivative"))
}
h <- h / shrink
}
The successive combinations reduce four rows to one gradient. The returned steps give the initial increments. The status nonfinite_derivative means that at least one resulting derivative estimate is nonfinite; it does not identify which function evaluation caused the problem.
1
2
3
4
5
6
7
8
# Eliminate one more even power of the increment at each pass.
for (m in seq_len(n_est - 1)) {
est <- (est[-1, , drop = FALSE] * 4^m -
est[-nrow(est), , drop = FALSE]) / (4^m - 1)
}
list(gradient = c(est), steps = h0, evaluations = evaluations,
reason = if (all(is.finite(est))) "evaluated" else "nonfinite_derivative")
}
For the quadratic $f(x)=(x_1^2+100x_2^2)/2$, the first derivatives at $(2,2)$ are 2 and 200. The numerical approximation records the work needed to recover both components.
1
print(num_grad(quadratic, c(2, 2)))
1
2
3
4
5
6
7
8
9
10
11
$gradient
[1] 2 200
$steps
[1] 2e-04 2e-04
$evaluations
[1] 17
$reason
[1] "evaluated"
Each coordinate started at $2\times10^{-4}$. Four evaluations on each side of each coordinate plus one at the center account for all 17.
In num_hess(), supplying gr gives two gradient evaluations per column. The largest absolute difference between transposed entries measures their disagreement before averaging. Symmetry after averaging alone gives no measure of accuracy.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
num_hess <- function(fn, par, gr = NULL, step = NULL) {
stopifnot(is.numeric(par), is.null(dim(par)), length(par) > 0L, all(is.finite(par)))
p <- length(par)
nf <- ng <- 0L
f <- function(x) { nf <<- nf + 1L; fn(x) }
if (!is.null(gr)) {
g <- function(x) { ng <<- ng + 1L; gr(x) }
eps <- if (is.null(step)) 1e-3 else step
H <- matrix(0, p, p)
dpar <- par
for (i in seq_len(p)) {
dpar[i] <- dpar[i] + eps
df1 <- g(dpar)
dpar[i] <- dpar[i] - 2 * eps
df2 <- g(dpar)
if (length(df1) != p || length(df2) != p) stop("Invalid gradient length")
for (j in seq_len(p)) H[j, i] <- 1 * (df1[j] - df2[j]) / (2 * eps * 1 * 1)
dpar[i] <- dpar[i] + eps
}
# Measure the disagreement before imposing symmetry.
asymmetry <- max(abs(H - t(H)))
for (i in seq_len(p)) for (j in seq_len(i - 1L)) {
tmp <- 0.5 * (H[j, i] + H[i, j]); H[j, i] <- tmp; H[i, j] <- tmp
}
return(list(hessian = H, steps = rep(eps, p), objective = nf, gradient = ng,
asymmetry = asymmetry,
reason = if (all(is.finite(H))) "evaluated" else "nonfinite_derivative"))
}
With function values and a supplied step, write $F_{st}=f(x+s h e_j+t h e_k)$ for $s,t\in\lbrace -1,1\rbrace $. The two successive differences give $(F_{++}-F_{+-}-F_{-+}+F_{- -})/(4h^2)$. Here dj and dk locate those four evaluations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if (!is.null(step)) {
H <- matrix(0, p, p)
f0 <- f(par)
for (j in seq_len(p)) {
dj <- numeric(p); dj[j] <- step
H[j, j] <- (f(par + dj) - 2 * f0 + f(par - dj)) / step^2
if (j > 1L) for (k in seq_len(j - 1L)) {
dk <- numeric(p); dk[k] <- step
H[j, k] <- (f(par + dj + dk) - f(par + dj - dk) -
f(par - dj + dk) + f(par - dj - dk)) /
(4 * step * step)
H[k, j] <- H[j, k]
}
}
return(list(hessian = H, steps = rep(step, p), objective = nf, gradient = ng,
asymmetry = 0, reason = if (all(is.finite(H))) "evaluated" else "nonfinite_derivative"))
}
With default steps, the evaluations along each axis first give extrapolated diagonal entries in pure.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
tiny <- sqrt(.Machine$double.eps / 7e-7); n_est <- 4; shrink <- 2
invisible(f(par))
f0 <- f(par)
h0 <- abs(0.1 * par) + 1e-4 * (abs(par) < tiny)
unit <- function(i) seq_len(p) == i
# est has one column per step size; each round combines neighboring columns.
extrapolate <- function(est) {
for (m in seq_len(ncol(est) - 1)) {
est <- (est[, -1, drop = FALSE] * 4^m - est[, -ncol(est), drop = FALSE]) / (4^m - 1)
}
est[, 1]
}
# Use single-coordinate moves to estimate the diagonal curvatures.
pure <- matrix(0, length(f0), p)
for (i in seq_len(p)) {
est <- matrix(0, length(f0), n_est)
h <- h0
for (k in seq_len(n_est)) {
est[, k] <- (f(par + unit(i) * h) - 2 * f0 + f(par - unit(i) * h)) / h[i]^2
h <- h / shrink
}
pure[, i] <- extrapolate(est)
}
# Column i of pure now holds the extrapolated second derivative along coordinate i.
For the mixed entry, set $v=h_i e_i+h_j e_j$. The quadratic term in $f(x+v)-2f(x)+f(x-v)$ is $v^\top H v$. Removing the two diagonal contributions leaves $2h_i h_j H_{ij}$ in that quadratic term, giving the estimate
\[\frac{f(x+v)-2f(x)+f(x-v)-h_i^2\widehat H_{ii}-h_j^2\widehat H_{jj}}{2h_i h_j}.\]The code halves both increments together, extrapolates these estimates and fills the symmetric matrix.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Mixed differences fill the lower triangle; the upper triangle repeats them.
H <- matrix(NA_real_, p, p)
# Diagonal entries come from pure; each mixed entry is computed once.
for (i in seq_len(p)) {
H[i, i] <- pure[, i]
for (j in seq_len(i - 1L)) {
# Mixed entry for the pair (i, j), i > j.
est <- matrix(0, length(f0), n_est)
h <- h0
for (k in seq_len(n_est)) {
# Remove both diagonal terms from the second difference along the joint move.
up <- f(par + unit(i) * h + unit(j) * h); down <- f(par - unit(i) * h - unit(j) * h)
fix_i <- pure[, i] * h[i]^2; fix_j <- pure[, j] * h[j]^2
est[, k] <- (up - 2 * f0 + down - fix_i - fix_j) / (2 * h[i] * h[j])
h <- h / shrink
}
# Extrapolate over the four joint step sizes.
H[i, j] <- extrapolate(est)
H[j, i] <- H[i, j]
}
}
# Adding the transpose of the lower triangle and halving the diagonal would give the
# same numbers: x + 0 = x off the diagonal and (x + x) / 2 = x on it.
# The steps reported are the first, largest ones.
list(hessian = H, steps = h0, objective = nf, gradient = ng, asymmetry = 0,
reason = if (all(is.finite(H))) "evaluated" else "nonfinite_derivative")
}
For the same quadratic at $(2,2)$, the second derivatives along the coordinate axes are 1 and 100. Each slope is independent of the other coordinate, giving zero off the diagonal.
1
print(num_hess(quadratic, c(2, 2))[c("hessian", "objective", "gradient")])
1
2
3
4
5
6
7
8
9
10
$hessian
[,1] [,2]
[1,] 1.00000e+00 -3.12033e-15
[2,] -3.12033e-15 1.00000e+02
$objective
[1] 26
$gradient
[1] 0
The mixed entry was $-3.12\times10^{-15}$. The two calls at the center, 16 along individual axes and eight along the joint direction account for all 26 function evaluations. Differencing the gradient requires fewer calls.
1
2
print(num_hess(quadratic, c(2, 2), gr = quadratic_gr)[c("hessian",
"objective", "gradient")])
1
2
3
4
5
6
7
8
9
10
$hessian
[,1] [,2]
[1,] 1 0
[2,] 0 100
$objective
[1] 0
$gradient
[1] 4
Two gradient evaluations per axis recovered the analytic matrix to the printed precision, with no evaluation of the quadratic itself.
Step size, scaling and evaluation points
Away from a quadratic, truncation error also depends on the increment. The following grid varies the absolute step from $10^{-1}$ to $10^{-8}$ at four points. For an analytic vector or matrix $B$ and its approximation $A$, the grid uses $\max\vert A-B\vert /\max(1,\max\vert B\vert )$, with each maximum taken over the entries. This gives one error per step. The table reports the minimum down each series.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
step_grid <- 10^seq(-1, -8, by = -0.5)
derivative_cases <- list(
logit_zero = list(fn = logit_model$fn, gr = logit_model$gr,
he = logit_model$he, point = c(0, 0)),
logit_shifted = list(fn = logit_model$fn, gr = logit_model$gr,
he = logit_model$he, point = c(.4, -.7)),
rosen_start = list(fn = rosenbrock, gr = rosenbrock_gr,
he = rosenbrock_he, point = rosen_start),
rosen_valley = list(fn = rosenbrock, gr = rosenbrock_gr,
he = rosenbrock_he, point = c(.8, .7)))
derivative_errors <- data.frame()
for (name in names(derivative_cases)) {
case <- derivative_cases[[name]]
for (h in step_grid) {
g <- num_grad(case$fn, case$point, h)$gradient
# Compare entire vectors or matrices on the scale of the analytic derivative.
Hf <- num_hess(case$fn, case$point, step = h)$hessian
Hg <- num_hess(case$fn, case$point, gr = case$gr, step = h)$hessian
error <- function(a, b) max(abs(a - b)) / max(1, max(abs(b)))
derivative_errors <- rbind(derivative_errors, data.frame(point = name, step = h,
gradient = error(g, case$gr(case$point)),
objective_hessian = error(Hf, case$he(case$point)),
gradient_hessian = error(Hg, case$he(case$point))))
}
}
print(aggregate(cbind(gradient, objective_hessian, gradient_hessian) ~ point,
derivative_errors, min), digits = 3)
1
2
3
4
5
point gradient objective_hessian gradient_hessian
1 logit_shifted 1.89e-11 5.86e-09 1.06e-11
2 logit_zero 5.92e-16 2.52e-09 2.04e-11
3 rosen_start 2.67e-11 4.67e-10 7.15e-12
4 rosen_valley 1.76e-11 1.63e-09 1.18e-11
At the shifted regression coefficients $(0.4,-0.7)$, the gradient error reached its minimum at $10^{-5}$. At the Rosenbrock points in table order it did so at $3.16\times10^{-6}$ and $10^{-6}$. For the Hessian from function values, the smallest errors occurred at larger steps, respectively $3.16\times10^{-4}$, $10^{-4}$ and $3.16\times10^{-5}$. The full error curves distinguish the behavior on either side of each minimum.
Figure 3.1. Errors as the absolute coordinate increment varies, on logarithmic axes. Circles give the scaled error of the numerical gradient. Triangles and squares mark Hessian errors from differencing function values and gradients, respectively.
In Figure 3.1, reading from right to left, the gradient errors at the three nonzero points fall and then rise as rounding overtakes truncation. At zero the smallest gradient error was already $5.92\times10^{-16}$ at the largest step. Along either coordinate through zero, each linear predictor of the logistic model is proportional to the displacement $t$. The identity $\log(1+e^t)=t/2+\log(2\cosh(t/2))$ makes the negative log likelihood a linear term plus an even function along that axis. The even part cancels at every symmetric pair, so the gradient check there detects only rounding. The plotting floor of $10^{-16}$ applies to the marks alone. A mark at the floor could represent any error from zero through $10^{-16}$. The table uses the measured errors.
A componentwise comparison can reveal an error even when another component agrees closely. For components on different scales, check_grad() divides each absolute discrepancy by the largest of one and the two magnitudes in that row.
1
2
3
4
5
6
7
8
9
check_grad <- function(fn, gr, par, step = NULL) {
numerical <- num_grad(fn, par, step)
analytic <- gr(par)
stopifnot(is.numeric(analytic), is.null(dim(analytic)), length(analytic) == length(par))
error <- abs(analytic - numerical$gradient)
data.frame(coordinate = seq_along(par), analytic = analytic,
numerical = numerical$gradient, absolute_error = error,
scaled_error = error / pmax(1, abs(analytic), abs(numerical$gradient)))
}
The following check deliberately reverses the second component of the analytic gradient at the Rosenbrock starting point.
1
2
3
4
5
6
wrong_gradient <- function(x) {
g <- rosenbrock_gr(x)
g[2] <- -g[2]
g
}
print(check_grad(rosenbrock, wrong_gradient, rosen_start), digits = 5)
1
2
3
coordinate analytic numerical absolute_error scaled_error
1 1 -215.6 -215.6 2.2107e-09 1.0254e-11
2 2 88.0 -88.0 1.7600e+02 2.0000e+00
The first components differed by only $2.2\times10^{-9}$. In the second row the supplied 88 and the numerical $-88$ give $176/88=2$ after scaling.
Even a correct derivative needs evaluation points at which the function is defined and finite. Ten successes contribute $-10\log p$ to the negative log likelihood at a common success probability $p$. Choose $u=30$ for the log odds. The resulting probability is close enough to one to test whether both trial probabilities remain strictly between zero and one.
1
2
3
4
5
boundary_fn <- function(u) 10 * log1pexp(-u)
boundary_gr <- function(u) -10 * plogis(-u)
near_one <- plogis(30)
probability_step <- 1e-4 * abs(near_one)
print(c(probability = near_one, upper_trial = near_one + probability_step))
1
2
probability upper_trial
1.0000 1.0001
Although the probability rounds to 1.0000, the upper trial point of 1.0001 exceeds one. On the logit scale the same function is $10\log(1+e^{-u})$ with derivative $-10/(1+e^u)$. Both $u-h$ and $u+h$ are finite log odds and correspond, in exact arithmetic, to probabilities strictly between zero and one.
1
print(check_grad(boundary_fn, boundary_gr, 30), digits = 6)
1
2
coordinate analytic numerical absolute_error scaled_error
1 1 -9.35762e-13 -9.35762e-13 6.2707e-24 6.2707e-24
At $u=30$, the analytic and numerical derivatives agree to an absolute error of $6.27\times10^{-24}$. The finite-difference comparison requires finite function values at both displaced points. Repeating it at another point can uncover an error that symmetry concealed. The supplied num_grad() and num_hess() are adapted from grad(), hessian() and genD() of numDeriv (code/NOTICE.md); numDeriv and stats provide numerical derivatives.
3.2 Steepest descent and line searches with Armijo and Wolfe conditions
A gradient gives the direction of steepest local change, but a search must also decide how far to move. At $(2,2)$, the gradient of $f(x)=(x_1^2+100x_2^2)/2$ is $(2,200)^\top$. Which direction gives the greatest local decrease per unit distance? For a displacement $td$ with $t>0$ and $\Vert d\Vert _2=1$, the linear approximation is $f(x)+t g^\top d$, where $g=\nabla f(x)$. By Cauchy-Schwarz, $g^\top d\ge-\Vert g\Vert _2$. For $g\ne0$, equality selects $d=-g/\Vert g\Vert _2$. The unnormalized vector $-g$ traces the same ray with a different step length. Now measure distance in $v=(x_1,10x_2)^\top$. The function becomes $(v_1^2+v_2^2)/2$. At $v=(2,20)^\top$, the negative gradient $(-2,-20)^\top$ maps back to $(-2,-2)^\top$ in the original coordinates. This points straight toward zero, whereas $(-2,-200)^\top$ points almost vertically. A unit circle of displacements in $v$ corresponds to an ellipse in $x$.
Once the direction $d$ is chosen, the remaining unknown is a scalar multiplier $\alpha$. Write $\phi(\alpha)=f(x+\alpha d)$. By the chain rule, its slope at a trial point is $\phi^{\prime}(\alpha)=\nabla f(x+\alpha d)^\top d$. A negative slope at zero makes small positive steps downhill. The Armijo test compares the trial value with a line of slope $c_1\phi^{\prime}(0)$,
\[\phi(\alpha)\le\phi(0)+c_1\alpha\phi'(0).\]For step $\alpha$, the tangent predicts a decrease of $-\alpha\phi^{\prime}(0)$, of which the trial must deliver at least the fraction $c_1$. The multiplier equals the Euclidean distance moved only for a unit direction.
A very short positive step can pass this test while the function is still falling almost as steeply as at the start. For a smooth function, the actual decrease then approaches the tangent prediction in relative terms. The Wolfe curvature condition requires $\phi^{\prime}(\alpha)\ge c_2\phi^{\prime}(0)$, with $0<c_1<c_2<1$. This condition compares first derivatives along the search line; it does not test whether the Hessian is positive definite. Together with sufficient decrease, it gives the Wolfe conditions. A large positive slope can still meet the curvature bound after passing a minimum. The strong curvature condition limits the slope magnitude to a fraction of its starting magnitude,
\[|\phi'(\alpha)|\le c_2|\phi'(0)|.\]The search below uses $c_1=0.001$ and $c_2=0.9$. Under these strong Wolfe conditions, even a trial below the Armijo line needs a slope whose magnitude has fallen by at least one tenth.
The Moré-Thuente line search
The Moré-Thuente search enforces both conditions. Its implementation here, line_search(), takes the current point, its function value and gradient, and a proposed direction. From the book directory, load the interval and interpolation routines and the search that uses them.
1
2
source("code/lib/lbfgsb.R")
source("code/lib/line_search.R")
In the definition, lb_dot() sums the products of corresponding vector entries. Applied to gradient and direction, it gives the initial directional derivative stored in slope. A nonnegative or nonfinite value rules out the direction before any trial.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
line_search <- function(fn, gr, par, value, gradient, direction, initial = 1,
step_max = 1e10,
max_evaluations = 20L) {
stopifnot(length(par) == length(gradient), length(direction) == length(par),
all(is.finite(par)), is.finite(value), initial > 0, step_max >= initial)
slope <- lb_dot(gradient, direction)
counts <- c(objective = 0L, gradient = 0L)
fail <- function(reason, trials) list(accepted = FALSE, reason = reason,
alpha = NA_real_,
evaluations = counts, trial_steps = trials)
# Use the supplied gradient at the current point.
if (!is.finite(slope) || slope >= 0) return(fail("non_descent_direction", list()))
L <- list(status = "START")
step <- initial; f <- value; gdir <- slope; g <- gradient; x <- par
trials <- list()
In code/lib/lbfgsb.R, lb_more_thuente() tests the current step and lb_more_thuente_step() selects another by cubic or quadratic interpolation, restricting the proposed step to the interval allowed by the search. The returned list L stores the search state between trials, including the bracket and endpoint values. The returned step gives the next multiplier or the multiplier at termination.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
repeat {
res <- lb_more_thuente(L, f, gdir, step, 1e-3, .9, .1, 0, step_max)
L <- res$L; step <- res$step
if (startsWith(L$status, "CONV") || startsWith(L$status, "WARN")) break
if (startsWith(L$status, "ERROR")) return(fail(L$status, trials))
if (length(trials) >= max_evaluations) return(fail("line_search_limit", trials))
# Count the trial function call before deciding whether a derivative exists.
x <- step * direction + par
counts["objective"] <- counts["objective"] + 1L
f <- fn(x)
if (!is.finite(f)) {
trials[[length(trials) + 1L]] <- c(alpha = step, value = f,
directional_derivative = NA_real_)
return(fail("nonfinite_objective", trials))
}
Only a finite function value warrants a call to gr. A nonfinite directional derivative is recorded after both counters have advanced. The limit of 20 counts trial points along this direction. A warning leaves the step unaccepted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Only a finite function value reaches this gradient evaluation.
counts["gradient"] <- counts["gradient"] + 1L
g <- gr(x)
gdir <- lb_dot(g, direction)
if (!is.finite(gdir)) {
trials[[length(trials) + 1L]] <- c(alpha = step, value = f,
directional_derivative = gdir)
return(fail("nonfinite_directional_derivative", trials))
}
trials[[length(trials) + 1L]] <- c(alpha = step, value = f,
directional_derivative = gdir)
}
list(accepted = startsWith(L$status, "CONV"), reason = L$status, alpha = step, par = x,
value = f, gradient = g, evaluations = counts,
trial_steps = trials)
}
The imported interval search chooses the trials that the wrapper evaluates. If a trial improves the function value but falls short of sufficient decrease, the first stage interpolates the modified function $\phi(\alpha)-c_1\alpha\phi^{\prime}(0)$. Once sufficient decrease and a nonnegative slope coincide, the search uses the original function. The search can extend the step until a higher value or a slope reversal encloses a line minimum between two trial step lengths. Interpolation then uses values and slopes at the endpoints, with bisection if the interval shrinks too slowly.
A bracket can yield a warning if rounding prevents a trial strictly between the bracket endpoints or its width is at most one tenth of its upper endpoint. A warning at the upper step bound $10^{10}$ requires sufficient decrease and $\phi^{\prime}(\alpha)\le c_1\phi^{\prime}(0)$. The lower-bound warning at zero requires insufficient decrease or $\phi^{\prime}(\alpha)\ge c_1\phi^{\prime}(0)$. Passing both strong Wolfe tests takes precedence over a warning.
For the quadratic, take $d=-g=(-2,-200)^\top$. Along this line $\phi^{\prime}(\alpha)=-g^\top g+\alpha g^\top H g$, where $H=\operatorname{diag}(1,100)$. The positive second derivative $\phi^{\prime\prime}(\alpha)=g^\top Hg$ gives a unique minimum at $\alpha=g^\top g/(g^\top H g)=40004/4000004$. The search can be assessed against this exact multiplier.
1
2
3
4
5
6
7
quadratic <- function(x) 0.5 * sum(c(1, 100) * x^2)
quadratic_gr <- function(x) c(1, 100) * x
quad_start <- c(2, 2)
quad_g <- quadratic_gr(quad_start)
quad_line <- line_search(quadratic, quadratic_gr, quad_start,
quadratic(quad_start), quad_g, -quad_g)
print(quad_line[c("alpha", "value", "gradient", "evaluations", "reason")])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$alpha
[1] 0.01000099
$value
[1] 1.960198
$gradient
[1] 1.97999802 -0.01979998
$evaluations
objective gradient
2 2
$reason
[1] "CONVERGENCE"
The returned gradient still has a component near 1.98. The derivative along the line should be near zero there. The trials show how interpolation reached that point.
1
print(do.call(rbind, quad_line$trial_steps))
1
2
3
alpha value directional_derivative
[1,] 1.00000000 1.960200e+06 3.96000e+06
[2,] 0.01000099 1.960198e+00 5.54059e-11
At step 1, the function rose from 202 to 1,960,200, and the slope changed from $-40004$ to $3{,}960{,}000$. The opposite signs place the line minimum strictly between those steps. Interpolation recovered its multiplier to the printed precision. At the second trial, the Armijo upper bound was about 201.600, well above 1.960198, and the slope magnitude $5.54\times10^{-11}$ was below $0.9(40004)$. A very short initial multiplier tests the need for expansion.
1
2
3
4
5
short_start <- line_search(quadratic, quadratic_gr, quad_start,
quadratic(quad_start), quad_g, -quad_g, initial = 1e-8)
print(c(initial_alpha = 1e-8, accepted_alpha = short_start$alpha,
trials = length(short_start$trial_steps),
directional_derivative_ratio = abs(sum(short_start$gradient * quad_g)) / sum(quad_g^2)))
1
2
3
4
initial_alpha accepted_alpha trials
0.00000001 0.00349525 10.00000000
directional_derivative_ratio
0.65050960
At $10^{-8}$, the decrease suffices, but the slope is scarcely changed. The tenth trial, at 0.00349525, was the first with a slope ratio below 0.9. The ratio was 0.6505096, enough for acceptance before the line minimum.
The function $x-\log x$, started at 2 in direction $-2$, tests what happens outside the domain.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
gradient <- function(x) c(1, 100) * x
start <- c(2, 2)
direction <- -gradient(start)
step <- line_search(quadratic, gradient, start, quadratic(start),
gradient(start), direction)
logarithmic <- function(x) if (x <= 0) Inf else x - log(x)
logarithmic_gradient <- function(x) 1 - 1/x
invalid <- line_search(logarithmic, logarithmic_gradient, 2, logarithmic(2),
logarithmic_gradient(2), -2)
stopifnot(!invalid$accepted, is.infinite(invalid$trial_steps[[1L]][["value"]]),
identical(unname(invalid$evaluations), c(1L, 0L)))
searches <- list(quadratic = step, logarithmic = invalid)
for (case in names(searches)) {
trials <- do.call(rbind, searches[[case]]$trial_steps)
colnames(trials) <- c("step_length", "function_value", "directional_derivative")
cat(case, "\n")
print(trials)
}
1
2
3
4
5
6
7
quadratic
step_length function_value directional_derivative
[1,] 1.00000000 1.960200e+06 3.96000e+06
[2,] 0.01000099 1.960198e+00 5.54059e-11
logarithmic
step_length function_value directional_derivative
[1,] 1 Inf NA
The initial directional derivative was $(1-1/2)(-2)=-1$, so this direction did give descent at 2. The unit trial evaluated the function at zero. The supplied function returned Inf there, so the directional derivative is missing. The counters distinguish these searches.
1
2
3
counts <- rbind(quadratic = step$evaluations, logarithmic = invalid$evaluations)
colnames(counts) <- c("function_evaluations", "gradient_evaluations")
print(counts)
1
2
3
function_evaluations gradient_evaluations
quadratic 2 2
logarithmic 1 0
The search on the quadratic used two calls to the objective function and two to the gradient. The logarithmic example used one function call and no gradient call beyond the supplied start.
A steepest-descent routine
The strong-Wolfe search above chooses a step along a supplied direction. To examine successive steepest-descent directions and the effect of coordinate scaling, the following steepest_descent() uses its own search: it halves a trial length until the value decreases, then compares that trial with a quadratic interpolation proposal. Its direction at each iteration is the unit negative gradient.
First, count_evaluations() returns functions fn, gr and he that evaluate the objective function and its derivatives while updating shared counters. Its counts() function returns the current three counts. If an analytic derivative is omitted, the corresponding function uses num_grad() or num_hess(). Their calls through the counted functions also advance the counters, so one request for a Hessian can require several gradient and objective function evaluations. Load the numerical derivatives it can call and the constructor for the returned fit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
source("code/lib/result.R")
source("code/lib/differentiation.R")
count_evaluations <- function(fn, gr = NULL, he = NULL) {
counts <- c(objective = 0L, gradient = 0L, hessian = 0L)
objective <- function(x) {
counts[1] <<- counts[1] + 1L
fn(x)
}
gradient <- function(x) {
counts[2] <<- counts[2] + 1L
if (is.null(gr)) num_grad(objective, x)$gradient else gr(x)
}
hessian <- function(x) {
counts[3] <<- counts[3] + 1L
if (is.null(he)) num_hess(objective, x, gr = gradient)$hessian else he(x)
}
list(fn = objective, gr = gradient, he = hessian, counts = function() counts)
}
At the beginning of an iteration, record the coordinates and compute the gradient length. An exactly zero length precludes normalization and gives zero_gradient with converged = FALSE. This flag records how this implementation stops; a zero gradient identifies a stationary point but does not by itself establish a minimum. Normalize a nonzero gradient by its Euclidean length.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
steepest_descent <- function(fn, gr, par, control = list()) {
stopifnot(all(names(control) %in% c("maxit", "tol")))
settings <- modifyList(list(maxit = 100L, tol = .Machine$double.eps^(1 / 2)), control)
ev <- count_evaluations(fn, gr)
x <- par
history <- list()
k <- 1L
converged <- FALSE
reason <- "iteration_limit"
while (k <= settings$maxit) {
f1 <- ev$fn(x)
g1 <- ev$gr(x)
# Record the point before choosing a displacement.
history[[length(history) + 1L]] <- list(par = x, value = f1,
max_abs_gradient = max(abs(g1)))
z1 <- sqrt(sum(g1^2))
if (z1 == 0) {
reason <- "zero_gradient"
break
}
g1 <- g1 / z1
The first trial subtracts this unit vector from the current point. While the value is at least as high as at the start, halve the length along the same direction.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
a3 <- 1
f3 <- ev$fn(x - a3 * g1)
stalled <- FALSE
while (f3 >= f1) {
a3 <- a3 / 2
# Evaluate the shorter step before testing the length threshold.
f3 <- ev$fn(x - a3 * g1)
if (a3 < settings$tol / 2) {
stalled <- TRUE
break
}
}
if (stalled) {
converged <- TRUE
reason <- "small_step"
break
}
After each halving, the method evaluates the function before testing the length. A length below $\sqrt{\epsilon}/2$, where $\epsilon$ is machine epsilon, gives small_step and a true flag even if that last trial improved the value. The parameter vector remains at its value from the start of that iteration. Given a decreasing step $a$, fit a quadratic through the values at $0,a/2,a$. With a2 equal to $a/2$, the first divided difference h1 and second divided difference h3 give the interpolant $q(t)=f_1+h_1t+h_3t(t-a_2)$. Solving $q^{\prime}(t)=0$ gives a0, $(a_2-h_1/h_3)/2$.
1
2
3
4
5
6
7
8
9
a2 <- a3 / 2
f2 <- ev$fn(x - a2 * g1)
# Divided differences determine the slope and curvature of the quadratic.
h1 <- (f2 - f1) / a2
h2 <- (f3 - f2) / (a3 - a2)
h3 <- (h2 - h1) / a3
a0 <- 0.5 * (a2 - h1 / h3)
f0 <- ev$fn(x - a0 * g1)
a <- if (f0 < f3) a0 else a3
The update uses this candidate only if its function value beats the one at $a$. Reaching 100 updates gives iteration_limit with a false flag.
1
2
3
4
5
6
7
x <- x - a * g1
k <- k + 1L
}
if (converged) x[abs(x) < .Machine$double.eps] <- 0
value <- ev$fn(x)
new_result(x, value, ev$gr(x), converged, reason, k - 1L, ev$counts(), history)
}
Fit the quadratic from $(2,2)$ in $x$ and $(2,20)$ in $v$. The rescaled fit reports $v$. Start Rosenbrock’s function at $(-1.2,1)$.
1
2
3
4
5
6
7
8
9
10
11
12
rosenbrock <- function(x) 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2
rosenbrock_gr <- function(x) c(-400 * x[1] * (x[2] - x[1]^2) + 2 * (x[1] - 1),
200 * (x[2] - x[1]^2))
rosen_start <- c(-1.2, 1)
sd_quad <- steepest_descent(quadratic, quadratic_gr, quad_start)
sd_rosen <- steepest_descent(rosenbrock, rosenbrock_gr, rosen_start)
scaled_fn <- function(v) quadratic(c(v[1], v[2] / 10))
scaled_gr <- function(v) v
sd_scaled <- steepest_descent(scaled_fn, scaled_gr, c(2, 20))
for (fit in list(quadratic = sd_quad, rescaled = sd_scaled, rosenbrock = sd_rosen)) {
print(fit[c("par", "value", "converged", "reason", "iterations", "evaluations")])
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
$par
[1] 1.720968e-10 1.720968e-10
$value
[1] 1.495675e-18
$converged
[1] TRUE
$reason
[1] "small_step"
$iterations
[1] 10
$evaluations
objective gradient hessian
193 12 0
$par
[1] 2.244871e-13 2.245315e-12
$value
[1] 2.545917e-24
$converged
[1] TRUE
$reason
[1] "small_step"
$iterations
[1] 1
$evaluations
objective gradient hessian
35 3 0
$par
[1] -0.8322013 0.6972328
$value
[1] 3.359146
$converged
[1] FALSE
$reason
[1] "iteration_limit"
$iterations
[1] 100
$evaluations
objective gradient hessian
1088 101 0
The original quadratic took ten updates to reach about $1.72\times10^{-10}$ in each coordinate, using 193 function and 12 gradient evaluations. Rescaling reduced the Hessian condition number from 100 to 1. One update brought both rescaled coordinates within $3\times10^{-12}$ of zero, with counts of 35 and 3. Both fits stopped on step length. Rosenbrock’s function still had value 3.359146 after 100 updates, at $(-0.8322013,0.6972328)$, despite 1,088 function and 101 gradient evaluations.
The paths in Figure 3.2 join the coordinates recorded at each iteration’s start. Dividing the rescaled path’s second coordinate by ten puts both quadratic paths on the same contours.
1
2
3
4
5
6
history_points <- function(fit) do.call(rbind, lapply(fit$history, function(row) row$par))
quadratic_path <- history_points(sd_quad)
rescaled_path <- history_points(sd_scaled)
# Express the second coordinate in the original units.
rescaled_path[, 2] <- rescaled_path[, 2] / 10
rosenbrock_path <- history_points(sd_rosen)
Figure 3.2. The dot marks the start and the cross the minimum. The dashed segment maps the rescaled quadratic path back to the original axes.
The original quadratic path drops almost parallel to the $x_2$ axis, then runs along the valley floor. The rescaled path heads directly to the minimum. On Rosenbrock’s contours the path turns down the left arm. Its last plotted point, about $(-0.82955,0.70321)$, starts the hundredth update. The returned coordinates include that update and are still far from $(1,1)$. The counts measure work, not accuracy. Substituting the returned coordinates into rosenbrock_gr() gives a largest absolute component of about 2.11, evidence that the function still has appreciable slope there. In R, pracma provides steepest descent. The supplied lb_more_thuente() is translated from the Moré-Thuente search of the limited-memory BFGS method with bounds (L-BFGS-B) that the stats package uses in optim() (code/NOTICE.md).
3.3 The secant condition, BFGS updates, and limited-memory BFGS with bounds
After a downhill step on Rosenbrock’s function, the gradients at the two ends of the step are available. Their difference gives information about how the Hessian acts on that particular displacement. Let $x_+=x+s$, let $g=\nabla f(x)$ and write $y=\nabla f(x_+)-g$. If the Hessian is continuous near $x$, expanding the gradient gives
\[y=\nabla^2 f(x)s+o(\|s\|).\]For a Newton step, the inverse relation converts a gradient into a displacement. A quasi-Newton method estimates that map from successive points. If $H_+$ denotes the new approximation to the inverse Hessian, requiring $H_+y=s$ makes it reproduce the step just observed. This is the secant equation. In several dimensions, a single pair specifies the action of the matrix in only one direction.
Start from a symmetric approximation $H$ to the inverse Hessian. The Broyden-Fletcher-Goldfarb-Shanno update, abbreviated BFGS, modifies it to satisfy the new equation. For $y^\top s>0$, set $\rho=1/(y^\top s)$ and write
\[H_+=(I-\rho s y^\top)H(I-\rho y s^\top)+\rho s s^\top.\]Multiply on the right by $y$. The factor nearest $y$ gives $y-\rho y(s^\top y)=0$, and the last term gives $\rho s(s^\top y)=s$. Expanding the product and collecting the terms in $ss^\top$ gives the form used for computation,
\[H_+=H+\frac{\{1+y^\top H y/(y^\top s)\}ss^\top-(Hy)s^\top-s(Hy)^\top}{y^\top s}.\]In bfgs_update(), sy is $y^\top s$, By is $Hy$ and coef is the coefficient $1+y^\top Hy/(y^\top s)$. The loops sum the products in coordinate order because changing the order of floating-point additions can change the result. Copying the lower triangle to the upper gives a symmetric result.
A small example shows the update at work. From the book directory, use $H=I$, $s=(1,2)^\top$ and $y=(2,6)^\top$.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bfgs_update <- function(inverse, s, y) {
# Sum the inner products and matrix columns in coordinate order.
n <- length(s)
sy <- 0
for (i in seq_len(n)) sy <- sy + s[i] * y[i]
if (!(sy > 0)) return(list(inverse = diag(n),
action = "reset_identity", curvature = sy))
By <- numeric(n)
for (j in seq_len(n)) By <- By + inverse[, j] * y[j]
coef <- 0
for (i in seq_len(n)) coef <- coef + By[i] * y[i]
coef <- 1 + coef / sy
updated <- inverse + (outer(coef * s, s) - outer(By, s) - outer(s, By)) / sy
# Copy the lower triangle into the upper triangle.
updated[upper.tri(updated)] <- t(updated)[upper.tri(updated)]
list(inverse = updated, action = "bfgs", curvature = sy)
}
s_pair <- c(1, 2)
y_pair <- c(2, 6)
secant <- bfgs_update(diag(2), s_pair, y_pair)
print(c(secant_error = max(abs(secant$inverse %*% y_pair - s_pair)),
minimum_eigenvalue = min(eigen(secant$inverse, symmetric = TRUE)$values)))
1
2
secant_error minimum_eigenvalue
0.0000000 0.3463301
Here $y^\top s=14$. The update gives $H_+=\tfrac1{98}\left(\begin{smallmatrix}97&-16\cr -16&38\end{smallmatrix}\right)$, so its product with $(2,6)^\top$ is $(1,2)^\top$, as the zero residual confirms. The smallest eigenvalue, 0.3463301, answers a different question: it is positive, so every nonzero direction has positive quadratic form under this matrix.
The condition $y^\top s>0$ is necessary for a positive definite solution when $y\ne0$, since the secant equation gives $y^\top H_+ y=y^\top s$. It also suffices for this update if $H$ is positive definite. For $z\ne0$, put $w=(I-\rho y s^\top)z$. Then $z^\top H_+z=w^\top H w+\rho(s^\top z)^2$. If $s^\top z=0$, the first term is positive because $w=z$. Otherwise the second is positive. A Wolfe step ensures $y^\top s>0$. For a descent step $s=\alpha d$, multiplying the Wolfe slope inequality by $\alpha>0$ and subtracting $g^\top s$ yields $y^\top s\ge(c_2-1)g^\top s>0$. An Armijo decrease alone gives no such guarantee. A gradient change opposite to the displacement tests this restriction.
1
print(bfgs_update(diag(2), c(1, 0), c(-1, 0))$action)
1
[1] "reset_identity"
The inner product is $-1$. The routine discards this pair and returns the identity for the next direction.
A BFGS routine with Armijo backtracking
The secant update now goes into a complete optimizer. The unconstrained optimizer bfgs() uses Armijo backtracking and checks whether $y^\top s>0$ for each proposed update. Its working coordinates are $b_i=x_i/a_i$, where par_scale supplies the positive scales $a_i$, all one by default. Thus the working gradient has entries $a_i g_i$. With an identity matrix, a unit trial would change $x_i$ by $-a_i^2g_i$. This matters for a log standard deviation in a mixed model, where a large negative first move can put the variance near zero on a nearly flat likelihood. Without an analytic gradient, bfgs() approximates each partial derivative by central differences of the objective function at $b_i\pm0.001$ by default. Load the constructor for its returned fit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
source("code/lib/result.R")
bfgs <- function(fn, gr = NULL, par, control = list()) {
stopifnot(all(names(control) %in% c("maxit", "rel_tol", "abs_tol", "par_scale", "diff_step")))
settings <- modifyList(list(maxit = 100L, rel_tol = sqrt(.Machine$double.eps),
abs_tol = -Inf,
par_scale = 1, diff_step = 1e-3), control)
n <- length(par)
scale <- rep_len(settings$par_scale, n)
diff_step <- rep_len(settings$diff_step, n)
stopifnot(is.numeric(par), n > 0L, all(is.finite(par)), all(scale > 0), all(diff_step > 0))
f_scaled <- function(v) {
value <- fn(v * scale)
if (!is.numeric(value) ||
length(value) != 1L) stop("The objective function must return one number")
value
}
# Difference one working coordinate at a time when no gradient is supplied.
g_scaled <- if (is.null(gr)) function(v) {
vapply(seq_len(n), function(i) {
e <- numeric(n)
e[i] <- diff_step[i]
(f_scaled(v + e) - f_scaled(v - e)) / (2 * diff_step[i])
}, 0)
} else function(v) gr(v * scale) * scale
The function first checks the starting value. For a finite start and a positive iteration allowance, it initializes the gradient count and the iteration count at one, records the starting point and sets B, the working inverse Hessian approximation, to the identity.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
shrink <- 0.2
armijo_c <- 1e-4
test_shift <- 10
b <- par / scale
f <- f_scaled(b)
if (!is.finite(f)) {
return(new_result(par, f, rep(NA_real_, n), FALSE, "nonfinite_initial_value", 0L,
c(objective = 1L, gradient = 0L, hessian = 0L), list()))
}
f_best <- f
n_fn <- 1L
if (settings$maxit <= 0) {
result <- new_result(par, f_best, rep(NA_real_, n), TRUE, "converged", 0L,
c(objective = n_fn, gradient = 0L, hessian = 0L), list())
result$par_scale <- scale
return(result)
}
g <- g_scaled(b)
n_gr <- 1L
iter <- 1L
restart_at <- n_gr
# B represents inverse curvature in the working coordinates.
B <- diag(n)
history <- list(list(par = b * scale, value = f_best, max_abs_gradient = max(abs(g / scale)),
step = NA_real_, update = "initial"))
Write $F(b)=f(a_1b_1,\ldots,a_n b_n)$ for the objective function in working coordinates. With its gradient $g$, the trial direction t is $-Bg$. For a negative directional derivative slope, start with multiplier one and multiply by 0.2 after each failed trial. Accept a finite value when $F(b+\alpha t)\le f_{\min}+10^{-4}\alpha g^\top t$. Trial evaluations cease if adding 10 to the old and proposed coordinates gives equal values in every position at machine precision.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
repeat {
if (restart_at == n_gr) B <- diag(n)
b_start <- b
g_old <- g
t <- numeric(n)
for (j in seq_len(n)) t <- t - B[, j] * g[j]
slope <- 0
for (i in seq_len(n)) slope <- slope + t[i] * g[i]
if (slope < 0) {
step_len <- 1
accepted <- FALSE
repeat {
b <- b_start + step_len * t
# Compare both points after adding the same floating-point offset.
n_same <- sum(test_shift + b_start == test_shift + b)
if (n_same < n) {
f <- f_scaled(b)
n_fn <- n_fn + 1L
accepted <- is.finite(f) && f <= f_best + slope * step_len * armijo_c
if (!accepted) step_len <- step_len * shrink
}
if (n_same == n || accepted) break
}
For the default relative tolerance $\sqrt{\epsilon}\approx1.49\times10^{-8}$, the accepted decrease must exceed $\sqrt{\epsilon}(\vert f_{\min}\vert +\sqrt{\epsilon})$ to warrant a new gradient for the update. A decrease at or below the threshold records the accepted point as final_step. If a restart follows, it initially uses the preceding gradient. When the decrease is sufficient for an update, step_len * t and g - g_old are the two vectors for the secant equation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
progress <- (f > settings$abs_tol) &&
abs(f - f_best) > settings$rel_tol * (abs(f_best) + settings$rel_tol)
if (!progress) {
# Keep the accepted point for the restart or final return.
if (n_same < n) history[[length(history) + 1L]] <- list(par = b * scale, value = f,
max_abs_gradient = NA_real_, step = step_len, update = "final_step")
n_same <- n
f_best <- f
}
if (n_same < n) {
f_best <- f
g <- g_scaled(b)
n_gr <- n_gr + 1L
iter <- iter + 1L
# Use the accepted displacement and its gradient difference.
update <- bfgs_update(B, step_len * t, g - g_old)
if (update$action == "bfgs") B <- update$inverse else restart_at <- n_gr
history[[length(history) + 1L]] <- list(par = b * scale, value = f_best,
max_abs_gradient = max(abs(g / scale)), step = step_len, update = update$action)
} else if (restart_at < n_gr) {
n_same <- 0L
restart_at <- n_gr
}
If $g^\top t\ge0$, the direction gives no first-order decrease. In that case, or after insufficient progress, restart_at marks a retry from the identity unless the current attempt already used that restart. A second unsuccessful attempt ends the run. The method also restarts after more than $2n$ gradient evaluations since the restart marker, where $n$ is the number of coordinates. The default limit is 100 counted iterations. At return, multiplying entry $(i,j)$ of B by $a_i a_j$ restores the inverse approximation to the original units.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
} else {
n_same <- 0L
if (restart_at == n_gr) n_same <- n else restart_at <- n_gr
}
if (iter >= settings$maxit) break
if (n_gr - restart_at > 2L * n) restart_at <- n_gr
if (!(n_same != n || restart_at != n_gr)) break
}
converged <- iter < settings$maxit
# This endpoint gradient is outside the iteration count.
final_gradient <- if (is.null(gr)) g_scaled(b) / scale else gr(b * scale)
result <- new_result(b * scale, f_best, final_gradient, converged,
if (converged) "converged" else "iteration_limit", iter,
c(objective = n_fn, gradient = n_gr, hessian = 0L), history)
result$inverse_hessian <- B * outer(scale, scale)
result$par_scale <- scale
result
}
Fit Rosenbrock’s function from $(-1.2,1)$ and the grouped logistic regression from zero intercept and slope. For the regression, each row gives successes and trials at one fixed covariate value. The function being minimized is their negative log likelihood. Read those observed counts and restore the analytic derivatives for the two fits.
1
2
3
4
5
6
7
8
9
10
11
12
13
source("code/lib/stability.R")
source("code/lib/logit.R")
source("code/lib/glm.R")
LOGIT3 <- read.csv("data/source/LOGIT3.csv")
logit_model <- make_glm(cbind(intercept = 1, x = LOGIT3$x),
LOGIT3$successes, "binomial", LOGIT3$trials)
rosenbrock <- function(x) 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2
rosenbrock_gr <- function(x) c(-400 * x[1] * (x[2] - x[1]^2) + 2 * (x[1] - 1),
200 * (x[2] - x[1]^2))
rosen_start <- c(-1.2, 1)
bfgs_rosen <- bfgs(rosenbrock, rosenbrock_gr, rosen_start)
bfgs_logit <- bfgs(logit_model$fn, logit_model$gr, c(0, 0))
print(bfgs_rosen[c("par", "value", "gradient", "reason", "iterations", "evaluations")])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$par
[1] 1 1
$value
[1] 9.594956e-18
$gradient
[1] -1.226542e-09 -2.481815e-09
$reason
[1] "converged"
$iterations
[1] 43
$evaluations
objective gradient hessian
110 43 0
In this printout, both coordinates round to one. Evaluating Rosenbrock’s function at the stored coordinates gave $9.59\times10^{-18}$. For the regression, the gradient at the returned coefficients measures the remaining local slope.
1
print(bfgs_logit[c("par", "value", "gradient", "reason")])
1
2
3
4
5
6
7
8
9
10
11
12
$par
[1] 0.000000 1.386294
$value
[1] 3.796766
$gradient
intercept x
0.000000e+00 -5.275953e-08
$reason
[1] "converged"
The slope prints as 1.386294. The partial derivative of the negative log likelihood function with respect to the slope, at the returned coefficients, is approximately $-5.28\times10^{-8}$. At the minimizing slope $\log 4$, the two groups with covariates $\pm1$ each contribute $10(0.2)(0.8)$ to the second partial derivative with respect to the slope. The middle group contributes zero, and symmetry cancels the mixed derivative at intercept zero. Dividing the slope component by 3.2 estimates the fitted slope minus $\log 4$, about $-1.65\times10^{-8}$. The function-change test can stop with a small coefficient error. The Rosenbrock history identifies what its 43 counted iterations include.
1
print(table(vapply(bfgs_rosen$history[-1], function(row) row$update, character(1))))
1
2
bfgs final_step reset_identity
39 2 3
After the initial gradient, 39 matrix updates and three restarts when $y^\top s\le0$ used 42 fresh gradients. The two final_step entries added no iterations. The first led to a retry with the identity and the second ended the fit. Backtracking brought the reported function count to 110. The code evaluated the gradient once more for the returned point, outside the reported 43 gradient evaluations.
BFGS is a practical general-purpose choice when the likelihood gradient is available analytically or cheaply by differences and a Hessian is expensive to form. Newton’s method needs the Hessian at the current iterate. BFGS uses gradient changes already obtained in fitting, whereas Nelder-Mead uses only function values.
For standard BFGS with Wolfe line searches that try the unit step first, use $0<c_1<1/2$ and $c_1<c_2<1$. A sufficient local convergence result assumes twice continuous differentiability of $f$, convergence to a minimizer $x_\ast $, a positive definite Hessian there, a locally Lipschitz continuous Hessian, and $\sum_k\Vert x_k-x_\ast \Vert<\infty$. The Lipschitz condition bounds $\Vert\nabla^2 f(x)-\nabla^2 f(x_\ast )\Vert$ by a constant times $\Vert x-x_\ast \Vert$ nearby. Under these conditions the convergence is superlinear: the ratio of successive parameter-error norms tends to zero. This result does not establish a rate for the Armijo search and identity restarts used in the implementation here.
Limited-memory BFGS with bounds
The routine above stores a full inverse Hessian approximation and lets every coordinate move freely. Box constraints specify lower and upper bounds for individual coordinates. A downhill direction may then point outside the permitted region. The function lbfgsb() implements L-BFGS-B. It represents a local quadratic approximation to the objective function with up to five recent pairs $(s,y)$ and avoids storing a full Hessian approximation.
Let $P$ clip each coordinate to its bounds. Along $P(x-tg)$, a coordinate stops moving when it reaches a bound. Between bound hits, the path is straight, so the model is quadratic in $t$. On each such segment, dividing minus the current model slope by the second derivative of that model with respect to $t$ locates a minimum. If a bound comes first, it fixes that coordinate and continues with the remaining direction. The first local minimum on the projected path is the generalized Cauchy point. From there, the optimizer seeks a model minimum over the coordinates not fixed at bounds and searches toward the resulting candidate using the Moré-Thuente rule. A warning can also end this inner search.
The projected gradient used for termination is $x-P(x-g)$, where $g=\nabla f(x)$. Its largest absolute component is the largest coordinate displacement in the move from $x$ to $P(x-g)$. It can be zero at a boundary even when $g$ is nonzero: the bounds can exclude every direction of first-order decrease. In code/lib/lbfgsb.R, lb_cauchy_point() follows the projected path described above. The function lbfgsb_core() only stores the pair when $s^\top y>\epsilon(-g_{\rm old}^\top s)$, so even a positive $s^\top y$ that is too small relative to the predicted first-order decrease is skipped. The function lbfgsb() that the fits below call prepares the problem for lbfgsb_core(), which carries out these steps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
lbfgsb <- function(par, fn, gr = NULL, lower = -Inf, upper = Inf, control = list()) {
n <- length(par)
settings <- modifyList(list(maxit = 100L, eps_factor = 1e7, proj_grad_tol = 0, memory = 5L,
par_scale = rep(1, n), value_scale = 1, diff_step = rep(1e-3, n)), control)
p_scale <- rep_len(settings$par_scale, n); v_scale <- settings$value_scale
lower <- rep_len(as.double(lower), n) / p_scale
upper <- rep_len(as.double(upper), n) / p_scale
bound_type <- ifelse(!is.finite(lower), ifelse(!is.finite(upper), 0L, 3L),
ifelse(!is.finite(upper), 1L, 2L))
f_scaled <- function(p) fn(p * p_scale) / v_scale
g_scaled <- if (!is.null(gr)) function(p) gr(p * p_scale) * p_scale / v_scale else function(p) {
grad <- numeric(n)
for (i in seq_len(n)) {
h_back <- settings$diff_step[i]; h_fwd <- h_back
x_i <- p[i] + h_back
if (x_i > upper[i]) { x_i <- upper[i]; h_fwd <- x_i - p[i] }
x <- p * p_scale; x[i] <- x_i * p_scale[i]
f_fwd <- fn(x) / v_scale
x_i <- p[i] - h_back
if (x_i < lower[i]) { x_i <- lower[i]; h_back <- p[i] - x_i }
x[i] <- x_i * p_scale[i]
f_back <- fn(x) / v_scale
grad[i] <- (f_fwd - f_back) / (h_fwd + h_back)
if (!is.finite(grad[i])) stop("non-finite finite-difference value")
}
grad
}
fit <- lbfgsb_core(par / p_scale, function(p) list(value = f_scaled(p), gradient = g_scaled(p)),
lower, upper, bound_type, m = settings$memory, eps_factor = settings$eps_factor, proj_grad_tol = settings$proj_grad_tol,
maxit = settings$maxit)
fit$par <- fit$par * p_scale
fit$value <- fit$value * v_scale
fit
}
The settings follow the controls of optim(): at most 100 iterations, the relative-reduction factor eps_factor of $10^7$, the projected-gradient tolerance proj_grad_tol, five stored pairs (memory), and scales for the coordinates and the objective. The search works with the scaled coordinates par/par_scale and the scaled objective fn()/value_scale, and the bounds are scaled in the same way. The vector bound_type codes each coordinate as unbounded (0), bounded below (1), bounded on both sides (2) or bounded above (3), the coding of the translated program. Without gr, the gradient is estimated by central differences with step diff_step; a step that would cross a bound is shortened to end at it, and the difference is divided by the two shortened widths together. The function lbfgsb_core() takes the scaled start, a function returning the scaled value and gradient, the bounds and the settings, and returns the solution with its counts and message; the coordinates and the value are then returned to the original scales. Load the full routine and compare two fits from the same start.
1
2
3
4
5
source("code/lib/lbfgsb.R")
lb_rosen <- lbfgsb(rosen_start, rosenbrock, rosenbrock_gr)
lb_rosen_box <- lbfgsb(rosen_start, rosenbrock, rosenbrock_gr,
lower = c(-2, -2), upper = c(0.5, 2))
print(lb_rosen[c("par", "value", "counts", "convergence", "message")])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$par
[1] 0.9999997 0.9999995
$value
[1] 2.267577e-13
$counts
function gradient
47 47
$convergence
[1] 0
$message
[1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"
With no bounds, the function and gradient were each evaluated 47 times. The relative decrease, $(f_{\rm old}-f_{\rm new})/\max(1,\vert f_{\rm old}\vert ,\vert f_{\rm new}\vert )$, was at most $10^7\epsilon$. Now inspect the fit with $-2\le x_1\le0.5$ and $-2\le x_2\le2$.
1
print(lb_rosen_box[c("par", "value", "counts", "convergence", "message")])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$par
[1] 0.50 0.25
$value
[1] 0.25
$counts
function gradient
31 31
$convergence
[1] 0
$message
[1] "CONVERGENCE: NORM OF PROJECTED GRADIENT <= PGTOL"
At $(0.5,0.25)$, the residual $x_2-x_1^2$ vanishes, giving gradient $(-1,0)^\top$. The first downhill component would increase $x_1$ past 0.5. Thus $P(x-g)=(0.5,0.25)^\top$ and both entries of $x-P(x-g)$ are zero. Its largest absolute entry, computed by lb_projected_gradient_norm(), meets the default threshold of zero. After an accepted step, the routine increments the count and checks whether it exceeds 100 before testing the projected gradient and the relative decrease. The three Rosenbrock fits illustrate how the bounds change the minimum and its stopping condition.
1
2
3
4
5
6
7
8
9
10
lb_logit <- lbfgsb(c(0, 0), logit_model$fn, logit_model$gr)
print(data.frame(method = c("BFGS", "L-BFGS-B", "L-BFGS-B, x1 <= 0.5"),
x1 = c(bfgs_rosen$par[1], lb_rosen$par[1], lb_rosen_box$par[1]),
x2 = c(bfgs_rosen$par[2], lb_rosen$par[2], lb_rosen_box$par[2]),
rosenbrock_value = c(bfgs_rosen$value, lb_rosen$value, lb_rosen_box$value),
function_evaluations = c(unname(bfgs_rosen$evaluations[1]), lb_rosen$counts[1],
lb_rosen_box$counts[1]),
gradient_evaluations = c(unname(bfgs_rosen$evaluations[2]), lb_rosen$counts[2],
lb_rosen_box$counts[2]),
message = c(bfgs_rosen$reason, lb_rosen$message, lb_rosen_box$message)), digits = 8)
1
2
3
4
5
6
7
8
method x1 x2 rosenbrock_value function_evaluations gradient_evaluations
1 BFGS 1.00000000 0.99999999 9.5949556e-18 110 43
2 L-BFGS-B 0.99999972 0.99999947 2.2675773e-13 47 47
3 L-BFGS-B, x1 <= 0.5 0.50000000 0.25000000 2.5000000e-01 31 31
message
1 converged
2 CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH
3 CONVERGENCE: NORM OF PROJECTED GRADIENT <= PGTOL
The unbounded limited-memory fit reached $(0.99999972,0.99999947)$ with value $2.27\times10^{-13}$. The restricted fit used 31 evaluations of each kind and attained 0.25. This is the best feasible value because $(1-x_1)^2\ge0.25$ throughout the box and the other squared term vanishes at the fitted point. Applying the same limited-memory method to the logistic likelihood gives a comparison on the coefficient scale.
1
print(lb_logit[c("par", "value", "counts", "message")])
1
2
3
4
5
6
7
8
9
10
11
12
$par
[1] 0.000000 1.386294
$value
[1] 3.796766
$counts
function gradient
7 7
$message
[1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"
The slope again rounds to 1.386294. The relative-decrease criterion ended the search after seven function evaluations and seven gradient evaluations.
L-BFGS-B can enforce bounds on unique variances in a factor model or on parameters in a variational fit. The double-dogleg method supplies quasi-Newton steps for fitting structural equation models. In mixed models, BOBYQA can optimize bounded parameters using quadratic interpolation of function values. The supplied bfgs() and lbfgsb() are translated from the BFGS and L-BFGS-B routines behind optim() in the stats package (code/NOTICE.md), which provides both methods.
3.4 Nelder-Mead simplex steps and derivative-free quadratic models (BOBYQA)
Suppose Rosenbrock’s function can be evaluated at any pair of coordinates, but its gradient is unavailable. Three function values suffice to choose a side of a triangle across which to search. In $p$ dimensions, the Nelder-Mead method uses a simplex, the convex hull of $p+1$ vertices, consisting of their weighted averages with nonnegative weights that sum to one. It is nondegenerate when the vertices are affinely independent. Equivalently, subtracting one vertex from the other $p$ gives $p$ linearly independent displacements. Order the vertices by the value of the objective function $f$, with the smallest value first. The vertex with the largest value, $x_h$, is the one to replace.
The other $p$ vertices define the opposite face. Their centroid $c$ is their coordinatewise average. Moving from $x_h$ to $c$ takes displacement $c-x_h$. Continuing by the same displacement reflects the worst vertex across the centroid. If that direction is promising, an expansion takes twice the reflected displacement measured from $c$. The two trial points are therefore
\[r=c+(c-x_h)=2c-x_h,\qquad e=c+2(r-c)=2r-c.\]A contraction instead tests the midpoint between $c$ and a vertex $v$. With coefficient $1/2$, the trial point is $(c+v)/2$. Which side of the face it lies on depends on whether $v$ is the original worst vertex or its reflection.
The method compares trial values to choose among reflection, expansion, contraction and shrinkage. The code below records these moves so their effects can be followed in the worked example.
Implementing the simplex moves
The function nelder_mead() takes an objective function and a starting vector. From the book directory, code/lib/result.R supplies the result constructor. In the matrix P, each vertex occupies a column, with its function value below its coordinates. To build the first simplex, displace the start along each coordinate separately by $0.1\max_j\vert x_j\vert $, using 0.1 at the origin. A nonfinite initial value prevents construction. At later trials, the routine substitutes $10^{35}$ for a nonfinite trial value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
source("code/lib/result.R")
nelder_mead <- function(fn, par, control = list()) {
stopifnot(all(names(control) %in% c("maxit", "rel_tol", "abs_tol")))
settings <- modifyList(list(maxit = 500L, rel_tol = sqrt(.Machine$double.eps),
abs_tol = -Inf),
control)
reflect <- 1
contract <- 0.5
expand <- 2
huge_value <- 1e35
n <- length(par)
n_evals <- 0L
evaluate <- function(x) {
n_evals <<- n_evals + 1L
v <- fn(x)
if (is.finite(v)) v else huge_value
}
f <- fn(par)
if (!is.finite(f)) {
return(new_result(par, f, rep(NA_real_, n), FALSE, "nonfinite_initial_value", 0L,
c(objective = 1L, gradient = 0L, hessian = 0L), list()))
}
n_evals <- 1L
# Fix the spread tolerance using the value at the starting point.
spread_tol <- settings$rel_tol * (abs(f) + settings$rel_tol)
nv <- n + 1L
C <- n + 2L
P <- matrix(0, nv, C)
P[nv, 1] <- f
P[seq_len(n), 1] <- par
L <- 1L
size <- 0
step <- max(0, 0.1 * abs(par))
if (step == 0) step <- 0.1
# Displace one coordinate per new vertex.
for (j in 2:nv) {
P[seq_len(n), j] <- par
offset <- step
while (P[j - 1L, j] == par[j - 1L]) {
P[j - 1L, j] <- par[j - 1L] + offset
offset <- offset * 10
}
size <- size + offset
}
size_prev <- size
recompute <- TRUE
fail <- 0L
action <- "build"
history <- list()
rows <- seq_len(n)
The loop identifies the best and worst columns, L and H. Each record gives the best vertex and its value, the spread between extremes, the preceding move and the evaluations to date. Write $f_0$ for the starting value and $\tau=\sqrt{\epsilon}$ for the default relative tolerance at machine precision $\epsilon$. The run stops when the spread is at most $\tau(\vert f_0\vert +\tau)$. A finite absolute tolerance abs_tol also ends the search if the best value reaches or falls below it. Its default is $-\infty$.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
repeat {
if (recompute) {
for (j in seq_len(nv)) if (j != L) P[nv, j] <- evaluate(P[rows, j])
recompute <- FALSE
}
# Locate the lowest and highest values in the last row.
f_low <- P[nv, L]
f_high <- f_low
H <- L
for (j in seq_len(nv)) if (j != L) {
f <- P[nv, j]
if (f < f_low) {
L <- j
f_low <- f
}
if (f > f_high) {
H <- j
f_high <- f
}
}
history[[length(history) + 1L]] <- list(par = P[rows, L], value = f_low,
spread = f_high - f_low,
action = action, evaluations = n_evals)
if (f_high <= f_low + spread_tol || f_low <= settings$abs_tol) break
Column C initially contains the centroid. When the reflected value f_refl is below the best value f_low, both candidates are available for comparison after one further evaluation at the expanded point.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Omit column H when averaging the vertex coordinates.
P[rows, C] <- (rowSums(P[rows, seq_len(nv), drop = FALSE]) - P[rows, H]) / n
trial <- (1 + reflect) * P[rows, C] - reflect * P[rows, H]
f_refl <- evaluate(trial)
action <- "reflection"
if (f_refl < f_low) {
P[nv, C] <- f_refl
expanded <- expand * trial + (1 - expand) * P[rows, C]
P[rows, C] <- trial
f <- evaluate(expanded)
if (f < f_refl) {
P[rows, H] <- expanded
P[nv, H] <- f
action <- "extension"
} else {
P[rows, H] <- P[rows, C]
P[nv, H] <- f_refl
}
In the remaining cases, the midpoint calculation uses the coordinates now in column H. Shrinkage sets recompute so the next pass evaluates the moved vertices. The code sums their absolute coordinate differences from the best and compares this size with the stored reference for shrinkage. The evaluation budget maxit defaults to 500 and is tested after a move, so the count can exceed it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
} else {
action <- "hi_reduction"
if (f_refl < f_high) {
P[rows, H] <- trial
P[nv, H] <- f_refl
action <- "lo_reduction"
}
# Column H now holds the reflection or the original worst vertex.
contracted <- (1 - contract) * P[rows, H] + contract * P[rows, C]
f <- evaluate(contracted)
if (f < P[nv, H]) {
P[rows, H] <- contracted
P[nv, H] <- f
} else if (f_refl >= f_high) {
action <- "shrink"
recompute <- TRUE
size <- 0
# Move each of the other vertices halfway toward the best.
for (j in seq_len(nv)) if (j != L) {
P[rows, j] <- contract * (P[rows, j] - P[rows, L]) + P[rows, L]
size <- size + sum(abs(P[rows, j] - P[rows, L]))
}
if (size < size_prev) {
size_prev <- size
} else {
fail <- 10L
break
}
}
}
if (n_evals > settings$maxit) break
}
if (n_evals > settings$maxit) fail <- 1L
reason <- if (fail == 0L) "converged" else if (fail == 1L) "iteration_limit" else
"degenerate_simplex"
result <- new_result(P[rows, L], P[nv, L], rep(NA_real_, n), fail == 0L, reason,
length(history) - 1L, c(objective = n_evals, gradient = 0L, hessian = 0L), history)
result$simplex <- t(P[rows, seq_len(nv), drop = FALSE])
result
}
The comparisons in this version determine which point replaces the worst vertex. If $f(r)$ is below the current best value, try the expansion. When $f(e)<f(r)$, the expanded point replaces the worst and the move is recorded as extension. Otherwise the reflected point replaces the worst and the move is recorded as reflection.
When $f(r)$ does not beat the best but improves on the worst, first replace the worst vertex by $r$, then try a contraction toward $r$. This is lo_reduction. If the contracted point fails to improve on $r$, the reflected point is retained. When $f(r)$ is at least as large as the worst value, hi_reduction tries the midpoint toward $x_h$. If that contraction also fails, shrink the simplex by moving every vertex except the best halfway toward the best. Reevaluating the moved vertices costs $p$ evaluations.
If the measured size after shrinking does not fall below the stored reference size, this implementation returns degenerate_simplex. That stopping rule does not test whether the vertex displacements are linearly independent.
Simplex moves on two test functions
Begin with the quadratic bowl $f(x)=\Vert x-(2,1)\Vert ^2$. A start at $(0,0)$ gives a triangle with other vertices $(0.1,0)$ and $(0,0.1)$. At the start and the two displaced vertices, the respective values are $5$, $1.9^2+1=4.61$ and $4+0.9^2=4.81$. The first history entry identifies the best of these three vertices.
1
2
first_fit <- nelder_mead(function(x) sum((x - c(2, 1))^2), c(0, 0))
print(first_fit$history[[1]])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$par
[1] 0.1 0.0
$value
[1] 4.61
$spread
[1] 0.39
$action
[1] "build"
$evaluations
[1] 3
The spread is $5-4.61=0.39$ after three evaluations. The two better vertices have centroid $(0.05,0.05)$. Reflecting the origin gives $(0.1,0.1)$ with value $1.9^2+0.9^2=4.42$, an improvement on 4.61. Expanding to $(0.15,0.15)$ lowers the value further to $1.85^2+0.85^2=4.145$. The fifth evaluation thus supplies the new best vertex.
1
2
3
print(do.call(rbind, lapply(head(first_fit$history, 6),
function(row) data.frame(action = row$action,
value = row$value, spread = row$spread, evaluations = row$evaluations))))
1
2
3
4
5
6
7
action value spread evaluations
1 build 4.6100000 0.390000 3
2 extension 4.1450000 0.665000 5
3 extension 3.5912500 1.018750 7
4 extension 2.5390625 1.605938 9
5 extension 1.4878906 2.103359 11
6 extension 0.2344727 2.304590 13
Four more expansions cost two evaluations apiece. By evaluation 13, the best value had fallen to 0.2344727 while the spread had grown to 2.304590. The expanding triangle brought one vertex closer to the minimum while others still had larger values.
How much agreement among the vertices ends a search in Rosenbrock’s curved valley? Use the start $(-1.2,1)$.
1
2
rosenbrock <- function(x) 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2
rosen_start <- c(-1.2, 1)
Choose one of the following two routes to run and print the Rosenbrock fit: execute the displayed block, or source its file in the next block. The displayed block gives the contents of code/checks/ch03_simplex_runs.R. Its last call omits the initial build when counting moves.
1
2
3
4
5
nm_rosen <- nelder_mead(rosenbrock, rosen_start)
print(nm_rosen[c("par", "value", "gradient", "converged",
"reason", "iterations", "evaluations")])
print(tail(nm_rosen$history, 1))
print(table(vapply(nm_rosen$history[-1], function(row) row$action, character(1))))
The alternative call runs that same block from the file.
1
source("code/checks/ch03_simplex_runs.R")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
$par
[1] 1.000260 1.000506
$value
[1] 8.825241e-08
$gradient
[1] NA NA
$converged
[1] TRUE
$reason
[1] "converged"
$iterations
[1] 96
$evaluations
objective gradient hessian
195 0 0
[[1]]
[[1]]$par
[1] 1.000260 1.000506
[[1]]$value
[1] 8.825241e-08
[[1]]$spread
[1] 6.754618e-08
[[1]]$action
[1] "hi_reduction"
[[1]]$evaluations
[1] 195
extension hi_reduction lo_reduction reflection
28 34 19 15
The fit stopped at $(1.000260,1.000506)$ with function value $8.83\times10^{-8}$. The final table counts the four move types. The reduction labels count attempts along the two midpoint directions. With no shrink, the 96 moves each evaluated the reflection and one further point, giving $3+2(96)=195$ evaluations. The final spread of $6.75\times10^{-8}$ fell below $\sqrt{\epsilon}(24.2+\sqrt{\epsilon})\approx3.6\times10^{-7}$. A larger absolute starting value permits more variation among the final vertex values. The gradient plays no part in this test. Against the known minimum, the larger coordinate error was about $0.000506$.
Figure 3.3 plots the best vertices to show how the simplex reached this neighborhood. For comparison, BFGS starts at the same point and uses the analytic gradient. The function history_points() places the coordinates from each history entry in one row.
1
2
3
4
5
source("code/lib/quasi_newton.R")
rosenbrock_gr <- function(x) c(-400 * x[1] * (x[2] - x[1]^2) + 2 * (x[1] - 1),
200 * (x[2] - x[1]^2))
bfgs_rosen <- bfgs(rosenbrock, rosenbrock_gr, rosen_start)
history_points <- function(fit) do.call(rbind, lapply(fit$history, function(row) row$par))
Each gray contour connects pairs of coordinates with an equal value of Rosenbrock’s function. Joining the history points in order shows how each search moved relative to those contours.
1
2
bfgs_path <- history_points(bfgs_rosen)
simplex_path <- history_points(nm_rosen)
Figure 3.3. The dot marks the common start and the cross marks the minimum. The solid line joins BFGS history points. The dashed line joins successive best simplex vertices.
The simplex first selected $(-1.08,1)$ after comparing three vertices, so its dashed path begins to the right of $(-1.2,1)$. Both paths turn toward $(1,1)$ along the valley floor. BFGS counted its initial gradient evaluation among 43 iterations. The simplex counted 96 moves after construction.
Quadratic models from function values (BOBYQA)
Nelder-Mead chooses moves by comparing vertex values. BOBYQA, short for Bound Optimization BY Quadratic Approximation, instead uses function values to construct a local quadratic model. A radius limits the displacement over which it uses that model; Section 3.5 develops this trust-region idea.
Here the model interpolates four function values. A quadratic in two coordinates has six coefficients, one constant, two linear and three quadratic. Four interpolation equations do not determine all entries of the Hessian of the model. Among updates satisfying the interpolation conditions, the method minimizes the change in the second-derivative matrix measured by the Frobenius norm, the square root of the sum of squared matrix entries. The method seeks a step that approximately minimizes the quadratic. The new coordinates must satisfy their bounds, and the length of the step cannot exceed the current radius. It can also choose a point to reduce near linear dependence among the interpolation conditions, improving the numerical determination of the model. In code/lib/bobyqa.R, bq_trust_step() computes the radius-limited step, and bq_main() can request a point to improve the interpolation conditions. The function bobyqa() called below checks the settings and the starting point and then passes them to bq_main().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
bobyqa <- function(par, fn, lower = -Inf, upper = Inf, control = list()) {
n <- length(par)
defaults <- list(radius_start = NA, radius_end = NA, n_interp = min(2L * n, n + 2L), max_evals = 10000L, stop_outside = TRUE, print_level = 0L)
settings <- modifyList(defaults, control); most <- ((n + 1L) * (n + 2L)) %/% 2L
n_interp <- as.integer(max(n + 2L, min(settings$n_interp, most)))
radius_start <- settings$radius_start; if (is.na(radius_start)) radius_start <- min(0.95, 0.2 * max(abs(par)))
if (length(radius_start) != 1L || !is.finite(radius_start) || radius_start <= 0)
stop("Supply a positive finite initial trust-region radius (radius_start) for this starting value.")
# Both requested radii are set together. A narrow box can subsequently reduce only
# the initial radius; the final radius continues to refer to the original setting.
radius_end <- if (is.na(settings$radius_end)) 1e-6 * radius_start else settings$radius_end
if (length(radius_end) != 1L || !is.finite(radius_end) || radius_end <= 0 || radius_end > radius_start)
stop("The final radius must be positive and at most the requested initial radius.")
first <- fn(par)
if (!is.numeric(first) || length(first) != 1L) stop("The objective function must return one numeric value.")
expand <- function(b) { b <- as.numeric(b); if (length(b) == 1L) rep(b, n) else b }
lower <- expand(lower); upper <- expand(upper)
stopifnot(length(lower) == n, length(upper) == n, all(lower < upper))
outside <- any(par < lower | par > upper)
if (outside && isTRUE(settings$stop_outside)) stop("Starting values violate the bounds.")
if (outside) {
if (all(is.finite(c(lower, upper)))) {
# With finite bounds this rule also changes coordinates that started inside.
# The first interpolation point is placed within the bounds below.
par <- pmax(par, upper)
} else {
par <- pmax(lower, pmin(par, upper))
}
warning("Starting values were adjusted before forming the interpolation points.")
}
width <- upper - lower
if (min(width) < 2 * radius_start) {
radius_start <- 0.2 * min(width)
warning("The initial radius was reduced to fit inside the bounds.")
}
if (settings$print_level >= 2L) cat("radius_start =", radius_start, ", radius_end =", radius_end, "\n")
count <- 0L
f_count <- function(x) { count <<- count + 1L; v <- fn(x); if (!is.finite(v)) .Machine$double.xmax else v }
B <- new.env()
B$n <- n; B$n_interp <- n_interp; B$b_rows <- n_interp + n; B$x <- as.double(par); B$x_lower <- lower; B$x_upper <- upper
B$radius_start <- radius_start; B$radius_end <- radius_end; B$max_evals <- as.integer(settings$max_evals)
if (n_interp < n + 2L || n_interp > ((n + 2L) * (n + 1L)) %/% 2L) stop("NPT is not in the required interval")
B$gap_down <- numeric(n); B$gap_up <- numeric(n)
for (j in seq_len(n)) {
temp <- B$x_upper[j] - B$x_lower[j]
if (temp < radius_start + radius_start) stop("one of the box constraint ranges is too small (< 2*RHOBEG)")
B$gap_down[j] <- B$x_lower[j] - B$x[j]; B$gap_up[j] <- B$x_upper[j] - B$x[j]
if (B$gap_down[j] >= -radius_start) {
if (B$gap_down[j] >= 0) { B$x[j] <- B$x_lower[j]; B$gap_down[j] <- 0; B$gap_up[j] <- temp } else {
B$x[j] <- B$x_lower[j] + radius_start; B$gap_down[j] <- -radius_start; B$gap_up[j] <- max(B$x_upper[j] - B$x[j], radius_start)
}
} else if (B$gap_up[j] <= radius_start) {
if (B$gap_up[j] <= 0) { B$x[j] <- B$x_upper[j]; B$gap_down[j] <- -temp; B$gap_up[j] <- 0 } else {
B$x[j] <- B$x_upper[j] - radius_start; B$gap_down[j] <- min(B$x_lower[j] - B$x[j], -radius_start); B$gap_up[j] <- radius_start
}
}
}
r <- bq_main(B, f_count)
codes <- c(`320` = 5L, `390` = 1L, `430` = 3L)
list(par = r$par, value = fn(r$par), evaluations = count,
code = if (r$exit_code == 0L) 0L else codes[[as.character(r$exit_code)]],
message = switch(as.character(r$exit_code), `0` = "Normal exit",
`320` = "Too much cancellation in a denominator",
`390` = "Maximum number of function evaluations exceeded",
`430` = "A trust region step failed to reduce the quadratic model"))
}
With $n$ coordinates the model interpolates n_interp values, by default $\min(2n,n+2)$; the count must lie between $n+2$ and $(n+1)(n+2)/2$. The defaults of the radii radius_start and radius_end, and their adjustment to narrow bounds, are given after the two fits below. A start outside the bounds stops the fit unless stop_outside = FALSE, in which case the start is adjusted with a warning by the rule in the comments. The function f_count() counts evaluations and replaces a nonfinite value by the largest representable number. Before the iterations, a coordinate closer than radius_start to a bound is moved onto the bound if it lies on or beyond it, and otherwise to distance radius_start from it; gap_down and gap_up record the distances to the lower and upper bounds. The state is placed in the environment B, and bq_main() runs the iterations and returns the final point with an exit code. The returned code and message translate that code, and value evaluates the objective once more at the returned point, outside the count evaluations.
The two fits below use the same Rosenbrock function. The second restricts both coordinates to a box whose first coordinate has upper bound 0.5.
1
2
3
4
5
6
7
8
9
10
11
source("code/lib/bobyqa.R")
rosenbrock <- function(x) 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2
rosen_start <- c(-1.2, 1)
bq_rosen <- bobyqa(rosen_start, rosenbrock)
bq_rosen_box <- bobyqa(rosen_start, rosenbrock, lower = c(-2, -2), upper = c(0.5, 2))
print(data.frame(method = c("Nelder-Mead", "BOBYQA", "BOBYQA, x1 <= 0.5"),
x1 = c(nm_rosen$par[1], bq_rosen$par[1], bq_rosen_box$par[1]),
x2 = c(nm_rosen$par[2], bq_rosen$par[2], bq_rosen_box$par[2]),
value = c(nm_rosen$value, bq_rosen$value, bq_rosen_box$value),
evaluations = c(unname(nm_rosen$evaluations[1]), bq_rosen$evaluations, bq_rosen_box$evaluations),
message = c(nm_rosen$reason, bq_rosen$message, bq_rosen_box$message)), digits = 8)
1
2
3
4
method x1 x2 value evaluations message
1 Nelder-Mead 1.0002601 1.0005060 8.8252410e-08 195 converged
2 BOBYQA 1.0000005 1.0000009 2.8448854e-13 290 Normal exit
3 BOBYQA, x1 <= 0.5 0.5000000 0.2500000 2.5000000e-01 158 Normal exit
From $(-1.2,1)$, the unbounded fit reached $(1.0000005,1.0000009)$ with value $2.84\times10^{-13}$ after 290 evaluations. With $x_1\le0.5$, it reached $(0.5,0.25)$ with value 0.25 after 158. Both messages indicate normal termination under the radius rule.
The default initial radius is $\min(0.95,0.2\max_i\vert x_i\vert )$, which gives zero at the origin. At that start, specify a positive initial radius with radius_start. For the choice 0.2, the final radius defaults to $10^{-6}(0.2)=2\times10^{-7}$. The routine sets this value before examining the bounds. If the narrowest interval has width $w$ below twice the requested initial radius, the search begins with radius $w/5$ and retains the final radius already set. The evaluation limit is 10,000.
1
2
3
# At an all-zero start, supply a positive radius on the scale of the parameters.
bq_zero <- bobyqa(c(0, 0), rosenbrock, control = list(radius_start = 0.2))
print(bq_zero[c("par", "value", "code")])
1
2
3
4
5
6
7
8
$par
[1] 1.0000000 0.9999999
$value
[1] 1.171065e-15
$code
[1] 0
The zero exit code records a normal stop without a gradient evaluation. The returned point rounded to $(1.0000000,0.9999999)$. The value of the function at the unrounded point was about $1.17\times10^{-15}$. To seven decimal places, only the second coordinate differs from the minimizer $(1,1)$, by $10^{-7}$. The supplied nelder_mead() is translated from the Nelder-Mead routine behind optim() in stats, and bobyqa() from Powell’s BOBYQA code as distributed in minqa (code/NOTICE.md); both packages provide these methods.
3.5 Trust regions, double dogleg steps, and a bound-constrained quasi-Newton method
A quadratic model can describe a curved valley accurately near one point yet poorly farther away. At $x$, let $g$ be the gradient of the objective function $f$ and let $B$ be its Hessian or a symmetric approximation to that Hessian. The model predicts a change $q(d)$ for a displacement $d$. A trust region limits how far the model may be used. With a Euclidean ball of radius $\Delta>0$, the subproblem is
\[\min_{\|d\|\le\Delta} q(d),\qquad q(d)=g^\top d+\tfrac12 d^\top B d.\]A line search varies a multiplier along a chosen direction. Here, changing the radius can change both the length and the direction of the minimizing step.
Introduce a multiplier $\mu$ for the constraint $(\Vert d\Vert ^2-\Delta^2)/2\le0$. Differentiating the Lagrangian gives $(B+\mu I)d=-g$. At a global minimizer, the shifted matrix is positive semidefinite, $\mu\ge0$, and $\mu(\Delta-\Vert d\Vert )=0$. To see why these conditions suffice, take any feasible $z$. Substituting the stationarity equation gives
\[q(z)-q(d)=\tfrac12(z-d)^\top(B+\mu I)(z-d) +\tfrac{\mu}{2}(\|d\|^2-\|z\|^2)\ge0.\]The second term vanishes when $\mu=0$ and is nonnegative when $\Vert d\Vert =\Delta$. If $B$ is positive definite and the Newton step fits, $\mu=0$ gives the solution. Otherwise, diagonalize $B=V\operatorname{diag}(\lambda_i)V^\top$ with orthonormal columns and set $\tilde g=V^\top g$. When $B+\mu I$ is invertible, the step has eigenvector coordinates $-\tilde g_i/(\lambda_i+\mu)$, so
\[\|d(\mu)\|^2=\sum_i\frac{\tilde g_i^2}{(\lambda_i+\mu)^2}.\]For a step with $\Vert d\Vert=\Delta$ and invertible $B+\mu I$, solve $1/\Vert d(\mu)\Vert -1/\Delta=0$. The reciprocal length increases with the shift and is nearly linear for large $\mu$, since each denominator then grows at the same rate. A solution with $\Vert d\Vert=\Delta$ may instead occur when $B+\mu I$ is singular, at $\mu=-\lambda_{\min}$. Components of the gradient in the entire lowest eigenspace must then vanish for the stationarity equation to have a solution. The other components determine part of the step. Any remaining length can be supplied in that eigenspace. This construction also permits negative eigenvalues of $B$.
A bracketing root finder
To solve the boundary equation for the shift, first implement a scalar root finder, then use it inside trust_subproblem(). The function brent_root() finds a zero of a continuous scalar function whose values have opposite signs at the two endpoints. Run the code from the book directory. An exact endpoint zero finishes the search. A missing endpoint value returns missing_value. When requested, upX extends the bracket for an upward crossing and downX for a downward crossing. An endpoint whose value has the wrong sign moves outward. Its first increment is $0.01\max(10^{-4},\vert \text{endpoint}\vert )$ and each subsequent increment at that end is twice as large.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
brent_root <- function(f, lower, upper, tol = .Machine$double.eps^0.25, max_iter = 1000L,
extend = c("no", "upX", "downX")) {
extend <- match.arg(extend)
big <- .Machine$double.xmax; clamp <- function(v) min(max(v, -big), big)
evaluations <- 0L
g <- function(x) {
evaluations <<- evaluations + 1L
f(x)
}
failure <- function(reason) list(root = NA_real_, value_at_root = NA_real_, iter = 0L,
precision = NA_real_, converged = FALSE, reason = reason, evaluations = evaluations,
bracket = c(lower, upper))
stopifnot(is.finite(lower), is.finite(upper), lower < upper)
fa <- g(lower)
fb <- g(upper)
if (is.na(fa) || is.na(fb)) return(failure("missing_value"))
n_widen <- 0L
# Move only the endpoint whose sign is incompatible with the requested crossing.
if (extend != "no") {
direction <- if (extend == "upX") 1 else -1
step <- 0.01 * pmax(1e-4, abs(lower))
repeat {
if (!isTRUE(direction * fa > 0)) break
n_widen <- n_widen + 1L
if (n_widen > max_iter) return(failure("no_sign_change"))
lower <- lower - step; fa <- g(lower); step <- 2 * step
}
step <- 0.01 * pmax(1e-4, abs(upper))
repeat {
if (!isTRUE(direction * fb < 0)) break
n_widen <- n_widen + 1L
if (n_widen > max_iter) return(failure("no_sign_change"))
upper <- upper + step; fb <- g(upper); step <- 2 * step
}
if (anyNA(c(fa, fb))) return(failure("missing_value"))
}
if (isTRUE(sign(fa) * sign(fb) > 0) || is.na(sign(fa) * sign(fb)))
return(failure("no_sign_change"))
fa <- clamp(fa)
fb <- clamp(fb)
a <- lower
b <- upper
c <- a
fc <- fa
if (fa == 0) return(list(root = a, value_at_root = 0, iter = n_widen, precision = 0,
converged = TRUE, reason = "converged", evaluations = evaluations,
bracket = c(lower, upper)))
if (fb == 0) return(list(root = b, value_at_root = 0, iter = n_widen, precision = 0,
converged = TRUE, reason = "converged", evaluations = evaluations,
bracket = c(lower, upper)))
In the loop, b is the current estimate and c brackets the zero with it. Bisection proposes the midpoint. Two distinct points allow a secant step, and three distinct ordinates allow inverse quadratic interpolation, which estimates the location at function value zero. The interpolation replaces bisection only when the proposed move remains inside the bracket and improves sufficiently on the previous step.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
maxit <- max_iter + 1L
used <- 0L
while (maxit > 0L) {
maxit <- maxit - 1L
step_prev <- b - a
if (abs(fc) < abs(fb)) {
a <- b; b <- c; c <- a
fa <- fb; fb <- fc; fc <- fa
}
# Keep bisection as the candidate until an interpolation passes both safeguards.
tol_now <- 2 * .Machine$double.eps * abs(b) + tol / 2
step_new <- (c - b) / 2
if (abs(step_new) <= tol_now || fb == 0) {
return(list(root = b, value_at_root = fb, iter = max_iter - maxit + n_widen,
precision = abs(c - b), converged = TRUE, reason = "converged",
evaluations = evaluations, bracket = c(lower, upper)))
}
# Use a secant for two points or inverse quadratic interpolation for three.
if (abs(step_prev) >= tol_now && abs(fa) > abs(fb)) {
span <- c - b
if (a == c) {
t1 <- fb / fa
p <- span * t1
q <- 1 - t1
} else {
q <- fa / fc
t1 <- fb / fc
t2 <- fb / fa
p <- t2 * (span * q * (q - t1) - (b - a) * (t1 - 1))
q <- (q - 1) * (t1 - 1) * (t2 - 1)
}
if (p > 0) q <- -q else p <- -p
if (p < (0.75 * span * q - abs(tol_now * q) / 2) && p < abs(step_prev * q / 2))
step_new <- p / q
}
The search stops as soon as $f(b)=0$ or half the bracket width falls to $2\epsilon\vert b\vert +\text{tol}/2$ or less. Here $\epsilon$ is machine precision and the default is $\text{tol}=\epsilon^{1/4}$. The returned precision records the final bracket width in the root variable’s units; an exact endpoint zero returns zero. The default reported iteration limit is 1,000. If a value at a trial strictly between the bracket endpoints is nonfinite, the routine warns. It replaces a missing value by the largest finite double and an infinite value by the finite bound of the same sign. A returned root estimate then needs a check in the original function, since an undefined ordinate cannot establish a zero.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
if (abs(step_new) < tol_now) step_new <- if (step_new > 0) tol_now else -tol_now
a <- b
fa <- fb
b <- b + step_new
fb <- g(b)
if (!is.finite(fb)) {
# Brent's interpolation needs a finite ordinate for a trial between the endpoints.
warning("A non-finite function value between the endpoints was replaced by a finite bound.")
fb <- if (is.na(fb)) .Machine$double.xmax else clamp(fb)
}
# Restore opposite signs at b and c.
if ((fb > 0 && fc > 0) || (fb < 0 && fc < 0)) {
c <- a
fc <- fa
}
}
list(root = b, value_at_root = fb, iter = max_iter + n_widen, precision = abs(c - b),
converged = FALSE, reason = "iteration_limit", evaluations = evaluations,
bracket = c(lower, upper))
}
Solving the trust-region subproblem
Now apply the root finder to the trust-region subproblem. The function trust_subproblem() takes the eigendecomposition, the rotated gradient and the radius r. After testing the Newton step, it uses the shifted root variable shift, equal to $t=\mu+\lambda_{\min}$. With $\beta_i=\lambda_i-\lambda_{\min}$, the denominators become $\beta_i+t$. The quantity sum_min sums $\tilde g_i^2$ over every index with $\beta_i=0$. At $t=0$, sum_free gives the squared length determined by the remaining indices.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
trust_subproblem <- function(eig, g_rot, r) {
# A step in the eigenbasis, w, is -V w in the original coordinates.
step_from <- function(w) as.numeric(-eig$vectors %*% w)
if (all(eig$values > 0)) {
p_try <- step_from(g_rot / eig$values)
if (sqrt(sum(p_try^2)) <= r) return(list(step = p_try, type = "Newton"))
}
beta <- eig$values - min(eig$values)
# Include every eigenvector with the minimum eigenvalue.
is_min <- beta == 0
sum_all <- sum(g_rot * g_rot)
sum_free <- sum(((g_rot / beta)^2)[!is_min])
sum_min <- sum((g_rot * g_rot)[is_min])
hard_case <- sum_min == 0
In the shifted coordinates, boundary_residual() evaluates the left side of the boundary equation
For $t>0$, the step length is at least $\sqrt{\mathtt{sum_min}}/t$ and at most $\Vert g\Vert /t$. These bounds bracket the root in shift between $\sqrt{\mathtt{sum_min}}/\Delta$ and $\Vert g\Vert /\Delta$. The implementation labels a nonzero projection onto the lowest eigenspace easy-easy. When the projection vanishes but sum_free exceeds $\Delta^2$, the part of the step along eigenvectors with eigenvalues above the minimum is already longer than the radius at $t=0$. The positive root then gives the label hard-easy. These strings distinguish code branches; the conditions just stated specify their mathematical meaning.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (!hard_case || sum_free > r^2) {
boundary_residual <- function(shift) {
if (shift == 0) return(if (sum_min > 0) -1 / r else sqrt(1 / sum_free) - 1 / r)
scaled <- g_rot / (beta + shift)
sqrt(1 / sum(scaled * scaled)) - 1 / r
}
# These bounds bracket the zero in the shifted multiplier.
shift_lo <- sqrt(sum_min) / r
shift_hi <- sqrt(sum_all) / r
at_hi <- boundary_residual(shift_hi)
root <- if (at_hi <= 0) shift_hi else if (boundary_residual(shift_lo) >= 0) shift_lo else
brent_root(boundary_residual, shift_lo, shift_hi)$root
p_try <- step_from(g_rot / (beta + root))
type <- if (hard_case) "hard-easy" else "easy-easy"
Otherwise, the branch labeled hard-hard uses $t=0$, so $B+\mu I$ is singular. With the lowest-space coordinates set to zero, p_try has squared length sum_free. The code adds $\sqrt{\Delta^2-\Vert \mathtt{p_try}\Vert ^2}$ times one unit vector from the lowest eigenspace. Orthogonality makes the completed length $\Delta$.
1
2
3
4
5
6
7
8
9
10
11
} else {
# Complete the regular step in the lowest eigenspace.
w_try <- g_rot / beta
w_try[is_min] <- 0
p_try <- step_from(w_try)
u_try <- sqrt(r^2 - sum(p_try^2))
if (u_try > 0) p_try <- p_try + u_try * eig$vectors[, is_min, drop = FALSE][, 1]
type <- "hard-hard"
}
list(step = p_try, type = type)
}
Consider $f(x)=(x_1^2+100x_2^2)/2$ at $(2,2)$. The gradient is $(2,200)$ and the Hessian is diagonal with entries 1 and 100. Only the radius varies in these three trials.
1
2
3
4
5
6
7
8
9
10
11
12
quadratic <- function(x) 0.5 * sum(c(1, 100) * x^2)
quadratic_gr <- function(x) c(1, 100) * x
quadratic_he <- function(x) diag(c(1, 100))
quad_start <- c(2, 2)
quad_g <- quadratic_gr(quad_start)
quad_eigen <- eigen(quadratic_he(quad_start), symmetric = TRUE)
for (radius in c(0.5, 2.1, 4)) {
sub <- trust_subproblem(quad_eigen,
as.numeric(t(quad_eigen$vectors) %*% quad_g), radius)
print(c(radius = radius, norm = sqrt(sum(sub$step^2)), sub$step))
print(sub$type)
}
1
2
3
4
5
6
7
8
9
radius norm
0.500000000 0.500000000 -0.006643739 -0.499955859
[1] "easy-easy"
radius norm
2.100000 2.100000 -0.737274 -1.966323
[1] "easy-easy"
radius norm
4.000000 2.828427 -2.000000 -2.000000
[1] "Newton"
At radius 0.5, the boundary step is $(-0.006643739,-0.499955859)$. Moving the same distance directly downhill gives $-0.5g/\Vert g\Vert \approx(-0.0049998,-0.4999750)$. The subproblem solution, computed to the root-finding tolerance, puts more displacement along the first coordinate, whose second derivative is smaller. At radius 2.1, the step $(-0.737274,-1.966323)$ also reaches the boundary to the root-finding tolerance. At radius 4, the Newton step $(-2,-2)$ fits with length $\sqrt{8}\approx2.828427$.
Accepting steps and adjusting the radius
A step can minimize the model and still raise the objective function. In trust_region(), pred_change is the signed predicted change $q(d)$ and f_try - f is the signed actual change. Negating both gives the ratio of actual to predicted decrease,
When the predicted decrease is positive, a ratio near one means that the quadratic approximation predicts the actual decrease closely. A negative ratio means that the trial raises the objective function. After a rejection, the current point and its derivatives still define the model for the smaller radius. The example loads the result constructor, the numerical derivative routines and the evaluation counter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
source("code/lib/result.R")
source("code/lib/differentiation.R")
source("code/lib/line_search.R")
trust_region <- function(fn, gr = NULL, he = NULL, par, control = list()) {
allowed <- c("radius_init", "radius_max", "maxit", "f_stop", "m_stop")
stopifnot(all(names(control) %in% allowed))
tiny <- sqrt(.Machine$double.eps)
settings <- modifyList(list(radius_init = 1, radius_max = 100, maxit = 100L, f_stop = tiny,
m_stop = tiny), control)
ev <- count_evaluations(fn, gr, he)
r <- settings$radius_init
theta <- par
f_theta <- ev$fn(theta)
stopifnot(is.finite(f_theta))
accept <- TRUE
stop_now <- FALSE
history <- list()
model_at <- function(x) {
B <- ev$he(x); g <- ev$gr(x)
eig <- eigen(B, symmetric = TRUE)
list(B = B, g = g, eig = eig, g_rot = as.numeric(t(eig$vectors) %*% g))
}
for (trial in seq_len(settings$maxit)) {
# Reuse the current derivatives after a rejected trial.
if (accept) { model <- model_at(theta); f <- f_theta }
sub <- trust_subproblem(model$eig, model$g_rot, r)
p_try <- sub$step
type <- sub$type
# This is the model change, with a negative sign for a predicted decrease.
pred_change <- sum(p_try * (model$g + as.numeric(model$B %*% p_try) / 2))
theta_try <- theta + p_try
f_try <- ev$fn(theta_try)
For a finite trial, the routine checks the magnitudes of both changes before deciding by the ratio. If either is below $\sqrt{\epsilon}$ at the default tolerances, small_change ends the fit. Only a strictly lower function value moves the point on that trial. Positive infinity gives $\rho=-\infty$. A missing value or negative infinity raises an error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if (is.na(f_try) ||
f_try == -Inf) stop("Invalid objective function value in minimization.")
actual <- f_try - f
rho <- if (is.finite(f_try)) actual / pred_change else -Inf
stop_now <- is.finite(f_try) &&
(abs(actual) < settings$f_stop || abs(pred_change) < settings$m_stop)
radius_before <- r
# At a small change, updated records whether this trial moved the parameters.
move <- if (stop_now) f_try < f else rho >= 1 / 4
if (move) {
theta <- theta_try
f_theta <- f_try
}
if (!stop_now) accept <- move else if (move) accept <- TRUE
if (!stop_now && !move) r <- r / 4
if (!stop_now && move && rho > 3 / 4 && type != "Newton") r <- min(2 * r, settings$radius_max)
On a nonterminal trial, a ratio below $1/4$ rejects the step and quarters the radius. Otherwise the step is accepted. A ratio above $3/4$ doubles the radius up to its maximum when the step is not of type Newton. For Rosenbrock, the initial radius is 1, the maximum radius is 100 and the limit is 100 trials. Each history entry records the proposed Euclidean step length in step_norm and this trial’s decision in updated. At termination, accepted can still describe the previous trial.
1
2
3
4
5
6
7
8
9
10
11
12
history[[length(history) + 1L]] <- list(iteration = trial, par = theta,
value = f_theta,
trial_value = f_try, ratio = rho, radius = radius_before, step_type = type,
accepted = accept, updated = if (stop_now) f_try < f else accept,
step_norm = sqrt(sum(p_try^2)))
if (stop_now) break
}
# Count the gradient at the returned parameters.
gradient <- ev$gr(theta)
new_result(theta, f_theta, gradient, stop_now,
if (stop_now) "small_change" else "iteration_limit", trial, ev$counts(), history)
}
Starting the quadratic at $(2,2)$ with radius 4 allows a full Newton step. For comparison, use the analytic derivatives of Rosenbrock’s function from $(-1.2,1)$.
1
2
3
4
5
6
7
8
9
10
11
rosenbrock <- function(x) 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2
rosenbrock_gr <- function(x) c(-400 * x[1] * (x[2] - x[1]^2) + 2 * (x[1] - 1),
200 * (x[2] - x[1]^2))
rosenbrock_he <- function(x) matrix(c(1200 * x[1]^2 - 400 * x[2] + 2,
-400 * x[1], -400 * x[1], 200), 2)
rosen_start <- c(-1.2, 1)
tr_quad <- trust_region(quadratic, quadratic_gr, quadratic_he, quad_start,
list(radius_init = 4, radius_max = 100))
tr_rosen <- trust_region(rosenbrock, rosenbrock_gr, rosenbrock_he, rosen_start,
list(radius_init=1,radius_max=100))
print(tr_quad[c("par", "value", "iterations")])
1
2
3
4
5
6
7
8
$par
[1] 0 0
$value
[1] 0
$iterations
[1] 2
The quadratic reached the origin on its first step. The next block loads the library version of the function just developed and repeats this quadratic fit to inspect its final history entry, which accounts for the second reported iteration. The previously computed tr_rosen remains available for the following comparison.
1
2
3
4
5
6
7
8
9
source("code/lib/result.R")
source("code/lib/line_search.R")
source("code/lib/trust_region.R")
quadratic <- function(x) sum(c(1, 100) * x^2) / 2
quadratic_gr <- function(x) c(1, 100) * x
quadratic_he <- function(x) diag(c(1, 100))
trial <- trust_region(quadratic, quadratic_gr, quadratic_he, c(2, 2), list(radius_init = 4))
last <- tail(trial$history, 1L)[[1L]]
print(last[c("value", "trial_value", "step_norm", "accepted", "updated")])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$value
[1] 0
$trial_value
[1] 0
$step_norm
[1] 0
$accepted
[1] TRUE
$updated
[1] FALSE
Both function values are zero. The proposed displacement has length zero, accepted is true from the preceding step, and updated is false. Rosenbrock’s valley requires repeated changes of radius.
1
print(tr_rosen[c("par", "value", "reason", "iterations", "evaluations")])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$par
[1] 1 1
$value
[1] 3.790157e-22
$reason
[1] "small_change"
$iterations
[1] 27
$evaluations
objective gradient hessian
28 24 23
Both coordinates round to one after 27 trials. The 28 function evaluations include the start. The 24 gradient evaluations include the returned gradient, and the Hessian was evaluated 23 times. Because the stopping test measures changes, the final gradient and Hessian bear on whether the endpoint is near a local minimum. In tr_rosen$gradient, the largest absolute component is about $3\times10^{-10}$. Substituting tr_rosen$par into rosenbrock_he() gives a first diagonal entry near 802 and a determinant near 400, both positive. The first six records explain why the radius did not grow on every successful trial.
1
2
3
print(do.call(rbind, lapply(head(tr_rosen$history, 6),
function(row) data.frame(radius = row$radius,
ratio = row$ratio, accepted = row$accepted, type = row$step_type))))
1
2
3
4
5
6
7
radius ratio accepted type
1 1.00 1.0027677 TRUE Newton
2 1.00 -0.4297488 FALSE easy-easy
3 0.25 1.0140899 TRUE easy-easy
4 0.50 0.8462499 TRUE easy-easy
5 1.00 1.2809548 TRUE Newton
6 1.00 1.3585029 TRUE Newton
The first Newton step gave a ratio of 1.0028. On the second trial, Rosenbrock’s function rose from about 4.73 to 5.39 despite the predicted decrease. This accounts for the negative ratio of $-0.4297$. The point remained fixed and the radius fell from 1 to 0.25. The next two boundary steps gave ratios of 1.014 and 0.846, increasing the radius first to 0.5 and then to 1.
1
print(table(vapply(tr_rosen$history, function(row) row$accepted, logical(1))))
1
2
3
FALSE TRUE
4 23
Of the 27 recorded acceptance flags, 23 were true and four were false.
Double dogleg steps with bounds
The preceding solver uses an eigendecomposition to minimize each quadratic model over the ball. The double-dogleg method builds a path of candidate steps from a positive definite model, avoiding that eigendecomposition. It updates the Hessian approximation from changes in the gradient. The supplied function dogleg_minimize() stores the positive definite BFGS approximation $B$ to the Hessian through its Cholesky factor. At unit scales, its double dogleg path starts along $-g$. Minimizing $q(-ag)$ over $a$ places the first corner at $-g(g^\top g)/(g^\top Bg)$ for nonzero $g$. From there the path joins a shortened quasi-Newton step and then the full step $-B^{-1}g$. Starting with radius 1, the method takes the full step if it fits or follows the path to the radius.
At a bound, a coordinate remains fixed if its negative gradient component points outward. A trial displacement that crosses a bound is cut back to its first intersection. The feasible step predicts a reduction of $-g^\top d-d^\top Bd/2$. The predicted reduction is compared with the measured reduction $f(x)-f(x+d)$ to assess the trial and set the next radius.
The function dogleg_minimize() called below exchanges values with the translated iteration until the iteration reports a stop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
dogleg_minimize <- function(start, objective, gradient = NULL, scale = 1, control = list(),
lower = -Inf, upper = Inf) {
n <- length(start)
init <- dg_defaults(n)
P <- new.env()
P$iw <- init$iw; P$v <- init$v
integer_slots <- setNames(17:19, c("max_evals", "max_iter", "trace"))
real_slots <- setNames(c(31:38, 42L), c("abs_tol", "rel_tol", "x_tol", "false_tol", "step_lo", "step_hi",
"sing_tol", "scale_init", "f_rel_error"))
for (nm in names(control)) {
key <- match.arg(nm, c(names(integer_slots), names(real_slots)))
if (key %in% names(integer_slots)) P$iw[integer_slots[[key]]] <- as.integer(control[[nm]]) else P$v[real_slots[[key]]] <- as.double(control[[nm]])
}
P$x <- as.double(start); P$d <- rep_len(as.double(scale), n)
bounded <- any(lower != -Inf) || any(upper != Inf)
if (bounded) {
if (is.null(gradient)) stop("Bounds are handled here only with a gradient")
b <- rbind(rep_len(as.double(lower), n), rep_len(as.double(upper), n))
}
fx <- Inf; g <- NULL
calls <- c(objective = 0L, gradient = 0L)
repeat {
if (bounded) dg_iterate_bounded(P, fx, g, b) else
if (is.null(gradient)) fx <- dg_iterate_fd(P, fx) else dg_iterate(P, fx, g)
if (P$iw[1L] == 2L && !is.null(gradient)) {
g <- as.double(gradient(P$x)); calls[2] <- calls[2] + 1L
if (anyNA(g)) stop("NA/NaN gradient evaluation")
} else {
fx <- objective(P$x); calls[1] <- calls[1] + 1L
if (is.nan(fx)) fx <- Inf
}
if (P$iw[1L] >= 3L) break
}
code <- P$iw[1L]
list(par = P$x, objective = P$v[V_F], convergence = if (code %in% 3:6) 0L else 1L,
iterations = P$iw[I_ITER], evaluations = c(`function` = P$iw[I_F_CALLS],
gradient = P$iw[I_G_CALLS]), message = dg_message(code), calls = calls)
}
The translated program stores its settings in an integer array iw and a real array v, which dg_defaults() fills with the defaults for $n$ coordinates; the names allowed in control select entries of these arrays. The vector d contains the coordinate scales. Bounds require a gradient function. In each pass of the loop, dg_iterate(), dg_iterate_fd() (gradient by finite differences) or dg_iterate_bounded() advances the iteration and sets iw[1] to the next request: 2 asks for the gradient at P$x, a smaller value for the objective, and a value of 3 or more ends the fit. Codes 3 to 6 are the convergence codes of the translated program, so they give convergence = 0; dg_message() turns the code into the message, and calls counts the evaluations made here.
The bounded fit requires a gradient function. Here the Rosenbrock gradient is available analytically. Without bounds, the method can use finite differences. The logistic fit minimizes the grouped binomial negative log likelihood for successes out of ten trials at each of three covariate values.
1
2
3
4
5
6
7
8
9
10
11
source("code/lib/dogleg.R")
rosenbrock <- function(x) 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2
rosenbrock_gr <- function(x) c(-400 * x[1] * (x[2] - x[1]^2) + 2 * (x[1] - 1),
200 * (x[2] - x[1]^2))
rosen_start <- c(-1.2, 1)
source("code/lib/stability.R")
source("code/lib/logit.R")
source("code/lib/glm.R")
LOGIT3 <- read.csv("data/source/LOGIT3.csv")
logit_model <- make_glm(cbind(intercept = 1, x = LOGIT3$x),
LOGIT3$successes, "binomial", LOGIT3$trials)
In the loaded implementation, dg_double_dogleg_step() follows the path described above, and dg_assess_step() compares predicted and measured reduction.
The last fit starts the intercept and slope at zero. Its two coefficient estimates appear in the same columns as the two coordinates in the Rosenbrock fits. The messages in the following comparison distinguish two stopping tests: X-convergence measures a scaled relative displacement of the parameters, while relative function convergence compares the predicted decrease with a tolerance relative to the function value and also checks the actual decrease. Both stopping criteria can be satisfied at the same point.
1
2
3
4
5
6
7
8
9
10
pt_rosen <- dogleg_minimize(rosen_start, rosenbrock, rosenbrock_gr)
pt_rosen_fd <- dogleg_minimize(rosen_start, rosenbrock)
pt_rosen_box <- dogleg_minimize(rosen_start, rosenbrock, rosenbrock_gr, lower = c(-2, -2),
upper = c(0.5, 2))
pt_logit <- dogleg_minimize(c(0, 0), logit_model$fn, logit_model$gr)
print(do.call(rbind, lapply(list(gradient = pt_rosen, differences = pt_rosen_fd,
`x1 <= 0.5` = pt_rosen_box, logit = pt_logit),
function(f) data.frame(x1 = f$par[1], x2 = f$par[2], function_value = f$objective,
iterations = f$iterations, function_evaluations = unname(f$evaluations[1]),
gradient_evaluations = unname(f$evaluations[2]), message = f$message))), digits = 8)
1
2
3
4
5
6
7
8
9
10
x1 x2 function_value iterations function_evaluations gradient_evaluations
gradient 1.0 1.0000000 4.2919664e-22 35 43 36
differences 1.0 1.0000000 1.2286957e-20 35 45 74
x1 <= 0.5 0.5 0.2500000 2.5000000e-01 19 23 19
logit 0.0 1.3862944 3.7967662e+00 6 7 7
message
gradient X-convergence (3)
differences X-convergence (3)
x1 <= 0.5 both X-convergence and relative convergence (5)
logit relative convergence (4)
With the gradient, dogleg_minimize() reached $(1,1)$ to the displayed precision at $4.29\times10^{-22}$ in 35 iterations, using 43 function and 36 gradient evaluations. With differences, it reached $1.23\times10^{-20}$ in 35 iterations. Here 45 counts ordinary function evaluations and 74 counts additional function requests for differences. Including the final evaluation made by dogleg_minimize() gives 120 function calls. The box fit reached $(0.5,0.25)$ in 19 iterations. The logistic slope reached 1.3862944 in six iterations. The four messages identify stopping tests 3, 3, 5 and 4. The convergence field summarizes these messages for the two analytic Rosenbrock fits.
1
print(pt_rosen[c("par", "objective", "convergence", "iterations", "evaluations")])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$par
[1] 1 1
$objective
[1] 4.291966e-22
$convergence
[1] 0
$iterations
[1] 35
$evaluations
function gradient
43 36
The free fit reports zero in that field. The bounded fit stopped with both change criteria satisfied.
1
print(pt_rosen_box[c("par", "objective", "convergence", "iterations", "evaluations")])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$par
[1] 0.50 0.25
$objective
[1] 0.25
$convergence
[1] 0
$iterations
[1] 19
$evaluations
function gradient
23 19
The function dogleg_minimize() returns convergence = 0 for all four fits and records the specific test in message. Code 3 identifies X-convergence with tolerance about $1.5\times10^{-8}$. Code 4 identifies relative function convergence with tolerance $10^{-10}$, and code 5 identifies both. The method assigns code 6 to absolute function convergence, 7 to singular convergence and 8 to false convergence. In the singular-convergence test, the predicted decrease is compared with sing_tol times the absolute function value at the start of the current iteration, with additional step-length and actual-decrease conditions; the test can also evaluate the model at the specified maximum step length. It does not directly test whether the Hessian is singular. False convergence means that a very small relative displacement accompanies no decrease or too little decrease. These are PORT stopping labels. The default budgets are 150 iterations and 200 ordinary function evaluations. The supplied dogleg_minimize() and brent_root() are translated from the routines behind nlminb() and uniroot() in stats, and trust_region() is adapted from trust() of the trust package (code/NOTICE.md); these R functions provide the same methods.
3.6 Transforming variances, probabilities, covariance matrices, and ordered cutpoints
To pass regression coefficients and a covariance matrix to an optimizer, first arrange their numerical coordinates in a single vector. An intercept and slope fit naturally in a named vector, while variances occupy the diagonal of a matrix and the covariance appears twice off the diagonal. The optimizers here add a proposed step to a single vector. Its entries must therefore have the same meaning on every call to the likelihood. The example below separates two tasks: arranging coordinates for the optimizer and transforming them into model parameters. The list parameter_list illustrates the arrangement. Its first block is a vector with coefficients 0.2 and $-0.4$. The second is a one-column matrix with three entries, $\log(1.2)$, 0.3 and $\log(0.8)$. These describe a lower triangular Cholesky factor from which the covariance matrix will be constructed. Placing all five numbers in a vector settles where the optimizer can find them. The covariance transformation, developed after the packing example, constructs a positive definite matrix from the last three finite coordinates in exact arithmetic.
The function pack() forms the optimizer vector from a list of parameter blocks, and unpack() restores the blocks using a template. Run the example from the book directory.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
pack <- function(parameters) {
stopifnot(is.list(parameters), length(parameters) > 0L,
!is.null(names(parameters)), !anyNA(names(parameters)),
all(nzchar(names(parameters))),
!anyDuplicated(names(parameters)))
valid <- vapply(parameters, function(x) {
is.double(x) && length(x) > 0L && all(is.finite(x)) &&
(is.null(dim(x)) || is.matrix(x))
}, logical(1))
stopifnot(all(valid))
unlist(parameters, use.names = FALSE)
}
unpack <- function(par, template) {
expected <- pack(template)
stopifnot(is.double(par), is.null(dim(par)), all(is.finite(par)),
length(par) == length(expected))
result <- template
offset <- 0L
for (j in seq_along(template)) {
size <- length(template[[j]])
# Replace the entries while retaining the attributes of this block.
result[[j]][] <- par[offset + seq_len(size)]
offset <- offset + size
}
result
}
The function pack() visits the blocks in list order and takes each matrix one column at a time, from top to bottom. It accepts nonempty vectors or matrices of finite doubles in a list whose names are distinct and nonempty. Its result has no names. To recover the structure, unpack() starts from a template and replaces the entries of each block. If the preceding blocks contain $k$ entries altogether, a block of length $m$ receives positions $k+1$ through $k+m$. Assignment into the existing block preserves its dimensions and labels. The following template assigns names both to the coefficients and to the entries of the Cholesky factor.
1
2
3
4
5
parameter_list <- list(beta = c(intercept = 0.2, slope = -0.4),
cholesky_work = matrix(c(log(1.2), 0.3, log(0.8)), ncol = 1,
dimnames = list(c("log_L11", "L21", "log_L22"), "working")))
packed <- pack(parameter_list)
print(packed)
1
[1] 0.2000000 -0.4000000 0.1823216 0.3000000 -0.2231436
The coefficients occupy positions one and two. The next three values follow the order of the Cholesky factor entries in the column. The same ordering applies to a step or a gradient supplied to the optimizer. An exact comparison checks whether unpacking restores the structure.
1
print(identical(parameter_list, unpack(packed, parameter_list)))
1
[1] TRUE
The exact comparison includes the coefficient names, the matrix dimensions and its row and column names. Changing just the fourth coordinate tests its assignment to the template.
1
2
3
changed <- packed
changed[4] <- 0.6
print(unpack(changed, parameter_list)$cholesky_work)
1
2
3
4
working
log_L11 0.1823216
L21 0.6000000
log_L22 -0.2231436
The coefficient block has length two, so the value at position four is assigned to cholesky_work[2,1]. It changes the entry in row two, column one of the lower Cholesky factor, $L_{21}$, from 0.3 to 0.6. The row name identifies that entry when printed. Its position was determined by the offset.
Positive variances and probabilities
Each restricted block needs a map from unrestricted working coordinates onto its domain. For a strictly positive variance $v$, use a real working coordinate $u=\log v$. The inverse transformation $v=\exp(u)$ has derivative $dv/du=\exp(u)=v$. Thus a small increment $du$ produces a change of about $v\,du$ on the variance scale. Equal displacements on the log scale have the same multiplicative effect at different starting variances. A variance can approach zero as $u$ tends to $-\infty$, but zero has no finite log coordinate. If the maximum likelihood estimate is zero, the log scale can represent points approaching that boundary. The functions log_to_positive() and positive_to_log() implement the two directions of the map for positive variances.
1
2
3
4
5
6
7
8
9
10
11
log_to_positive <- function(u) {
stopifnot(is.numeric(u), all(is.finite(u)))
value <- exp(u)
if (any(!is.finite(value) | value <= 0)) stop("Unrepresentable positive transform")
value
}
positive_to_log <- function(value) {
stopifnot(is.numeric(value), all(is.finite(value)), all(value > 0))
log(value)
}
For a probability $0<p<1$, the log odds $u=\log\lbrace p/(1-p)\rbrace $ give the inverse transformation $p=e^u/(1+e^u)$, with derivative $p(1-p)$. A mixing proportion $p_j$ is the population proportion in component $j$. For $K$ positive mixing proportions that sum to one, choose the last component as baseline and let $u_j=\log(p_j/p_K)$ for $j<K$. Setting the last logit to zero gives the unnormalized values $(e^{u_1},\ldots,e^{u_{K-1}},1)$. Dividing each by their sum gives the inverse of the baseline-category logit transformation. Adding a common constant to all $K$ logits multiplies all unnormalized values by the same factor and leaves the proportions unchanged. Fixing the last logit removes that undetermined shift. The following functions implement the scalar and multiple-proportion maps in both directions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
source("code/lib/stability.R")
logit_to_prob <- function(u) {
stopifnot(is.numeric(u), all(is.finite(u)))
value <- plogis(u)
if (any(value <= 0 | value >= 1)) stop("Probability rounded to a boundary")
value
}
prob_to_logit <- function(value) {
stopifnot(is.numeric(value), all(is.finite(value)), all(value > 0 & value < 1))
qlogis(value)
}
logits_to_proportions <- function(u) {
stopifnot(is.numeric(u), is.null(dim(u)), length(u) > 0L, all(is.finite(u)))
value <- normalize_logweights(c(u, 0))
if (any(value <= 0) || any(!is.finite(value))) stop("Simplex mass underflow")
value
}
proportions_to_logits <- function(value) {
stopifnot(is.numeric(value), is.null(dim(value)), length(value) >= 2L,
all(is.finite(value)), all(value > 0), abs(sum(value) - 1) < 1e-12)
log(head(value, -1)) - log(tail(value, 1))
}
The function logits_to_proportions() passes the free logits followed by zero to normalize_logweights(), which normalizes their exponentials. The inverse function proportions_to_logits() computes each log ratio as $\log p_j-\log p_K$.
For each free coordinate $u_j$, differentiation of the numerator gives a contribution only in category $j$, while differentiation of the denominator affects every category. Writing $\delta_{ij}=1$ for $i=j$ and zero otherwise gives $\partial p_i/\partial u_j=p_i(\delta_{ij}-p_j)$. The Jacobian collects these derivatives, with one row per proportion and one column per free log ratio. Thus proportions_jacobian() has $K$ rows and $K-1$ columns. For the scalar maps, compare a variance of one half with a probability whose odds are three to one.
1
2
3
4
5
6
proportions_jacobian <- function(u) {
probability <- logits_to_proportions(u)
diag(probability)[, seq_along(u), drop = FALSE] -
tcrossprod(probability, head(probability, -1))
}
print(c(variance = log_to_positive(log(0.5)), probability = logit_to_prob(log(3))))
1
2
variance probability
0.50 0.75
Exponentiating $\log(0.5)$ recovers variance 0.5. Log odds of $\log 3$ correspond to odds of three to one, hence probability 0.75. With two free logits, the denominator includes the baseline value $e^0=1$.
1
2
mixture_u <- c(log(2), log(3))
print(logits_to_proportions(mixture_u))
1
[1] 0.3333333 0.5000000 0.1666667
The unnormalized values 2, 3 and 1 sum to 6, giving proportions $(1/3,1/2,1/6)$. Each column below describes the effect of changing one logit on all three proportions.
1
print(proportions_jacobian(mixture_u))
1
2
3
4
[,1] [,2]
[1,] 0.22222222 -0.16666667
[2,] -0.16666667 0.25000000
[3,] -0.05555556 -0.08333333
The upper-left entry is $(1/3)(1-1/3)=2/9$, about 0.2222. In that column, the decreases in the other two proportions exactly offset the increase in the first, since the sum remains one. The checks in code/checks/ch03.R verify the round trips and rejection of invalid inputs, including zero for positive_to_log() and one for prob_to_logit(). The inverse functions require valid inputs without clipping them to an endpoint.
Covariance matrices through a log-Cholesky factor
In a two-variable covariance matrix $G$, positive definiteness constrains the off-diagonal entry as well as the variances. Besides positive variances, it requires $G_{21}^2<G_{11}G_{22}$. For a $q\times q$ positive definite covariance matrix $G$, use the $q(q+1)/2$ free entries of a lower triangular Cholesky factor $L$. Take them down successive columns, exponentiating each diagonal coordinate and copying each entry below the diagonal. In the two-variable example, this log-Cholesky parameterization gives
\[L=\begin{pmatrix}e^{u_1}&0\\u_2&e^{u_3}\end{pmatrix},\qquad G=LL^\top= \begin{pmatrix} e^{2u_1}&e^{u_1}u_2\\ e^{u_1}u_2&u_2^2+e^{2u_3} \end{pmatrix}.\]Because $L$ is invertible, $z^\top Gz=\Vert L^\top z\Vert ^2>0$ for every nonzero $z$. Conversely, chol() returns the upper triangular Cholesky factor of a positive definite matrix. Transposing it recovers the unique lower triangular Cholesky factor with positive diagonal. Reading the same triangle and logging just its diagonal recovers the working vector.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
logchol_factor <- function(u) {
stopifnot(is.numeric(u), is.null(dim(u)), all(is.finite(u)))
q <- (sqrt(1 + 8 * length(u)) - 1) / 2
stopifnot(q >= 1, q == floor(q))
L <- matrix(0, q, q)
index <- which(lower.tri(L, diag = TRUE), arr.ind = TRUE)
# The lower triangle is indexed down one column at a time.
L[index] <- u
diagonal <- which(index[, 1] == index[, 2])
L[cbind(seq_len(q), seq_len(q))] <- log_to_positive(u[diagonal])
L
}
logchol_to_cov <- function(u) {
L <- logchol_factor(u)
G <- tcrossprod(L)
if (any(!is.finite(G)) || inherits(tryCatch(chol(G), error = identity), "error")) {
stop("Covariance not representable as positive definite")
}
G
}
cov_to_logchol <- function(G) {
stopifnot(is.matrix(G), nrow(G) == ncol(G), all(is.finite(G)),
max(abs(G - t(G))) <= 1e-12 * max(1, max(abs(G))))
L <- t(chol(G))
index <- which(lower.tri(L, diag = TRUE), arr.ind = TRUE)
u <- L[index]
diagonal <- which(index[, 1] == index[, 2])
# Undo the exponential only where the row and column indices agree.
u[diagonal] <- log(diag(L))
u
}
To differentiate $G$, vary one working coordinate at a time. If the coordinate is $\log L_{kk}$, the corresponding derivative $dL$ has $L_{kk}$ in position $(k,k)$. For a coordinate below the diagonal, $dL$ has one in that position. Its other entries are zero. The product rule gives $dG=dL\,L^\top+L\,dL^\top$. Taking the lower triangle of $dG$ fills one column of the Jacobian. Use the original entries of the Cholesky factor, with $L_{21}=0.3$.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
logchol_jacobian <- function(u) {
L <- logchol_factor(u)
index <- which(lower.tri(L, diag = TRUE), arr.ind = TRUE)
D <- matrix(0, length(u), length(u))
for (j in seq_along(u)) {
dL <- matrix(0, nrow(L), ncol(L))
row <- index[j, 1]
col <- index[j, 2]
# Differentiate the one Cholesky factor entry controlled by coordinate j.
dL[row, col] <- if (row == col) L[row, col] else 1
dG <- dL %*% t(L) + L %*% t(dL)
# Save the derivatives of the distinct covariance entries in column j.
D[, j] <- dG[index]
}
D
}
cov_u <- c(log(1.2), 0.3, log(0.8))
print(logchol_to_cov(cov_u))
1
2
3
[,1] [,2]
[1,] 1.44 0.36
[2,] 0.36 0.73
The first variance is $1.2^2=1.44$ and the covariance is $1.2(0.3)=0.36$. Both entries in the second row of $L$ contribute to the second variance, $0.3^2+0.8^2=0.73$. Applying the inverse to this covariance gives
1
print(cov_to_logchol(logchol_to_cov(cov_u)))
1
[1] 0.1823216 0.3000000 -0.2231436
The inverse recovers the original working coordinates, with the free entry between the two log diagonals. In the derivative matrix, the rows correspond to $(G_{11},G_{21},G_{22})$.
1
print(logchol_jacobian(cov_u))
1
2
3
4
[,1] [,2] [,3]
[1,] 2.88 0.0 0.00
[2,] 0.36 1.2 0.00
[3,] 0.00 0.6 1.28
Changing the first log diagonal produces derivatives $2L_{11}^2=2.88$ and $L_{11}L_{21}=0.36$ in the first two rows. The middle column records the effects of varying $L_{21}$ on $G_{21}$ and $G_{22}$. Those derivatives are $L_{11}=1.2$ and $2L_{21}=0.6$, respectively. The final log diagonal affects only that variance, with derivative $2L_{22}^2=1.28$. This explains why changing one packed entry can change two model parameters. Replacing 0.3 by 0.6 in the Cholesky factor would give covariance $1.2(0.6)=0.72$ and second variance $0.6^2+0.8^2=1.00$.
Ordered cutpoints
For cutpoints $c_1<\cdots<c_m$, the first cutpoint can be any real number. Encode each subsequent gap by its logarithm, $u_j=\log(c_j-c_{j-1})$ for $j\ge2$. Starting with $c_1=u_1$, accumulate the positive increments to obtain $c_i=u_1+\sum_{j=2}^i e^{u_j}$. Subtracting consecutive cutpoints and logging the differences gives the inverse used by cutpoints_to_cutpoint_coordinates().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
cutpoint_coordinates_to_cutpoints <- function(u) {
stopifnot(is.numeric(u), is.null(dim(u)), length(u) >= 1L, all(is.finite(u)))
cuts <- cumsum(c(u[1], log_to_positive(u[-1])))
if (any(!is.finite(cuts)) ||
any(diff(cuts) <= 0)) stop("Cutpoint increments not representable")
cuts
}
cutpoints_to_cutpoint_coordinates <- function(cuts) {
stopifnot(is.numeric(cuts), is.null(dim(cuts)), length(cuts) >= 1L,
all(is.finite(cuts)), all(diff(cuts) > 0))
c(cuts[1], log(diff(cuts)))
}
cuts_jacobian <- function(u) {
cuts <- cutpoint_coordinates_to_cutpoints(u)
D <- matrix(0, length(u), length(u))
# Coordinate j affects cutpoints j through the last cutpoint.
for (j in seq_along(u)) D[j:length(u), j] <- if (j == 1L) 1 else exp(u[j])
D
}
cut_u <- c(-1, log(1.5), log(0.8))
print(cutpoint_coordinates_to_cutpoints(cut_u))
1
[1] -1.0 0.5 1.3
The first cutpoint is $-1$. Adding 1.5 gives 0.5 and adding another 0.8 gives 1.3. To see which cutpoints move together, differentiate the cumulative sum.
1
print(cuts_jacobian(cut_u))
1
2
3
4
[,1] [,2] [,3]
[1,] 1 0.0 0.0
[2,] 1 1.5 0.0
[3,] 1 1.5 0.8
The first column consists of ones because an increment to $u_1$ translates every cutpoint equally. Changing $u_2$ moves both later cutpoints at rate 1.5. Changing $u_3$ moves only the last one, at rate 0.8. Ordering alone does not determine a common additive shift of the cutpoints. In a model that depends on cutpoints minus an intercept, shifting all cutpoints and that intercept together preserves every difference.
Derivatives on the working scale
An optimizer working in these coordinates needs the gradient in them as well. Let $\theta=h(u)$ collect the model parameters and let $F(\theta)$ be the function to minimize. With $J_{ij}=\partial\theta_i/\partial u_j$, a displacement $du$ gives $d\theta=J\,du$. Substitution into $dF=(\nabla_\theta F)^\top d\theta$ yields
\[\nabla_u(F\circ h)=J^\top\nabla_\theta F.\]For a bivariate normal negative log likelihood, write $g_{11},g_{21},g_{22}$ for its partial derivatives in the order $G_{11},G_{21},G_{22}$. At the Cholesky factor entries above, the middle Jacobian column gives the derivative for $L_{21}$ as $1.2g_{21}+0.6g_{22}$.
The transformation checks in code/checks/ch03.R differentiate one scalar output $h_i$ at a time with num_grad(). Its gradient forms row $i$ of $J$. For the covariance map, the expression G[lower.tri(G, diag = TRUE)][i] selects that scalar. Choosing $i=2$ checks how $G_{21}$ changes with each of the three working coordinates. The covariance and cutpoint checks use each of $(-0.3,0.2,-0.1)$ and $(0.4,-0.5,0.2)$, two finite input vectors different from the printed examples. Their covariance matrices are positive definite and their cutpoints strictly increasing in exact arithmetic. The check for mixing proportions uses the displayed logits $(\log 2,\log 3)$.
For fixed data $y$, the likelihood at working coordinates $u$ is $\mathcal L_y(h(u))$. A Jacobian determinant enters when an integral is rewritten in a new variable of integration. Here the data are fixed and the candidate model is unchanged, so substituting $h(u)$ leaves the likelihood value intact. Differentiating that same likelihood in $u$ still requires the matrix $J$.
In exact arithmetic, these maps take finite working coordinates into the stated parameter domains. In floating-point arithmetic, an exponential can overflow, a probability can round to one, or a positive increment can disappear when added to a cutpoint. The routines check the computed values and reject such failures. For strictly positive variances, probabilities strictly between zero and one, positive proportions summing to one, positive definite covariance matrices, and strictly increasing cutpoints, the inverse maps use the same coordinate order as the forward maps.
In R, nlme provides the log-Cholesky parameterization through pdLogChol(). That function orders the log diagonal entries first and then the entries above the diagonal of an upper Cholesky factor. The lower-triangle column order used here is different, so the coordinate vectors are not interchangeable.
3.7 Jacobians and standard errors on the original parameter scale
Exponentiating a fitted log variance gives a variance estimate. How does uncertainty in the fitted log variance translate into uncertainty in the variance itself? Let $u_0$ be the true parameter vector in the coordinates used for fitting, $\hat u$ its estimate, and $\theta_0=h(u_0)$ the parameter on the reporting scale. Under repeated sampling, the observations change and so does $\hat u$. The true values $u_0$ and $\theta_0$ remain fixed. If $h$ is differentiable at $u_0$ and the estimation error is small, its Jacobian $J=Dh$ gives the first-order expansion
\[h(\hat u)-h(u_0)\approx J(u_0)(\hat u-u_0).\]With $p$ working coordinates and $q$ quantities to report, row $i$ of the $q\times p$ matrix $J$ gives the partial derivatives of $h_i$ in working-coordinate order. The covariance of a linear transformation $AZ$ is $A\operatorname{Cov}(Z)A^\top$. Applying this identity to the expansion gives $J(u_0)\operatorname{Cov}(\hat u)J(u_0)^\top$ as the first-order sampling covariance of $h(\hat u)$. The multivariate delta method replaces the unknown derivative by its value at the estimate and uses an estimate of the sampling covariance of $\hat u$, denoted $\widehat V_u$. The result is the $q\times q$ matrix
\[\widehat V_\theta=J(\hat u)\widehat V_uJ(\hat u)^\top .\]For example, if two working estimates tend to increase together, the effect on a reported quantity depends on the signs of its two derivatives. The matrix multiplication accounts for that dependence. Its diagonal contains estimated sampling variances. The square root of entry $(i,i)$ is the standard error for $h_i(\hat u)$, and entry $(i,j)$ describes how two reported estimates vary together across samples.
Suppose the fitted log variance is $\hat u=\log(0.5)$ and the estimated sampling variance of this log-variance estimator is 0.04. The standard error of the log-variance estimate is $\sqrt{0.04}=0.2$. The variance estimate is $e^{\hat u}=0.5$. At this point the derivative of $e^u$ is 0.5. Multiplying that slope by 0.2 gives a standard error of approximately 0.1. The estimated standard deviation of the response is $e^{\hat u/2}=0.7071068$. Its derivative is $\tfrac12e^{u/2}$, giving a standard error of $\tfrac12(0.7071068)(0.2)\approx0.0707107$. The value 0.7071068 describes individual spread. The value 0.0707107 measures uncertainty in estimating that spread.
The function delta_cov() implements this propagation of uncertainty for quantities specified by formulas. It uses delta_jacobian() to evaluate the required derivatives at the fitted working coordinates. From the book directory, load the differentiation, packing and transformation functions used here and in the bivariate example that follows.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
source("code/lib/differentiation.R")
source("code/lib/parameters.R")
source("code/lib/transforms.R")
delta_jacobian <- function(g, mean) {
forms <- if (is.list(g)) g else list(g)
vars <- sprintf("x%d", seq_along(mean))
values <- list2env(setNames(as.list(mean), vars), parent = environment())
# Put the derivatives of one reporting formula in each row.
rows <- lapply(forms, function(form) as.numeric(attr(eval(deriv(form, vars), values), "gradient")))
do.call(rbind, rows)
}
delta_cov <- function(g, mean, cov, as_se = TRUE) {
cov <- as.matrix(cov)
n <- length(mean)
if (!all(dim(cov) == n)) stop(sprintf("Covariances should be a %d by %d matrix", n, n))
# First-order variance of g(theta): G Sigma G' with G the Jacobian at mean.
G <- delta_jacobian(g, mean)
covariance <- G %*% cov %*% t(G)
if (as_se) sqrt(diag(covariance)) else covariance
}
To evaluate the formulas, delta_jacobian() assigns the working estimates to x1, x2 and so on. For each formula, deriv() differentiates symbolically and evaluation at those estimates gives one Jacobian row. In delta_cov(), the local variable G is that Jacobian. By default, the function returns standard errors. Setting as_se = FALSE returns the estimated sampling covariance matrix.
With a single working coordinate, the variance and standard deviation formulas are evaluated separately.
1
2
3
4
5
6
7
log_variance <- log(0.5)
variance_u <- matrix(0.04)
scalar_formulas <- list(variance = ~ exp(x1), standard_deviation = ~ exp(x1 / 2))
# With one working parameter each formula is carried separately.
print(cbind(estimate = c(exp(log_variance), exp(log_variance / 2)),
standard_error = vapply(scalar_formulas, delta_cov, numeric(1), mean = log_variance,
cov = variance_u)))
1
2
3
estimate standard_error
variance 0.5000000 0.10000000
standard_deviation 0.7071068 0.07071068
The scalar results agree with the derivatives evaluated at $\log(0.5)$.
Standard errors for a bivariate normal covariance
A covariance entry can depend on more than one working coordinate, so its uncertainty also requires the covariances among the working estimates. Consider the first two columns of NORMAL3, two complete simulated responses for each of 240 independent people. For a bivariate normal model, let $\mu$ be the two means and $\Sigma$ the response covariance. Each $\mu_j$ is the population mean of response $j$, in that response’s units. Each $\Sigma_{jj}$ describes variation between people’s responses, in squared response units. The covariance $\Sigma_{12}$ describes how the two responses on the same person vary together; a positive value indicates that above-mean values of one tend to accompany above-mean values of the other. Its units are the product of the two response units.
Changing $\mu$ shifts the center of the joint distribution, while $\Sigma$ describes its dispersion and association. This response covariance differs from $\widehat V_u$, which describes variation of the parameter estimates across repeated samples. The five working coordinates are the means followed by the three log-Cholesky coordinates for $\Sigma$. With $S=\sum_i(y_i-\mu)(y_i-\mu)^\top$, the negative log likelihood is
\[n\log(2\pi)+\tfrac n2\log|\Sigma|+\tfrac12\operatorname{tr}(\Sigma^{-1}S).\]With $A=\Sigma^{-1}$, differentiating the log determinant and trace terms gives the matrix derivative $(nA-ASA)/2$. A change to the free covariance changes both symmetric off-diagonal entries, so its ordinary partial derivative adds those two contributions. Multiplication by the transposed log-Cholesky Jacobian converts the three covariance derivatives to working-coordinate derivatives. The function normal_cov_model() implements this likelihood and gradient.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
normal_cov_model <- function(Y) {
stopifnot(is.matrix(Y), ncol(Y) == 2L, all(is.finite(Y)))
n <- nrow(Y)
template <- list(mean = c(0, 0), covariance = c(0, 0, 0))
evaluate <- function(u, derivative = FALSE) {
parameters <- unpack(u, template)
G <- logchol_to_cov(parameters$covariance)
R <- chol(G)
inverse <- chol2inv(R)
# Subtract the two candidate means from the corresponding response columns.
residual <- sweep(Y, 2, parameters$mean)
cross <- crossprod(residual)
value <- n * log(2 * pi) + n * sum(log(diag(R))) + 0.5 * sum(inverse * cross)
if (!derivative) return(value)
# The free covariance changes both off-diagonal matrix entries.
matrix_gradient <- 0.5 * n * inverse - 0.5 * inverse %*% cross %*% inverse
covariance_gradient <- c(matrix_gradient[1, 1], 2 * matrix_gradient[2, 1],
matrix_gradient[2, 2])
c(-drop(inverse %*% colSums(residual)),
drop(t(logchol_jacobian(parameters$covariance)) %*% covariance_gradient))
}
list(fn = function(u) tryCatch(evaluate(u), error = function(e) Inf),
gr = function(u) tryCatch(evaluate(u, TRUE), error = function(e) rep(NA_real_, 5)),
template = template)
}
In normal_cov_model(), cross contains $S$, and chol() supplies the triangular Cholesky factor used for the log determinant. The vector covariance_gradient contains the ordinary partial derivatives with respect to $(\Sigma_{11},\Sigma_{21},\Sigma_{22})$. Its second component doubles the off-diagonal matrix derivative because the free covariance changes both symmetric entries.
The returned object contains likelihood functions with Y fixed and a template specifying how to divide the supplied vector u. The group named covariance in that template contains three working coordinates, not three entries of $\Sigma$ itself.
| Working entries | Model quantities |
|---|---|
u[1:2] | The two response means $\mu$ |
u[3], u[4], u[5] | $\log L_{11}$, $L_{21}$, $\log L_{22}$ for the lower Cholesky factor $L$ |
logchol_to_cov(parameters$covariance) | The response covariance $\Sigma=LL^\top$, stored locally as G |
At the trial means $(0,1)$, use Cholesky factor diagonal entries 1.2 and 0.8 and the entry 0.3 below the diagonal. Compare the analytic derivatives with numerical differences there.
1
2
3
4
5
cov_u <- c(log(1.2), 0.3, log(0.8))
normal_data <- readRDS("data/simulated/ch01/NORMAL3.rds")[, 1:2]
normal_model <- normal_cov_model(normal_data)
normal_start <- c(0, 1, cov_u)
print(check_grad(normal_model$fn, normal_model$gr, normal_start), digits = 4)
1
2
3
4
5
6
coordinate analytic numerical absolute_error scaled_error
1 1 -17.23 -17.23 2.894e-09 1.680e-10
2 2 63.20 63.20 6.187e-09 9.789e-11
3 3 95.88 95.88 1.693e-08 1.765e-10
4 4 -13.52 -13.52 1.072e-08 7.931e-10
5 5 -435.55 -435.55 2.003e-08 4.599e-11
For each coordinate, check_grad() computes the scaled error of Section 3.1. The largest scaled error was $7.931\times10^{-10}$. A second check passes the same trial vector through the parameter template.
1
2
print(c(original = normal_model$fn(normal_start),
round_trip = normal_model$fn(pack(unpack(normal_start, normal_model$template)))))
1
2
original round_trip
843.1533 843.1533
Both representations gave the value 843.1533 for the negative log likelihood function at the trial point. For the bivariate fit, the maximum likelihood estimates are the two sample means and $S/n$ computed after centering at those means, with $n=240$. For the same data, cov() uses $n-1=239$. Form the five fitted coordinates directly from the maximum likelihood estimates. Differencing the analytic gradient gives the observed information. Invert the full five-coordinate matrix first, then take rows and columns 3 through 5 of normal_work_cov for the covariance parameters.
1
2
3
4
5
6
7
normal_mean <- colMeans(normal_data)
normal_centered <- sweep(normal_data, 2, normal_mean)
normal_cov <- crossprod(normal_centered) / nrow(normal_data)
normal_hat <- c(normal_mean, cov_to_logchol(normal_cov))
normal_information <- num_hess(normal_model$fn, normal_hat, gr = normal_model$gr)$hessian
# Invert the information for both means and all three covariance coordinates.
normal_work_cov <- solve(normal_information)
The three formulas below report $\Sigma_{11}$, $\Sigma_{21}$ and $\Sigma_{22}$ in lower-triangle order. In the formulas, x1 is $\log L_{11}$, x2 is $L_{21}$ and x3 is $\log L_{22}$. The middle formula multiplies the two entries in the first column of $L$.
1
2
3
4
5
6
7
8
9
10
11
# The Cholesky factor L has columns (exp(x1), x2) and (0, exp(x3)), so L L' has these entries.
natural_formulas <- list(variance_1 = ~ exp(x1)^2, covariance_21 = ~ exp(x1) * x2,
variance_2 = ~ x2^2 + exp(x3)^2)
normal_D <- delta_jacobian(natural_formulas, normal_hat[3:5])
dimnames(normal_D) <- list(names(natural_formulas), c("u1", "u2", "u3"))
natural_covariance <- delta_cov(natural_formulas, normal_hat[3:5],
normal_work_cov[3:5, 3:5],
as_se = FALSE)
dimnames(natural_covariance) <- list(names(natural_formulas), names(natural_formulas))
print(cbind(estimate = normal_cov[lower.tri(normal_cov, diag = TRUE)],
standard_error = sqrt(diag(natural_covariance))), digits = 6)
1
2
3
4
estimate standard_error
variance_1 0.888965 0.0811510
covariance_21 0.266946 0.0845751
variance_2 1.850970 0.1689696
The variance estimates 0.888965 and 1.850970 have standard errors 0.081151 and 0.168970. The covariance estimate 0.266946 has standard error 0.084575. For normal maximum likelihood estimates, the plug-in large-sample formula is $\sqrt{(\hat\Sigma_{ii}\hat\Sigma_{jj}+\hat\Sigma_{ij}^2)/240}$. Substituting 0.888965, 1.850970 and 0.266946 gives 0.084575 for the off-diagonal entry. All three standard errors agree to six decimal places despite the finite-difference approximation to the observed information. The full result also describes associations among the three estimates.
1
print(natural_covariance, digits = 6)
1
2
3
4
variance_1 covariance_21 variance_2
variance_1 0.006585488 0.00197755 0.000593836
covariance_21 0.001977550 0.00715295 0.004117581
variance_2 0.000593836 0.00411758 0.028550722
For example, entry $(1,2)$ is 0.00197755. It estimates how $\hat\Sigma_{11}$ and $\hat\Sigma_{21}$ covary across samples. To see which working uncertainties contribute to a standard error, compare the full calculation with one using only the diagonal of the working covariance.
1
2
3
4
5
print(data.frame(quantity=rownames(normal_D),
estimate=normal_cov[lower.tri(normal_cov,diag=TRUE)],
normal_D,SE=sqrt(diag(natural_covariance)),SE_ignoring_cross_covariances=
sqrt(diag(normal_D %*% diag(diag(normal_work_cov[3:5,3:5])) %*% t(normal_D)))),
row.names=FALSE)
1
2
3
4
quantity estimate u1 u2 u3 SE SE_ignoring_cross_covariances
variance_1 0.8889652 1.7779303 0.0000000 0.000000 0.08115102 0.08115102
covariance_21 0.2669464 0.2669464 0.9428495 0.000000 0.08457511 0.08280116
variance_2 1.8509697 0.0000000 0.5662546 3.541617 0.16896959 0.16896959
Index the three-coordinate block locally. For the estimated covariance $e^{u_1}u_2$, the two nonzero derivatives are the covariance itself and $e^{u_1}$. Thus its row has $J_1=0.266946$, $J_2=0.942850$ and $J_3=0$. The diagonal contributions sum to approximately 0.00685603. The working covariance $\widehat V_{u,12}$, entry [3,4] of the full inverse information, is about 0.00058985. It contributes the additional term
Including it gives an estimated sampling variance of 0.00715295 and standard error 0.084575. If the two working estimates were treated as uncorrelated, the reported standard error would fall to 0.082801.
Limits of the linear approximation
The delta method linearizes each transformation at the fit. To examine the effect of the nonlinear terms omitted by that approximation, draw 50,000 triples from the fitted normal approximation in log-Cholesky coordinates. Write $R$ for the upper triangular Cholesky factor returned by chol() on the working covariance block. For a standard normal row $z$ with independent entries, the covariance of $zR$ is $R^\top R$. Adding the three fitted coordinates then sets the mean of each simulated row. The generator and seed below fix this comparison.
1
2
3
4
5
6
7
8
9
10
11
12
13
RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
set.seed(100307)
local_normals <- matrix(rnorm(50000 * 3), ncol = 3)
working_draws <- sweep(local_normals %*% chol(normal_work_cov[3:5, 3:5]),
2, normal_hat[3:5], "+")
# Columns of each lower triangular Cholesky factor are (exp(u1), u2) and (0, exp(u3)).
# Compute the three entries of L L' for all draws without 50,000 factorizations.
l11 <- exp(working_draws[,1])
l21 <- working_draws[,2]
l22 <- exp(working_draws[,3])
natural_draws <- cbind(variance_1=l11^2,covariance_21=l11*l21,variance_2=l21^2+l22^2)
print(cbind(delta_se = sqrt(diag(natural_covariance)),
transformed_sd = apply(natural_draws, 2, sd)), digits = 6)
1
2
3
4
delta_se transformed_sd
variance_1 0.0811510 0.0818875
covariance_21 0.0845751 0.0849894
variance_2 0.1689696 0.1717579
Applying the full nonlinear transformations to the draws gave standard deviations of 0.081888, 0.084989 and 0.171758, close to the three delta standard errors. These draws sample the local approximation with the observed fit fixed. A bootstrap would resample or simulate datasets and refit the model. Posterior draws would require a posterior distribution.
If a true variance is zero, its estimate cannot fluctuate symmetrically around zero. A boundary can therefore undermine a normal approximation. When the observed information is singular, its inverse is unavailable as an estimate of working covariance. The last example isolates an invalid input to the propagation formula.
1
2
3
print(withCallingHandlers(delta_cov(~ exp(x1), 0, matrix(-1)),
warning = function(w) { cat("warning:", conditionMessage(w),
"\n"); invokeRestart("muffleWarning") }))
1
2
warning: NaNs produced
[1] NaN
Here $h(0)=e^0=1$ and $h^{\prime}(0)=1$. The supplied working variance is $-1$, so the multiplication gives an estimated sampling variance of $1(-1)1=-1$. Taking its square root produced the warning and NaN. A meaningful standard error requires a valid sampling covariance on the working scale. The supplied delta_jacobian() and delta_cov() are adapted from deltamethod() of msm (code/NOTICE.md), which provides delta-method standard errors in R.
3.8 Multiple starting values and diagnosing unsuccessful optimization
A standard error describes uncertainty near a fitted solution. Would the optimizer have reached the same solution from a different starting point? Consider Himmelblau’s function, $H(x,y)=(x^2+y-11)^2+(x+y^2-7)^2$, and Rosenbrock’s function. Both take two unrestricted coordinates. In a statistical model the interpretation of a start depends on the working scale. For example, setting a log variance to zero starts the variance at one. Here the optimizer takes $x$ and $y$ directly. From the book directory, load the fitting routines and define the two functions and their derivatives.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
source("code/lib/result.R")
source("code/lib/differentiation.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/search.R")
rosenbrock <- function(x) 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2
rosenbrock_gr <- function(x) c(-400 * x[1] * (x[2] - x[1]^2) + 2 * (x[1] - 1),
200 * (x[2] - x[1]^2))
rosenbrock_he <- function(x) matrix(c(1200 * x[1]^2 - 400 * x[2] + 2,
-400 * x[1], -400 * x[1], 200), 2)
rosen_start <- c(-1.2, 1)
himmelblau <- function(x) (x[1]^2 + x[2] - 11)^2 + (x[1] + x[2]^2 - 7)^2
himmelblau_gr <- function(x) c(4*x[1]*(x[1]^2 + x[2] - 11) + 2*(x[1] + x[2]^2 - 7),
2*(x[1]^2 + x[2] - 11) + 4*x[2]*(x[1] + x[2]^2 - 7))
The comparison uses the same 29 starts for both functions. The nine ordered pairs from $\lbrace -4,0,4\rbrace ^2$ cover a regular grid, beginning with $(-4,-4)$. For the other twenty pairs, draw each coordinate uniformly on $[-5,5]$. The first twenty draws fill the first column of random_starts and the next twenty fill the second.
1
2
3
4
5
grid_starts <- as.matrix(expand.grid(x1 = c(-4, 0, 4), x2 = c(-4, 0, 4)))
RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
set.seed(100308)
random_starts <- matrix(runif(40, -5, 5), ncol = 2)
all_starts <- rbind(grid_starts, random_starts)
Each row of all_starts initiates a separate BFGS fit. The function multiple_starts() records one result row per starting point, including starts whose fits fail.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
multiple_starts <- function(start_mat, fn, gr) {
stopifnot(is.matrix(start_mat), nrow(start_mat) > 0L)
n <- ncol(start_mat)
big <- .Machine$double.xmax * 0.01
objective <- function(x) {
value <- fn(x)
if (is.complex(value) || !is.finite(value)) big else value
}
# Keep one result row for every row of starting coordinates.
rows <- lapply(seq_len(nrow(start_mat)), function(i) {
run <- tryCatch(bfgs(objective, gr, start_mat[i, ],
list(maxit = 500 * round(sqrt(n + 1)))),
error = function(e) NULL)
# A caught error leaves the endpoint and both evaluation counts missing.
if (is.null(run)) return(c(rep(NA_real_, n),
0.5 * .Machine$double.xmax, NA, NA, 9999))
c(run$par, run$value, run$evaluations[["objective"]], run$evaluations[["gradient"]],
if (run$converged) 0 else 1)
})
table <- as.data.frame(do.call(rbind, rows))
names(table) <- c(if (is.null(colnames(start_mat))) paste("p", seq_len(n), sep = "") else
colnames(start_mat), "value", "fn_count", "gr_count", "convergence")
row.names(table) <- seq_len(nrow(start_mat))
table
}
With $n$ coordinates, multiple_starts() allows $500\,\mathrm{round}(\sqrt{n+1})$ iterations per fit, or 1,000 for these functions. Its objective() wrapper replaces a complex or nonfinite function value with a penalty equal to 0.01 times the largest representable double. This lets BFGS treat that trial point as very poor.
A returned fit supplies its final coordinates, function value and counts of function and gradient evaluations. Its convergence flag alone determines the code, zero for true and one for false. To recover the stopping reason, inspect the underlying fit or rerun BFGS from that row’s start.
A start whose fit raises an error still receives its own row, with code 9999, missing coordinates and counts, and a value set to half the largest double. Since both replacements are finite, a finite number in the value column alone cannot establish that the original function was defined there.
The first two columns of himmel_runs contain the final coordinates. The row number identifies the start in all_starts.
1
2
3
himmel_runs <- multiple_starts(all_starts, himmelblau, himmelblau_gr)
rosen_runs <- multiple_starts(all_starts, rosenbrock, rosenbrock_gr)
print(himmel_runs, digits = 3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
x1 x2 value fn_count gr_count convergence
1 -3.78 -3.28 4.10e-29 30 9 0
2 -2.81 3.13 5.32e-19 32 13 0
3 3.58 -1.85 2.17e-26 31 10 0
4 -3.78 -3.28 3.19e-28 40 13 0
5 3.00 2.00 1.45e-19 29 12 0
6 3.58 -1.85 6.21e-23 31 10 0
7 -2.81 3.13 1.41e-19 26 11 0
8 -2.81 3.13 1.15e-17 38 14 0
9 3.00 2.00 8.74e-18 24 11 0
10 3.58 -1.85 2.23e-17 33 12 0
11 -3.78 -3.28 1.26e-29 37 14 0
12 -3.78 -3.28 4.10e-29 32 10 0
13 -2.81 3.13 2.78e-21 27 11 0
14 -2.81 3.13 1.01e-21 26 11 0
15 -3.78 -3.28 1.58e-29 32 10 0
16 -3.78 -3.28 2.66e-27 43 15 0
17 -2.81 3.13 5.35e-25 34 10 0
18 3.00 2.00 5.23e-25 39 17 0
19 -3.78 -3.28 1.29e-28 40 14 0
20 3.00 2.00 1.06e-21 24 11 0
21 3.58 -1.85 2.42e-23 24 11 0
22 -3.78 -3.28 1.18e-23 27 11 0
23 3.58 -1.85 1.01e-16 36 13 0
24 3.58 -1.85 9.54e-24 25 11 0
25 3.58 -1.85 9.62e-27 44 15 0
26 3.00 2.00 3.40e-26 42 15 0
27 3.58 -1.85 3.22e-26 31 10 0
28 3.00 2.00 7.80e-19 25 11 0
29 3.58 -1.85 2.14e-17 30 12 0
Starting at $(-4,-4)$ took 30 function evaluations and nine gradient evaluations and ended near $(-3.78,-3.28)$. All 29 rows have code zero. Their values range from about $1.3\times10^{-29}$ to $1.0\times10^{-16}$. All endpoints have finite coordinates and finite values of the original polynomial. For a new function, evaluate it directly at the unrounded coordinates of each candidate and check that the result is real and finite before ranking the converged fits.
To see how many distinct points the Himmelblau runs reached, select the rows by convergence code and cluster their coordinates. Complete linkage uses the largest Euclidean distance between members of the two groups being joined. Cutting at 0.001 ensures that the distance between any two endpoints in a group is at most that value.
1
2
3
4
5
6
himmel_ended <- himmel_runs[himmel_runs$convergence == 0, ]
himmel_group <- cutree(hclust(dist(himmel_ended[, 1:2])), h = 1e-3)
# Retain the first endpoint and count all runs in its group.
himmel_solutions <- do.call(rbind, lapply(split(himmel_ended, himmel_group), function(d)
data.frame(d[1, 1:2], value = d$value[1], runs = nrow(d), row.names = NULL)))
print(himmel_solutions, digits = 6)
1
2
3
4
5
x1 x2 value runs
1 -3.77931 -3.28319 4.10208e-29 8
2 -2.80512 3.13131 5.31673e-19 6
3 3.58443 -1.84813 2.17221e-26 9
4 3.00000 2.00000 1.44761e-19 6
The four groups contain eight, six, nine and six runs. Each row shows the coordinates and value of the first fit in that group. Thus the first value belongs to the run from $(-4,-4)$, even though another run attained a smaller numerical value nearby. The four points approximate simultaneous zeros of $x^2+y-11$ and $x+y^2-7$. At $(3,2)$, for instance, the residuals are $9+2-11=0$ and $3+4-7=0$. Both squares vanish at each exact solution. Zero is a global minimum because a sum of squares cannot be negative.
For Rosenbrock’s function, the stopping codes identify any runs requiring further diagnosis.
1
print(table(rosen_runs$convergence))
1
2
0
29
1
print(rosen_runs[rosen_runs$convergence != 0, ])
1
2
[1] x1 x2 value fn_count gr_count convergence
<0 rows> (or 0-length row.names)
All 29 fits met the BFGS stopping rule. The empty table leaves no unsuccessful run in this set to diagnose. Separate calculations isolate the effects of step length, direction and iteration limits.
Coordinate scales, derivative conditions, and search failure
Take $f(x)=x^2/2000$ at $x=1$ and follow $d=-0.001$. Along this line, $\phi(\alpha)=f(1-0.001\alpha)$ and $\phi^{\prime}(0)=-10^{-6}$. Thus the absolute ratio of the trial to the initial directional derivative is $\vert 1-\alpha/1000\vert $. The function inspect_steps() tests two specified lengths against Armijo sufficient decrease with $c_1=10^{-4}$ and strong Wolfe curvature with $c_2=0.9$.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
inspect_steps <- function(label, fn, gr, par, direction) {
directional_derivative0 <- sum(gr(par)*direction)
stopifnot(directional_derivative0 < 0)
do.call(rbind,lapply(c(64,128),function(alpha) {
point <- par+alpha*direction
trial <- fn(point)
# Compare slope magnitudes along the same search direction.
ratio <- abs(sum(gr(point)*direction)/directional_derivative0)
data.frame(start=label,current_value=fn(par),current_gradient=max(abs(gr(par))),
alpha=alpha,trial_value=trial,
sufficient_decrease=trial<=fn(par)+1e-4*alpha*directional_derivative0,
directional_derivative_ratio=ratio,curvature=ratio<=.9)
}))
}
# The derivative ratio is exactly |1-alpha/1000| along this descent direction.
cap_example <- inspect_steps("quadratic",function(x)x^2/2000,function(x)x/1000,1,-.001)
print(cap_example,row.names=FALSE)
1
2
3
4
5
6
start current_value current_gradient alpha trial_value sufficient_decrease directional_derivative_ratio
quadratic 5e-04 0.001 64 0.000438048 TRUE 0.936
quadratic 5e-04 0.001 128 0.000380192 TRUE 0.872
curvature
FALSE
TRUE
From 0.0005, the function falls to 0.000438048 at 64 and to 0.000380192 at 128. Both meet the decrease requirement. The derivative ratios of 0.936 and 0.872 explain why only 128 passes the curvature test. Any positive step below 100 leaves the ratio above 0.9. The Moré-Thuente search allows steps up to $10^{10}$ and uses $c_1=10^{-3}$.
The BFGS routine used for the multiple-start fits accepts steps by Armijo sufficient decrease, as in Section 3.3. Applying inspect_steps() to one of its directions would diagnose decrease and curvature separately; it would not reproduce that routine’s acceptance rule. For a failed Rosenbrock run, the trial lengths along its final BFGS direction can be inspected if the gradient is finite and the direction is downhill.
1
2
3
4
5
6
7
8
9
10
11
12
13
stops <- which(rosen_runs$convergence != 0)
rosen_diagnoses <- lapply(stops,function(i) {
run <- bfgs(rosenbrock, rosenbrock_gr, all_starts[i, ], list(maxit = 1000))
if(is.null(run$inverse_hessian) || any(!is.finite(run$gradient))) return(NULL)
# Form the trial direction from the last inverse Hessian approximation.
direction <- -drop(run$inverse_hessian%*%run$gradient)
if(sum(direction*run$gradient)>=0) return(NULL)
inspect_steps(as.character(i),rosenbrock,rosenbrock_gr,run$par,direction)
})
failed_search_diagnosis <- do.call(rbind,rosen_diagnoses)
print(rosen_runs[stops,,drop=FALSE])
if(!is.null(failed_search_diagnosis)) print(failed_search_diagnosis,
digits=6,row.names=FALSE)
1
2
[1] x1 x2 value fn_count gr_count convergence
<0 rows> (or 0-length row.names)
Here stops is empty, so the loop examined no directions.
One way to isolate a stopping reason is to impose a one-iteration limit on BFGS from $(-1.2,1)$. Another is to supply the gradient itself as the search direction on the quadratic $q(x,y)=(x^2+100y^2)/2$. The line search uses the dot product supplied by lbfgsb.R.
1
2
3
4
5
6
7
8
9
source("code/lib/lbfgsb.R")
quadratic <- function(x) 0.5 * sum(c(1, 100) * x^2)
quadratic_gr <- function(x) c(1, 100) * x
quad_start <- c(2, 2)
quad_g <- quadratic_gr(quad_start)
limited_run <- bfgs(rosenbrock, rosenbrock_gr, rosen_start, list(maxit = 1L))
invalid_direction <- line_search(quadratic, quadratic_gr, quad_start,
quadratic(quad_start), quad_g, quad_g)
print(c(limited = limited_run$reason, direction = invalid_direction$reason))
1
2
limited direction
"iteration_limit" "non_descent_direction"
The first run reports iteration_limit. In the second, $g=(2,200)$ at $(2,2)$, so $g^\top g>0$. The search returns non_descent_direction before trying a step.
The next block contains two further calculations. Changing the coordinate scale can also change the work required. Set $v=(x,10y)$ so that the same quadratic becomes $(v_1^2+v_2^2)/2$. A separate calculation shows why a small working-coordinate gradient need not identify an interior estimate. For a boundary example, suppose all ten trials are successes. The common success probability has logit $u$, and boundary_gr() differentiates the negative log likelihood with respect to $u$.
1
2
3
4
5
6
7
8
sd_quad <- steepest_descent(quadratic, quadratic_gr, quad_start)
scaled_fn <- function(v) quadratic(c(v[1], v[2] / 10))
scaled_gr <- function(v) v
sd_scaled <- steepest_descent(scaled_fn, scaled_gr, c(2, 20))
boundary_gr <- function(u) -10 * plogis(-u)
print(c(scaled_quad_iterations = sd_scaled$iterations,
original_quad_iterations = sd_quad$iterations,
boundary_gradient = boundary_gr(30)))
1
2
scaled_quad_iterations original_quad_iterations boundary_gradient
1.000000e+00 1.000000e+01 -9.357623e-13
Steepest descent took ten updates on the original quadratic and one from the equivalent start on the rescaled quadratic.
For the ten successes, the derivative at $u=30$ is already about $-9.36\times10^{-13}$. The likelihood continues to increase as the probability approaches one and the logit tends to infinity.
The Hessian eigenvalues also need to be read alongside the gradient.
1
print(eigen(rosenbrock_he(c(0, 1)), symmetric = TRUE)$values)
1
[1] 200 -398
At $(0,1)$ Rosenbrock’s Hessian has eigenvalues 200 and $-398$. Those signs would identify a saddle at a stationary point. The gradient there is $(-2,200)$, which rules out stationarity.
The frequency with which a solution appears depends on where the runs started. For Himmelblau’s function, attaining the lower bound of zero establishes global optimality for all four solutions. For mixture and factor models, recording one row per start also makes it possible to see which fits reached the same value and which stopped elsewhere. In data/derived/ch03/start-results.csv each row preserves the starting point alongside the endpoint, value, evaluation counts and code. Its max_abs_gradient gives the largest absolute gradient component at that endpoint. In R, optimx provides multiple-start optimization through multistart().
3.9 Profile likelihood intervals and root finding
How much support do the observations give a particular regression slope when the intercept is unknown? Write $\psi$ for the slope on its original coefficient scale and $\lambda$ for the intercept. For every proposed $\psi$, let $\hat\lambda(\psi)$ be the intercept that maximizes the log likelihood with that slope fixed. The profile log likelihood is
\[\ell_p(\psi)=\ell\bigl(\psi,\hat\lambda(\psi)\bigr)=\max_{\lambda}\ell(\psi,\lambda).\]The intercept is a nuisance parameter for this question. Its value can change along the curve, giving each proposed slope the best fit it can attain.
In the constructed PROFILE3 example, group $i$ supplies a count $y_i$ of successes in ten independent trials at covariate value $x_i$. The three groups are independent. The success probability $p_i$ satisfies $\log[p_i/(1-p_i)]=\lambda+\psi x_i$. Here $\lambda$ is the log odds of success at $x=0$. A one-unit increase in $x$ changes the log odds by $\psi$, multiplying the odds by $e^\psi$. A positive slope therefore associates larger $x$ with a higher success probability. The following code loads the functions from the book directory and constructs the three counts.
1
2
3
4
5
6
for (library_file in c("stability", "result", "logit", "glm", "differentiation",
"line_search", "quasi_newton", "trust_region", "dogleg", "search")) {
source(paste0("code/lib/", library_file, ".R"))
}
profile_data <- data.frame(x = 0:2, trials = rep(10, 3), successes = c(1, 4, 8))
print(profile_data)
1
2
3
4
x trials successes
1 0 10 1
2 1 10 4
3 2 10 8
With $\eta_i=\lambda+\psi x_i$, the grouped binomial log likelihood is
\[\ell(\psi,\lambda)=\sum_i\left[\log\binom{10}{y_i}+y_i\eta_i-10\log(1+e^{\eta_i})\right].\]The binomial coefficients enter the reported values of the negative log likelihood function and cancel when comparing slopes. Two slopes give exact checks before optimization. At slope zero the fitted probability is the pooled proportion $13/30$, giving intercept $\log(13/17)$. At slope $\log 6$, an intercept of $-\log 9$ gives successive odds $1/9$, $6/9$ and $36/9$. The corresponding probabilities 0.1, 0.4 and 0.8 each maximize their group’s binomial likelihood, so this pair maximizes the joint likelihood. Between these checks the intercept must adjust. Setting the partial derivative of the log likelihood with respect to the intercept to zero gives $\sum_i(y_i-10p_i)=0$. Differentiating along the fitted curve gives $0=-\sum_i w_i[\hat\lambda^{\prime}(\psi)+x_i]$, with $w_i=10p_i(1-p_i)$. Hence
\[\hat\lambda'(\psi)=-\frac{\sum_i w_i x_i}{\sum_i w_i}.\]The weights are positive and two covariate values exceed zero. Increasing the slope therefore lowers the fitted intercept.
For any fixed finite slope, the expected total count increases continuously from zero to 30 as the intercept runs from $-\infty$ to $+\infty$. Subtracting it from 13 gives the intercept component of the score vector, which falls from 13 to $-17$. Its derivative is $-\sum_i w_i<0$, so its unique zero identifies the conditional maximum.
Fitting the intercept at each fixed slope
The function make_profile() performs the conditional optimization at each specified slope and retains its result. In the R vector the intercept comes first and the slope second.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
make_profile <- function(fn, gr, fitted, index) {
nuisance <- setdiff(seq_along(fitted), index)
stopifnot(length(index) == 1L, index %in% seq_along(fitted), length(nuisance) > 0L)
evaluations <- list()
at <- function(fixed) {
expand <- function(offset) {
full <- fitted
full[index] <- fixed
# The double-dogleg method varies the offset of the intercept from its unrestricted estimate.
full[nuisance] <- fitted[nuisance] + offset
full
}
run <- dogleg_minimize(numeric(length(nuisance)), function(o) fn(expand(o)),
function(o) gr(expand(o))[nuisance], control = list(step_lo = 0.001))
# Keep the conditional fit and its stopping status together.
answer <- list(fixed = fixed, par = expand(run$par), value = run$objective,
converged = isTRUE(run$convergence == 0L) && is.finite(run$objective),
reason = run$message, run = run)
evaluations[[length(evaluations) + 1L]] <<- answer
answer
}
list(at = at, history = function() evaluations)
}
For a specified slope, expand() restores the full vector from an intercept offset. The double-dogleg method starts that offset at zero, corresponding to the unrestricted intercept estimate, and minimizes the negative log likelihood with step_lo = 0.001. The gradient passed to dogleg_minimize() selects the intercept component. For point <- profile$at(slope), the flag point$converged requires convergence code zero and a finite function value.
First obtain the unrestricted fit, starting both coefficients at zero with BFGS.
1
2
3
4
5
profile_model <- make_glm(cbind(intercept = 1, x = profile_data$x),
profile_data$successes, "binomial", profile_data$trials)
profile_fit <- bfgs(profile_model$fn, profile_model$gr, c(0, 0))
stopifnot(profile_fit$converged)
print(profile_fit$par, digits = 7)
1
[1] -2.197225 1.791760
Each estimate is within $10^{-6}$ of its exact value. The next calculation includes the unrestricted slope $\hat\psi$ among five fixed values. For each row the final column evaluates the same negative log likelihood function with the intercept fixed at its unrestricted estimate, $-2.197225$.
1
2
3
4
5
6
7
8
9
10
11
profile <- make_profile(profile_model$fn, profile_model$gr, profile_fit$par, 2)
profile_values <- do.call(rbind, lapply(c(0, 0.5, profile_fit$par[2], 2, 3),
function(slope) {
result <- profile$at(slope)
stopifnot(result$converged)
# The slice uses the unrestricted intercept for every slope.
c(slope = unname(slope), intercept = unname(result$par[1]),
profile_neg_log_likelihood = unname(result$value),
fixed_intercept_neg_log_likelihood = profile_model$fn(c(profile_fit$par[1], slope)))
}))
print(profile_values, digits = 6)
1
2
3
4
5
6
slope intercept profile_neg_log_likelihood fixed_intercept_neg_log_likelihood
[1,] 0.00000 -0.268264 9.07060 20.26838
[2,] 0.50000 -0.779368 6.17809 12.48258
[3,] 1.79176 -2.197225 3.52862 3.52862
[4,] 2.00000 -2.436196 3.57818 3.70866
[5,] 3.00000 -3.593257 4.85638 8.13972
As the slope rises from zero to three, the fitted intercept falls from $-0.268264$ to $-3.593257$. The first value agrees with $\log(13/17)$. The minimum over intercepts can be no larger than the value at any particular intercept. At slope zero, allowing the intercept to move gives 9.07060, while the fixed-intercept slice gives 20.26838.
Both curves pass through the unrestricted minimum of 3.52862. Subtracting that minimum from each value of the negative log likelihood function and doubling the difference puts the two curves on a common scale.
1
2
3
4
5
print(data.frame(slope=profile_values[,"slope"],intercept=profile_values[,"intercept"],
twice_profile_loglik_drop=2*(profile_values[,"profile_neg_log_likelihood"]-
profile_fit$value),
twice_fixed_intercept_loglik_drop=2*
(profile_values[,"fixed_intercept_neg_log_likelihood"]-profile_fit$value)))
1
2
3
4
5
6
slope intercept twice_profile_loglik_drop twice_fixed_intercept_loglik_drop
1 0.00000 -0.2682640 11.08396463 33.4795286
2 0.50000 -0.7793682 5.29894427 17.9079247
3 1.79176 -2.1972246 0.00000000 0.0000000
4 2.00000 -2.4361964 0.09912949 0.3600886
5 3.00000 -3.5932572 2.65553212 9.2222171
At slope three, doubling the increase from 3.52862 to 4.85638 gives 2.65553 using the unrounded values. This is the likelihood-ratio statistic for testing that slope. It lies below the 95% cutoff of 3.84146. Fixing the intercept gives 9.22222 because the slice also prevents the intercept from compensating for the larger slope.
Interval limits by root finding
The profile values on a grid bracket each interval limit, and a root finder then locates it. For this correctly specified model with finite true intercept and slope, both coefficients can vary in a neighborhood of their true values. As the numbers of independent binomial trials increase at the fixed covariate values, with positive limiting proportions in the groups and nonsingular limiting Fisher information per trial, $2\lbrace \ell_p(\hat\psi)-\ell_p(\psi)\rbrace $ evaluated at the true slope has an approximate $\chi^2_1$ distribution in large samples. The approximate 95% confidence set retains the slopes whose statistic is at most $\chi^2_{1,0.95}$. Under this approximation, repeating the sampling and interval construction would include the true slope in about 95% of samples. Each boundary solves
\[\ell_p(\hat\psi)-\ell_p(\psi)-\tfrac12\chi^2_{1,0.95}=0.\]To locate each crossing, use Brent’s root-finding method on a bracket whose endpoints have opposite signs. First check the root finder on $x^2-2$ over $[0,2]$.
1
print(brent_root(function(x) x^2 - 2, 0, 2)[c("root", "iter", "precision")])
1
2
3
4
5
6
7
8
$root
[1] 1.414213
$iter
[1] 6
$precision
[1] 6.103516e-05
The root finder approximates $\sqrt{2}$ by 1.414213 after six iterations, with a final bracket width, stored in precision, of $6.1\times10^{-5}$.
A missing sign change produces a different result, illustrated by $x^2+1$ on $[-1,1]$.
1
print(brent_root(function(x) x^2 + 1, -1, 1)$reason)
1
[1] "no_sign_change"
Both ends give positive values.
For the profile calculation, let $s$ be the slope standard error from the inverse of the full Hessian of the negative log likelihood, computed by differencing the gradient at the unrestricted fit. Search separately on $[\hat\psi-7s,\hat\psi]$ and $[\hat\psi,\hat\psi+7s]$. These brackets are proposals: either may fail to reach the likelihood-ratio cutoff.
The function profile_ci() obtains the unrestricted fit and passes it to profile_limits() to search for the two crossings.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
profile_ci <- function(fn, gr, par, index, level = 0.95, control = list()) {
fitted <- bfgs(fn, gr, par, control)
if (!fitted$converged) return(list(converged = FALSE,
reason = "unrestricted_fit_failed", fit = fitted))
profile <- make_profile(fn, gr, fitted$par, index)
profile_limits(fitted, profile, index, level, fn, gr)
}
profile_limits <- function(fitted, profile, index, level = .95, fn, gr, sd_range = 7) {
stopifnot(length(sd_range) %in% 1:2, all(is.finite(sd_range)), all(sd_range > 0))
target <- 0.5 * qchisq(level, df = 1)
center <- fitted$par[index]
# Take the slope variance after inverting the full information matrix.
variance <- tryCatch(solve(num_hess(fn, fitted$par, gr = gr)$hessian)[index, index],
error = function(e) NA_real_)
if (!is.finite(variance) || variance <= 0) {
return(list(interval = rep(NA_real_, 2), converged = FALSE,
reason = "invalid_profile_scale",
fit = fitted, cutoff = 2 * target, standard_error = NA_real_,
range = rep(NA_real_, 2),
roots = list(), history = profile$history()))
}
sd0 <- sqrt(variance)
profile_value <- function(x) tryCatch(profile$at(x)$value, error = function(e) NA_real_)
value0 <- profile_value(center)
# The offset x is measured from the unrestricted slope estimate.
equation <- function(x) profile_value(center + x) - value0 - target
range <- c(-1, 1) * sd0 * sd_range
Here equation(x) measures the increase in the minimized negative log likelihood at a slope offset x and subtracts the half-cutoff. Each root is therefore an offset to add to the fitted slope.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
side <- function(end, interval) {
at_end <- equation(end)
if (is.na(at_end) || at_end < 0) {
reason <- if (is.na(at_end)) "nuisance_fit_failed" else "cutoff_not_reached"
return(list(root = NA_real_, converged = FALSE, reason = reason,
value_at_root = NA_real_, iter = 0L, precision = NA_real_))
}
# The root on this side is an offset from the fitted slope.
root <- brent_root(equation, interval[1], interval[2])
if (root$reason == "missing_value") root$reason <- "nuisance_fit_failed"
root
}
roots <- list(side(range[1], c(range[1], 0)), side(range[2], c(0, range[2])))
success <- all(vapply(roots, function(x) isTRUE(x$converged), logical(1)))
conditional_history <- profile$history()
conditional_converged <- vapply(conditional_history, function(x) isTRUE(x$converged), logical(1))
list(interval = center + vapply(roots, function(x) x$root, numeric(1)),
converged = success, root_converged = success, conditional_fit_converged = conditional_converged,
reason = if (success) "profile_interval" else paste(unique(vapply(
Filter(function(x) !isTRUE(x$converged), roots),
`[[`, "", "reason")), collapse = ", "), fit = fitted,
cutoff = 2 * target, standard_error = sd0, range = center + range, roots = roots,
history = profile$history())
}
An unavailable, nonfinite or nonpositive slope variance gives invalid_profile_scale. At the outer end of a bracket, a missing conditional value gives nuisance_fit_failed and a finite drop below the cutoff gives cutoff_not_reached. The returned converged flag records whether both root searches succeeded. The separate conditional_fit_converged vector records the optimizer status for each conditional fit. Because the root search still uses a finite value from a fit with a nonzero code, these two checks answer different questions. Reading point$run$convergence beside the intercept derivative helps assess a conditional fit.
The five grid fits already belong to profile, so that same object can supply the interval. The Wald interval uses a normal approximation to the slope estimate’s sampling distribution. Its limits are the estimated slope plus or minus the 97.5th percentile of the standard normal distribution times its standard error, making the interval symmetric on this coefficient scale. Here that standard error uses the inverse analytic Hessian.
1
2
3
4
5
6
profile_interval <- profile_limits(profile_fit, profile, 2, fn = profile_model$fn,
gr = profile_model$gr)
stopifnot(profile_interval$converged)
slope_se <- sqrt(solve(profile_model$he(profile_fit$par))[2, 2])
wald_interval <- profile_fit$par[2] + c(-1, 1) * qnorm(.975) * slope_se
print(rbind(profile = profile_interval$interval, Wald = wald_interval), digits = 7)
1
2
3
[,1] [,2]
profile 0.6734615 3.291659
Wald 0.5266083 3.056911
Taking the square root of entry $(2,2)$ of the inverse analytic Hessian at profile_fit$par gives the Wald standard error, 0.645497. The Wald interval extends $1.959964(0.645497)$ to either side of 1.791760, giving $[0.52661,3.05691]$. The profile reaches its cutoff about 1.12 slope units below the estimate and 1.50 above it. Its asymmetry here explains why the two intervals differ.
The root residuals check how closely the two profile limits satisfy the cutoff equation.
1
print(vapply(profile_interval$roots, function(x) x$value_at_root, numeric(1)))
1
[1] -3.776815e-05 -5.517043e-07
The profile limits are 0.6735 and 3.2917. Both are positive, so every slope within this interval associates a one-unit increase in $x$ with higher success odds. Their equation residuals are about $-3.8\times10^{-5}$ and $-5.5\times10^{-7}$. Refitting the intercept at each slope limit checks both roots.
1
2
3
4
5
6
7
8
endpoints <- do.call(rbind,lapply(profile_interval$interval,function(slope) {
endpoint <- profile$at(slope)
c(slope=slope,intercept=unname(endpoint$par[1]),
twice_loglik_drop=2*(endpoint$value-profile_fit$value),cutoff=profile_interval$cutoff,
# This column records the magnitude of the intercept derivative.
abs_intercept_derivative=abs(profile_model$gr(endpoint$par)[1]))
}))
print(endpoints)
1
2
3
slope intercept twice_loglik_drop cutoff abs_intercept_derivative.intercept
[1,] 0.6734615 -0.9618536 3.841383 3.841459 3.185123e-10
[2,] 3.2916590 -3.9270711 3.841458 3.841459 4.804757e-11
The two likelihood-ratio statistics, 3.841383 and 3.841458, are close to 3.841459. The last column reports the absolute value of the partial derivative of the negative log likelihood function with respect to the intercept, about $3.2\times10^{-10}$ and $4.8\times10^{-11}$. The grid permits the same derivative check.
1
2
3
grid_intercept_derivatives <- apply(profile_values,1,function(row)
unname(profile_model$gr(c(row["intercept"],row["slope"]))[1]))
print(grid_intercept_derivatives)
1
[1] -4.359624e-12 3.471348e-08 1.122709e-06 1.972864e-10 3.323761e-10
The largest magnitude on the grid is $1.1\times10^{-6}$. The interval object records the optimizer statuses at the end of the search.
1
2
table(vapply(profile_interval$history, function(p) as.integer(p$run$convergence),
integer(1)))
All 28 codes are zero. Five evaluations belong to the grid and 23 to the interval search, including repeated slopes. The two subsequent endpoint checks are outside that count.
Repeating the calculation in a fresh session
To repeat the calculation in a fresh session, start R anew with the book directory as the working directory and read the distributed counts.
1
2
3
4
5
6
7
8
9
for (library_file in c("stability", "result", "logit", "glm", "differentiation",
"line_search", "quasi_newton", "trust_region", "dogleg", "search")) {
source(paste0("code/lib/", library_file, ".R"))
}
data <- readRDS("data/source/ch03/PROFILE3.rds")
model <- make_glm(cbind(intercept = 1, x = data$x), data$successes,
"binomial", data$trials)
interval <- profile_ci(model$fn, model$gr, c(0, 0), index = 2)
print(interval[c("interval", "converged", "reason")])
1
2
3
4
5
6
7
8
$interval
[1] 0.6734615 3.2916590
$converged
[1] TRUE
$reason
[1] "profile_interval"
Refitting the intercept at each returned slope pairs its stopping code with the signed derivative of the negative log likelihood.
1
2
3
4
5
6
7
8
9
10
11
12
13
if (interval$converged) {
# At either endpoint the likelihood-ratio statistic must reach its cutoff.
profile <- make_profile(model$fn, model$gr, interval$fit$par, index = 2)
endpoints <- do.call(rbind, lapply(interval$interval, function(slope) {
point <- profile$at(slope)
data.frame(slope = slope, intercept = point$par[1],
likelihood_ratio_statistic = 2 * (point$value - interval$fit$value),
cutoff = interval$cutoff,
nuisance_derivative = model$gr(point$par)[1],
inner_stop_code = point$run$convergence)
}))
print(endpoints, row.names = FALSE)
}
1
2
3
4
5
6
slope intercept likelihood_ratio_statistic cutoff nuisance_derivative
0.6734615 -0.9618536 3.841383 3.841459 3.185123e-10
3.2916590 -3.9270711 3.841458 3.841459 -4.804757e-11
inner_stop_code
0
0
At both limits, convergence code zero accompanies a near-zero partial derivative of the negative log likelihood with respect to the intercept. The fitted intercepts therefore nearly satisfy the conditional likelihood equation where the likelihood-ratio statistic reaches its cutoff.
A shorter search may locate only one crossing. Report the limit found on that side and leave the other limit missing. The unexamined slopes beyond the bracket could still contain a crossing. In R, TMB provides profile likelihood limits through tmbroot().
3.10 Comparing solutions, tolerances, and evaluation counts in nonlinear regression
Two optimizers can stop at slightly different coefficients. How much difference does that make to the fitted likelihood? In LOGIT3 both fits use the same grouped counts, so their score vectors are directly comparable. Run the example from the book directory. BFGS starts both logistic coefficients at zero. The rows marked Newton identify the comparison for these data. The estimates from the reference fit are in reference_estimate, in the order of the two design columns.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/logit.R")
source("code/lib/glm.R")
source("code/lib/differentiation.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
logit_data <- read.csv("data/source/LOGIT3.csv")
logit_model <- make_glm(cbind(intercept = 1, x = logit_data$x), logit_data$successes,
"binomial", logit_data$trials)
bfgs_logit <- bfgs(logit_model$fn, logit_model$gr, c(0, 0))
glm_book <- bfgs_logit
recorded <- read.csv("data/derived/ch02/coefficients.csv",stringsAsFactors=FALSE)
# Select the rows that carry the reference intercept and slope for these counts.
recorded <- subset(recorded,dataset=="LOGIT3" & method=="Newton")
stopifnot(identical(recorded$term,colnames(logit_model$X)),nrow(recorded)==2L)
reference_beta <- recorded$reference_estimate
print(c(max_coefficient_difference=max(abs(glm_book$par-reference_beta)),
log_likelihood_difference=abs(-glm_book$value-recorded$reference_loglik[1]),
book_max_abs_score_component=max(abs(logit_model$gr(glm_book$par))),
reference_max_abs_score_component=max(abs(logit_model$gr(reference_beta)))))
1
2
3
4
max_coefficient_difference log_likelihood_difference book_max_abs_score_component
1.641438e-08 1.776357e-15 5.275953e-08
reference_max_abs_score_component
2.335057e-10
The largest absolute coefficient difference is $1.6\times10^{-8}$, whereas the absolute difference in log likelihood is only $1.8\times10^{-15}$. The largest absolute score components are small at both points. The same comparison can assess whether parameter differences appreciably change the fit of a nonlinear mean function. The next example compares seven optimizers on one such model, using the attained likelihood, the gradient and the evaluation counts together.
Seven optimizers on a concentration curve
After a single oral dose $D$, suppose the drug enters one compartment with first-order absorption rate constant $k_a$ and leaves with first-order elimination rate constant $k_e$. With volume $V>0$ and $k_a>k_e>0$, the mean concentration at time $t\geq0$ is
\[m(t)=\frac{D k_a}{V(k_a-k_e)}\left(e^{-k_et}-e^{-k_at}\right).\]The absorption exponential decays faster, allowing the curve to rise from zero before elimination dominates. Increasing $k_a$ shortens the absorption time scale. At late times, when the absorption term is negligible, the mean is proportional to $e^{-k_et}$. Thus $k_e$ is the late rate of decline in log concentration, and a larger value gives a steeper decline. With the dose and both rate constants fixed, multiplying $V$ by a factor divides every mean concentration by that factor. The stats function SSfol() expresses this mean using clearance $k_eV$.
For one subject, model the errors in the concentration measurements as independent normal variables with mean zero and a common standard deviation $\sigma$. This $\sigma$ describes the spread of measurements around the person’s mean concentration curve at any given time, in concentration units. It does not describe variation between people or the standard error of an estimated curve parameter.
The eleven measurements for subject 1 in the observed Theoph data distributed with R give time in hours and concentration in mg/L. They are repeated measurements of one person. Each row records the same oral dose in mg/kg and body weight in kg; their product gives $D$ in mg. Thus $V$ is measured in liters, $k_e$ and $k_a$ in inverse hours, and $\sigma$ in mg/L. The R dataset documentation describes the study. Applying nonlinear regression to social-science trajectories requires a mean function suited to the response and assumptions about dependence between measurements. Here independence of the measurement errors is a model assumption.
1
2
3
theoph <- as.data.frame(datasets::Theoph[datasets::Theoph$Subject == "1", ])
dose_mg <- theoph$Dose * theoph$Wt
print(theoph[c("Wt", "Dose", "Time", "conc")])
1
2
3
4
5
6
7
8
9
10
11
12
Wt Dose Time conc
1 79.6 4.02 0.00 0.74
2 79.6 4.02 0.25 2.84
3 79.6 4.02 0.57 6.57
4 79.6 4.02 1.12 10.50
5 79.6 4.02 2.02 9.66
6 79.6 4.02 3.82 8.58
7 79.6 4.02 5.10 8.36
8 79.6 4.02 7.03 7.47
9 79.6 4.02 9.05 6.89
10 79.6 4.02 12.12 5.94
11 79.6 4.02 24.37 3.28
1
print(unique(dose_mg))
1
[1] 319.992
Multiplying 4.02 mg/kg by 79.6 kg gives one dose of 319.992 mg. The recorded concentration at time zero, 0.74 mg/L, enters the likelihood even though $m(0)=0$.
Write $a=k_a-k_e$ and use $u=(\log V,\log k_e,\log a,\log\sigma)$. Exponentiation gives positive parameters and $k_a=k_e+a$ preserves their ordering. Varying $\log k_e$ with $\log a$ fixed changes both rate constants, preserving their difference. Varying $\log a$ with $\log k_e$ fixed changes only the absorption rate constant. The derivatives below follow these working coordinates.
For observed concentrations $y_i$ at the given times, put $e_i=y_i-m(t_i)$. The negative log likelihood is
\[f(u)=n\log\sigma+\tfrac n2\log(2\pi)+\tfrac12\sum_i(e_i/\sigma)^2,\qquad n=11.\]To differentiate the mean, factor $e^{-k_et}$ out of the difference of exponentials and set $x=at$. The remaining factor $1-e^{-x}$ can be computed as -expm1(-x) even when the rates are close. For $t>0$, write the log mean as $\log D-\log V+\log k_a-k_et+\log(1-e^{-x})-\log a$. Differentiating $\log k_a$ with respect to $\log k_e$ or $\log a$ gives $k_e/k_a$ or $a/k_a$. Differentiating $\log(1-e^{-x})$ with respect to $\log a$ gives $x/(e^x-1)$. Multiplication by $m=m(t)$ now gives one row of the Jacobian of the mean with respect to the first three working coordinates,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
pk_mean <- function(u, time, dose, jacobian = FALSE) {
stopifnot(length(u) == 3L, all(is.finite(u)), all(is.finite(time)), all(time >= 0),
length(dose) %in% c(1L, length(time)), all(is.finite(dose)), all(dose > 0))
natural <- exp(u)
if (any(!is.finite(natural)) ||
any(natural <= 0)) stop("Unrepresentable kinetic parameter")
V <- natural[1]
ke <- natural[2]
gap <- natural[3]
ka <- ke + gap
if (!is.finite(ka) || ka <= ke) stop("Rate ordering is not representable")
x <- gap * time
# Factor out elimination before computing the difference of exponentials.
mean <- dose / V * ka * exp(-ke * time) * (-expm1(-x)) / gap
if (!jacobian) return(mean)
ratio <- numeric(length(x))
# The continuous limit of x/expm1(x) at zero is one.
small <- abs(x) < 1e-4
ratio[small] <- 1 - x[small] / 2 + x[small]^2 / 12 - x[small]^4 / 720
ratio[!small] <- x[!small] / expm1(x[!small])
cbind(log_V = -mean, log_ke = mean * (ke / ka - ke * time),
log_gap = mean * (gap / ka - 1 + ratio))
}
As $x$ tends to zero the ratio tends to one. The small-$x$ expansion in pk_mean() supplies this limit, so the time-zero row consists of three zeros. The default return is the vector of means. With jacobian = TRUE the function returns an eleven-by-three matrix for these data. The fourth coordinate, $\log\sigma$, affects the error distribution.
The function make_pk() uses those derivatives to construct the negative log likelihood function and its gradient. Differentiating a residual gives minus the corresponding row of $J$. The derivatives of $f$ with respect to the first three working coordinates therefore form $-J^\top e/\sigma^2$. For $\log\sigma$, the normalizing term contributes $n$ and the squared residuals contribute $-\sum_i(e_i/\sigma)^2$. The first observation contributes to this derivative with respect to $\log\sigma$ even though its mean derivatives vanish.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
make_pk <- function(time, concentration, dose) {
stopifnot(length(time) == length(concentration), all(is.finite(concentration)))
n <- length(time)
evaluate <- function(u, derivative = FALSE) {
stopifnot(length(u) == 4L)
mean <- tryCatch(pk_mean(u[1:3], time, dose), error = function(e) rep(NA_real_, n))
sigma <- exp(u[4])
if (any(!is.finite(mean)) || !is.finite(sigma) || sigma <= 0) {
return(if (derivative) rep(NA_real_, 4) else Inf)
}
# One residual per concentration measurement, including time zero.
residual <- concentration - mean
scaled <- residual / sigma
value <- n * (log(sigma) + 0.5 * log(2 * pi)) + 0.5 * sum(scaled^2)
if (!derivative) return(if (is.finite(value)) value else Inf)
# The mean depends on the first three working coordinates.
J <- pk_mean(u[1:3], time, dose, jacobian = TRUE)
c(-drop(crossprod(J, residual)) / sigma^2, n - sum(scaled^2))
}
list(fn = function(u) evaluate(u), gr = function(u) evaluate(u, TRUE),
original_scale = function(u) setNames(c(exp(u[1]), exp(u[2]),
exp(u[2]) + exp(u[3]), exp(u[4])),
c("V", "ke", "ka", "sigma")),
contributions = function(u) dnorm(concentration, pk_mean(u[1:3], time, dose),
exp(u[4]), log = TRUE))
}
The gradient code forms $J^\top e$ with crossprod(J, residual) and the squared standardized residuals with sum(scaled^2).
The object pk constructed below fixes the measurement times, observed concentrations and dose inside its returned functions. Its argument u remains the four-coordinate vector $(\log V,\log k_e,\log(k_a-k_e),\log\sigma)$. The function pk$original_scale(u) returns the parameters on their original scales, with names V, ke, ka and sigma; its third entry adds the positive rate difference to $k_e$. The function pk$contributions(u) returns one normal log density per observation, whose negative sum is pk$fn(u).
At the starting values $V=40$, $k_e=0.1$, $k_a=1$, $\sigma=1$, the volume and standard deviation are positive and the rates satisfy $k_a>k_e>0$. The third input to the logarithm is the rate difference 0.9. All four gradient components can be checked there.
1
2
3
pk <- make_pk(theoph$Time, theoph$conc, dose_mg)
pk_start <- log(c(40, 0.1, 0.9, 1))
print(check_grad(pk$fn, pk$gr, pk_start), digits = 4)
1
2
3
4
5
coordinate analytic numerical absolute_error scaled_error
log_V 1 130.15 130.15 6.013e-10 4.620e-12
log_ke 2 45.02 45.02 5.403e-10 1.200e-11
log_gap 3 -23.31 -23.31 1.099e-08 4.713e-10
4 -97.76 -97.76 1.400e-09 1.432e-11
The analytic derivatives 130.15, 45.02, $-23.31$ and $-97.76$ agree with numerical differences to scaled errors below $5\times10^{-10}$.
All seven methods start at this same vector. The functions below retain each method’s stopping reason and reported counts, and evaluate the returned points with the same likelihood and gradient functions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
source("code/lib/lbfgsb.R")
source("code/lib/simplex.R")
source("code/lib/trust_region.R")
source("code/lib/dogleg.R")
source("code/lib/bobyqa.R")
source("code/lib/nonlinear.R")
compare_solutions <- function(fits, fn, gr) {
rows <- lapply(names(fits), function(name) {
fit <- fits[[name]]
# Evaluate every returned point once with the same two functions.
value <- fn(fit$par)
gradient <- gr(fit$par)
data.frame(method = name, negative_log_likelihood = value,
max_abs_gradient_component = max(abs(gradient)),
converged = fit$converged, reason = fit$reason, iterations = fit$iterations,
nll_evaluations = unname(fit$evaluations[1]),
gradient_evaluations = unname(fit$evaluations[2]),
hessian_evaluations = unname(fit$evaluations[3]),
final_nll_checks = 1L, final_gradient_checks = 1L)
})
do.call(rbind, rows)
}
as_fit <- function(par, converged, reason, iterations, objective, gradient)
list(par = par, converged = converged, reason = reason, iterations = iterations,
evaluations = c(objective = objective, gradient = gradient, hessian = 0L))
The helper as_fit() arranges an already computed fit in the fields used by compare_solutions(). Its arguments objective and gradient are evaluation counts, stored as the first two entries of evaluations. At each returned point, compare_solutions() makes one additional call each to fn and gr. Thus even a method that used no gradient during fitting has a measured gradient at its solution.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
pk_lb <- lbfgsb(pk_start, pk$fn, pk$gr)
pk_dogleg <- dogleg_minimize(pk_start, pk$fn, pk$gr)
pk_bq <- bobyqa(pk_start, pk$fn)
pk_fits <- list(steepest = steepest_descent(pk$fn, pk$gr, pk_start),
BFGS = bfgs(pk$fn, pk$gr, pk_start), simplex = nelder_mead(pk$fn, pk_start),
trust = trust_region(pk$fn, pk$gr, par = pk_start),
`L-BFGS-B` = as_fit(pk_lb$par, pk_lb$convergence == 0L, pk_lb$message, pk_lb$iterations,
pk_lb$counts[[1]], pk_lb$counts[[2]]),
Dogleg = as_fit(pk_dogleg$par, pk_dogleg$convergence == 0L, pk_dogleg$message,
pk_dogleg$iterations,
pk_dogleg$evaluations[[1]], pk_dogleg$evaluations[[2]]),
BOBYQA = as_fit(pk_bq$par, pk_bq$code == 0L, pk_bq$message, NA_integer_, pk_bq$evaluations, 0L))
pk_comparison <- compare_solutions(pk_fits, pk$fn, pk$gr)
print(pk_comparison, digits = 6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
method negative_log_likelihood max_abs_gradient_component converged
1 steepest 10.4249 2.91438e-01 FALSE
2 BFGS 10.4244 2.10596e-04 TRUE
3 simplex 10.4244 1.99146e-02 TRUE
4 trust 10.4244 2.22126e-07 TRUE
5 L-BFGS-B 10.4244 5.16743e-04 TRUE
6 Dogleg 10.4244 8.52184e-06 TRUE
7 BOBYQA 10.4244 3.21806e-04 TRUE
reason iterations nll_evaluations gradient_evaluations
1 iteration_limit 100 1094 101
2 converged 21 58 21
3 converged 144 293 0
4 small_change 11 12 82
5 CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH 20 23 23
6 relative convergence (4) 24 34 25
7 Normal exit NA 257 0
hessian_evaluations final_nll_checks final_gradient_checks
1 0 1 1
2 0 1 1
3 0 1 1
4 9 1 1
5 0 1 1
6 0 1 1
7 0 1 1
Six methods report convergence and give 10.4244 to the printed precision. Steepest descent reaches its limit of 100 updates at 10.4249 with a largest absolute gradient component of 0.291.
Nelder-Mead reports 293 function evaluations over 144 moves. It stops when the spread of negative log likelihood values across the vertices falls within tolerance. Nearby vertices can satisfy this test on a slope. Here the largest absolute gradient component is 0.020. The trust-region fit stops on a small actual or predicted change in the negative log likelihood after eleven iterations, with largest component $2.2\times10^{-7}$.
The trust-region method’s 82 gradient evaluations include $9\times2\times4=72$ to construct nine Hessians by central differences in four coordinates. BOBYQA reports 257 function evaluations and leaves the iteration count missing. The two final-check columns are separate from the fitting counts.
Even within a fit, a returned counter can omit a call, as bfgs() does when obtaining the gradient it returns. If its gradient is obtained by finite differences, its reported function count also excludes the function calls used for those differences. The next table transforms the fitted coordinates back to volume, rate constants and residual standard deviation.
1
print(do.call(rbind, lapply(pk_fits, function(fit) pk$original_scale(fit$par))), digits = 7)
1
2
3
4
5
6
7
8
V ke ka sigma
steepest 29.39120 0.05400417 1.776091 0.6284025
BFGS 29.39342 0.05395471 1.777413 0.6242037
simplex 29.39261 0.05395735 1.777376 0.6242033
trust 29.39343 0.05395455 1.777414 0.6242092
L-BFGS-B 29.39344 0.05395459 1.777411 0.6242129
Dogleg 29.39343 0.05395455 1.777414 0.6242093
BOBYQA 29.39343 0.05395457 1.777408 0.6242101
Among the six converged fits the volume estimates range from 29.39261 to 29.39344 L. Steepest descent gives 29.39120 L and a larger residual standard deviation.
At fixed $\sigma$, only the sum of squared residuals in $f(u)$ depends on the mean parameters. A least-squares fit therefore provides a check. The gradient attribute supplies the Jacobian of the mean function to stats::nls(). A second reference, stats::optim(), uses BFGS on all four working coordinates.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
pk_reference_mean <- function(log_V, log_ke, log_gap, time, dose) {
u <- c(log_V, log_ke, log_gap)
mean <- pk_mean(u, time, dose)
attr(mean, "gradient") <- pk_mean(u, time, dose, jacobian = TRUE)
mean
}
reference_nls <- stats::nls(conc ~ pk_reference_mean(log_V, log_ke,
log_gap, Time, dose_mg),
data = theoph,
start = as.list(setNames(pk_start[1:3], c("log_V", "log_ke", "log_gap"))))
reference_sigma <- sqrt(sum(residuals(reference_nls)^2) / nrow(theoph))
reference_u <- c(coef(reference_nls), log(reference_sigma))
reference_optim <- stats::optim(pk_start, pk$fn, pk$gr, method = "BFGS")
print(rbind(book = pk$original_scale(pk_fits$BFGS$par), nls = pk$original_scale(reference_u),
optim = pk$original_scale(reference_optim$par)), digits = 7)
1
2
3
4
V ke ka sigma
book 29.39342 0.05395471 1.777413 0.6242037
nls 29.39342 0.05395461 1.777410 0.6242092
optim 29.39342 0.05395471 1.777413 0.6242037
1
2
print(c(book = pk_fits$BFGS$value, nls = pk$fn(reference_u),
optim = reference_optim$value))
1
2
book nls optim
10.42436 10.42436 10.42436
1
2
print(c(nls_converged = reference_nls$convInfo$isConv,
nls_RSS = sum(residuals(reference_nls)^2), nls_sigma_ML = reference_sigma))
1
2
nls_converged nls_RSS nls_sigma_ML
1.0000000 4.2860090 0.6242092
The maximum likelihood residual standard deviation from least squares is $\sqrt{4.286009/11}=0.6242092$. On the concentration scale, this estimates a spread of about 0.624 mg/L around the subject’s fitted mean curve. The trust-region and double-dogleg estimates agree with the least-squares estimates to four decimal places for all four parameters.
The two BFGS fits agree at the displayed precision and each reports 58 function and 21 gradient evaluations. That agreement, including the counts, checks the book’s translation of the minimizer of optim(); the least-squares fit uses Gauss-Newton iterations through nls(), with the same supplied mean function and Jacobian. It checks the likelihood solution using a different fitting criterion and iteration, while sharing those model calculations.
All three likelihood values round to 10.42436. This agreement measures the likelihood attained at the observed fits. A gradient describes the local slope there, and a global optimality claim would require information about other possible solutions.
Book and reference implementations on earlier examples
The remaining comparisons return to the optimization examples and covariance calculation earlier in this chapter. Table 3.1 compares the book and reference implementations on shared inputs. The Rosenbrock runs start at $(-1.2,1)$, with bounds $(-2,-2)$ and $(0.5,2)$ for the box-constrained fits. The coefficient difference in the table is the largest absolute coordinate difference. For example, the bounded double-dogleg comparison pairs a saved endpoint with a new fit using the same gradient and bounds.
1
2
3
4
5
6
7
8
9
rosenbrock <- function(x) 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2
rosenbrock_gr <- function(x) c(-400 * x[1] * (x[2] - x[1]^2) + 2 * (x[1] - 1),
200 * (x[2] - x[1]^2))
rosen_start <- c(-1.2, 1)
runs <- readRDS("data/derived/ch03/optimizer-runs.rds")$rosenbrock
pt_rosen_box <- runs[["Dogleg box"]]
reference_nlminb_box <- stats::nlminb(rosen_start, rosenbrock, rosenbrock_gr,
lower = c(-2, -2),
upper = c(0.5, 2))
The section script code/practice/3.10.R also compares all 29 Himmelblau runs from Section 3.8 and the transformed covariance from the bivariate normal fit in Section 3.7. The code below reads the saved results into the corresponding object names. The identity tests omit matrix names.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
himmelblau <- function(x) (x[1]^2 + x[2] - 11)^2 + (x[1] + x[2]^2 - 7)^2
himmelblau_gr <- function(x) c(4*x[1]*(x[1]^2 + x[2] - 11) + 2*(x[1] + x[2]^2 - 7),
2*(x[1]^2 + x[2] - 11) + 4*x[2]*(x[1] + x[2]^2 - 7))
all_starts <- readRDS("data/source/ch03/starts.rds")
himmel_runs <- readRDS("data/derived/ch03/multiple_starts.rds")$Himmelblau
delta <- readRDS("data/derived/ch03/delta-summary.rds")
normal_hat <- delta$working_fit
normal_work_cov <- delta$working_covariance
natural_covariance <- delta$natural_covariance
natural_formulas <- list(variance_1 = ~ exp(x1)^2, covariance_21 = ~ exp(x1) * x2,
variance_2 = ~ x2^2 + exp(x3)^2)
reference_multistart <- optimx::multistart(all_starts, himmelblau, himmelblau_gr,
method = "BFGS")
reference_delta <- msm::deltamethod(natural_formulas, normal_hat[3:5],
normal_work_cov[3:5, 3:5],
as_se = FALSE)
print(c(multistart_identical = identical(unname(as.matrix(reference_multistart)),
unname(as.matrix(himmel_runs))),
delta_identical = identical(unname(reference_delta), unname(natural_covariance))))
1
2
multistart_identical delta_identical
FALSE TRUE
The transformed covariance matrices agree exactly after removing names. The multiple-start results do not, although the numerical differences summarized in Table 3.1 are small. An exact identity test distinguishes those cases even when their printed values agree.
Table 3.1. Endpoints and reported evaluation counts for the book and reference implementations. Paired counts give function and gradient evaluations, in that order.
| Calculation and reference | Result at the endpoint | Reported counts |
|---|---|---|
Rosenbrock BFGS, stats::optim() | Function values $9.594956\times10^{-18}$ and $9.594955\times10^{-18}$ | 110/43 each |
Nelder-Mead, stats::optim() | Same point $(1.00026,1.000506)$ and value $8.825241\times10^{-8}$ | Endpoint comparison |
L-BFGS-B, stats::optim() | Coefficient difference $9.4\times10^{-13}$, zero with bounds | Equal in both cases |
Double dogleg, stats::nlminb() | Coefficient differences $1.0\times10^{-15}$ with analytic gradients and $9.7\times10^{-11}$ with differences | Equal in each comparison |
Bounded double dogleg, stats::nlminb() | Both return $(0.5,0.25)$ with value 0.25 | 23/19 and 29/22 |
BOBYQA, minqa::bobyqa() | Coefficient difference $1.2\times10^{-6}$ | 290 and 412 function evaluations |
Himmelblau, optimx::multistart() | Maximum differences $2.22\times10^{-16}$ in the second coordinate and $1.37\times10^{-26}$ in the function value | Equal at every start |
Estimated sampling covariance, msm::deltamethod() | All nine entries identical | No fit required |
Every row of Table 3.1 compares the book implementation with the implementation from which it was adapted (Section E.3). The book’s BFGS, Nelder-Mead, L-BFGS-B, double-dogleg and BOBYQA routines and its delta-method covariance are translated from code that the references run (code/NOTICE.md), so their agreement checks reproduction on these particular inputs.
Matching endpoints need not imply matching calculations along the way. The function observe_solver() records the objective and gradient calls so that two optimizer histories can be compared with first_difference().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
observe_solver <- function(solve,fn,gr=NULL) {
history <- list()
record_evaluation <- function(fun,kind) function(p,...) {
result <- fun(p,...)
history[[length(history)+1L]] <<- list(kind=kind,
par=unname(as.numeric(p)),result=unname(as.numeric(result)))
result
}
fit <- solve(record_evaluation(fn,"objective"),
if(!is.null(gr)) record_evaluation(gr,"gradient"))
list(fit=fit,history=history)
}
first_difference <- function(x,y) {
for(i in seq_len(min(length(x),length(y)))) if(!identical(x[[i]],y[[i]])) return(i)
if(length(x)!=length(y)) min(length(x),length(y))+1L else NA_integer_
}
pair03 <- list(Dogleg=list(
book=observe_solver(function(f,g)dogleg_minimize(rosen_start,f,g,
lower=c(-2,-2),upper=c(.5,2)),rosenbrock,rosenbrock_gr),
reference=observe_solver(function(f,g)nlminb(rosen_start,f,g,
lower=c(-2,-2),upper=c(.5,2)),rosenbrock,rosenbrock_gr)),
BOBYQA=list(book=observe_solver(function(f,g)bobyqa(rosen_start,f),rosenbrock),
reference=observe_solver(function(f,g)minqa::bobyqa(rosen_start,f),rosenbrock)))
Inside observe_solver(), record_evaluation() saves the arguments and return value of each call. The argument solve is a function that invokes an optimizer with these recorded objective and gradient functions. The result contains the fit and the ordered history. Comparing two histories with first_difference() gives the first unequal evaluation, or the first unmatched position if one history ends sooner. Identical histories give NA.
The recorded calls give bounded double-dogleg counts of 24/19 and 30/22, and BOBYQA counts of 292 and 414. The first unequal calls occur at positions 6 and 9, respectively. The bounded double-dogleg fit took 19 iterations in the book and 22 in the reference implementation. The traces locate the first numerical differences.
In the multiple-start comparison, start 6 is the first unequal row. Its traces first differ at call 5, and every start has the same stopping code in both implementations.
Returning to the concentration measurements, BFGS and the trust-region fit give residual standard deviations of 0.6242037 and 0.6242092. The residual standard deviations agree to four decimal places and the values of the negative log likelihood function to five. The trust-region method used more derivative evaluations and left a substantially smaller gradient at its endpoint.


