Building logistic regression with IRLS

From the score equations to simulation-based checks of asymptotic approximations

Statistics
Generalised Linear Models
Statistical Computing
I derived and implemented a Bernoulli logistic-regression fitter, then examined what its sampling distributions actually looked like.

I derived the score and Fisher information for Bernoulli logistic regression, used them to implement IRLS in R, then simulated the sampling distributions of the fitted coefficients and deviance.

The two parts answered different questions. A large simulated dataset let me check the implementation against known coefficients. A second experiment, with only 30 observations and fixed predictors, exposed a substantial mismatch between the deviance distribution and its usual chi-squared reference. The coefficient distributions agreed more closely with their normal approximations near the centre.

Light-blue histogram of simulated deviances concentrated towards the upper end of the plotted range, with a broader navy chi-squared density peaking further left.
Figure 1: Simulated Bernoulli deviances with the chi-squared reference density overlaid.

The Bernoulli model

For observation \(i\), I used

\[ Y_i\sim\operatorname{Bernoulli}(\pi_i),\qquad \eta_i=\mathbf{x}_i^{\mathsf T}\boldsymbol\beta =\operatorname{logit}(\pi_i). \]

The inverse link, mean and variance are

\[ \pi_i=\frac{e^{\eta_i}}{1+e^{\eta_i}},\qquad \mu_i=\pi_i,\qquad \operatorname{Var}(Y_i)=\pi_i(1-\pi_i). \]

The design matrix \(X\) contains the predictor row vectors \(\mathbf{x}_i^{\mathsf T}\). For the intercept-and-slope examples, its two columns are a column of ones and the observed predictor values.

Deriving the score

Starting from the general GLM score equation,

\[ U_j(\boldsymbol\beta)=\sum_{i=1}^{n} \frac{y_i-\mu_i}{\operatorname{Var}(Y_i)} \frac{\partial\mu_i}{\partial\eta_i}x_{ij}, \]

the derivative of the inverse logit is

\[ \frac{\partial\mu_i}{\partial\eta_i} =\frac{e^{\eta_i}}{(1+e^{\eta_i})^2} =\pi_i(1-\pi_i). \]

The derivative and Bernoulli variance cancel in the score, leaving

\[ U_j(\boldsymbol\beta)=\sum_{i=1}^{n}(y_i-\pi_i)x_{ij}, \qquad \mathbf U(\boldsymbol\beta)=X^{\mathsf T}(\mathbf y-\boldsymbol\pi). \]

Fisher information and weights

The GLM weights are

\[ w_i=\frac{1}{\operatorname{Var}(Y_i)} \left(\frac{\partial\mu_i}{\partial\eta_i}\right)^2 =\pi_i(1-\pi_i). \]

With \(W=\operatorname{diag}(w_1,\ldots,w_n)\), the Fisher information is

\[ I(\boldsymbol\beta)=X^{\mathsf T}WX. \]

Both the score and the information depend on \(\boldsymbol\beta\) through the fitted probabilities. That is why I update the weights as the coefficient estimate changes.

Turning the equations into IRLS

At iteration \(t\), I form the working response

\[ \mathbf z^{(t)}=X\boldsymbol\beta^{(t)}+\mathbf u^{(t)}, \qquad u_i^{(t)}=\frac{y_i-\pi_i^{(t)}}{\pi_i^{(t)}(1-\pi_i^{(t)})}. \]

The next estimate solves the weighted least-squares system

\[ X^{\mathsf T}W^{(t)}X\boldsymbol\beta^{(t+1)} =X^{\mathsf T}W^{(t)}\mathbf z^{(t)}. \]

I initialise the coefficients at zero and stop when

\[ \max_j\left|\beta_j^{(t+1)}-\beta_j^{(t)}\right|<10^{-6}, \]

or when the loop reaches 1,000 iterations. I then recompute the information matrix at the final estimate.

The original R fitter

The R function below implements the iteration and returns the fitted coefficients and final information matrix.

fit_logistic <- function(X, y) {
  num_obs = nrow(X)
  num_predictors = ncol(X)
  beta = rep(0, num_predictors)
  tol = 1e-6
  converged = FALSE

  for (i in 1:1000) {
    eta = as.vector(X %*% beta)
    pi = exp(eta)/(1+exp(eta))
    weights = pi*(1-pi)
    W_matrix = diag(weights)
    u = (y-pi)/(weights)
    z_pseudodata = eta + u
    info_mat = t(X) %*% W_matrix %*% X
    beta_new = as.vector(
      solve(info_mat, t(X) %*% W_matrix %*% z_pseudodata)
    )
    if (max(abs(beta_new - beta)) < tol) {
      beta = beta_new
      converged = TRUE
      break
    }
    beta = beta_new
  }
  if (!converged) {
    print("ran for all iterations, without converging.")
  }
  eta = as.vector(X %*% beta)
  pi = exp(eta)/(1+exp(eta))
  weights = pi*(1-pi)
  W_matrix = diag(weights)
  info_mat = t(X) %*% W_matrix %*% X
  return(list(beta = beta, info_mat = info_mat))
}

The matching simulation function keeps the supplied design matrix and draws one Bernoulli response for each row:

sim_logistic <- function(X, beta) {
  num_obs = nrow(X)
  eta = as.vector(X %*% beta)
  pi = exp(eta)/(1+exp(eta))
  y = rbinom(num_obs, size=1, prob=pi)
  return(list(X = X, y = y))
}

Checking the fitter against known parameters

For the first check, I simulated \(n=10{,}000\) observations with \(x_i\sim U(-1,1)\) and chose

\[ \boldsymbol\beta^*=\begin{bmatrix}0&1\end{bmatrix}^{\mathsf T}. \]

