Logistic Regression › Example

Michael BrenndoerferJune 24, 202513 min read
Machine Learning from ScratchAll chapters
Part 4 of 9Regression Models
Chapter 37Logistic Regression › Example
Reading section 4 of 8 · Example · 13 minSection 4 of 8 · 13 min

Book contents

Section 4 of 8 · 13 min read

Logistic Regression › ExampleOne section · Sections in this chapter4 / 8 ↓
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 step-by-step example of logistic regression using a simple dataset. Suppose we want to predict whether a student will pass an exam based on their study hours and previous test scores.

Given 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]

Step 1: Set up the design matrix

First, we organize our data into matrix form. Each row represents one student, and each column is a feature (including a column of 1s for the intercept):

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}

where:

  • X\mathbf{X} is the design matrix (a 7×37 \times 3 matrix with 7 students and 3 columns)
  • The first column contains all 1s (for the intercept term β0\beta_0)
  • The second column contains study hours (feature x1x_1)
  • The third column contains previous scores (feature x2x_2)

The response vector (whether each student passed) is:

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

where:

  • y\mathbf{y} is the response vector (a 7×17 \times 1 vector of binary outcomes)
  • yi=0y_i = 0 indicates student ii failed the exam
  • yi=1y_i = 1 indicates student ii passed the exam

Step 2: Initialize coefficients

We start with initial coefficient values. A common choice is to set all coefficients to zero:

β(0)=[β0(0)β1(0)β2(0)]=[000]\boldsymbol{\beta}^{(0)} = \begin{bmatrix} \beta_0^{(0)} \\ \beta_1^{(0)} \\ \beta_2^{(0)} \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \\ 0 \end{bmatrix}

where:

  • β(0)\boldsymbol{\beta}^{(0)} is the initial coefficient vector at iteration 0 (the starting point for optimization)
  • β0(0)=0\beta_0^{(0)} = 0 is the initial intercept (the baseline log-odds)
  • β1(0)=0\beta_1^{(0)} = 0 is the initial coefficient for study hours
  • β2(0)=0\beta_2^{(0)} = 0 is the initial coefficient for previous scores

This means our initial model predicts a 50% probability for all students (since η=0\eta = 0 implies p=0.5p = 0.5).

Step 3: Calculate the linear predictor

For the first iteration, with all coefficients at zero:

η(0)=Xβ(0)=[1260136514701575168017851890][000]=[0000000]\boldsymbol{\eta}^{(0)} = \mathbf{X}\boldsymbol{\beta}^{(0)} = \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} \begin{bmatrix} 0 \\ 0 \\ 0 \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \\ 0 \end{bmatrix}

where:

  • η(0)\boldsymbol{\eta}^{(0)} is the vector of linear predictors at iteration 0 (a 7×17 \times 1 vector, one value per student)
  • Each element is computed as ηi(0)=1⋅0+xi1⋅0+xi2⋅0=0\eta_i^{(0)} = 1 \cdot 0 + x_{i1} \cdot 0 + x_{i2} \cdot 0 = 0 for student ii

Step 4: Calculate predicted probabilities

Using the logistic function:

p(0)=11+e−η(0)=[11+e011+e011+e011+e011+e011+e011+e0]=[0.50.50.50.50.50.50.5]\boldsymbol{p}^{(0)} = \frac{1}{1 + e^{-\boldsymbol{\eta}^{(0)}}} = \begin{bmatrix} \frac{1}{1 + e^0} \\ \frac{1}{1 + e^0} \\ \frac{1}{1 + e^0} \\ \frac{1}{1 + e^0} \\ \frac{1}{1 + e^0} \\ \frac{1}{1 + e^0} \\ \frac{1}{1 + e^0} \end{bmatrix} = \begin{bmatrix} 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \end{bmatrix}

where:

  • p(0)\boldsymbol{p}^{(0)} is the vector of predicted probabilities at iteration 0 (a 7×17 \times 1 vector, one probability per student)
  • The logistic function is applied element-wise to each ηi(0)\eta_i^{(0)}
  • Since e0=1e^0 = 1, we have pi(0)=11+1=12=0.5p_i^{(0)} = \frac{1}{1+1} = \frac{1}{2} = 0.5 for all students

Step 5: Calculate the log-likelihood

