Generalized Linear Models › Example: Logistic Regression

Michael BrenndoerferApril 1, 202512 min read
Machine Learning from ScratchAll chapters
Part 4 of 9Regression Models
Chapter 40Generalized Linear Models › Example: Logistic Regression
Reading section 6 of 12 · Example: Logistic Regression · 12 minSection 6 of 12 · 12 min

Book contents

Section 6 of 12 · 12 min read

Generalized Linear Models › Example: Logistic RegressionOne section · Sections in this chapter6 / 12 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Let's work through a detailed example of logistic regression, which is one of the most common GLMs. Suppose we want to predict whether a student will pass an exam based on their study hours and previous test scores.

Data:

  • Study hours: [2, 3, 4, 5, 6, 7, 8]
  • Previous scores: [60, 65, 70, 75, 80, 85, 90]
  • Pass (1) or Fail (0): [0, 0, 1, 1, 1, 1, 1]

This is our model specification:

  • Distribution: Binomial
  • Link function: Logit
  • Model: log⁡(p1−p)=β0+β1⋅hours+β2⋅scores\log\left(\frac{p}{1-p}\right) = \beta_0 + \beta_1 \cdot \text{hours} + \beta_2 \cdot \text{scores}

Let's solve this step by step.

Step 1: Set up the design matrix

First, we organize our data into a matrix form suitable for regression. Each row of the matrix corresponds to one observation (student), and each column is a feature (including a column of 1s for the intercept). For our example, the features are:

  • Intercept (always 1)
  • Study hours
  • Previous test score

So, for our 7 students, the design matrix X\mathbf{X} looks like:

X=[1260136514701575168017851890]\mathbf{X} = \begin{bmatrix} 1 & 2 & 60 \\\\ 1 & 3 & 65 \\\\ 1 & 4 & 70 \\\\ 1 & 5 & 75 \\\\ 1 & 6 & 80 \\\\ 1 & 7 & 85 \\\\ 1 & 8 & 90 \end{bmatrix}

The corresponding response vector (whether the student passed) is:

y=[0011111]\mathbf{y} = \begin{bmatrix} 0 \\\\ 0 \\\\ 1 \\\\ 1 \\\\ 1 \\\\ 1 \\\\ 1 \end{bmatrix}

Step 2: Initialize coefficients

We start the iterative process by choosing initial values for the coefficients (the β\beta parameters). A common choice is to set all coefficients to zero:

β(0)=[000]\boldsymbol{\beta}^{(0)} = \begin{bmatrix} 0 \\\\ 0 \\\\ 0 \end{bmatrix}

This means our initial model predicts the same probability for all students, regardless of their features.

Step 3: IRLS (Iteratively Reweighted Least Squares) Iteration

The IRLS algorithm updates the coefficients in a series of steps, using the current estimate to improve the next one. For each iteration kk:

