Generalized Linear Models › Example: Logistic Regression
Machine Learning from ScratchAll chapters 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:
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 looks like:
The corresponding response vector (whether the student passed) is:
Step 2: Initialize coefficients
We start the iterative process by choosing initial values for the coefficients (the parameters). A common choice is to set all coefficients to zero:
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 :
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.
-
Calculate the linear predictor:
Compute .where:
- is the vector of linear predictors at iteration (one entry per observation)
- is the design matrix (each row is one observation)
- is the coefficient vector at iteration
- For the first iteration with , all entries in equal 0
-
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:where:
- is the vector of fitted values (predicted probabilities) at iteration
- is the inverse link function (for logistic regression, this is the logistic sigmoid function)
- The formula is applied element-wise: for each observation
- For the first iteration with , all predicted probabilities equal 0.5 (since )
-
Calculate the working response:
This step creates a "pseudo-response" that allows us to use weighted least squares:where:
- is the vector of working responses at iteration (adjusted target values for the weighted least squares step)
- is the vector of observed responses (actual outcomes: 0 or 1 for each observation)
- is the residual vector (difference between actual and predicted values)
- is computed element-wise and represents the variance of the Bernoulli distribution for each observation (i.e., )
- Division is performed element-wise
-
Calculate the weights:
The weights for each observation are based on the variance of the predicted probability:where:
- is an diagonal weight matrix at iteration
- creates a diagonal matrix with the elements of vector on the diagonal
- The diagonal entries are , which is the variance of the Bernoulli distribution for observation
- Observations with predicted probabilities near 0.5 receive higher weights (maximum variance of 0.25), while those near 0 or 1 receive lower weights
-
Update the coefficients:
Solve the weighted least squares problem to get the new coefficient estimates:where:
- is the updated coefficient vector for iteration
- is the transpose of the design matrix
- is the inverse of the weighted cross-product matrix (analogous to in ordinary least squares)
- This formula is the solution to the weighted least squares problem: minimize
Step 4: Check for convergence
After each iteration, check if the coefficients have stabilized:
where:
- is the Euclidean norm (also called the L2 norm), which measures the magnitude of a vector:
- is the coefficient vector at iteration (the newly updated coefficients)
- is the coefficient vector at iteration (the previous coefficients)
- is the change in coefficients between iterations
- is a small tolerance threshold (e.g., ), which defines how close to convergence we need to be
If the change is smaller than , 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.



Final Results
After convergence (typically after 5-10 iterations), we obtain the maximum likelihood estimates:
where:
- is the estimated intercept
- is the estimated coefficient for study hours
- is the estimated coefficient for previous scores
So the fitted model is:
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)
where:
- is the linear predictor (the log-odds of passing)
- is the intercept (baseline log-odds when all features are zero)
- is the contribution from study hours (each hour adds 0.8 to the log-odds)
- is the contribution from previous scores (each point adds 0.1 to the log-odds)
- The sum 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:
where:
- is the predicted probability of passing (the outcome we want)
- is the exponential of the negative linear predictor
- (computed using a calculator or computer)
- The denominator represents the normalization factor
- The final probability 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.