The log-likelihood for logistic regression is:

ℓ(β)=∑i=1n[yilog⁡(pi)+(1−yi)log⁡(1−pi)]\ell(\boldsymbol{\beta}) = \sum_{i=1}^n [y_i \log(p_i) + (1-y_i) \log(1-p_i)]

where:

  • ℓ(β)\ell(\boldsymbol{\beta}) is the log-likelihood function (measures how well the model fits the data)
  • nn is the number of observations (in our case, n=7n = 7 students)
  • yiy_i is the actual outcome for observation ii (either 0 or 1)
  • pip_i is the predicted probability for observation ii (from the logistic function)
  • The sum aggregates the log-likelihood contributions from all observations

For our first iteration:

ℓ(β(0))=∑i=17[yilog⁡(0.5)+(1−yi)log⁡(0.5)]\ell(\boldsymbol{\beta}^{(0)}) = \sum_{i=1}^7 [y_i \log(0.5) + (1-y_i) \log(0.5)]

Breaking this down by observation:

=[0⋅log⁡(0.5)+1⋅log⁡(0.5)]+[0⋅log⁡(0.5)+1⋅log⁡(0.5)]+[1⋅log⁡(0.5)+0⋅log⁡(0.5)]= [0 \cdot \log(0.5) + 1 \cdot \log(0.5)] + [0 \cdot \log(0.5) + 1 \cdot \log(0.5)] + [1 \cdot \log(0.5) + 0 \cdot \log(0.5)] +[1⋅log⁡(0.5)+0⋅log⁡(0.5)]+[1⋅log⁡(0.5)+0⋅log⁡(0.5)]+ [1 \cdot \log(0.5) + 0 \cdot \log(0.5)] + [1 \cdot \log(0.5) + 0 \cdot \log(0.5)] +[1⋅log⁡(0.5)+0⋅log⁡(0.5)]+[1⋅log⁡(0.5)+0⋅log⁡(0.5)]+ [1 \cdot \log(0.5) + 0 \cdot \log(0.5)] + [1 \cdot \log(0.5) + 0 \cdot \log(0.5)]

Simplifying (since each term equals log⁡(0.5)\log(0.5)):

=7⋅log⁡(0.5)=7⋅(−0.693)=−4.851= 7 \cdot \log(0.5) = 7 \cdot (-0.693) = -4.851

Step 6: Update coefficients using gradient ascent

The gradient of the log-likelihood with respect to the coefficients is:

∂ℓ∂β=XT(y−p)\frac{\partial \ell}{\partial \boldsymbol{\beta}} = \mathbf{X}^T(\mathbf{y} - \mathbf{p})

where:

  • ∂ℓ∂β\frac{\partial \ell}{\partial \boldsymbol{\beta}} is the gradient vector (a (p+1)×1(p+1) \times 1 vector containing the partial derivatives with respect to each coefficient)
  • XT\mathbf{X}^T is the transpose of the design matrix (a (p+1)×n(p+1) \times n matrix, in our case 3×73 \times 7)
  • y\mathbf{y} is the vector of actual outcomes (a n×1n \times 1 vector, in our case 7×17 \times 1)
  • p\mathbf{p} is the vector of predicted probabilities (a n×1n \times 1 vector, in our case 7×17 \times 1)
  • (y−p)(\mathbf{y} - \mathbf{p}) is the residual vector (the difference between actual and predicted values)
Optimization Algorithm

In practice, logistic regression typically uses more sophisticated optimization algorithms than simple gradient ascent, such as Newton-Raphson method, Iteratively Reweighted Least Squares (IRLS), or L-BFGS. These methods converge faster and are more numerically stable than basic gradient ascent. The gradient ascent approach shown here is for educational purposes to illustrate the core optimization principle.

For our first iteration, we compute XT(y−p)\mathbf{X}^T(\mathbf{y} - \mathbf{p}):

First, calculate the residuals (y−p)(\mathbf{y} - \mathbf{p}):

y−p=[0011111]−[0.50.50.50.50.50.50.5]=[−0.5−0.50.50.50.50.50.5]\mathbf{y} - \mathbf{p} = \begin{bmatrix} 0 \\ 0 \\ 1 \\ 1 \\ 1 \\ 1 \\ 1 \end{bmatrix} - \begin{bmatrix} 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \end{bmatrix} = \begin{bmatrix} -0.5 \\ -0.5 \\ 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \end{bmatrix}