Note: The following steps are a detailed explanation of the IRLS algorithm to demonstrate the process. We will not go into the very specific details of the algorithm in this section. In reality, you would not compute the IRLS algorithm by hand. Modern statistical and machine learning libraries, including NumPy and scikit-learn as well as R packages, implement this algorithm efficiently.

  1. Calculate the linear predictor:
    Compute η(k)=Xβ(k)\boldsymbol{\eta}^{(k)} = \mathbf{X}\boldsymbol{\beta}^{(k)}.

    where:

    • η(k)\boldsymbol{\eta}^{(k)} is the vector of linear predictors at iteration kk (one entry per observation)
    • X\mathbf{X} is the n×(p+1)n \times (p+1) design matrix (each row is one observation)
    • β(k)\boldsymbol{\beta}^{(k)} is the coefficient vector at iteration kk
    • For the first iteration with β(0)=0\boldsymbol{\beta}^{(0)} = \mathbf{0}, all entries in η(0)\boldsymbol{\eta}^{(0)} equal 0
  2. Calculate fitted values (predicted probabilities):
    Apply the inverse link function (the logistic sigmoid for logistic regression) to get the predicted probability of passing for each student:

    μ(k)=g−1(η(k))=11+e−η(k)\boldsymbol{\mu}^{(k)} = g^{-1}(\boldsymbol{\eta}^{(k)}) = \frac{1}{1 + e^{-\boldsymbol{\eta}^{(k)}}}

    where:

    • μ(k)\boldsymbol{\mu}^{(k)} is the vector of fitted values (predicted probabilities) at iteration kk
    • g−1(⋅)g^{-1}(\cdot) is the inverse link function (for logistic regression, this is the logistic sigmoid function)
    • The formula is applied element-wise: μi(k)=11+e−ηi(k)\mu_i^{(k)} = \frac{1}{1 + e^{-\eta_i^{(k)}}} for each observation ii
    • For the first iteration with η(0)=0\boldsymbol{\eta}^{(0)} = \mathbf{0}, all predicted probabilities equal 0.5 (since 11+e0=12\frac{1}{1+e^0} = \frac{1}{2})
  3. Calculate the working response:
    This step creates a "pseudo-response" that allows us to use weighted least squares:

    z(k)=η(k)+y−μ(k)μ(k)(1−μ(k))\mathbf{z}^{(k)} = \boldsymbol{\eta}^{(k)} + \frac{\mathbf{y} - \boldsymbol{\mu}^{(k)}}{\boldsymbol{\mu}^{(k)}(1 - \boldsymbol{\mu}^{(k)})}

    where:

    • z(k)\mathbf{z}^{(k)} is the vector of working responses at iteration kk (adjusted target values for the weighted least squares step)
    • y\mathbf{y} is the vector of observed responses (actual outcomes: 0 or 1 for each observation)
    • y−μ(k)\mathbf{y} - \boldsymbol{\mu}^{(k)} is the residual vector (difference between actual and predicted values)
    • μ(k)(1−μ(k))\boldsymbol{\mu}^{(k)}(1 - \boldsymbol{\mu}^{(k)}) is computed element-wise and represents the variance of the Bernoulli distribution for each observation (i.e., Var(Yi)=μi(1−μi)\text{Var}(Y_i) = \mu_i(1-\mu_i))
    • Division is performed element-wise
  4. Calculate the weights:
    The weights for each observation are based on the variance of the predicted probability:

    W(k)=diag(μ(k)(1−μ(k)))\mathbf{W}^{(k)} = \text{diag}(\boldsymbol{\mu}^{(k)}(1 - \boldsymbol{\mu}^{(k)}))

    where:

    • W(k)\mathbf{W}^{(k)} is an n×nn \times n diagonal weight matrix at iteration kk
    • diag(v)\text{diag}(\mathbf{v}) creates a diagonal matrix with the elements of vector v\mathbf{v} on the diagonal
    • The diagonal entries are Wii(k)=μi(k)(1−μi(k))W_{ii}^{(k)} = \mu_i^{(k)}(1 - \mu_i^{(k)}), which is the variance of the Bernoulli distribution for observation ii
    • Observations with predicted probabilities near 0.5 receive higher weights (maximum variance of 0.25), while those near 0 or 1 receive lower weights
  5. Update the coefficients:
    Solve the weighted least squares problem to get the new coefficient estimates:

    β(k+1)=(XTW(k)X)−1XTW(k)z(k)\boldsymbol{\beta}^{(k+1)} = (\mathbf{X}^T\mathbf{W}^{(k)}\mathbf{X})^{-1}\mathbf{X}^T\mathbf{W}^{(k)}\mathbf{z}^{(k)}

    where:

    • β(k+1)\boldsymbol{\beta}^{(k+1)} is the updated coefficient vector for iteration k+1k+1
    • XT\mathbf{X}^T is the transpose of the design matrix
    • (XTW(k)X)−1(\mathbf{X}^T\mathbf{W}^{(k)}\mathbf{X})^{-1} is the inverse of the weighted cross-product matrix (analogous to (XTX)−1(\mathbf{X}^T\mathbf{X})^{-1} in ordinary least squares)
    • This formula is the solution to the weighted least squares problem: minimize (z(k)−Xβ)TW(k)(z(k)−Xβ)(\mathbf{z}^{(k)} - \mathbf{X}\boldsymbol{\beta})^T\mathbf{W}^{(k)}(\mathbf{z}^{(k)} - \mathbf{X}\boldsymbol{\beta})

