Logistic Regression › Example
Machine Learning from ScratchAll chapters 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):
where:
- is the design matrix (a matrix with 7 students and 3 columns)
- The first column contains all 1s (for the intercept term )
- The second column contains study hours (feature )
- The third column contains previous scores (feature )
The response vector (whether each student passed) is:
where:
- is the response vector (a vector of binary outcomes)
- indicates student failed the exam
- indicates student passed the exam
Step 2: Initialize coefficients
We start with initial coefficient values. A common choice is to set all coefficients to zero:
where:
- is the initial coefficient vector at iteration 0 (the starting point for optimization)
- is the initial intercept (the baseline log-odds)
- is the initial coefficient for study hours
- is the initial coefficient for previous scores
This means our initial model predicts a 50% probability for all students (since implies ).
Step 3: Calculate the linear predictor
For the first iteration, with all coefficients at zero:
where:
- is the vector of linear predictors at iteration 0 (a vector, one value per student)
- Each element is computed as for student
Step 4: Calculate predicted probabilities
Using the logistic function:
where:
- is the vector of predicted probabilities at iteration 0 (a vector, one probability per student)
- The logistic function is applied element-wise to each
- Since , we have for all students
Step 5: Calculate the log-likelihood
The log-likelihood for logistic regression is:
where:
- is the log-likelihood function (measures how well the model fits the data)
- is the number of observations (in our case, students)
- is the actual outcome for observation (either 0 or 1)
- is the predicted probability for observation (from the logistic function)
- The sum aggregates the log-likelihood contributions from all observations
For our first iteration:
Breaking this down by observation:
Simplifying (since each term equals ):
Step 6: Update coefficients using gradient ascent
The gradient of the log-likelihood with respect to the coefficients is:
where:
- is the gradient vector (a vector containing the partial derivatives with respect to each coefficient)
- is the transpose of the design matrix (a matrix, in our case )
- is the vector of actual outcomes (a vector, in our case )
- is the vector of predicted probabilities (a vector, in our case )
- is the residual vector (the difference between actual and predicted values)
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 :
First, calculate the residuals :
Then, multiply by :
Computing each element of the gradient:
Step 7: Update coefficients
Using gradient ascent with learning rate :
where:
- is the updated coefficient vector after iteration 1
- 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:
where:
- is the final estimated coefficient vector (the maximum likelihood estimates)
- is the estimated intercept (the log-odds when study hours and previous scores are both zero)
- is the estimated coefficient for study hours (the change in log-odds per additional hour of study)
- is the estimated coefficient for previous scores (the change in log-odds per additional point on previous scores)
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:


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:
where:
- is the probability of passing the exam (the outcome we're predicting)
- is the number of study hours (feature )
- is the previous test score (feature )
Interpretation:
Intercept (): 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 (): For each additional hour of study, the log-odds of passing increase by 0.8, holding previous scores constant
Previous scores coefficient (): 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:
Then, apply the logistic function to get the probability:
Since :
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:
Then, apply the logistic function:
Since :
This student has a 25% chance of passing.