The report used seed 888. The fitted results were:

Coefficient True value MLE Estimated standard error
\(\beta_0\) 0 -0.00637904 0.02090296
\(\beta_1\) 1 1.06175740 0.03756057

I obtained the standard errors from the inverse information matrix:

\[ \widehat{\operatorname{Cov}}(\widehat{\boldsymbol\beta}) =I(\widehat{\boldsymbol\beta})^{-1},\qquad \widehat{\operatorname{SE}}(\widehat\beta_j) =\sqrt{\left[I(\widehat{\boldsymbol\beta})^{-1}\right]_{jj}}. \]

The estimates were reasonably close to the generating coefficients, providing the implementation check I wanted before moving to the smaller dataset.

n = 10000
x = runif(n,-1,1)
X = cbind(1,x)
beta = c(0,1)
sim_data = sim_logistic(X,beta)
fit_model = fit_logistic(sim_data$X, sim_data$y)
beta_estimates = fit_model$beta
info_mat = fit_model$info_mat
inverted_info_mat = solve(info_mat)
se_beta = sqrt(diag(inverted_info_mat))

Holding the predictors fixed

I next fitted the supplied 30-observation dataset and plotted the fitted curve.

Binary responses plotted at zero and one, with a gently increasing navy fitted logistic curve.
Figure 2: Observed binary responses and the fitted logistic curve.

For the sampling-distribution experiment, I retained its predictor matrix \(X_2\) and generated 10,000 new response vectors under \(\boldsymbol\beta^*=(0,1)^{\mathsf T}\). Fixing \(X_2\) makes this a study of sampling variation conditional on those predictors. Regenerating the predictors would introduce a second source of variation.

Each simulated dataset was fitted with R’s glm, and I stored both estimated coefficients and the deviance. This separates the sampling-distribution experiment from the custom-fitter implementation check.

x_2 = data$x
y_2 = data$y
X_2 = cbind(1,x_2)
beta_true_2 = c(0,1)
num_simulations = 10000
beta_0_samples = rep(0, num_simulations)
beta_1_samples = rep(0, num_simulations)
deviance_samples = rep(0, num_simulations)

for (i in 1:num_simulations) {
  sim_data_2 = sim_logistic(X_2, beta_true_2)
  fit_model_2 = glm(sim_data_2$y ~ x_2,
                    family = binomial(link = "logit"))
  beta_0_samples[i] = fit_model_2$coefficients[1]
  beta_1_samples[i] = fit_model_2$coefficients[2]
  deviance_samples[i] = fit_model_2$deviance
}

What happened to the deviance approximation?

With \(n=30\) and two estimated coefficients, the reference distribution examined in the report was \(\chi^2_{28}\). Its density did not track the simulated histogram well. The report described a sharper simulated peak near 39, compared with the broader chi-squared reference peaking near 26.

The report connected this failure to the Bernoulli setting. Each response contains a single trial, so increasing the number of observations does not create large expected success and failure counts within each observation. The familiar chi-squared goodness-of-fit approximation therefore cannot be assumed to improve merely because the number of individual Bernoulli responses increases.

I also measured what would happen if I nevertheless used the reference distribution’s 95th percentile as a rejection threshold:

type_1_error = mean(deviance_samples > qchisq(0.95, df = 28))

All datasets were generated from the stated logistic model, so every rejection was a Type I error in this experiment. There were 367 rejections out of 10,000:

\[ \widehat\alpha=\frac{367}{10000}=0.0367. \]

The empirical rejection rate was 3.67%, below the nominal 5%. The mismatch in the overall density and this tail probability are different aspects of the same comparison; the histogram is important alongside the single rejection-rate estimate.

Coefficient distributions and the information matrix

For the coefficient reference curves, I used the asymptotic approximation

\[ \widehat{\boldsymbol\beta}_{\mathrm{MLE}} \overset{\mathrm{approx}}\sim \operatorname{MVN}\!\left(\boldsymbol\beta^*,I(\boldsymbol\beta^*)^{-1}\right). \]

Here the information is evaluated at the true generating coefficients, rather than at a fitted estimate:

\[ \pi_i^*=\frac{\exp(\mathbf x_i^{\mathsf T}\boldsymbol\beta^*)} {1+\exp(\mathbf x_i^{\mathsf T}\boldsymbol\beta^*)},\qquad W^*=\operatorname{diag}\{\pi_i^*(1-\pi_i^*)\},\qquad I(\boldsymbol\beta^*)=X_2^{\mathsf T}W^*X_2. \]

The diagonal entries of its inverse give the approximate marginal variances. Their square roots are the standard deviations used for the normal overlays, centred at 0 and 1 respectively.

Histogram of simulated intercept estimates concentrated around zero, overlaid with a normal density.
Figure 3: Sampling distribution of the intercept estimate, with its normal reference curve.
Histogram of simulated slope estimates concentrated near one, with a long plotted right tail and normal overlay.
Figure 4: Sampling distribution of the slope estimate, with its normal reference curve.

My report found reasonably good agreement around the central regions, although the intercept histogram had a sharper peak. It expected the coefficient approximation to improve with a substantially larger sample. That conclusion is separate from the Bernoulli deviance issue: the two approximations concern different statistics and have different requirements.

What the investigation established

The large-sample check recovered estimates close to the generating coefficients. With 30 observations and fixed predictors, the normal reference curves agreed reasonably well with the centres of the simulated coefficient distributions, while the chi-squared density described the deviance poorly.

The fixed-design experiment gave a 3.67% rejection rate at a nominal 5% threshold. That estimate applies to this simulation, not to other designs or sample sizes.

Originally completed as part of STA3048S · Statistical Modelling and Bayesian Analysis, University of Cape Town, 2026.