Step 4: Check for convergence

After each iteration, check if the coefficients have stabilized:

∣∣β(k+1)−β(k)∣∣<ϵ||\boldsymbol{\beta}^{(k+1)} - \boldsymbol{\beta}^{(k)}|| < \epsilon

where:

  • ∣∣⋅∣∣||\cdot|| is the Euclidean norm (also called the L2 norm), which measures the magnitude of a vector: ∣∣v∣∣=v12+v22+⋯+vp2||\mathbf{v}|| = \sqrt{v_1^2 + v_2^2 + \cdots + v_p^2}
  • β(k+1)\boldsymbol{\beta}^{(k+1)} is the coefficient vector at iteration k+1k+1 (the newly updated coefficients)
  • β(k)\boldsymbol{\beta}^{(k)} is the coefficient vector at iteration kk (the previous coefficients)
  • β(k+1)−β(k)\boldsymbol{\beta}^{(k+1)} - \boldsymbol{\beta}^{(k)} is the change in coefficients between iterations
  • ϵ\epsilon is a small tolerance threshold (e.g., ϵ=10−6\epsilon = 10^{-6}), which defines how close to convergence we need to be

If the change is smaller than ϵ\epsilon, the algorithm has converged. Otherwise, repeat the steps above with the new coefficients. The process continues until the change in coefficients is very small, indicating that we've found the maximum likelihood estimates.

Summary of what happens

  • We start with all coefficients at zero (no effect from features).
  • At each step, we use the current model to predict probabilities, then adjust the coefficients to better fit the observed outcomes, giving more weight to observations where the model is less certain.
  • This process repeats, gradually improving the fit, until the coefficients stop changing significantly.
Out[5]:
Visualization
Three marked coefficient paths across twenty IRLS iterations for the intercept, study-hours coefficient, and previous-score coefficient, retaining the very large scientific-notation scale and all iterations.
Coefficient evolution across IRLS iterations. Starting from zero initialization, the three coefficient paths (intercept β₀, hours β₁, and score β₂) change sharply after the first updates and then oscillate on this small, nearly separated teaching dataset rather than settling to stable finite estimates.
Marked log-likelihood path across twenty IRLS iterations, including the steep early gain and later oscillations, with the final numerical value annotated.
Log-likelihood path during IRLS optimization. The largest improvement occurs in the early iterations, followed by small oscillations near the best value on this small, nearly separated teaching dataset.
Out[6]:
Visualization
Seven marked predicted-probability paths across twenty IRLS iterations, one for each student with hours, score, and pass or fail outcome retained in a two-column legend below the plot, plus a dashed horizontal decision threshold at probability 0.5.
Evolution of predicted probabilities for each student. All students start with equal probability (0.5) and then separate according to their features. On this small, nearly separated teaching dataset, the probability paths become extreme and some continue to oscillate around the 0.5 decision threshold as the undamped IRLS updates remain unstable.

Final Results

After convergence (typically after 5-10 iterations), we obtain the maximum likelihood estimates:

β^=[β^0β^1β^2]=[−15.20.80.1]\hat{\boldsymbol{\beta}} = \begin{bmatrix} \hat{\beta}_0 \\ \hat{\beta}_1 \\ \hat{\beta}_2 \end{bmatrix} = \begin{bmatrix} -15.2 \\ 0.8 \\ 0.1 \end{bmatrix}

