Likelihood and Newton methods
In a small constructed example, success counts in three groups rise as the covariate increases. A researcher fitting a binomial regression wants to estimate how strongly success probability is related to that covariate. The likelihood gives a way to compare proposed intercepts and slopes, but writing it down does not supply the coefficient estimates. Changes in the likelihood near a proposed value indicate how to adjust the coefficients, turning the observed counts into an estimate through successive updates. The chapter develops these updates for generalized linear models, following one small example, the three LOGIT3 groups, from the score and information through Newton and scoring updates to the safeguards needed when a full step fails.
2.1 Generalized linear models, score functions, and information matrices
Each row of LOGIT3 records the number of successes in an independent group of trials. From the book directory, read the three rows and load log1pexp(), the function for evaluating $\log(1+e^t)$ accurately at a given $t$.
1
2
3
4
5
6
source("code/lib/stability.R")
LOGIT3 <- read.csv("data/source/LOGIT3.csv")
X <- cbind(intercept = 1, x = LOGIT3$x)
y <- LOGIT3$successes
trials <- LOGIT3$trials
print(LOGIT3)
1
2
3
4
x trials successes
1 -1 10 2
2 0 10 5
3 1 10 8
At covariate value $x_i$, group $i$ has $m_i=10$ independent trials with a common success probability $p_i$. Denote the observed count by $y_i$. The covariates and trial totals are fixed. In this generalized linear model, the log odds of success are linear in the covariate. Write $\beta=(\beta_0,\beta_1)^\top$ for the coefficients and $a_i^\top=(1,x_i)$ for row $i$ of the $3\times2$ design matrix $X$. In covariate order,
\[X=\begin{pmatrix}1&-1\\1&0\\1&1\end{pmatrix},\qquad \eta=X\beta,\qquad \log\frac{p_i}{1-p_i}=\eta_i=\beta_0+\beta_1 x_i,\qquad p_i=\frac{1}{1+e^{-\eta_i}}.\]The intercept is the log odds in the middle group. A unit increase in $x_i$ adds $\beta_1$ to the log odds. The inverse link function converts each linear predictor $\eta_i$ into a probability per trial. Multiplying by $m_i$ gives the expected count on the scale of the observations.
How likely are the three recorded counts at a proposed $\beta$? Any particular ordering of the trials in group $i$ with $y_i$ successes has probability $p_i^{y_i}(1-p_i)^{m_i-y_i}$. There are $\binom{m_i}{y_i}$ such orderings, all recorded as the same count. Multiplying by that number gives the count probability, and independence makes the joint probability the product across groups. The resulting likelihood $L$ and its logarithm $\ell$ are functions of the coefficients through $p_i$.
\[\begin{aligned} L(\beta)&=\prod_{i=1}^3 \binom{m_i}{y_i}p_i^{y_i}(1-p_i)^{m_i-y_i},\\ \ell(\beta)&=\sum_{i=1}^3\left\{\log\binom{m_i}{y_i} +y_i\log p_i+(m_i-y_i)\log(1-p_i)\right\}. \end{aligned}\]Including the binomial coefficients gives the full likelihood for the observed counts. Their logarithms do not depend on $\beta$, so they drop out when $\ell$ is differentiated with respect to $\beta$. Since the logarithm increases with its argument, maximizing $\ell$ also maximizes $L$. Changing the sign reverses the ranking of coefficient vectors, so minimizing the objective function $f(\beta)=-\ell(\beta)$ gives the maximum likelihood estimate of $\beta$.
The function make_nll_logit() takes the design matrix X, success counts y, and trial totals trials. It checks these data once and returns the negative log likelihood function, whose only argument is the coefficient vector beta. Each evaluation uses those data. For the logit model, the two log probabilities in a row are $\log p_i=-\log(1+e^{-\eta_i})$ and $\log(1-p_i)=-\log(1+e^{\eta_i})$. Computing them directly avoids taking $\log 0$ when a small probability rounds to zero or its complement rounds to one.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
make_nll_logit <- function(X, y, trials) {
stopifnot(is.matrix(X), is.numeric(X), nrow(X) > 0L, ncol(X) > 0L,
all(is.finite(X)), is.numeric(y), is.null(dim(y)),
is.numeric(trials), is.null(dim(trials)),
length(y) == nrow(X), length(trials) == nrow(X),
all(is.finite(y)), all(is.finite(trials)),
all(y == floor(y)), all(trials == floor(trials)),
all(y >= 0), all(trials >= y))
# These terms depend only on the observed counts and totals.
constant <- lchoose(trials, y)
function(beta) {
stopifnot(is.numeric(beta), is.null(dim(beta)), length(beta) == ncol(X))
if (any(!is.finite(beta))) return(Inf)
eta <- drop(X %*% beta)
if (any(!is.finite(eta))) return(Inf)
log_terms <- constant - y * log1pexp(-eta) - (trials - y) * log1pexp(eta)
-sum(log_terms)
}
}
Each design row requires an integer count and trial total, with successes between zero and the total. The vector constant stores the log binomial coefficients. The matrix product gives one linear predictor value per group. A nonfinite coefficient or linear predictor value yields Inf. For finite linear predictor values, log_terms combines the two log probabilities using the actual numbers of successes and failures. Its negative sum is the value of the full negative log likelihood function at beta.
Evaluating the function at two proposed coefficient vectors shows how it ranks the group probabilities that each vector implies. At beta_zero, both coefficients are zero, so every group has odds of one. At beta_exact, the proposed intercept is zero and the proposed slope is $\log 4$. Exponentiating the three linear predictors gives odds of one quarter, one, and four. The function plogis() converts the linear predictors to probabilities.
1
2
3
4
5
fn <- make_nll_logit(X, y, trials)
beta_zero <- c(0, 0)
beta_exact <- c(0, log(4))
print(rbind(zero = plogis(drop(X %*% beta_zero)),
supplied = plogis(drop(X %*% beta_exact))))
1
2
3
[,1] [,2] [,3]
zero 0.5 0.5 0.5
supplied 0.2 0.5 0.8
The first proposal predicts five successes per group. Multiplying the second set of probabilities by ten recovers the three observed counts. The function fn() evaluates the same negative log likelihood function at both proposals.
1
print(c(zero = fn(beta_zero), supplied = fn(beta_exact)))
1
2
zero supplied
7.651661 3.796766
The value of the negative log likelihood function falls from 7.651661 to 3.796766. This comparison ranks the two proposed pairs. To choose a direction from an arbitrary pair, one needs to know how the log likelihood changes when either coefficient moves a small distance.
For group $i$, substitute the logit probabilities into its contribution $\ell_i$ to the log likelihood and collect the terms in $\eta_i$. The derivative of $\log(1+e^{\eta_i})$ is $p_i$. By the chain rule, a change in the intercept changes $\eta_i$ at rate one, and a change in the slope changes it at rate $x_i$. Hence
\[\begin{aligned} \ell_i&=\log\binom{m_i}{y_i}+y_i\eta_i-m_i\log(1+e^{\eta_i}),\\ \frac{\partial\ell_i}{\partial\eta_i}&=y_i-m_ip_i,\qquad \nabla_\beta\ell_i=a_i(y_i-m_ip_i),\\ U(\beta)&=\nabla_\beta\ell=\sum_i a_i(y_i-m_ip_i)=X^\top(y-mp). \end{aligned}\]Here $y$ collects the observed counts and $mp$ has entries $m_ip_i$. Their difference is a vector of count residuals. The score vector $U$ sums the group derivatives for each coefficient. A positive component means that a small increase in that coefficient raises the log likelihood, with the other coefficients and the data fixed. The function logit_score() writes the residual as $y_i(1-p_i)-(m_i-y_i)p_i$ so it can evaluate the two probabilities at the linear predictor and its negative.
1
2
3
4
5
6
logit_score <- function(beta, X, y, trials) {
eta <- drop(X %*% beta)
# plogis(-eta) is the failure probability 1 - p.
residual <- y * plogis(-eta) - (trials - y) * plogis(eta)
drop(crossprod(X, residual))
}
At zero, the residuals are $-3$, 0, and 3. The two partial derivatives contributed by each row are $(-3,3)$, $(0,0)$, and $(3,3)$. Their contributions to the derivative with respect to the intercept cancel. For the slope, the products of covariate and residual sum to $3+0+3=6$. Increasing the slope slightly lowers the predicted count toward two at the low end and raises it toward eight at the high end.
Differentiating a group’s contribution to the score once more gives its contribution to the matrix of second derivatives of $\ell$. Since $dp_i/d\eta_i=p_i(1-p_i)$, the residual decreases at rate $w_i=m_ip_i(1-p_i)$ as the linear predictor increases. Multiplication by the two design entries for the coefficients being differentiated gives the corresponding second derivative. With $W$ the diagonal matrix of the three weights, the observed information $J$ is
\[J(\beta)=-\nabla_\beta^2\ell(\beta) =\sum_i w_i a_i a_i^\top=X^\top W X.\]Thus a minimization routine receives the gradient $-U$ and the Hessian $J$, the matrix of second partial derivatives of the negative log likelihood function. The Hessian describes curvature: for a displacement $d$, the second derivative along that direction is $d^\top Jd$. In logit_info(), w * X multiplies each row by its weight before crossprod() multiplies on the left by the transposed design matrix. The functions gr() and he() give this gradient and Hessian for the fixed data.
1
2
3
4
5
6
7
logit_info <- function(beta, X, trials) {
eta <- drop(X %*% beta)
w <- trials * plogis(eta) * plogis(-eta)
crossprod(X, w * X)
}
gr <- function(beta) -logit_score(beta, X, y, trials)
he <- function(beta) logit_info(beta, X, trials)
At zero coefficients, each row’s contributions to the derivatives and its weight show how the residuals enter the score and the weights enter the information matrix.
1
2
3
4
5
6
7
8
# At zero, the count mean is five in each group.
# Multiply the count residual by x for the derivative with respect to slope.
mu_zero <- trials * plogis(drop(X %*% beta_zero))
residual_zero <- y - mu_zero
print(data.frame(x = LOGIT3$x, trials, successes = y, count_mean = mu_zero,
residual = residual_zero, d_loglik_d_intercept = residual_zero,
d_loglik_d_slope = LOGIT3$x * residual_zero,
weight = mu_zero * (1 - mu_zero / trials)))
1
2
3
4
x trials successes count_mean residual d_loglik_d_intercept d_loglik_d_slope weight
1 -1 10 2 5 -3 -3 3 2.5
2 0 10 5 5 0 0 0 2.5
3 1 10 8 5 3 3 3 2.5
The middle group has a zero residual, yet its ten trials contribute 2.5 to the intercept diagonal entry of the information matrix. Its zero covariate makes its contribution to the slope diagonal entry zero. The score function sums the two derivative columns.
1
print(logit_score(beta_zero, X, y, trials))
1
2
intercept x
0 6
The two sums measure sensitivity to a common shift in log odds and to a change in slope, respectively.
The observed information is the negative of the log likelihood Hessian evaluated for the recorded responses. To obtain expected or Fisher information $I(\beta)$, average this matrix over response vectors $Y$ generated at $\beta$ for the same design and trial totals. The binomial model uses its canonical link function, the logit, and has no free dispersion parameter. The weights depend only on the linear predictors and trial totals, so every possible response vector has the same $J(\beta)$ at a given $\beta$. Taking its expectation gives $I(\beta)=J(\beta)$.
For the three binomial counts at zero, each weight is 2.5. The diagonal entries sum $w_i$ for the intercept and $w_i x_i^2$ for the slope. The latter uses just the two outer groups. The off-diagonal entry is zero because their terms $w_i x_i$ have opposite signs and equal magnitudes.
1
print(he(beta_zero))
1
2
3
intercept x
intercept 7.5 0
x 0.0 5
At the proposed slope $\log 4$ and intercept zero, each expected count equals its observation. Thus each residual vanishes, as the printed score rounded to twelve decimal places shows. A coefficient vector where all components of the score vanish is a stationary point.
1
print(round(logit_score(beta_exact, X, y, trials), 12))
1
2
intercept x
0 0
The outer weights are now $10(0.2)(0.8)=1.6$ and the middle weight is still 2.5. The same sums give the information at this stationary point.
1
print(he(beta_exact))
1
2
3
intercept x
intercept 5.7 0.0
x 0.0 3.2
Both diagonal entries are positive. To establish uniqueness, consider any finite $\beta$. All three weights are positive, and the columns of $X$ are linearly independent. For any nonzero two-component vector $d$, at least one entry of $Xd$ is nonzero, so $d^\top Jd=\sum_i w_i(a_i^\top d)^2>0$. Positive curvature in every direction at every finite point makes the negative log likelihood function strictly convex. Its stationary point $(0,\log 4)$ therefore gives the unique maximum likelihood estimate. The fitted odds of success quadruple for each unit increase in the covariate. Each diagonal entry of the inverse information estimates the sampling variance of one coefficient estimate, and its square root is the standard error.
1
print(sqrt(diag(solve(he(beta_exact)))))
1
2
intercept x
0.4188539 0.5590170
These standard errors use a large-sample likelihood approximation to the sampling standard deviations. Its assumptions include a correctly specified model, a log likelihood that can be differentiated near the true coefficient vector, and nonsingular information. Every sufficiently small change of the true vector in any direction must remain within the permitted parameter values. Here both coefficients may be any real numbers, so this last condition is met at every finite vector. The approximation concerns repeated samples with increasing information; here it is applied to 30 trials. The estimated standard error is 0.4188539 for the log odds at $x=0$ and 0.5590170 for the log odds change per unit increase in $x$.
The equality of observed and expected information in this example depends on the model and parameterization. The following comparisons show where the response residual can enter observed information.
For comparison, consider independent normal responses with conditional mean $X\beta$ and covariance $vI_n$, where $X$ is a fixed design with $n$ rows and $I_n$ is the identity matrix. With an intercept column, the intercept is the mean response when all covariates are zero. Each slope gives the change in that mean per unit increase in its covariate, with the other covariates fixed. The unknown variance $v=\sigma^2$ describes variation of responses about their conditional means, in squared response units, and is common to all rows. The part of the normal log likelihood involving $\beta$ is $-\lVert y-X\beta\rVert^2/(2v)$. Differentiating gives
\[\nabla_\beta\ell=\frac{X^\top(y-X\beta)}{v},\qquad \frac{\partial}{\partial v}\nabla_\beta\ell =-\frac{X^\top(y-X\beta)}{v^2}.\]The mixed derivative can be nonzero for the observed sample. Its expectation is zero because the residual vector has mean zero at the coefficients generating the responses. The corresponding block of observed information can therefore differ from its expectation.
For independent Poisson counts, specify $\log\mu_i=\eta_i=a_i^\top\beta$, where $\mu_i$ is the expected count for observation $i$. With an intercept column, the intercept is the log expected count at zero covariate values. A unit increase in covariate $j$ multiplies the expected count by $\exp(\beta_j)$, with the other covariates fixed. The Poisson variance equals its mean. The cumulant function $b(\xi)=e^\xi$ has first and second derivatives equal to $e^\xi$. With the canonical log link function, the natural parameter $\xi_i$ equals $\eta_i$. Differentiating the log probability once with respect to $\eta_i$ gives a count residual, and differentiating again gives the negative mean. Let $\mu$ collect the means. Combining the derivatives with the design rows gives
\[\ell_i=y_i\eta_i-e^{\eta_i}-\log(y_i!),\qquad U=X^\top(y-\mu),\qquad J=X^\top\operatorname{diag}(\mu)X.\]For an exponential-family response with fixed dispersion and a general link function, the derivative of the log probability or log density with respect to the mean is the residual divided by the variance $V_i$ conditional on the design and any trial total. On the scale of the linear predictor, multiply by $\mu^{\prime}_i=d\mu_i/d\eta_i$. Write $h_i=\mu^{\prime}_i/V_i$ for this factor on the residual. The score is $X^\top u$, where
\[u_i=(y_i-\mu_i)h_i,\qquad \frac{du_i}{d\eta_i}=-\mu'_i h_i+(y_i-\mu_i)\frac{dh_i}{d\eta_i}.\]For the Poisson log and grouped binomial logit link functions, the derivative of the count mean equals the count variance, giving $h_i=1$. With a noncanonical link function, $h_i$ can change with the linear predictor. Its derivative then introduces a residual into the observed information, even though that residual has expectation zero. The stats package fits binomial and Poisson regression models.
2.2 Newton-Raphson updates from a quadratic approximation
The score indicates which way to change the coefficients, and the information indicates how quickly the score itself changes. At zero intercept and slope, increasing the slope improves the fit to the three binomial counts. How large an increase should the first update make? Let $\beta$ be the current coefficient vector, $d$ a proposed displacement, and $f(\beta)=-\ell(\beta)$ the negative log likelihood function for the fixed counts. Its gradient at $\beta$ is $g=-U(\beta)$, the negative of the score vector. Its Hessian is the observed information $H=J(\beta)$. Expand $f$ to second order about $\beta$ and write $q(d)$ for the resulting approximation.
\[f(\beta+d)\ \approx\ q(d)=f(\beta)+g^\top d+\tfrac12 d^\top H d.\]The linear term predicts the change from the current gradient alone. The quadratic term uses the curvature at $\beta$ to predict how the gradient will change. Farther from $\beta$, the true Hessian can differ from the fixed matrix in $q$.
To choose the displacement, differentiate $q$ with respect to $d$. The Hessian is symmetric, so the derivative of the quadratic term is $Hd$. The Newton direction solves
\[\nabla_d q(d)=g+Hd=0,\qquad Hd=-g,\qquad J(\beta)d=U(\beta).\]A positive definite $H$ gives positive curvature in every direction and makes this solution the unique minimizer of $q$. For a nonzero solution, $g^\top d=-d^\top H d<0$, so a sufficiently short move along $d$ decreases $f$. A unit step adds the whole vector $d$ to $\beta$. In R, solve() returns the solution of the linear system for the matrix and right-hand side supplied to it. The fitting algorithm evaluates the derivatives and decides how much of that direction to take.
For LOGIT3, evaluate $f$ with fn(), $g$ with gr(), and $H$ with he(). At the starting vector beta_zero, the diagonal entries of the information are 7.5 and 5, the off-diagonal entries are zero, and the score vector is $(0,6)^\top$. The two equations reduce to $7.5d_1=0$ for the intercept and $5d_2=6$ for the slope.
1
2
3
4
5
6
g0 <- gr(beta_zero)
H0 <- he(beta_zero)
# Solve for the changes in intercept and slope together.
d0 <- drop(solve(H0, -g0))
beta_one <- beta_zero + d0
print(rbind(current = beta_zero, direction = d0, proposed = beta_one))
1
2
3
4
intercept x
current 0 0.0
direction 0 1.2
proposed 0 1.2
The proposed slope is 1.2. The direction and proposed coefficients coincide because the start is zero. Evaluating the negative log likelihood at both points gives the decrease achieved by the full step.
1
print(c(current = fn(beta_zero), proposed = fn(beta_one)))
1
2
current proposed
7.651661 3.854367
The value of the negative log likelihood function fell from 7.651661 to 3.854367. The quadratic approximation predicted a decrease of $-g^\top d/2=3.6$ at its minimum. The actual decrease was slightly larger, and the new value still exceeds 3.796766 at the exact solution.
Further unit steps use derivatives recomputed at each new coefficient vector. The loop records iteration zero before making a move. Before each update, it tests the largest absolute component of the current gradient against $10^{-8}$. A value at or below that tolerance ends the loop, and the loop allows at most 30 updates.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
beta <- beta_zero
value <- fn(beta)
gradient <- gr(beta)
values <- data.frame(iteration = 0, intercept = beta[1], slope = beta[2],
value = value, gradient = max(abs(gradient)), step_norm = 0)
# Test the current gradient before computing another update.
for (k in 1:30) {
if (max(abs(gradient)) <= 1e-8) break
direction <- drop(solve(he(beta), -gradient))
beta <- beta + direction
value <- fn(beta)
gradient <- gr(beta)
values <- rbind(values, data.frame(iteration = k, intercept = beta[1],
slope = beta[2], value = value, gradient = max(abs(gradient)),
step_norm = max(abs(direction))))
}
rownames(values) <- NULL
print(signif(values, 7))
1
2
3
4
5
6
iteration intercept slope value gradient step_norm
1 0 0.000000e+00 0.000000 7.651661 6.000000e+00 0.000000e+00
2 1 0.000000e+00 1.200000 3.854367 6.295043e-01 1.200000e+00
3 2 -6.485228e-18 1.376932 3.796907 3.004377e-02 1.769320e-01
4 3 -6.485228e-18 1.386268 3.796766 8.371151e-05 9.336216e-03
5 4 -6.485228e-18 1.386294 3.796766 6.569443e-10 2.615944e-05
In this table, gradient is $\max_j\vert g_j\vert $ and step_norm is the largest absolute coefficient change on the move to that row. From 1.2, the slope moves to 1.376932, then 1.386268 and finally 1.386294. The successive changes shrink from about 0.177 to 0.0093 to 0.000026. Here, $f$ has continuous third derivatives near the minimum, and its Hessian at the minimum is positive definite. Close enough to the minimum, the full Newton steps converge quadratically. The distance to the solution after one more step is then bounded by a constant times the square of the current distance. After four updates, the largest absolute gradient component is about $6.6\times10^{-10}$. That row meets the tolerance.
A fit needs to report which stopping rule it met. The function new_result() records the final coefficients, the value of the objective function there and the gradient vector alongside the convergence indicator, stopping reason, iteration count, evaluation counts and iteration history. It checks that the gradient has one entry per coefficient and that the three evaluation counts are named for the objective function, gradient and Hessian.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
new_result <- function(par, value = NA_real_,
gradient = rep(NA_real_, length(par)),
converged = FALSE, reason = "not evaluated",
iterations = 0L,
evaluations = c(objective = 0L, gradient = 0L, hessian = 0L),
history = list(), ...) {
stopifnot(is.numeric(par), is.null(dim(par)), length(par) > 0L,
is.numeric(value), is.null(dim(value)), length(value) == 1L,
is.numeric(gradient), is.null(dim(gradient)),
length(gradient) == length(par),
is.logical(converged), length(converged) == 1L, !is.na(converged),
is.character(reason), length(reason) == 1L, !is.na(reason),
is.numeric(iterations), is.null(dim(iterations)), length(iterations) == 1L,
is.numeric(evaluations), is.null(dim(evaluations)),
identical(names(evaluations), c("objective", "gradient", "hessian")),
is.list(history))
The second part of the function stores these fields. A fitting method can add named quantities without overwriting the common fields.
1
2
3
4
5
6
7
8
9
10
11
# Store the gradient vector separately from the iteration history.
result <- list(par = par, value = value, gradient = gradient,
converged = converged, reason = reason, iterations = iterations,
evaluations = evaluations, history = history)
extra <- list(...)
if (length(extra)) {
stopifnot(!is.null(names(extra)), !anyNA(names(extra)), all(nzchar(names(extra))),
!anyDuplicated(c(names(result), names(extra))))
}
c(result, extra)
}
A second stopping rule uses the deviance. A saturated binomial model fits each group’s observed proportion separately. Write $\ell_{\mathrm{sat}}$ for its log likelihood. The deviance $D(\beta)=2\lbrace \ell_{\mathrm{sat}}-\ell(\beta)\rbrace $ measures the loss of fit from imposing the linear predictor. For Poisson counts, the saturated fit assigns each observation its recorded count as its mean, and the same likelihood comparison defines the deviance. The function glm_deviance() compares each observed proportion with the per-trial probability returned by the binomial inverse link function and weights each group’s term of the deviance by its trial total. Groups with zero trials contribute nothing. For a Poisson response, the inverse link function returns a positive mean count, and each observed count enters with weight one.
1
2
3
4
5
6
7
8
9
10
11
12
glm_deviance <- function(beta, X, y, trials = rep(1, length(y)), family = "binomial") {
eta <- drop(X %*% beta)
if (family == "binomial") {
f <- stats::binomial()
active <- trials > 0
# Weight each observed proportion by its number of trials.
sum(f$dev.resids(y[active] / trials[active], f$linkinv(eta[active]), trials[active]))
} else {
f <- stats::poisson()
sum(f$dev.resids(y, f$linkinv(eta), rep(1, length(y))))
}
}
Assemble newton_unit() from the following three consecutive pieces. This version takes full Newton steps and stops on the relative change in deviance; the preceding manual loop stopped on the largest absolute gradient component. It takes the objective function and its two derivatives, a starting vector par, and a deviance function supplied in control. Evaluating the starting point costs one call each to fn() and gr(). At iteration zero, the history contains that point, and no Hessian has been evaluated.
1
2
3
4
5
6
7
8
9
10
11
12
newton_unit <- function(fn, gr, he, par, control = list()) {
# Count the initial evaluations and record the starting coefficients.
settings <- modifyList(list(maxit = 25L, epsilon = 1e-8, deviance = NULL), control)
stopifnot(is.function(settings$deviance))
evaluations <- c(objective = 0L, gradient = 0L, hessian = 0L)
value <- fn(par)
gradient <- gr(par)
evaluations[1:2] <- 1L
history <- list(list(iteration = 0L, par = par, value = value,
max_abs_gradient = max(abs(gradient))))
reason <- "iteration_limit"
converged <- FALSE
Each update evaluates the current Hessian, solves for the direction, and evaluates the objective function and its gradient at the full step. The function checks whether these values are finite. If both evaluations are finite, the function records the candidate even when the value of the objective function increases.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (k in seq_len(settings$maxit)) {
if (!is.finite(value) || any(!is.finite(gradient))) {
reason <- "nonfinite_evaluation"
break
}
# Use curvature at the current coefficients for this direction.
H <- he(par)
evaluations[3] <- evaluations[3] + 1L
direction <- tryCatch(drop(solve(H, -gradient)), error = function(e) NULL)
if (is.null(direction) || any(!is.finite(direction))) {
reason <- if (is.null(direction)) "linear_solve_failed" else "nonfinite_direction"
break
}
# Evaluate the full step.
candidate <- par + direction
candidate_value <- fn(candidate)
candidate_gradient <- gr(candidate)
evaluations[1:2] <- evaluations[1:2] + 1L
if (!is.finite(candidate_value) || any(!is.finite(candidate_gradient))) {
reason <- "nonfinite_evaluation"
break
}
Compute the deviances at the old and new coefficients. With $D$ the new deviance, the relative change must satisfy
\[\frac{|D-D_{\mathrm{old}}|}{|D|+0.1}<\epsilon,\qquad \epsilon=10^{-8}.\]The denominator remains positive even at a perfect fit. Each completed update adds one history entry after the starting point. The default limit is 25 updates.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
deviance_old <- settings$deviance(par)
par <- candidate
value <- candidate_value
gradient <- candidate_gradient
deviance_new <- settings$deviance(par)
# Record the candidate before testing the change in deviance.
history[[length(history) + 1L]] <- list(iteration = length(history), par = par,
value = value, max_abs_gradient = max(abs(gradient)))
if (!is.finite(deviance_new) || !is.finite(deviance_old)) {
reason <- "nonfinite_deviance"
break
}
if (abs(deviance_new - deviance_old) / (abs(deviance_new) + 0.1) < settings$epsilon) {
converged <- TRUE
reason <- "small_deviance_change"
break
}
}
new_result(par, value, gradient, converged, reason, length(history) - 1L,
evaluations, history)
}
Use newton() as a second name for this completed full-step function. Section 2.6 will assign that name to a function with step control; newton_unit() will remain available under its own name. The function logit3_deviance() evaluates the deviance for the fixed design, counts and trial totals. Start the fit at zero.
1
2
3
4
5
newton <- newton_unit
logit3_deviance <- function(beta) glm_deviance(beta, X, y, trials)
raw_fit <- newton(fn, gr, he, beta_zero, list(deviance = logit3_deviance))
print(raw_fit[c("par", "value", "gradient", "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
$par
intercept x
-6.485228e-18 1.386294e+00
$value
[1] 3.796766
$gradient
intercept x
0 0
$converged
[1] TRUE
$reason
[1] "small_deviance_change"
$iterations
[1] 5
$evaluations
objective gradient hessian
6 6 5
Both runs follow the same path from zero. The gradient satisfied its tolerance at update four. To see why the deviance criterion took five, use the fact that $D=0$ at the exact fit. Near slope $\log 4$, twice the excess of the negative log likelihood function over its minimum is approximately the second partial derivative with respect to the slope, 3.2, times the squared error in the slope. At update three, this gives $3.2(1.386268-\log 4)^2$, or $2.2\times10^{-9}$. At update four, the deviance is effectively zero. Dividing the change from update three by about 0.1 gives $2.2\times10^{-8}$, still above the tolerance. The change from update four to five passes the test. Five updates plus the starting evaluation account for six calls each to the objective function and gradient, and five Hessian evaluations. A one-update limit stops at the first proposal.
1
2
short_fit <- newton(fn, gr, he, beta_zero, list(maxit = 1L, deviance = logit3_deviance))
print(short_fit[c("par", "converged", "reason", "iterations")])
1
2
3
4
5
6
7
8
9
10
11
12
$par
intercept x
0.0 1.2
$converged
[1] FALSE
$reason
[1] "iteration_limit"
$iterations
[1] 1
The slope of 1.2 is the last permitted iterate. The reason iteration_limit, together with converged = FALSE, establishes that the fit stopped before meeting the deviance criterion.
Full Newton steps can also move away from the solution. Start the same algorithm at intercept zero and slope five. The outer groups now have probabilities $p_-=1/(1+e^5)$ and $p_+=1-p_-$. At these probabilities, close to zero and one, the component of the score vector for the slope is $(8-10p_+)-(2-10p_-)\approx-3.87$. The corresponding diagonal entry of the information matrix is only $20p_-(1-p_-)\approx0.133$. With the off-diagonal terms canceling, the full slope change is $-3.87/0.133\approx-29.1$. Curvature measured at five thus sends the slope past $\log 4$ to about $-24$.
1
2
3
4
bad_start <- c(0, 5)
bad_fit <- newton(fn, gr, he, bad_start, list(deviance = logit3_deviance))
print(bad_fit[c("par", "value", "converged", "reason", "iterations")])
print(vapply(bad_fit$history, function(row) row$value, numeric(1)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$par
intercept x
-6.266766e-16 2.289302e+10
$value
[1] 91572081187
$converged
[1] FALSE
$reason
[1] "linear_solve_failed"
$iterations
[1] 2
[1] 1.392302e+01 3.790246e+02 9.157208e+10
The value of the negative log likelihood function rises from 13.92302 to 379.0246. At slope $-24$, the outer groups have even smaller weights, and the second update sends the slope to $2.29\times10^{10}$. Its value reaches $9.157208\times10^{10}$. At that slope, the two outer weights round to zero, so the computed slope diagonal entry of the Hessian is zero. The next solve fails and the function returns linear_solve_failed. The observed increase on the first step shows how poorly the curvature at five describes the whole displacement. Limiting the displacement and testing the candidate for sufficient decrease would prevent acceptance of that uphill step. The stats package provides Newton-type minimization.
2.3 Fisher scoring and iteratively reweighted least squares
The Newton equation uses the observed information to turn the score vector into a change in coefficients. Fisher scoring averages the observed information over counts the model could generate at the current coefficients $\beta$. Write $Y$ for the random vector of counts and $y$ for the observed vector. The design matrix $X$ is fixed, as are the trial totals $m$ for grouped binomial observations. If $J(\beta;Y)$ is the observed information calculated from $Y$, then its expectation $I(\beta)$ determines the displacement $\Delta$ through the scoring equation.
\[I(\beta)=\mathrm E_\beta[J(\beta;Y)\mid X,m],\qquad I(\beta)\Delta=U(\beta;y),\qquad \beta_{\rm new}=\beta+\Delta .\]The score vector $U(\beta;y)$ still measures how the log likelihood changes for the observed counts. For independent responses in a generalized linear model with fixed dispersion, the expected information can be calculated from the mean and variance of each response.
To express the scoring update as a weighted regression, consider a row $i$ with linear predictor $\eta_i$. At the current coefficients, let $\mu_i$ and $V_i$ be the conditional mean and variance of its count given the design and any trial total. Write $d_i=d\mu_i/d\eta_i$. A small change in the linear predictor changes the mean by approximately $d_i$ times that change. For $d_i\ne0$, the adjustment to the linear predictor that would explain the count residual $y_i-\mu_i$ under this linear approximation is therefore $(y_i-\mu_i)/d_i$. Adding the adjustment gives the working response $z_i$. With $\eta_i$ and $d_i$ fixed during this step, the variance of $z_i$ over possible counts is $V_i/d_i^2$. For a row with positive variance, take the reciprocal to obtain its working weight $w_i$.
\[z_i=\eta_i+\frac{y_i-\mu_i}{d_i},\qquad w_i=\frac{d_i^2}{V_i},\qquad w_i(z_i-\eta_i)=\frac{d_i}{V_i}(y_i-\mu_i).\]The final product is the derivative of row $i$’s contribution to the log likelihood with respect to its linear predictor. A working response with greater conditional variance therefore receives less weight in the regression.
Collect the working responses in $z$ and their weights in the diagonal matrix $W$. With $a_i^\top$ denoting design row $i$, the corresponding contribution to the score vector is $a_i d_i(y_i-\mu_i)/V_i$. On differentiating its scalar factor with respect to $\eta_i$, the term involving the derivative of $d_i/V_i$ has expectation zero because it multiplies the residual. Differentiating the residual contributes $-d_i^2/V_i$. Changing the sign and summing the weighted outer products gives $I(\beta)=\sum_i w_i a_i a_i^\top=X^\top WX$. Substitute this and $U=X^\top W(z-X\beta)$ into the scoring equation and add $X^\top WX\beta$ on both sides.
\[X^\top WX(\beta_{\rm new}-\beta)=X^\top W(z-X\beta) \quad\Longrightarrow\quad X^\top WX\beta_{\rm new}=X^\top Wz .\]To see the least-squares problem, minimize $\tfrac12\sum_i w_i(z_i-a_i^\top b)^2$ over a coefficient vector $b$. Its gradient is $X^\top W(Xb-z)$, so setting it to zero gives exactly these normal equations. Their solution is the new coefficient vector. Each fit uses the current $z$ and $W$ only for that step, then recalculates them at the updated coefficients. Repeating this calculation gives iteratively reweighted least squares (IRLS).
For a row of LOGIT3, the mean $\mu_i=m_ip_i$ counts the expected successes across $m_i$ trials, each with success probability $p_i$. Differentiating the count mean with respect to the log odds gives $d_i=m_ip_i(1-p_i)=V_i$, so the working weight is also $m_ip_i(1-p_i)$. The function make_glm() combines the fixed data with functions for the negative log likelihood, its derivatives and the working quantities. Its binomial calculations use make_nll_logit(), logit_score() and logit_info(). For a Poisson count, the log mean is $\eta_i$, so the negative log likelihood sums $e^{\eta_i}-y_i\eta_i+\log(y_i!)$. Differentiation gives $X^\top(\mu-y)$ for the gradient and $X^\top\operatorname{diag}(\mu)X$ for the Hessian, as used in gr() and he().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
make_glm <- function(X, y, family = "binomial", trials = rep(1, length(y))) {
stopifnot(family %in% c("binomial", "poisson"), length(family) == 1L,
is.matrix(X), is.numeric(X), nrow(X) > 0L, nrow(X) == length(y),
ncol(X) > 0L, all(is.finite(X)), is.numeric(y),
is.null(dim(y)), all(is.finite(y)), all(y >= 0), all(y == floor(y)))
if (family == "binomial") {
# Grouped binomial counts with known trial totals.
fn <- make_nll_logit(X, y, trials)
gr <- function(beta) -logit_score(beta, X, y, trials)
he <- function(beta) logit_info(beta, X, trials)
} else {
stopifnot(length(trials) == length(y), all(trials == 1))
fn <- function(beta) {
stopifnot(is.numeric(beta), length(beta) == ncol(X), is.null(dim(beta)))
eta <- drop(X %*% beta)
if (any(!is.finite(eta)) || any(!is.finite(exp(eta)))) return(Inf)
# Include the log factorial for each observed count.
sum(exp(eta) - y * eta + lgamma(y + 1))
}
gr <- function(beta) drop(crossprod(X, exp(drop(X %*% beta)) - y))
he <- function(beta) crossprod(X, exp(drop(X %*% beta)) * X)
}
The inner function working() evaluates the mean and its derivative at the same coefficients. For both canonical link functions here, with dispersion one, the derivative equals the count variance. This explains both variance <- derivative and w = derivative. A binomial row with no trials has zero weight, so assigning its current linear predictor value to z leaves the normal equations unchanged.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
working <- function(beta) {
eta <- drop(X %*% beta)
if (family == "binomial") {
p <- plogis(eta)
mu <- trials * p
# Differentiate the expected count with respect to the log odds.
derivative <- trials * p * plogis(-eta)
residual <- y * plogis(-eta) - (trials - y) * p
} else {
mu <- exp(eta)
derivative <- mu
residual <- y - mu
}
# Both canonical models have unit dispersion.
variance <- derivative
z <- eta + residual / derivative
if (family == "binomial") z[trials == 0] <- eta[trials == 0]
list(mu = mu, derivative = derivative, variance = variance,
w = derivative, z = z)
}
The returned object stores the observed design X, counts y, trial totals trials and response family; these remain fixed during coefficient evaluation. For binomial data, X[i, ], y[i] and trials[i] correspond to the design row, $y_i$ and $m_i$. For Poisson data, trials contains ones solely to satisfy this shared function interface; the Poisson model has no binomial trial total. The coefficient vector $\beta$ is supplied separately to fn, gr, he, working or deviance when evaluating them. Constructing this object therefore specifies a function of $\beta$ without estimating or storing a fitted coefficient vector. Its deviance function evaluates the family deviance for any proposed coefficients.
1
2
3
4
list(X = X, y = y, trials = trials, family = family,
fn = fn, gr = gr, he = he, working = working,
deviance = function(beta) glm_deviance(beta, X, y, trials, family))
}
Evaluate the binomial model at zero intercept and slope with the design X, success counts y and trial totals trials from data/source/LOGIT3.csv.
1
2
3
4
binomial_model <- make_glm(X, y, "binomial", trials)
work <- binomial_model$working(beta_zero)
print(data.frame(mu = work$mu, derivative = work$derivative,
variance = work$variance, w = work$w, z = work$z))
1
2
3
4
mu derivative variance w z
1 5 2.5 2.5 2.5 -1.2
2 5 2.5 2.5 2.5 0.0
3 5 2.5 2.5 2.5 1.2
All three groups have ten trials and an expected count of five. For the first group, the derivative is $10(0.5)(1-0.5)=2.5$. Its residual is $2-5=-3$, so $z_1=0-3/2.5=-1.2$ on the log odds scale. The middle count equals its mean, and the last exceeds its mean by three. Their working responses are therefore 0 and 1.2. All three rows receive weight 2.5.
For a separate Poisson example, use the same covariates $-1$, 0 and 1 with observed counts 1, 2 and 4. With the log link function, differentiating $\mu_i=e^{\eta_i}$ gives $d_i=\mu_i$. A Poisson count with that mean also has variance $\mu_i$. Consequently, $w_i=\mu_i$ and $z_i=\eta_i+(y_i-\mu_i)/\mu_i$. Start with intercept $\log 2$ and slope zero.
1
2
poisson_model <- make_glm(X, c(1, 2, 4), "poisson")
print(poisson_model$working(c(log(2), 0))[c("w", "z")])
1
2
3
4
5
$w
[1] 2 2 2
$z
[1] 0.1931472 0.6931472 1.6931472
At the starting coefficients, all three expected counts are two, so all three working weights are two. The first count falls one below its mean, so its working response on the log mean scale is $\log 2-1/2=0.1931472$ to the printed precision. The middle row needs no adjustment. For the last count, the residual is two, giving a full unit increase from 0.6931472 to 1.6931472.
weighted_normal_equations() provisionally solves the normal equations; Section 2.4 replaces this solve with a QR decomposition. The two cross-products form $X^\top WX$ and $X^\top Wz$ by multiplying the design rows and the working responses by their respective weights. For a full-column-rank design with positive weights, the system has a unique solution.
1
2
3
weighted_normal_equations <- function(X, z, w) {
drop(solve(crossprod(X, w * X), crossprod(X, w * z)))
}
The provisional fitting function irls_unit() computes both working quantities at par, replaces the coefficients with the least-squares solution, and evaluates the deviance there. After each update it compares the old deviance $D_{\rm old}$ with the new deviance $D_{\rm new}$. With the default settings, it stops when $\vert D_{\rm new}-D_{\rm old}\vert /(\vert D_{\rm new}\vert +0.1)<10^{-8}$ or when it has taken 25 steps. The final line of the block makes irls a provisional second name for this function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Fit by repeated solutions of the normal equations.
irls_unit <- function(model, par, solver = weighted_normal_equations, maxit = 25, epsilon = 1e-8) {
history <- list(par)
for (k in seq_len(maxit)) {
deviance_old <- model$deviance(par)
# Compute the working weights and working dependent variable at par.
work <- model$working(par)
par <- solver(model$X, work$z, work$w)
history[[length(history) + 1L]] <- par
deviance_new <- model$deviance(par)
# Compare the deviances before and after this weighted fit.
if (abs(deviance_new - deviance_old) / (abs(deviance_new) + 0.1) < epsilon) break
}
list(par = par, value = model$fn(par), gradient = model$gr(par), history = history)
}
irls <- irls_unit
The object work still contains the binomial quantities at zero. Its working responses lie on the line $z_i=1.2x_i$, so a weighted regression with an intercept fits them exactly. The Newton proposal beta_one uses the same start, making its coefficients directly comparable.
1
2
scoring_one <- weighted_normal_equations(X, work$z, work$w)
print(rbind(newton = beta_one, scoring = scoring_one))
1
2
3
intercept x
newton 0 1.2
scoring 0 1.2
Both methods propose $(0,1.2)$. For the canonical binomial logit link function, $X^\top WX$ is both the expected and the observed information. The two methods therefore solve the same update equation at the same coefficients. The binomial fit recomputes the working quantities at each iterate.
1
print(irls(binomial_model, beta_zero)$par)
1
2
intercept x
0.000000 1.386294
The returned binomial slope of 1.386294 gives the fitted change in log odds per unit of the covariate. The same iteration also fits the Poisson counts from $(\log 2,0)$.
1
print(irls(poisson_model, c(log(2), 0))$par)
1
2
intercept x
0.6931472 0.6931472
In the Poisson fit, both returned coefficients equal $\log 2$ to the displayed precision. The fitted mean is two at $x=0$ and doubles for each unit increase in $x$, giving means of 1, 2 and 4 in covariate order. The irls_unit() used here takes the full weighted least-squares update at every iteration. The stats function glm() fits these models by iteratively reweighted least squares.
2.4 Solving weighted least squares with QR decomposition
An IRLS update fits a working response $z$ using the current weights $w_i$. The normal equations combine the design columns in the cross-product $X^\top WX$, where $W$ is diagonal with entries $w_i$. The same update can be computed by factoring a weighted design directly. Multiply row $a_i^\top$ of $X$ and the corresponding $z_i$ by the same factor $\sqrt{w_i}$. With $\beta$ denoting the candidate coefficients and $\Vert \cdot\Vert _2$ the Euclidean norm, the weighted residual criterion becomes
\[\widetilde X=W^{1/2}X,\qquad \widetilde z=W^{1/2}z,\qquad \sum_i w_i(z_i-a_i^\top\beta)^2=\|\widetilde z-\widetilde X\beta\|_2^2 .\]Squaring the transformed residual in row $i$ gives that row exactly one factor of $w_i$. Ordinary least squares on the transformed rows therefore minimizes the required criterion. A row with zero weight has no effect on the solution.
For a weighted design whose columns are linearly independent (full column rank), write its QR decomposition with column pivoting as $\widetilde X P=QR$. The permutation matrix $P$ specifies the column order, $Q$ has orthonormal columns, and $R$ is upper triangular. Write $\gamma=P^\top\beta$ for the coefficients in pivot order. The component of $\widetilde z$ perpendicular to the columns of $Q$ contributes the same squared error for every $\gamma$. The projection of $\widetilde z$ onto their span has coordinates $Q^\top\widetilde z$. Matching these coordinates gives a triangular system, followed by a permutation back to the design order.
\[R\gamma=Q^\top\widetilde z,\qquad \beta=P\gamma .\]Prepare the working weights and working response for the three LOGIT3 groups at zero intercept and slope. In a fresh R session, load the functions and data from the book directory.
1
2
3
4
5
6
7
8
9
10
11
source("code/lib/stability.R")
source("code/lib/logit.R")
source("code/lib/glm.R")
LOGIT3 <- read.csv("data/source/LOGIT3.csv")
X <- cbind(intercept = 1, x = LOGIT3$x)
y <- LOGIT3$successes
trials <- LOGIT3$trials
beta_zero <- c(0, 0)
binomial_model <- make_glm(X, y, "binomial", trials)
work <- binomial_model$working(beta_zero)
In weighted_qr(), A and b are the transformed design and dependent variable. The object returned by qr() stores the factors compactly and records both the pivot order and the numerical rank, the number of columns treated as linearly independent at the specified tolerance. With LAPACK = FALSE, the factorization moves a column to the right if its remaining norm has become negligible relative to its original norm at that tolerance. For a full-rank design, qr.coef() applies the orthogonal transformation, solves the triangular system and restores the original column order.
For a design with full column rank, the 2-norm condition number is $\kappa_2(\widetilde X)=\sigma_{\max}/\sigma_{\min}$, the ratio of its largest to smallest singular value. These two values are the largest and smallest lengths of $\widetilde Xd$ over coefficient directions with $\lVert d\rVert_2=1$. A large ratio means that coefficient changes of equal size can have very different effects on fitted values, making some coefficient combinations sensitive to small changes in the inputs. The function computes the singular values with svd(). If QR declares the design rank deficient at the specified tolerance, it reports condition = Inf without using the singular-value ratio; that reporting rule alone does not prove exact linear dependence.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
weighted_qr <- function(X, z, w, tol = 1e-11) {
stopifnot(is.matrix(X), is.numeric(X), length(z) == nrow(X),
length(w) == nrow(X), all(is.finite(X)), all(is.finite(z)),
all(is.finite(w)), all(w >= 0), is.finite(tol), tol > 0)
A <- sqrt(w) * X
b <- sqrt(w) * z
# The pivoted QR decomposition reports the rank of the weighted design.
decomposition <- qr(A, tol = tol, LAPACK = FALSE)
singular_values <- svd(A, nu = 0, nv = 0)$d
condition <- if (decomposition$rank < ncol(X)) Inf else
max(singular_values) / min(singular_values)
if (decomposition$rank < ncol(X)) {
return(list(coefficients = NULL, rank = decomposition$rank,
condition = condition, reason = "rank_deficient_design"))
}
list(coefficients = drop(qr.coef(decomposition, b)), rank = decomposition$rank,
condition = condition, reason = "full_rank")
}
qr_one <- weighted_qr(X, work$z, work$w)
print(qr_one)
1
2
3
4
5
6
7
8
9
10
11
12
$coefficients
intercept x
8.860503e-17 1.200000e+00
$rank
[1] 2
$condition
[1] 1.224745
$reason
[1] "full_rank"
Both columns contribute to the reported rank of two. The common weight of 2.5 gives squared column lengths $3(2.5)=7.5$ for the intercept and $2(2.5)=5$ for the covariate. The columns are orthogonal, so their lengths are the singular values. The condition number is therefore $\sqrt{7.5/5}\approx1.224745$. QR reproduces the first update of slope 1.2 with an intercept within rounding error of zero.
To use QR at every update, qr_solver() passes the coefficient vector to the iteration when the weighted design has full column rank. For a rank-deficient design, it stops with the reason returned by weighted_qr(). Bind irls to irls_unit() after loading glm.R so the call uses the provisional routine with a solver argument.
1
2
3
4
5
6
7
8
irls <- irls_unit
qr_solver <- function(X, z, w) {
answer <- weighted_qr(X, z, w)
if (answer$reason != "full_rank") stop(answer$reason, call. = FALSE)
answer$coefficients
}
print(irls(binomial_model, beta_zero, solver = qr_solver)$par)
1
2
intercept x
-4.483191e-17 1.386294e+00
From the zero start, the iteration returns a slope of 1.386294. The normal-equation calculation gave the same slope to the displayed precision. Both iterations recompute the same working quantities and use the same deviance stopping rule.
What happens when two design columns almost coincide? If $\sigma_j$ is a singular value of the full-rank weighted design, with right and left singular vectors $r_j$ and $s_j$, then $\widetilde Xr_j=\sigma_j s_j$ and $\widetilde X^\top s_j=\sigma_j r_j$. Multiplying the first equation by $\widetilde X^\top$ shows that $r_j$ is an eigenvector of the cross-product with eigenvalue $\sigma_j^2$. In exact arithmetic, its 2-norm condition number is
\[\kappa_2(\widetilde X^\top\widetilde X) =\frac{\sigma_{\max}^2}{\sigma_{\min}^2} =\kappa_2(\widetilde X)^2.\]The triangular factor in the direct QR calculation has the same singular values as $\widetilde X$ because the orthogonal transformation and column permutation preserve Euclidean lengths.
A separate design with twenty rows and weights increasing from one to two illustrates the effect. Its third column has values $x_i+\varepsilon v_i$, where $v_i=\sin(i)$. As $\varepsilon$ decreases, the third column approaches the second. The response includes fixed sine and cosine terms and is the same for all three designs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
x <- seq(-1, 1, length.out = 20)
v <- sin(seq_along(x))
response <- 0.5 + 2 * x + 0.1 * v + 0.01 * cos(seq_along(x))
weights <- seq(1, 2, length.out = 20)
conditioning <- data.frame()
for (epsilon in c(1e-4, 1e-6, 1e-8)) {
design <- cbind(1, x, x + epsilon * v)
qfit <- weighted_qr(design, response, weights)
# Use the coefficients at the smallest spacing for the response perturbation.
if (epsilon == 1e-8) near_fit <- qfit$coefficients
nfit <- tryCatch(weighted_normal_equations(design, response, weights),
error = function(e) rep(NA_real_, 3))
# Measure both fits with the same weighted residual criterion.
qr_rss <- sum(weights * (response - design %*% qfit$coefficients)^2)
normal_rss <- sum(weights * (response - design %*% nfit)^2)
conditioning <- rbind(conditioning, data.frame(epsilon, rank = qfit$rank,
condition = qfit$condition,
qr_status=qfit$reason,
normal_status=if(all(is.finite(nfit))) "solved" else "singular",
qr_rss, normal_rss, qr_residual_norm=sqrt(qr_rss),
normal_residual_norm=sqrt(normal_rss)))
}
print(conditioning, digits = 6, row.names = FALSE)
1
2
3
4
5
6
7
8
epsilon rank condition qr_status normal_status qr_rss normal_rss qr_residual_norm
1e-04 3 20663.6 full_rank solved 0.00139481 0.00139481 0.0373472
1e-06 3 2066361.6 full_rank solved 0.00139481 0.00139481 0.0373472
1e-08 3 206636167.8 full_rank singular 0.00139481 NA 0.0373472
normal_residual_norm
0.0373472
0.0373472
NA
At its tolerance of $10^{-11}$, QR assigns numerical rank three to all three designs. For the first two designs, both methods return the same weighted residual sum of squares to the precision shown. At $\varepsilon=10^{-8}$, the weighted design’s condition number reaches $2.07\times10^8$. Its square, about $4.3\times10^{16}$, exceeds the reciprocal of machine epsilon, about $4.5\times10^{15}$ in double precision. The normal-equation solve fails in this row. The test inside solve() uses the computed cross-product and rejects it if its estimated reciprocal 1-norm condition number is below .Machine$double.eps. The QR residual norm of 0.0373472 measures the distance from the transformed response to its fitted values. Squaring it gives the reported qr_rss.
With this last design fixed, adding $10^{-8}\cos(2i)$ to response $i$ reveals coefficient sensitivity.
1
2
3
4
5
near_design <- cbind(1, x, x + 1e-8 * v)
perturbed_fit <- weighted_qr(near_design, response + 1e-8 * cos(2 * seq_along(x)),
weights)$coefficients
print(c(coefficient_change = max(abs(near_fit - perturbed_fit)),
linear_predictor_change = max(abs(near_design %*% (near_fit - perturbed_fit)))))
1
2
coefficient_change linear_predictor_change
3.928905e-02 6.325457e-10
Across the three coefficients, the largest absolute change is about 0.039. Across the twenty fitted linear predictors, the largest absolute change is only $6.3\times10^{-10}$. For example, subtract $c$ from the coefficient of $x$ and add $c$ to the coefficient of $x+\varepsilon v$. The two changes together shift the fitted value at row $i$ by only $c\varepsilon v_i$.
An exactly duplicated $x$ column changes the question from sensitivity to uniqueness. For slopes $\beta_1$ and $\beta_2$, the two columns contribute $x_i(\beta_1+\beta_2)$ to every fitted value. Adding any number to the first slope and subtracting it from the second leaves every residual unchanged.
1
2
redundant <- weighted_qr(cbind(1, x, x), response, weights)
print(redundant[c("rank", "condition", "reason")])
1
2
3
4
5
6
7
8
$rank
[1] 2
$condition
[1] Inf
$reason
[1] "rank_deficient_design"
The rank is two for three coefficients. The nearly duplicated design determined unique coefficients in exact arithmetic, although a small perturbation could change them appreciably. Once the columns coincide, infinitely many slope pairs give the same fit. The function returns coefficients = NULL, an infinite condition number and the reason rank_deficient_design. R’s qr() computes the decomposition; qr.coef() uses it to obtain the least-squares coefficients.
2.5 Step halving, backtracking line search, and the maximum step length
Every update so far has taken the full step that its equation specifies. At intercept zero and slope five, the full Newton step raised the value of the negative log likelihood function of the three binomial counts from 13.92302 to 379.0246. What fraction of that step gives a sufficient decrease in the negative log likelihood? Let $f$ be the negative log likelihood function, $\beta$ the current coefficients and $g=\nabla f(\beta)$. For a direction $d$, write $\phi(\alpha)=f(\beta+\alpha d)$. The directional derivative at the start is $s=\phi^{\prime}(0)=g^\top d$. If $s<0$, then $d$ is a descent direction. For a positive step length $\alpha$, the linear approximation predicts a decrease of $-\alpha s$. The Armijo condition, also called the sufficient decrease condition, compares the actual decrease with a fraction $c$ of this prediction.
\[f(\beta+\alpha d)\leq f(\beta)+c\alpha g^\top d,\qquad c=10^{-4}.\]Shortening the step reduces the required decrease in proportion to $\alpha$. For a differentiable $f$, the actual change is $\alpha s+o(\alpha)$. Since $s<0$ and $c<1$, sufficiently small positive steps satisfy the test. The simplest backtracking rule is step halving. It starts at $\alpha=1$ and halves the multiplier after each rejection until the value of the negative log likelihood function at the trial point meets the condition.
A rejected trial also supplies information about curvature along the search direction. Suppose the full step gives a finite $\phi(1)$ above its Armijo threshold. Choose $q(t)=\phi(0)+st+at^2$ so the quadratic and $\phi$ have the same tangent at zero. Passing through the rejected point fixes $a=\phi(1)-\phi(0)-s$. The rejection means $\phi(1)>\phi(0)+cs$, so $a>-(1-c)s>0$. Solving $q^{\prime}(t)=s+2at=0$ gives the proposed multiplier
\[\alpha_{\rm quad}=\frac{-s}{2\{\phi(1)-\phi(0)-s\}} <\frac{1}{2(1-c)} .\]With $c=10^{-4}$, the upper bound is just above one half.
The function backtracking_search() takes a nonzero descent direction p. It first limits the Euclidean norm of the direction to max_step, then computes the directional derivative slope and the relative length rel_len from the scaled direction. Here x contains the current coefficients and f is the value of fn() there.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
backtracking_search <- function(fn, x, f, g, p, max_step, step_tol) {
# Bound the direction norm before computing its directional derivative.
p_norm <- sqrt(sum(p^2))
if (p_norm > max_step) {
p <- p * (max_step / p_norm)
p_norm <- max_step
}
slope <- sum(g * p)
rel_len <- max(abs(p) / pmax(abs(x), 1))
lambda_min <- step_tol / rel_len
lambda <- 1
first_try <- TRUE
lambda_prev <- 0
f_prev <- 0
line_trials <- list()
At each trial, lambda is the multiplier $\alpha$. The record pairs the value of fn() at each candidate with its acceptance threshold. The search accepts a candidate as soon as it meets the Armijo condition. After rejection, the search returns failure code 1 if $\alpha$ has fallen below step_tol divided by $\max_i\lbrace \vert d_i\vert /\max(\vert \beta_i\vert ,1)\rbrace $. On this return, x_new is the last rejected candidate. The caller can use the failure code to retain the current coefficients.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Evaluate each trial and test for sufficient decrease first.
repeat {
x_new <- x + lambda * p
f_new <- fn(x_new)
line_trials[[length(line_trials) + 1L]] <- c(lambda = lambda, value = f_new,
threshold = f + slope * 1e-4 * lambda)
if (f_new <= f + slope * 1e-4 * lambda) {
return(list(x = x_new, f = f_new, code = 0L, lambda = lambda,
near_maximum_step = lambda == 1 && p_norm > max_step * .99, trials = line_trials))
}
if (!is.finite(lambda) || lambda < lambda_min) {
return(list(x = x_new, f = f_new, code = 1L, lambda = lambda, near_maximum_step = FALSE,
trials = line_trials))
}
If the trial value reaches the largest finite double or is positive infinity, multiply the current step length by 0.1 and restart interpolation. For a finite rejected full step, use the quadratic above. After two successive finite rejections, the two trial values, the starting value and its derivative determine a cubic. The terms t1 and t2 subtract the starting tangent from the two trial values. For a cubic $\phi(0)+st+bt^2+at^3$, a3 represents $3a$, so the derivative to be solved is $s+2bt+3at^2=0$. Use the local minimum as a proposal and cap the cubic proposal at half the preceding multiplier. The lower bound for either interpolation proposal is one tenth of the current multiplier.
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
# A trial at the largest double or above calls for a tenfold reduction.
if (f_new >= .Machine$double.xmax) {
lambda <- lambda * 0.1
first_try <- TRUE
} else {
if (first_try) {
lambda_try <- -lambda * slope / ((f_new - f - slope) * 2)
first_try <- FALSE
} else {
# Match a cubic to the two rejected finite trials and the starting tangent.
t1 <- f_new - f - lambda * slope
t2 <- f_prev - f - lambda_prev * slope
t3 <- 1 / (lambda - lambda_prev)
a3 <- 3 * t3 * (t1 / lambda^2 - t2 / lambda_prev^2)
b <- t3 * (t2 * lambda / lambda_prev^2 - t1 * lambda_prev / lambda^2)
disc <- b^2 - a3 * slope
root <- sqrt(disc)
lambda_try <- if (disc > b^2) (-b + if (a3 < 0) -root else root) / a3 else
(-b + if (a3 < 0) root else -root) / a3
if (lambda_try > lambda * .5) lambda_try <- lambda * .5
}
lambda_prev <- lambda
f_prev <- f_new
# The interpolation proposal can reduce the multiplier at most tenfold.
lambda <- if (isTRUE(lambda_try < lambda * .1)) lambda * .1 else lambda_try
}
}
}
Return to the three LOGIT3 groups. From the book directory, prepare the negative log likelihood function and its gradient and Hessian, and set the starting slope to five.
1
2
3
4
5
6
7
8
9
10
11
source("code/lib/stability.R")
source("code/lib/logit.R")
LOGIT3 <- read.csv("data/source/LOGIT3.csv")
X <- cbind(intercept = 1, x = LOGIT3$x)
y <- LOGIT3$successes
trials <- LOGIT3$trials
fn <- make_nll_logit(X, y, trials)
gr <- function(beta) -logit_score(beta, X, y, trials)
he <- function(beta) logit_info(beta, X, trials)
bad_start <- c(0, 5)
The starting vector has norm five. The limit $\max(1000\Vert \beta\Vert _2,1000)=5000$ therefore admits the Newton direction of length 29.07724 without scaling. The following search evaluates the full displacement and a shorter proposal along that direction.
1
2
3
4
5
6
7
bad_g <- gr(bad_start)
bad_d <- drop(solve(he(bad_start), -bad_g))
backtracked <- backtracking_search(fn, bad_start, fn(bad_start), bad_g, bad_d,
max_step = max(1000 * sqrt(sum(bad_start^2)), 1000), step_tol = 1e-6)
print(rbind(start = c(par = bad_start[2], value = fn(bad_start)),
full = c(par = (bad_start + bad_d)[2], value = fn(bad_start + bad_d)),
accepted = c(par = backtracked$x[2], value = backtracked$f)))
1
2
3
4
par value
start 5.000000 13.923025
full -24.077241 379.024581
accepted 1.577336 3.852941
The full displacement changes the slope to $-24.077241$, beyond the optimum. The search accepted a much shorter displacement, ending at 1.577336. The returned field backtracked$trials records each multiplier, the value of the negative log likelihood function there and the threshold for acceptance. The input vector trials counts the binomial trials in each group.
1
print(do.call(rbind, backtracked$trials))
1
2
3
lambda value threshold
[1,] 1.0000000 379.024581 13.91178
[2,] 0.1177094 3.852941 13.92170
At multiplier one, 379.024581 exceeds the threshold of 13.91178. Here $s=g^\top d\approx-112.42$. Using this derivative and the two values of the negative log likelihood function in the interpolation formula gives a multiplier of 0.1177094 with the unrounded inputs. At that multiplier, the value of the function is 3.852941, below 13.92170. The search needed two evaluations at candidate points and used only the first quadratic reduction. The gradient and Hessian at the start also give a quadratic prediction for the full step.
1
2
print(c(quadratic_prediction = fn(bad_start) + sum(bad_g * bad_d) +
0.5 * sum(bad_d * drop(he(bad_start) %*% bad_d))))
1
2
quadratic_prediction
-42.28536
The quadratic approximation formed from the gradient and Hessian at the start predicts the value $-42.28536$ at the full step, far below the actual value 379.024581. The Hessian supplied curvature at the starting point. The interpolation quadratic used the measured value at the rejected point to propose a shorter step. Acceptance still required evaluating the negative log likelihood function at that new point.
The distance moved is the product of the multiplier and the direction’s length after scaling. The Newton fitting function introduced in Section 2.6 supplies max_step to this search. If $\beta_{\rm start}$ denotes its initial coefficient vector, that default limit is $\max(1000\Vert \beta_{\rm start}\Vert _2,1000)$. This default restricts displacements only when they are large relative to the initial coefficient scale. A limit of 0.5 makes the scaling active in the same search.
1
2
3
4
limited <- backtracking_search(fn, bad_start, fn(bad_start), bad_g, bad_d, max_step = 0.5,
step_tol = 1e-6)
print(c(newton_length = sqrt(sum(bad_d^2)), max_step = 0.5,
taken_length = sqrt(sum((limited$x - bad_start)^2)), maximum_taken = limited$near_maximum_step))
1
2
newton_length max_step taken_length maximum_taken
29.07724 0.50000 0.50000 1.00000
Scaling multiplies the direction by $0.5/29.07724$. The point reached with this scaled direction passed the Armijo test at $\alpha=1$, so the distance moved was 0.5. The printed one under maximum_taken represents a true near_maximum_step flag. That flag requires both acceptance at multiplier one and a direction norm after scaling strictly greater than $0.99$ times max_step. Section 2.6 uses this flag to count consecutive steps at the norm limit.
Descent directions from an indefinite Hessian
A line search can only shorten a step along its direction, which helps only if that direction points downhill. Multiplying $d$ by a positive number multiplies $g^\top d$ by the same number. Thus shortening an ascent direction leaves its directional derivative positive. An indefinite Hessian $H$, with both positive and negative eigenvalues, can give precisely such a Newton direction. For $g\ne0$, modify the diagonal entries as needed during Cholesky factorization to obtain a lower triangular factor $L$ with $LL^\top$ positive definite. This is a modified Cholesky factorization. The modification changes the local quadratic approximation used to choose a direction. The line search still evaluates candidate coefficients with the original negative log likelihood.
The function raised_cholesky() computes one row of $L$ at a time. The candidate pivot for the squared diagonal entry of $L$ is the current diagonal minus the sum of squares of the Cholesky factor entries already computed in that row. Let $\tau=\sqrt{\epsilon_{\rm mach}}$, where $\epsilon_{\rm mach}$ is machine epsilon. In the first factorization, a pivot at least $\tau$ times the largest diagonal of the matrix being factored is used under the square root. A smaller pivot is raised to the larger of that bound and the largest magnitude among the Cholesky factor entries to its left, taking zero for an empty row segment. The function also records the largest increase applied to a pivot.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
raised_cholesky <- function(A, largest_diag, tol) {
n <- nrow(A)
max_raise <- 0
pivot_floor <- largest_diag * tol
for (i in seq_len(n)) {
if (i > 1L) for (j in seq_len(i - 1L)) {
s <- if (j > 1L) sum(A[i, seq_len(j - 1L)] * A[j, seq_len(j - 1L)]) else 0
A[i, j] <- (A[i, j] - s) / A[j, j]
}
s <- if (i > 1L) sum(A[i, seq_len(i - 1L)]^2) else 0
# Subtract the contributions from previous columns to obtain the pivot.
pivot <- A[i, i] - s
if (pivot >= pivot_floor) {
A[i, i] <- sqrt(pivot)
} else {
max_off <- if (i > 1L) max(abs(A[i, seq_len(i - 1L)])) else 0
if (max_off <= pivot_floor) max_off <- pivot_floor
A[i, i] <- sqrt(max_off)
max_raise <- max(max_raise, max_off - pivot)
}
}
A[upper.tri(A)] <- 0
list(L = A, max_raise = max_raise)
}
The outer function perturbed_cholesky() copies the lower triangle of $H$ to form a symmetric matrix. Put $m=\min_i H_{ii}$ and $M=\max(0,\max_i H_{ii})$. If $m\leq\tau M$, the proposed initial shift is $\mu=\tau(M-m)-m$. Adding $\mu I$ when $\mu>0$ brings the smallest diagonal entry to $\tau(M-m)$. If the formula gives zero, the replacement shift depends on the off-diagonal entries. The replacement is one when they all vanish, and $(1+\tau)$ times the largest absolute entry otherwise.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
perturbed_cholesky <- function(H) {
n <- nrow(H)
tol <- sqrt(.Machine$double.eps)
A <- H
A[upper.tri(A)] <- t(A)[upper.tri(A)]
largest_diag <- max(diag(A))
smallest_diag <- min(diag(A))
largest_pos <- max(largest_diag, 0)
added <- 0
if (smallest_diag <= largest_pos * tol) {
# Adjust the diagonal before attempting the factorization.
shift <- tol * (largest_pos - smallest_diag) - smallest_diag
if (shift == 0) {
max_off <- if (n > 1L) max(abs(A[lower.tri(A)])) else 0
shift <- if (max_off == 0) 1 else max_off * (tol + 1)
}
diag(A) <- diag(A) + shift
largest_diag <- largest_diag + shift
added <- shift
}
If the first factorization raised a pivot, compute bounds from Gershgorin’s theorem. In row $i$, add the magnitudes of all entries outside the diagonal. This sum is the radius of an interval centered at the diagonal element. Gershgorin’s theorem places every eigenvalue of this symmetric matrix in at least one of these intervals. ev_low is the smaller of zero and the leftmost endpoint, and ev_high is the rightmost endpoint. The second uniform shift is the smaller of $\tau(\texttt{ev_high}-\texttt{ev_low})-\texttt{ev_low}$ and the largest increase applied to a pivot. The shifted matrix is then factored again. The field added accumulates the uniform shifts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
factor <- raised_cholesky(A, largest_diag, tol)
if (factor$max_raise > 0) {
# Use the off-diagonal row sums to bound the spectrum.
off <- abs(A)
diag(off) <- 0
row_off <- rowSums(off)
ev_low <- min(0, diag(A) - row_off)
ev_high <- max(A[1, 1], diag(A) + row_off)
shift <- min(tol * (ev_high - ev_low) - ev_low, factor$max_raise)
diag(A) <- diag(A) + shift
factor <- raised_cholesky(A, 0, tol)
added <- added + shift
}
list(L = factor$L, added = added)
}
For the solution of $LL^\top d=-g$, the directional derivative is
\[g^\top d=-g^\top(LL^\top)^{-1}g=-\|L^{-1}g\|_2^2<0 .\]Consider $H=\operatorname{diag}(-1,2)$ and $g=(1,1)^\top$. The unmodified equations give $d=(1,-0.5)^\top$, so $g^\top d=0.5$ indicates ascent. For the modified direction, forwardsolve() first solves $Lu=g$ for $u$. Then backsolve() solves $L^\top v=u$ for $v$, and the leading minus sign gives $d=-v$.
1
2
3
4
5
6
7
8
9
g_example <- c(1, 1)
H_example <- diag(c(-1, 2))
raw_direction <- drop(solve(H_example, -g_example))
perturbed <- perturbed_cholesky(H_example)
perturbed_direction <- -drop(backsolve(t(perturbed$L),
forwardsolve(perturbed$L, g_example)))
print(c(raw_directional_derivative = sum(g_example * raw_direction),
perturbed_directional_derivative = sum(g_example * perturbed_direction),
added = perturbed$added))
1
2
raw_directional_derivative perturbed_directional_derivative added
0.5 -22369621.3 1.0
For this diagonal Hessian, $M=2$ and $m=-1$, so the initial shift is $1+3\tau$. The sum of the shifts prints as 1.0, but the small excess above one matters. The first diagonal entry of the modified matrix is about $3\tau\approx4.47\times10^{-8}$. Dividing by this small diagonal entry gives a first direction component near $-2.24\times10^7$, which accounts for the directional derivative of $-22369621.3$. The factorization gives a descent direction. The norm limit and the line search determine how far to move along it. The supplied backtracking_search(), raised_cholesky() and perturbed_cholesky() are translated from the minimizer of nlm() in the stats package (code/NOTICE.md), which provides Newton-type minimization with step control.
2.6 Convergence criteria, indefinite Hessians, and logistic separation
Two questions remain: when to stop, and what the stopping point means. When an accepted step barely changes the coefficients, is the score vector already close to zero? Let $\beta$ be the new coefficient vector, $\beta_{\rm old}$ the preceding vector, $f$ the value of the negative log likelihood function at $\beta$, and $g$ its gradient there. Define $G$, the largest absolute component of the scaled gradient, and the relative step $S$ by
\[G=\max_i\frac{|g_i|\max(|\beta_i|,1)}{\max(|f|,1)},\qquad S=\max_i\frac{|\beta_i-\beta_{ {\rm old},i}|}{\max(|\beta_i|,1)} .\]The relative step $S$ scales each change by coefficient size, using one near zero. Each component of the scaled gradient measures sensitivity on its coefficient’s scale relative to the magnitude of $f$, with the same lower bound on the denominator.
These criteria can now be evaluated for fits to LOGIT3. Start R in the book directory. For LOGIT3, load the fitting functions and form the negative log likelihood function and its gradient and Hessian for the observed counts conditional on their trial totals and covariates.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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")
LOGIT3 <- read.csv("data/source/LOGIT3.csv")
X <- cbind(intercept = 1, x = LOGIT3$x)
y <- LOGIT3$successes
trials <- LOGIT3$trials
beta_zero <- c(0, 0)
binomial_model <- make_glm(X, y, "binomial", trials)
fn <- make_nll_logit(X, y, trials)
beta_exact <- c(0, log(4))
gr <- function(beta) -logit_score(beta, X, y, trials)
he <- function(beta) logit_info(beta, X, trials)
At zero, the Newton direction is $(0,1.2)^\top$. Take just $10^{-12}$ of it and evaluate both measures at the resulting point.
1
2
3
4
5
6
7
convergence_metrics <- function(par, value, gradient, old_par = par) {
c(max_abs_scaled_gradient = max(abs(gradient) * pmax(abs(par), 1)) / max(abs(value), 1),
relative_step = max(abs(par - old_par) / pmax(abs(par), 1)))
}
tiny_beta <- beta_zero + 1e-12 * drop(solve(he(beta_zero), -gr(beta_zero)))
print(convergence_metrics(tiny_beta, fn(tiny_beta), gr(tiny_beta), beta_zero))
1
2
max_abs_scaled_gradient relative_step
7.841434e-01 1.200000e-12
The two entries are $G$ and $S$, with par, old_par, value and gradient in place of $\beta$, $\beta_{\rm old}$, $f$ and $g$. The relative step is $1.2\times10^{-12}$ by construction. The slope component of the score vector is still close to six, giving $G=0.7841434$. A stopping rule based only on the small change in coefficients could therefore accept this move while the gradient remains large.
At the exact coefficients $(0,\log 4)^\top$, each fitted group mean equals its count, so the score vector vanishes. The eigenvalues of the negative log likelihood Hessian describe curvature at that point.
1
print(eigen(he(beta_exact), symmetric = TRUE, only.values = TRUE)$values)
1
[1] 5.7 3.2
Both eigenvalues, 5.7 and 3.2, are positive. Together with stationarity, this establishes a strict local minimum. Eigenvalues evaluated at a single coefficient vector describe curvature there.
A small score can also occur where the likelihood has no maximum. Consider four independent Bernoulli responses, failures at $x=-2,-1$ and successes at $x=1,2$, with log odds $\beta_0+\beta_1x$. Here each observation is a single trial: $\beta_0$ is the log odds of success at $x=0$, and $\beta_1$ is their change per unit increase in $x$. The threshold at zero separates all failures from all successes. This is complete separation: some coefficient vector gives a negative linear predictor for every failure and a positive one for every success. Starting at zero, use newton_unit() with its relative deviance stopping rule. Select the starting row, updates five and ten, and the final row. The two probabilities are fitted success probabilities at the inner covariate values, $-1$ and $1$.
1
2
3
4
5
6
7
8
9
10
11
12
separated_X <- cbind(intercept = 1, x = c(-2, -1, 1, 2))
separated_y <- c(0, 0, 1, 1)
separated <- make_glm(separated_X, separated_y, "binomial", rep(1, 4))
separation_history <- newton_unit(separated$fn, separated$gr, separated$he,
beta_zero, list(deviance = separated$deviance))
selected <- c(1, 6, 11, length(separation_history$history))
print(do.call(rbind, lapply(separation_history$history[selected], function(row) {
c(iteration = row$iteration, slope = row$par[2], log_lik = -row$value,
max_abs_score = row$max_abs_gradient,
p_left = plogis(drop(separated_X[2, , drop = FALSE] %*% row$par)),
p_right = plogis(drop(separated_X[3, , drop = FALSE] %*% row$par)))
})))
1
2
3
4
5
iteration slope log_lik max_abs_score p_left p_right
[1,] 0 0.000000 -2.772589e+00 3.000000e+00 5.000000e-01 0.5000000
[2,] 5 4.835391 -1.595059e-02 1.601434e-02 7.880975e-03 0.9921190
[3,] 10 9.822874 -1.083981e-04 1.084011e-04 5.419465e-05 0.9999458
[4,] 23 22.822788 -2.450298e-10 2.450298e-10 1.225149e-10 1.0000000
Over 23 updates, the slope grew from zero to 22.822788. The log likelihood rose toward zero while the largest absolute score component fell from 3 to about $2.5\times10^{-10}$. The relative deviance change then fell below $10^{-8}$. To see why the slope continued to increase, take $b=(0,1)^\top$ and let $a_i=(1,x_i)^\top$ denote a design row written as a column. Each success has $a_i^\top b>0$ and each failure has $a_i^\top b<0$. At coefficients $tb$, increasing $t$ raises the probability of every observed response. Their product approaches one. At any finite coefficients, even the success probability printed as 1.0000000 is strictly below one. Thus the likelihood has no finite maximizer.
A Newton function with step control
To see what step control changes, return to the start at slope five and first fit the grouped counts with unit steps, storing the result in bad_fit. The name newton refers to newton_unit() for this call.
1
2
3
4
newton <- newton_unit
logit3_deviance <- function(beta) glm_deviance(beta, X, y, trials)
bad_start <- c(0, 5)
bad_fit <- newton(fn, gr, he, bad_start, list(deviance = logit3_deviance))
Now replace the newton alias with a function that uses step control. The original newton_unit() remains available under its own name. The new function uses the scaled gradient and relative step defined above, with defaults maxit = 100 and grad_tol = step_tol = $10^{-6}$. Count calls made during fitting to the objective function, gradient and Hessian. Replace a nonfinite value of the objective function by the largest finite double so that the search can shorten the step. Require a finite gradient of the correct length and a finite, nearly symmetric Hessian of the required dimension.
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
newton <- function(fn, gr, he, par, control = list()) {
defaults <- list(maxit = 100L, grad_tol = 1e-6, step_tol = 1e-6, max_step = NA_real_)
stopifnot(all(names(control) %in% names(defaults)))
settings <- modifyList(defaults, control)
stopifnot(is.numeric(par), is.null(dim(par)), length(par) > 0L, all(is.finite(par)),
settings$maxit >= 0, settings$maxit == floor(settings$maxit),
settings$grad_tol >= 0, settings$step_tol > 0)
n <- length(par)
max_step <- if (is.na(settings$max_step)) max(1000 *
sqrt(sum(par^2)), 1000) else settings$max_step
evaluations <- c(objective = 0L, gradient = 0L, hessian = 0L)
# A nonfinite value of the objective function is replaced by the largest finite double.
objective <- function(x) {
evaluations[1] <<- evaluations[1] + 1L
value <- fn(x)
if (!is.numeric(value) || !is.null(dim(value)) ||
length(value) != 1L) return(NA_real_)
if (!is.finite(value)) .Machine$double.xmax else value
}
# Count derivative evaluations even when their dimensions or values are invalid.
gradient_at <- function(x) {
evaluations[2] <<- evaluations[2] + 1L
g <- gr(x)
if (!is.numeric(g) || !is.null(dim(g)) || length(g) != n ||
any(!is.finite(g))) NULL else g
}
hessian_at <- function(x) {
evaluations[3] <<- evaluations[3] + 1L
H <- he(x)
valid <- is.matrix(H) && identical(dim(H), c(n, n)) && all(is.finite(H)) &&
max(abs(H - t(H))) <= 1e-10 * max(1, max(abs(H)))
if (valid) H else NULL
}
# Evaluate curvature at the returned point separately from the fitting calls.
finish <- function(par, value, gradient, code, reason, history) {
curvature <- if (!is.null(gradient)) tryCatch(min(eigen(he(par), symmetric = TRUE,
only.values = TRUE)$values), error = function(e) NA_real_) else NA_real_
result <- new_result(par, value,
if (is.null(gradient)) rep(NA_real_, n) else gradient,
code %in% c(1L, 2L), reason, max(0L, length(history) - 1L), evaluations, history)
result$code <- code
result$smallest_hessian_eigenvalue <- curvature
result
}
At return, finish() calls he() separately for the smallest eigenvalue when available. This diagnostic evaluation is outside the Hessian count. The returned smallest_hessian_eigenvalue stores this smallest Hessian eigenvalue. A stationary point with an indefinite Hessian can meet the gradient tolerance even though some directions there have negative curvature.
At the start, check the value of the objective function and the gradient before recording iteration zero. Test only $G$ there, since no coefficients have moved. Obtain the first Hessian if an update is needed and allowed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
value <- objective(par)
if (is.na(value)) return(finish(par, NA_real_, NULL, NA_integer_,
"invalid_objective", list()))
gradient <- gradient_at(par)
if (is.null(gradient)) return(finish(par, value, NULL, NA_integer_,
"invalid_gradient", list()))
# Iteration zero has a gradient but no preceding displacement.
metrics <- convergence_metrics(par, value, gradient)
history <- list(list(iteration = 0L, par = par, value = value,
max_abs_gradient = max(abs(gradient)), metrics = metrics,
lambda = NA_real_, added = NA_real_))
if (metrics[["max_abs_scaled_gradient"]] <= settings$grad_tol) {
return(finish(par, value, gradient, 1L, "converged", history))
}
if (settings$maxit == 0) return(finish(par, value, gradient, 4L,
"iteration_limit", history))
H <- hessian_at(par)
if (is.null(H)) return(finish(par, value, gradient, NA_integer_,
"invalid_hessian", history))
consecutive_max <- 0L
Form the direction by two triangular solves using the Cholesky factor of the modified Hessian. The default norm limit is $\max(1000\Vert \beta_0\Vert _2,1000)$ at starting vector $\beta_0$. Pass step_tol on to the line search. Evaluate the gradient at the returned trial point, then check for search failure before checking the new gradient. On search failure, return the preceding point with outer code 3.
1
2
3
4
5
6
7
8
9
10
11
12
13
for (k in seq_len(settings$maxit)) {
# Use the modified Hessian for the direction and the actual function for the search.
factor <- perturbed_cholesky(H)
direction <- -drop(backsolve(t(factor$L), forwardsolve(factor$L, gradient)))
step <- backtracking_search(objective, par, value, gradient, direction,
max_step, settings$step_tol)
new_gradient <- gradient_at(step$x)
if (step$code == 1L) {
return(finish(par, value, gradient, 3L, "line_search_failed", history))
}
if (is.null(new_gradient)) {
return(finish(par, value, gradient, NA_integer_, "invalid_gradient", history))
}
At an accepted point, test the scaled gradient, relative step, iteration limit and consecutive steps at the norm limit, in that order. Record the point, both measures, the accepted multiplier and the diagonal shift. Rejected trials contribute function evaluations but no accepted coefficients, so they add no history rows. Evaluate another Hessian for the iteration only when continuing.
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
# Test the accepted point before requesting another Hessian.
metrics <- convergence_metrics(step$x, step$f, new_gradient, par)
code <- 0L
if (metrics[["max_abs_scaled_gradient"]] <= settings$grad_tol) {
code <- 1L
} else if (metrics[["relative_step"]] <= settings$step_tol) {
code <- 2L
} else if (k >= settings$maxit) {
code <- 4L
} else if (step$near_maximum_step) {
consecutive_max <- consecutive_max + 1L
if (consecutive_max >= 5L) code <- 5L
} else {
consecutive_max <- 0L
}
par <- step$x
value <- step$f
gradient <- new_gradient
history[[length(history) + 1L]] <- list(iteration = k, par = par, value = value,
max_abs_gradient = max(abs(gradient)), metrics = metrics, lambda = step$lambda,
added = factor$added)
if (code != 0L) {
reason <- c("converged", "small_relative_step", "line_search_failed",
"iteration_limit", "repeated_maximum_step")[code]
return(finish(par, value, gradient, code, reason, history))
}
H <- hessian_at(par)
if (is.null(H)) return(finish(par, value, gradient, NA_integer_,
"invalid_hessian", history))
}
}
Newton codes 1 and 2 identify termination by $G$ and the relative step $S$, respectively. A search that reaches its step-tolerance limit before finding sufficient decrease gives code 3. Code 4 records the iteration limit. Code 5 requires five consecutive accepted steps at multiplier one, each longer than 0.99 times max_step after scaling, provided the preceding tests have not stopped the fit. An invalid value of the objective function, gradient vector or Hessian matrix has its own reason and a missing numerical code.
An accepted step with the tiny-step diagnostics calculated earlier would miss the gradient tolerance grad_tol but meet the step tolerance step_tol, giving code 2. The returned code identifies the stopping condition, while the final history entry’s metrics contains the remaining max_abs_scaled_gradient.
Fit the same three counts from the saved starting vector with the new function and compare the endpoints.
1
2
3
difficult_fit <- newton(fn, gr, he, bad_start)
print(rbind(unit_steps = c(value = bad_fit$value, slope = bad_fit$par[2]),
line_search = c(value = difficult_fit$value, slope = difficult_fit$par[2])))
1
2
3
value slope.x
unit_steps 9.157208e+10 2.289302e+10
line_search 3.796766e+00 1.386294e+00
The unit-step fit stopped after two updates when the computed Hessian could no longer be used to solve the Newton equations numerically. Its slope was $2.289302\times10^{10}$, and the value of the negative log likelihood function there was $9.157208\times10^{10}$. The controlled fit reached slope 1.386294, where the function has value 3.796766. Its history shows which accepted displacements required shortening.
1
2
3
print(do.call(rbind, lapply(difficult_fit$history, function(row) c(
iteration = row$iteration,
value = row$value, lambda = row$lambda, added = row$added))))
1
2
3
4
5
6
iteration value lambda added
[1,] 0 13.923025 NA NA
[2,] 1 3.852941 0.1177094 0
[3,] 2 3.797003 1.0000000 0
[4,] 3 3.796766 1.0000000 0
[5,] 4 3.796766 1.0000000 0
Only the first move required shortening, to multiplier 0.1177094. Each of the three subsequent full steps passed the decrease test. The zeros under added show that the Hessian needed no uniform diagonal shift on any iteration. Step control therefore accounts for the different endpoints under the same model.
Design diagnostics and the final IRLS function
A fit that stops correctly can still describe a model without a unique finite estimate, so the final functions also diagnose the design. For a fitted model, glm_diagnosis() first checks design rank by QR decomposition with tolerance $10^{-11}$, omitting binomial groups with zero trials. A numerical rank below the number of columns gives the code label rank_deficient_design. When each active binomial group contains only successes or only failures, multiply its fitted linear predictor by $+1$ or $-1$, respectively. If every product exceeds $10^{-8}$, the supplied coefficients give a separating direction. Failure of this test at one vector leaves other directions possible. The function returns NULL when neither check detects a problem.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
glm_diagnosis <- function(model, beta) {
active <-
if (model$family == "binomial") model$trials > 0 else rep(TRUE, length(model$y))
X <- model$X[active, , drop = FALSE]
if (qr(X, tol = 1e-11)$rank < ncol(X)) return("rank_deficient_design")
# Only a sign pattern shared by every active group proves separation here.
if (model$family == "binomial" && all(is.finite(beta))) {
y <- model$y[active]
m <- model$trials[active]
# Checked only when every group has observed one outcome type.
if (all(y == 0 | y == m)) {
signed_predictors <- (2 * (y / m) - 1) * drop(X %*% beta)
if (all(signed_predictors > 1e-8)) return("complete_separation")
}
}
NULL
}
The next definition replaces the provisional irls <- irls_unit alias from Sections 2.3 and 2.4. It follows glm.fit() in computing the working response and weights and in halving steps when needed (code/NOTICE.md). Its arguments are a model and a control list; it constructs its starting means from the observed responses. IRLS starts with means for individual rows. For $y_i$ successes in $m_i$ trials, the initial probability is $(y_i+0.5)/(m_i+1)$. In the binomial calculation y stores proportions and weights stores trial totals. Accordingly, mu is a per-trial probability here; the expected success count is the trial total times mu. For Poisson counts, y stores counts, mu is an expected count and the initial mean is $y_i+0.1$. The family object supplies linkfun, linkinv and mu.eta for the link function, inverse link function and derivative of the inverse link function. It evaluates the variance function with variance and the deviance contributions with dev.resids. The starting means determine the first working weights. In the first binomial group the initial probability is $2.5/11$, whereas Newton from zero assigns it probability $1/2$.
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
irls <- function(model, control = list()) {
settings <- modifyList(list(epsilon = 1e-8, maxit = 25L), control)
stopifnot(all(names(settings) %in% c("epsilon", "maxit")))
family <- if (model$family == "binomial") stats::binomial() else stats::poisson()
X <- model$X
if (model$family == "binomial") {
weights <- model$trials
# Convert counts to proportions before constructing initial probabilities.
y <- ifelse(weights > 0, model$y / pmax(weights, 1), 0)
mustart <- (weights * y + 0.5) / (weights + 1)
} else {
weights <- rep(1, length(model$y))
y <- model$y
mustart <- y + 0.1
}
valid_mu <- function(mu) all(is.finite(mu)) &&
if (model$family == "binomial") all(mu > 0 & mu < 1) else all(mu > 0)
deviance <- function(mu) sum(family$dev.resids(y, mu, weights))
eta <- family$linkfun(mustart)
mu <- family$linkinv(eta)
dev_old <- deviance(mu)
coef_old <- NULL
coef <- rep(NA_real_, ncol(X))
history <- list()
converged <- FALSE
step_halved <- FALSE
reason <- "iteration_limit"
iterations <- 0L
dependent <- integer(0)
decomposition <- list(rank=NA_integer_,pivot=seq_len(ncol(X)))
The fixed input weights, called prior weights in R, are the trial totals for binomial proportions and one per Poisson observation here. They describe observation weights rather than a prior distribution for coefficients. For rows with positive input weight and nonzero mean derivative, form the working response z. Here w is the square root of the working weight. Multiply each informative design row and its working response by that same number. For deviance tolerance $\epsilon$, solve by pivoted QR with tolerance $\min(10^{-7},\epsilon/1000)$ and put zero in each dependent position before computing predictions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
for (iter in seq_len(settings$maxit)) {
iterations <- iter
mu_eta <- family$mu.eta(eta)
# Use square-root working weights on both sides of the least-squares problem.
good <- weights > 0 & mu_eta != 0
z <- (y - mu)[good] / mu_eta[good] + eta[good] # working response
w <- sqrt(mu_eta[good]^2 * weights[good] / family$variance(mu)[good])
decomposition <- qr(X[good, , drop = FALSE] * w,
tol = min(1e-7, settings$epsilon / 1000),
LAPACK = FALSE)
start <- drop(qr.coef(decomposition, z * w))
dependent <- setdiff(seq_len(ncol(X)),
decomposition$pivot[seq_len(decomposition$rank)])
start[dependent] <- 0
if (any(!is.finite(start))) {
reason <- "nonfinite_coefficients"
break
}
eta <- drop(X %*% start)
mu <- family$linkinv(eta)
dev <- deviance(mu)
halvings <- 0L
step_halved <- FALSE
If the deviance is nonfinite or the fitted means leave their domain, move halfway back to the previous coefficients and reevaluate. An invalid first step stops the routine because no previous coefficient vector is available for halving. A finite increase in deviance with valid means leaves the proposed step intact.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Correct a nonfinite deviance first, then an invalid fitted mean.
for (stage in 1:2) {
invalid <- function() if (stage==1L) !is.finite(dev) else !valid_mu(mu)
if (!invalid()) next
if (is.null(coef_old))
stop("no valid set of coefficients has been found",
call.=FALSE)
warning(if(stage==1L) "step size truncated due to divergence" else
"step size truncated: out of bounds",
call.=FALSE)
used <- 0L
while (invalid()) {
if (used >= settings$maxit) stop(sprintf(
"inner loop %d; cannot correct step size",stage),call.=FALSE)
used <- used + 1L
start <- (start + coef_old) / 2
eta <- drop(X %*% start)
mu <- family$linkinv(eta)
if(stage==1L) dev <- deviance(mu)
}
if(stage==2L) dev <- deviance(mu)
halvings <- halvings + used
step_halved <- TRUE
}
For successive deviances $D_{\rm old}$ and $D$, the stopping test is $\vert D-D_{\rm old}\vert /(\vert D\vert +0.1)<\epsilon$, with $\epsilon=10^{-8}$ and at most 25 iterations by default. Save the coefficient vector used for prediction in working_par before marking dependent entries NA in the reported vector. The returned step_halved flag records whether the final iteration required step halving.
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
coef <- start
history[[length(history) + 1L]] <- list(iteration = iter, par = coef, deviance = dev,
halvings = halvings)
if (abs(dev - dev_old) / (abs(dev) + 0.1) < settings$epsilon) {
converged <- TRUE
reason <- "small_deviance_change"
break
}
dev_old <- dev
coef_old <- coef
}
value <- if (all(is.finite(coef))) model$fn(coef) else NA_real_
gradient <- if (all(is.finite(coef))) model$gr(coef) else rep(NA_real_, ncol(X))
result <- new_result(coef, value, gradient, converged, reason, iterations,
c(objective = 1L, gradient = 1L, hessian = 0L), history)
result$deviance <- if (length(history)) tail(history, 1)[[1]]$deviance else NA_real_
result$step_halved <- step_halved
# Preserve coefficients used for prediction before marking dependent columns.
result$working_par <- coef
result$rank <- decomposition$rank
result$pivot <- decomposition$pivot
result$fitted.values <- mu
result$par[dependent] <- NA_real_
result
}
The function fit_glm() runs Newton or iteratively reweighted least squares (IRLS) and attaches the diagnosis and named coefficients. Each element of log_lik_contributions is the contribution of one row to the log likelihood, the log probability of its observed count. For prediction, use working_par when IRLS supplies it. This is the coefficient vector used internally to form linear predictors: it has zeros in positions corresponding to dependent columns, while the reported par has missing values in those positions. Otherwise use the returned coefficient vector. The metadata value method = "exact" refers to evaluating the specified binomial or Poisson log likelihood without a numerical integration approximation; the coefficient estimates are still obtained by numerical iteration.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fit_glm <- function(model, method = "newton", par = rep(0, ncol(model$X)),
control = list()) {
stopifnot(method %in% c("newton", "irls"))
answer <- if (method == "newton") newton(model$fn, model$gr, model$he,
par, control) else
irls(model, control)
# Use finite working coefficients for the per-row log probabilities.
working <- if (is.null(answer$working_par)) answer$par else answer$working_par
eta <- drop(model$X %*% working)
contributions <- if (model$family == "binomial") {
lchoose(model$trials, model$y) - model$y * log1pexp(-eta) -
(model$trials - model$y) * log1pexp(eta)
} else model$y * eta - exp(eta) - lgamma(model$y + 1)
c(answer, list(coefficients = setNames(answer$par, colnames(model$X)),
diagnosis = glm_diagnosis(model, answer$par),
constraints = "Unrestricted regression coefficients; full column rank required",
log_lik_contributions = contributions,
approximation = list(method = "exact", dispersion = 1), optimizer = answer))
}
Interpreting convergence and failure
A stopping condition reports why an iteration ended. The score and the rank of the information describe the returned point. The design determines whether different coefficients represent identical linear predictors or a direction separates the outcomes. The following fits leave the likelihood unpenalized because a penalty would change the estimation problem.
Five runs compare three designs. LOGIT3 is fitted by Newton, by IRLS and by Newton limited to one update. The separated responses and a version of LOGIT3 with a duplicated slope column are fitted by Newton.
1
2
3
4
5
6
7
8
9
10
11
12
final_newton <- fit_glm(binomial_model)
final_irls <- irls(binomial_model)
separated_fit <- fit_glm(separated)
limited_fit <- fit_glm(binomial_model, control = list(maxit = 1L))
singular_model <- make_glm(cbind(X, duplicate = X[, 2]), y, "binomial", trials)
singular_fit <- fit_glm(singular_model)
fits <- list(newton = final_newton, irls = final_irls,
separated = separated_fit, limited = limited_fit, singular = singular_fit)
print(data.frame(case = names(fits),
converged = vapply(fits, function(fit) fit$converged, logical(1)),
reason = vapply(fits, function(fit) fit$reason, character(1)),
iterations = vapply(fits, function(fit) fit$iterations, numeric(1))))
1
2
3
4
5
6
case converged reason iterations
newton newton TRUE converged 4
irls irls TRUE small_deviance_change 3
separated separated TRUE converged 18
limited limited FALSE iteration_limit 1
singular singular TRUE converged 4
On the ordinary data, Newton met its gradient tolerance in four iterations from zero. IRLS took three from its family starting means, stopping on relative deviance change. The one-iteration run reached its limit. Newton reported code 1 for both the separated data after 18 iterations and the duplicated column after four. For the separated observations, the signs along $b$ establish separation directly.
1
2
3
4
5
# For these four rows the slope direction separates all successes from failures.
# A different design may require a different direction or a feasibility test.
separating_direction <- c(0, 1)
print(data.frame(x=separated_X[,2],y=separated_y,
signed_linear_predictor=(2*separated_y-1)*drop(separated_X%*%separating_direction)))
1
2
3
4
5
x y signed_linear_predictor
1 -2 0 2
2 -1 0 1
3 1 1 1
4 2 1 2
All four products are positive. The endpoint score norms and information ranks give additional diagnostics for each design.
1
2
3
4
5
6
7
8
9
10
11
12
pairs <- list(regular=list(binomial_model,final_newton),
separated=list(separated,separated_fit),
duplicate_column=list(singular_model,singular_fit))
print(do.call(rbind,lapply(names(pairs),function(design) {
model <- pairs[[design]][[1]]
fit <- pairs[[design]][[2]]
data.frame(design,diagnosis=if(is.null(fit$diagnosis)) NA_character_ else fit$diagnosis,
optimizer_status=fit$reason,max_abs_score=max(abs(model$gr(fit$par))),
information_rank=qr(model$he(fit$par))$rank,
conclusion=switch(design,regular="unique finite MLE",separated="no finite MLE",
duplicate_column="coefficients not unique"))
})),row.names=FALSE)
1
2
3
4
5
6
7
8
design diagnosis optimizer_status max_abs_score information_rank
regular <NA> converged 6.569438e-10 2
separated complete_separation converged 3.636565e-08 2
duplicate_column rank_deficient_design converged 6.582006e-10 2
conclusion
unique finite MLE
no finite MLE
coefficients not unique
The conclusion column is written into the example; the following explanation supports each entry. For the original two-column LOGIT3 design, the largest absolute score component is $6.57\times10^{-10}$ at the numerical solution. At $(0,\log 4)^\top$ the fitted counts match the observations exactly. Positive binomial weights and independent design columns give strict convexity there and throughout the finite parameter space, hence a unique estimate. Under separation, the largest absolute score component is only $3.64\times10^{-8}$ and the information still has rank two at the returned point, yet the signed linear predictors establish that the likelihood continues to increase along $b$. With the duplicate, the largest absolute score component is $6.58\times10^{-10}$. The model has three coefficients and information rank two. The linear predictor depends on the slopes through their sum, so transferring any amount from one slope to the other preserves the fitted probabilities. The usual standard errors based on the inverse information require a positive definite information matrix at the finite maximum likelihood estimate, together with the large-sample assumptions described in Section 2.1. At the fitted intercept, every slope pair with the fitted sum attains the minimum even though the Hessian is singular. The stats package supplies Newton minimization and IRLS fitting for generalized linear models.
2.7 Checking coefficients and standard errors against existing GLM fits
The functions of this chapter have so far been checked against known solutions and their own diagnostics. For the three LOGIT3 groups, the information at the finite maximum likelihood estimate gives standard errors for the intercept and slope. Does a second implementation give the same coefficients and standard errors? The stats package provides iteratively reweighted least squares (IRLS) through glm(). Open a fresh R session in the book directory. Fit the grouped counts by Newton and IRLS.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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")
LOGIT3 <- read.csv("data/source/LOGIT3.csv")
X <- cbind(intercept = 1, x = LOGIT3$x)
y <- LOGIT3$successes
trials <- LOGIT3$trials
beta_zero <- c(0, 0)
binomial_model <- make_glm(X, y, "binomial", trials)
beta_exact <- c(0, log(4))
he <- binomial_model$he
final_newton <- fit_glm(binomial_model)
final_irls <- irls(binomial_model)
The matrix X has a column of ones and a column of covariate values. In the formula interface, an intercept is included by default. Give glm() two response columns, successes followed by failures. For a row with $y_i$ successes in $m_i$ trials, binomial() uses the proportion $y_i/m_i$ and prior weight $m_i$, so it represents the same successes and failures as the grouped count. Both IRLS fits start from the family means and use a relative deviance tolerance of $10^{-8}$ within 25 iterations. Newton starts at zero and uses scaled-gradient and relative-step tolerances of $10^{-6}$ within 100 iterations. The book’s irls() follows glm.fit() in its working response and weights and in its step halving (code/NOTICE.md), so agreement of the two IRLS fits checks that translation (Section E.3); the Newton fit computes updates from the analytic gradient and Hessian and selects their lengths by line search.
Fit the reference logit model. Place the exact coefficients $(0,\log 4)^\top$ beside both estimates. For the Newton fit, take the diagonal of the inverse observed information at the returned coefficients. The square root of each diagonal entry is the standard error of that coefficient. For the reference fit, obtain the covariance matrix with vcov().
1
2
3
4
5
6
reference_logit <- stats::glm(cbind(successes, trials - successes) ~ x,
family = binomial("logit"), data = LOGIT3)
print(cbind(book = final_newton$par, reference = coef(reference_logit),
analytic = beta_exact,
book_se = sqrt(diag(solve(he(final_newton$par)))),
reference_se = sqrt(diag(vcov(reference_logit)))))
1
2
3
book reference analytic book_se reference_se
(Intercept) 6.485228e-18 2.447173e-16 0.000000 0.4188539 0.4188528
x 1.386294e+00 1.386294e+00 1.386294 0.5590170 0.5590144
Both slopes equal 1.386294 to six decimal places, but their standard errors are 0.5590170 for Newton and 0.5590144 for the reference fit. The Newton calculation evaluates information at the returned coefficients. To obtain the covariance, vcov() uses the QR decomposition saved by glm(). The final weighted least-squares update used weights from the preceding coefficient vector. Recomputing the reference weights at its final coefficients will separate this evaluation-point difference from disagreement between estimates.
The maximized values of the full log likelihood function and the Newton score vector provide further comparisons.
1
2
3
print(c(book_log_lik = -final_newton$value,
reference_log_lik = as.numeric(logLik(reference_logit)),
max_abs_score = max(abs(final_newton$gradient))))
1
2
book_log_lik reference_log_lik max_abs_score
-3.796766e+00 -3.796766e+00 6.569438e-10
Both fits give $-3.796766$. The book calculation includes $\log\binom{m_i}{y_i}$ for each group. The binomial calculation underlying logLik() uses the count probabilities from dbinom(), including the same constants. The largest absolute score component is about $6.6\times10^{-10}$.
Observed responses in three R datasets
The model for the three LOGIT3 groups has two coefficients and a known exact solution. Three datasets distributed with R extend the comparison to observed responses with more coefficients: grouped case and control counts in esoph, individual binary outcomes in infert and Poisson counts in warpbreaks.
In esoph, one row gives case and control counts for a combination of age, alcohol consumption and tobacco consumption. The R dataset documentation describes the study. The binomial response is the case count, with the sum of cases and controls as the trial total. Its probability is that of case status within this case-control sample. Model its log odds as the sum of an intercept and indicators for the three grouping variables.
All three grouping variables are ordered factors. R ordinarily uses polynomial contrasts for ordered factors. Set treatment contrasts explicitly, with the first level as the baseline, and retain these contrasts for the reference fit. The intercept is the log odds for ages 25–34, alcohol consumption of 0–39 grams per day and tobacco consumption of 0–9 grams per day. Each indicator coefficient is a log odds difference from that variable’s baseline, with the other two groups fixed. Exponentiating it gives the corresponding odds ratio.
1
2
3
4
5
6
7
8
9
10
11
esoph_data <- datasets::esoph
esoph_contrasts <- lapply(esoph_data[c("agegp", "alcgp", "tobgp")],
function(x) contr.treatment(levels(x), base = 1))
esoph_X <- model.matrix(~ agegp + alcgp + tobgp, esoph_data,
contrasts.arg = esoph_contrasts)
esoph_trials <- with(esoph_data, ncases + ncontrols)
esoph_model <- make_glm(esoph_X, esoph_data$ncases, "binomial", esoph_trials)
esoph_fit <- fit_glm(esoph_model)
esoph_irls <- irls(esoph_model)
print(c(rows = nrow(esoph_X), columns = ncol(esoph_X),
cases = sum(esoph_data$ncases), controls = sum(esoph_data$ncontrols)))
1
2
rows columns cases controls
88 12 200 775
The 88 groups contain 200 cases and 775 controls. The intercept and factor indicators give 12 Newton coefficients on the log odds scale.
1
print(round(setNames(esoph_fit$par, colnames(esoph_X)), 6))
1
2
3
4
(Intercept) agegp35-44 agegp45-54 agegp55-64 agegp65-74 agegp75+ alcgp40-79 alcgp80-119
-6.895413 1.980883 3.776285 4.335180 4.896404 4.826540 1.434629 1.980717
alcgp120+ tobgp10-19 tobgp20-29 tobgp30+
3.602869 0.438052 0.512618 1.640997
At fixed age and tobacco group, alcgp120+ gives a log odds ratio for case status of 3.602869 comparing consumption of at least 120 grams per day with 0 to 39 grams per day in this case-control sample.
In infert, each row records one woman’s case status, one for a secondary infertility case and zero for a control. The R dataset documentation describes how controls were matched to cases. Fit an ordinary logistic regression for the probability of case status in this sample, with age, parity, education and two measures of previous abortions. The model uses a common intercept across matched sets, so its coefficients describe associations without conditioning on set membership.
Age is measured in years. The variable parity records the study’s count of previous pregnancies, including those ending in abortion. Their slopes give changes in log odds per additional year and per additional recorded pregnancy, respectively, with the other covariates fixed. The reference education group has zero to five years; the two education coefficients give log odds differences for six to eleven years and twelve or more years relative to that reference, at fixed values of the other covariates.
Each abortion variable is coded 0, 1 or 2, with 2 meaning two or more. Entering these codes numerically assigns the same log odds change to moving from 0 to 1 as from 1 to 2. The intercept is the log odds at the formal reference condition of age zero, parity zero and both abortion codes zero in the reference education group.
1
2
3
4
5
6
7
8
9
10
infert_data <- datasets::infert
infert_contrasts <- list(education = contr.treatment(levels(infert_data$education),
base = 1))
infert_X <- model.matrix(~ age + parity + education + spontaneous + induced,
infert_data, contrasts.arg = infert_contrasts)
infert_model <- make_glm(infert_X, infert_data$case)
infert_fit <- fit_glm(infert_model)
infert_irls <- irls(infert_model)
print(c(rows = nrow(infert_X), columns = ncol(infert_X),
cases = sum(infert_data$case), strata = length(unique(infert_data$stratum))))
1
2
rows columns cases strata
248 7 83 83
There are 83 cases among 248 people. Tabulating case status within stratum gives 82 sets with one case and two controls and one set containing just a case and its single control. The dataset documentation uses ordinary logistic regression as an example and recommends conditional logistic regression to account for matching.
1
print(round(setNames(infert_fit$par, colnames(infert_X)), 6))
1
2
3
4
(Intercept) age parity education6-11yrs education12+ yrs
-1.149237 0.039582 -0.828277 -1.044244 -1.403205
spontaneous induced
2.045905 1.288757
The Newton fit gives an intercept of $-1.149237$ and slopes of 0.039582 for age and $-0.828277$ for parity. Compared with zero to five years of education, the fitted log odds differences are $-1.044244$ for six to eleven years and $-1.403205$ for twelve or more, with the other covariates fixed. The spontaneous and induced abortion slopes, 2.045905 and 1.288757, are adjusted changes in log odds per unit increase in the recorded code. Thus each describes both the contrast between no abortions and one, and the contrast between one and two or more, under the model’s linear specification.
In warpbreaks, each loom observation counts yarn breaks during weaving over a fixed length of yarn. The R dataset documentation gives the source of the counts. Model these as independent Poisson counts, with the log mean equal to an intercept plus wool-type and tension indicators. Treatment contrasts make wool A and low tension the reference levels. The intercept is their log expected number of breaks. At fixed tension, exponentiating the wool B coefficient gives its mean count divided by the mean for wool A. At fixed wool type, exponentiating either tension coefficient compares its mean with that at low tension. With no interaction, each ratio is common across levels of the other factor. Exponentiating the Newton linear predictors gives the fitted means.
1
2
3
4
5
6
7
8
9
warp_data <- datasets::warpbreaks
warp_contrasts <- lapply(warp_data[c("wool", "tension")],
function(x) contr.treatment(levels(x), base = 1))
warp_X <- model.matrix(~ wool + tension, warp_data, contrasts.arg = warp_contrasts)
warp_model <- make_glm(warp_X, warp_data$breaks, "poisson")
warp_fit <- fit_glm(warp_model)
warp_irls <- irls(warp_model)
warp_mu <- exp(drop(warp_X %*% warp_fit$par))
print(round(setNames(warp_fit$par, colnames(warp_X)), 6))
1
2
(Intercept) woolB tensionM tensionH
3.691963 -0.205988 -0.321320 -0.518488
At fixed tension, the wool B coefficient is negative, and both higher tensions have lower fitted means than low tension at fixed wool type. The Pearson statistic sums squared count residuals divided by their fitted Poisson means, measuring variation about those means relative to the model’s variances. Divide by the residual degrees of freedom, the number of observations minus the number of estimated coefficients here, to obtain a ratio for comparison with the Poisson value of one.
1
print(sum((warp_data$breaks - warp_mu)^2 / warp_mu) / (nrow(warp_X) - ncol(warp_X)))
1
[1] 4.261522
Under the fitted Poisson model, the Pearson statistic’s approximate expectation in large samples is $54-4=50$, the residual degrees of freedom. Here the statistic is about $50\times4.261522=213.08$. The ratio 4.261522 estimates $\phi$ under $\operatorname{Var}(Y_i)=\phi\mu_i$, well above the Poisson value of one. The compared standard errors still fix dispersion at one. For event counts in social research, observation periods or opportunities must be comparable or explicitly accounted for, with independent units and a suitable variance assumption. Agreement between implementations establishes none of these conditions.
Coefficients and standard errors across the four datasets
Fit the remaining reference models with the same contrasts and assemble the four comparisons.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
reference_esoph <- stats::glm(cbind(ncases, ncontrols) ~ agegp + alcgp + tobgp,
data = esoph_data, family = binomial(), contrasts = esoph_contrasts)
reference_infert <- stats::glm(case ~ age + parity + education + spontaneous + induced,
data = infert_data, family = binomial(), contrasts = infert_contrasts)
reference_warp <- stats::glm(breaks ~ wool + tension,
data = warp_data, family = poisson(), contrasts = warp_contrasts)
models <- list(LOGIT3 = binomial_model, esoph = esoph_model,
infert = infert_model, warpbreaks = warp_model)
newton_fits <- list(final_newton, esoph_fit, infert_fit, warp_fit)
irls_fits <- list(final_irls, esoph_irls, infert_irls, warp_irls)
references <- list(reference_logit, reference_esoph, reference_infert, reference_warp)
comparison <- data.frame()
coefficient_comparison <- list()
for (i in seq_along(models)) {
model <- models[[i]]
reference <- references[[i]]
stopifnot(identical(colnames(model$X), colnames(model.matrix(reference))) || i == 1L)
At each final reference linear predictor $\eta_i$, compute the mean $\mu_i$ and its derivative. Multiply the prior weight by $(d\mu_i/d\eta_i)^2/V(\mu_i)$, where $V$ is the family variance function. The checks match design entries and binomial trial totals. The intercept column has the label intercept in X and (Intercept) in the reference design for LOGIT3. Put the recomputed weights on the diagonal of $W$. For these full-rank fits with dispersion fixed at one, the diagonal of $(X^\top W X)^{-1}$ gives estimated sampling variances evaluated at the final reference coefficients.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
eta_reference <- reference$linear.predictors
mean_reference <- reference$family$linkinv(eta_reference)
weight_reference <- reference$prior.weights * reference$family$mu.eta(eta_reference)^2 /
reference$family$variance(mean_reference)
# Match the design rows and the binomial trial totals.
stopifnot(isTRUE(all.equal(unname(model$X), unname(model.matrix(reference)),
check.attributes = FALSE)))
if (model$family == "binomial") {
stopifnot(isTRUE(all.equal(unname(model$trials), unname(reference$prior.weights))))
}
# reference_current_se: the reference fit's design and prior weights, with working
# weights at its final linear predictor.
reference_current_se <- sqrt(diag(solve(crossprod(model$X,
weight_reference * model$X))))
For each book fit, compute standard errors at its own estimate. Compare them with the recomputed reference errors and with those from vcov(). The two reference calculations use the same design and dispersion but evaluate their weights at the different coefficient vectors described at the first LOGIT3 comparison.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
for (method in c("Newton", "IRLS")) {
fit <- if (method == "Newton") newton_fits[[i]] else irls_fits[[i]]
# Evaluate the book information at this fit's coefficients.
se <- sqrt(diag(solve(model$he(fit$par))))
coefficient_comparison[[length(coefficient_comparison)+1L]] <- data.frame(
dataset=names(models)[i],
term=colnames(model$X),method,estimate=fit$par,
reference_estimate=as.numeric(coef(reference)),
SE=se,reference_SE_recomputed=reference_current_se,
loglik=-fit$value,reference_loglik=as.numeric(logLik(reference)))
# Summarize absolute differences for this dataset and method.
comparison <- rbind(comparison, data.frame(data = names(models)[i], method,
converged = fit$converged, beta_difference = max(abs(fit$par - coef(reference))),
log_lik_difference = abs(-fit$value - as.numeric(logLik(reference))),
se_difference_vcov = max(abs(se - sqrt(diag(vcov(reference))))),
se_difference_recomputed = max(abs(se - reference_current_se))))
}
}
print(comparison, digits = 3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
data method converged beta_difference log_lik_difference se_difference_vcov
1 LOGIT3 Newton TRUE 1.32e-10 0.00e+00 2.62e-06
2 LOGIT3 IRLS TRUE 0.00e+00 0.00e+00 2.62e-06
3 esoph Newton TRUE 1.74e-06 1.49e-12 2.16e-06
4 esoph IRLS TRUE 0.00e+00 1.42e-14 2.93e-06
5 infert Newton TRUE 2.43e-09 2.84e-14 1.40e-05
6 infert IRLS TRUE 0.00e+00 2.84e-14 1.40e-05
7 warpbreaks Newton TRUE 1.74e-08 1.14e-13 1.15e-07
8 warpbreaks IRLS TRUE 0.00e+00 0.00e+00 1.15e-07
se_difference_recomputed
1 2.22e-11
2 0.00e+00
3 7.70e-07
4 8.44e-15
5 4.41e-10
6 2.53e-14
7 3.51e-10
8 0.00e+00
Each coefficient or standard-error difference is the maximum absolute difference across terms. The absolute difference between the two maximized values of the full log likelihood function is largest for the esoph Newton fit, about $1.49\times10^{-12}$. The largest Newton coefficient difference is also on esoph, $1.74\times10^{-6}$. The following call prints $2(2+12+7+4)=50$ coefficient rows. The excerpt shows only the two esoph Newton rows needed to locate the maxima.
1
2
coefficient_comparison <- do.call(rbind,coefficient_comparison)
print(coefficient_comparison,row.names=FALSE)
1
2
3
4
5
6
dataset term method estimate reference_estimate SE
esoph (Intercept) Newton -6.895413e+00 -6.895415e+00 1.08594000
esoph agegp55-64 Newton 4.335180e+00 4.335182e+00 1.06505085
reference_SE_recomputed loglik reference_loglik
1.08594076 -98.695896 -98.695896
1.06505162 -98.695896 -98.695896
The largest coefficient difference occurs at the intercept. The largest standard-error difference falls from $2.16\times10^{-6}$ using vcov() to $7.70\times10^{-7}$ using the final reference weights. The latter occurs at agegp55-64, with 1.06505085 at the Newton estimate and 1.06505162 at the reference estimate. Recomputing the weights reduces the standard-error difference in every comparison. For IRLS, the coefficients agree exactly in all four datasets. On infert, its largest standard-error difference is $1.40\times10^{-5}$ using standard errors from the stored QR decomposition. When both calculations use the final coefficients, the largest absolute difference across all four IRLS fits is about $2.53\times10^{-14}$.