Then, multiply by XT\mathbf{X}^T:

∂ℓ∂β=XT(y−p)=[1111111234567860657075808590][−0.5−0.50.50.50.50.50.5]\frac{\partial \ell}{\partial \boldsymbol{\beta}} = \mathbf{X}^T(\mathbf{y} - \mathbf{p}) = \begin{bmatrix} 1 & 1 & 1 & 1 & 1 & 1 & 1 \\ 2 & 3 & 4 & 5 & 6 & 7 & 8 \\ 60 & 65 & 70 & 75 & 80 & 85 & 90 \end{bmatrix} \begin{bmatrix} -0.5 \\ -0.5 \\ 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \\ 0.5 \end{bmatrix}

Computing each element of the gradient:

=[1(−0.5)+1(−0.5)+1(0.5)+1(0.5)+1(0.5)+1(0.5)+1(0.5)2(−0.5)+3(−0.5)+4(0.5)+5(0.5)+6(0.5)+7(0.5)+8(0.5)60(−0.5)+65(−0.5)+70(0.5)+75(0.5)+80(0.5)+85(0.5)+90(0.5)]= \begin{bmatrix} 1(-0.5) + 1(-0.5) + 1(0.5) + 1(0.5) + 1(0.5) + 1(0.5) + 1(0.5) \\ 2(-0.5) + 3(-0.5) + 4(0.5) + 5(0.5) + 6(0.5) + 7(0.5) + 8(0.5) \\ 60(-0.5) + 65(-0.5) + 70(0.5) + 75(0.5) + 80(0.5) + 85(0.5) + 90(0.5) \end{bmatrix} =[−0.5−0.5+0.5+0.5+0.5+0.5+0.5−1.0−1.5+2.0+2.5+3.0+3.5+4.0−30.0−32.5+35.0+37.5+40.0+42.5+45.0]= \begin{bmatrix} -0.5 - 0.5 + 0.5 + 0.5 + 0.5 + 0.5 + 0.5 \\ -1.0 - 1.5 + 2.0 + 2.5 + 3.0 + 3.5 + 4.0 \\ -30.0 - 32.5 + 35.0 + 37.5 + 40.0 + 42.5 + 45.0 \end{bmatrix} =[1.512.5137.5]= \begin{bmatrix} 1.5 \\ 12.5 \\ 137.5 \end{bmatrix}

Step 7: Update coefficients

Using gradient ascent with learning rate α=0.01\alpha = 0.01:

β(1)=β(0)+α∂ℓ∂β\boldsymbol{\beta}^{(1)} = \boldsymbol{\beta}^{(0)} + \alpha \frac{\partial \ell}{\partial \boldsymbol{\beta}} =[000]+0.01[1.512.5137.5]= \begin{bmatrix} 0 \\ 0 \\ 0 \end{bmatrix} + 0.01 \begin{bmatrix} 1.5 \\ 12.5 \\ 137.5 \end{bmatrix} =[0+0.0150+0.1250+1.375]= \begin{bmatrix} 0 + 0.015 \\ 0 + 0.125 \\ 0 + 1.375 \end{bmatrix} =[0.0150.1251.375]= \begin{bmatrix} 0.015 \\ 0.125 \\ 1.375 \end{bmatrix}

where:

  • β(1)\boldsymbol{\beta}^{(1)} is the updated coefficient vector after iteration 1
  • α=0.01\alpha = 0.01 is the learning rate (controls the step size in the direction of the gradient)
  • The update rule moves the coefficients in the direction that increases the log-likelihood

Step 8: Iterate until convergence

We repeat steps 3-7 until the coefficients stop changing significantly. After several iterations, the algorithm converges to:

β^=[β^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:

  • β^\hat{\boldsymbol{\beta}} is the final estimated coefficient vector (the maximum likelihood estimates)
  • β^0=−15.2\hat{\beta}_0 = -15.2 is the estimated intercept (the log-odds when study hours and previous scores are both zero)
  • β^1=0.8\hat{\beta}_1 = 0.8 is the estimated coefficient for study hours (the change in log-odds per additional hour of study)
  • β^2=0.1\hat{\beta}_2 = 0.1 is the estimated coefficient for previous scores (the change in log-odds per additional point on previous scores)
Simplified Example

The coefficient values shown in this example are illustrative and simplified for educational purposes. In practice, the exact values depend on the specific data, the optimization algorithm used, and the convergence criteria. The key insight is understanding how the iterative optimization process works to find the maximum likelihood estimates.

Let's visualize how the optimization process converges during training:

Out[7]:
Visualization
Line plot of all 1,000 tracked log-likelihood values with a dashed reference and callout at the final value minus 10.093.
The log-likelihood generally improves during gradient ascent while oscillating around progressively higher values, ending at -10.093. The broad upward envelope shows rapid learning early and a slower approach to the final region.
Line plot of all 1,001 tracked values for the intercept, study-hours coefficient, and previous-scores coefficient, with final labels minus 0.231, 2.309, and minus 0.008.
The coefficients evolve during optimization, starting from initial values and converging to their final estimates. Each coefficient follows its own trajectory, with the rate of change decreasing as the algorithm approaches the optimal solution.

These visualizations demonstrate the iterative nature of logistic regression optimization:

Log-Likelihood Convergence: Shows how the model improves with each iteration, with rapid initial progress that gradually slows as it approaches the optimal solution. The log-likelihood is maximized (becomes less negative) as the model learns better parameters.

Coefficient Convergence: Illustrates how each coefficient evolves from its initial value to its final estimate. Different coefficients may converge at different rates depending on the data and feature scales. The convergence pattern shows that the optimization is working correctly: coefficients stabilize rather than oscillating or diverging.

Step 9: Final model interpretation

The fitted logistic regression 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}

where:

  • pp is the probability of passing the exam (the outcome we're predicting)
  • hours\text{hours} is the number of study hours (feature x1x_1)
  • scores\text{scores} is the previous test score (feature x2x_2)

Interpretation:

Intercept (β^0=−15.2\hat{\beta}_0 = -15.2): When both study hours and previous scores are 0, the log-odds are -15.2, corresponding to a very low probability of passing

Study hours coefficient (β^1=0.8\hat{\beta}_1 = 0.8): For each additional hour of study, the log-odds of passing increase by 0.8, holding previous scores constant

Previous scores coefficient (β^2=0.1\hat{\beta}_2 = 0.1): For each additional point on previous scores, the log-odds of passing increase by 0.1, holding study hours constant

Step 10: Make predictions

For a student with 5 hours of study and a previous score of 75:

First, calculate the linear predictor:

η=β^0+β^1⋅hours+β^2⋅scores\eta = \hat{\beta}_0 + \hat{\beta}_1 \cdot \text{hours} + \hat{\beta}_2 \cdot \text{scores} =−15.2+0.8⋅5+0.1⋅75= -15.2 + 0.8 \cdot 5 + 0.1 \cdot 75 =−15.2+4.0+7.5= -15.2 + 4.0 + 7.5 =−3.7= -3.7

Then, apply the logistic function to get the probability:

p=11+e−η=11+e−(−3.7)=11+e3.7p = \frac{1}{1 + e^{-\eta}} = \frac{1}{1 + e^{-(-3.7)}} = \frac{1}{1 + e^{3.7}}

Since e3.7≈40.45e^{3.7} \approx 40.45:

p=11+40.45=141.45≈0.024p = \frac{1}{1 + 40.45} = \frac{1}{41.45} \approx 0.024

This student has approximately a 2.4% chance of passing.

For a student with 7 hours of study and a previous score of 85:

First, calculate the linear predictor:

η=−15.2+0.8⋅7+0.1⋅85\eta = -15.2 + 0.8 \cdot 7 + 0.1 \cdot 85 =−15.2+5.6+8.5= -15.2 + 5.6 + 8.5 =−1.1= -1.1

Then, apply the logistic function:

p=11+e−(−1.1)=11+e1.1p = \frac{1}{1 + e^{-(-1.1)}} = \frac{1}{1 + e^{1.1}}

Since e1.1≈3.00e^{1.1} \approx 3.00:

p=11+3.00=14.00=0.25p = \frac{1}{1 + 3.00} = \frac{1}{4.00} = 0.25

This student has a 25% chance of passing.