where:

  • β^0=−15.2\hat{\beta}_0 = -15.2 is the estimated intercept
  • β^1=0.8\hat{\beta}_1 = 0.8 is the estimated coefficient for study hours
  • β^2=0.1\hat{\beta}_2 = 0.1 is the estimated coefficient for previous scores

So the fitted model is:

log⁡(p1−p)=−15.2+0.8⋅hours+0.1⋅scores\log\left(\frac{p}{1-p}\right) = -15.2 + 0.8 \cdot \text{hours} + 0.1 \cdot \text{scores}

Interpretation

The coefficients in a logistic regression model represent the change in log-odds for a one-unit increase in the predictor variable, holding all other variables constant.

  • For each additional hour of study, the log-odds of passing increase by 0.8
  • For each additional point on previous scores, the log-odds of passing increase by 0.1

Example calculation: To find the probability of passing for a student with 5 hours of study and a previous score of 75, we substitute these values into the fitted model.

Step 1: Calculate the linear predictor (log-odds)

η=β0+β1⋅hours+β2⋅score=−15.2+0.8⋅5+0.1⋅75=−15.2+4.0+7.5=−3.7\begin{aligned} \eta &= \beta_0 + \beta_1 \cdot \text{hours} + \beta_2 \cdot \text{score} \\ &= -15.2 + 0.8 \cdot 5 + 0.1 \cdot 75 \\ &= -15.2 + 4.0 + 7.5 \\ &= -3.7 \end{aligned}

where:

  • η\eta is the linear predictor (the log-odds of passing)
  • β0=−15.2\beta_0 = -15.2 is the intercept (baseline log-odds when all features are zero)
  • β1⋅hours=0.8⋅5=4.0\beta_1 \cdot \text{hours} = 0.8 \cdot 5 = 4.0 is the contribution from study hours (each hour adds 0.8 to the log-odds)
  • β2⋅score=0.1⋅75=7.5\beta_2 \cdot \text{score} = 0.1 \cdot 75 = 7.5 is the contribution from previous scores (each point adds 0.1 to the log-odds)
  • The sum −15.2+4.0+7.5=−3.7-15.2 + 4.0 + 7.5 = -3.7 is the total log-odds for this student

Step 2: Convert log-odds to probability

Then, we apply the inverse logit function (logistic sigmoid) to convert log-odds to probability:

p=11+e−η=11+e−(−3.7)=11+e3.7=11+40.45=141.45≈0.024\begin{aligned} p &= \frac{1}{1 + e^{-\eta}} \\ &= \frac{1}{1 + e^{-(-3.7)}} \\ &= \frac{1}{1 + e^{3.7}} \\ &= \frac{1}{1 + 40.45} \\ &= \frac{1}{41.45} \\ &\approx 0.024 \end{aligned}

where:

  • pp is the predicted probability of passing (the outcome we want)
  • e−η=e−(−3.7)=e3.7e^{-\eta} = e^{-(-3.7)} = e^{3.7} is the exponential of the negative linear predictor
  • e3.7≈40.45e^{3.7} \approx 40.45 (computed using a calculator or computer)
  • The denominator 1+40.45=41.451 + 40.45 = 41.45 represents the normalization factor
  • The final probability p≈0.024p \approx 0.024 or 2.4%, indicating this student is very unlikely to pass

Interpretation: With only 5 hours of study and a previous score of 75, the model predicts a 2.4% chance of passing. This low probability suggests that either more study hours or a higher previous score (or both) would be needed for a reasonable chance of success.

One of the major advantages of GLMs is that, despite their flexibility, they retain many of the familiar tools and interpretability of linear regression. This means we can perform hypothesis testing, construct confidence intervals, and assess the significance and impact of each feature in the model.just as we do in ordinary linear regression. As a result, GLMs provide both statistical rigor and insight into how each predictor influences the outcome.