Lecture%204%20logistic%20regression
Table of contents
- Logistic regression model validation
- Checking model assumptions
1. Logistic regression model validation
1.1 Recap: Model predictions
The fitted logistic regression model allows for predictions on various scales, enabling different interpretations of the model's output. The choice of scale depends on whether the primary goal is prediction or explanation 3.
- Log odds scale: The linear combination of predictors, logit^(p)=β^0+β^1X1+⋯+β^kXk.
- Odds scale: The exponentiated log odds, p^/(1−p^)=exp(β^0+β^1X1+⋯+β^kXk).
- Probability scale: The logistic function applied to the linear predictor, p^=1+exp(β^0+β^1X1+⋯+β^kXk)exp(β^0+β^1X1+⋯+β^kXk).
- Binary scale: A classification of 0 or 1 based on a chosen threshold 3.
1.2 Recap: Prediction or explanation
The purpose of a statistical model dictates the validation approach. Whether the model is intended for prediction or explanation influences the metrics and procedures used to assess its performance and reliability 4.
- Predictive modeling: Aims to estimate the outcome (Y) given predictors (X) as accurately as possible, focusing on predicting new observations.
- Explanatory modeling: Aims to understand the relationship between X and Y, often testing causal theories and focusing on inference 4.
📝 For explanatory modeling, if each hour spent revising increases the odds of passing Biostats II by a factor of 2.5, this describes the relationship between revision hours and passing odds 4.
1.3 Logistic regression model assumptions
Several core assumptions underpin logistic regression, which are crucial for valid inference and reliable predictions. Violations of these assumptions can lead to biased estimates and inaccurate conclusions 5.
- Binary outcome: The dependent variable must be binary, representing two distinct categories.
- Distribution: The outcome variable is assumed to follow a Bernoulli or binomial distribution.
- Linearity: A linear relationship must exist between the predictor variables and the log odds of the outcome.
- Independence: Observations must be independent of each other.
- Other considerations: While not core assumptions, issues like outliers, high leverage points, influential points, and multicollinearity can affect model performance and should be examined 5.
1.4 Residuals in logistic regression
Residuals in logistic regression are used to assess model fit and identify potential issues, though they do not follow the same distributional assumptions as in linear regression. Two commonly used types are Pearson and Deviance residuals 6.
- Pearson residual: Calculated as the difference between the observed outcome and the predicted probability, scaled by the standard deviation of the predicted probability.
- Deviance residual: Derived from the difference in log-likelihoods between the current model and a saturated model. It is the default residual for Generalized Linear Models (GLMs) in R and is important for goodness-of-fit assessments 6.
1.5 Deviance
Deviance quantifies the discrepancy between a fitted model and a saturated model, serving as a measure of goodness of fit. A smaller deviance indicates a better fit to the data 7.
- Definition: Deviance (D) is calculated as −2 times the difference between the log-likelihood of the current model and the log-likelihood of a saturated model (D=−2(logLcurrent−logLsaturated)).
- Interpretation: A saturated model has as many parameters as observations, perfectly fitting the data. If the current model fits perfectly, its log-likelihood will equal that of the saturated model, resulting in a deviance of zero.
- Model improvement: As predictors are added to a model, it generally approaches the fit of the saturated model, leading to a decrease in deviance 7.
2. Checking model assumptions
2.1 Checking model assumptions
Traditional residual plots, commonly used in linear regression, are not directly applicable or informative for logistic regression due to the nature of the outcome variable and the model's assumptions. Alternative methods are required to assess key assumptions 8.
- Limitations of traditional plots: Standard residual plots (e.g., residuals vs. fitted values, Q-Q plots) are not suitable for logistic regression 8.
- Focus on core assumptions: The primary focus for checking assumptions in logistic regression shifts to the linearity of predictors with log odds and the independence of observations 9.
2.2 Checking linearity of predictors with log odds
The assumption of a linear relationship between predictor variables and the log odds of the outcome is critical and requires specific graphical methods for assessment 9.
- Method: The
visregpackage in R can be used to visualize the relationship between each predictor and the fitted log odds, allowing for visual inspection of linearity. - Interpretation: A linear trend in the plot suggests the assumption is met, while non-linear patterns indicate a potential violation 9.
📝 A plot generated by the
visregpackage shows a linear trend between 'age' and the log odds of the outcome, indicating the linearity assumption is met 9.
2.3 Checking independence of observations
The assumption of independent observations is fundamental, particularly when data are collected through random sampling. Autocorrelation in residuals can indicate a violation of this assumption 10.
- Method: The autocorrelation function (ACF) of the residuals can be plotted to detect temporal or sequential dependencies.
- Interpretation: Significant autocorrelation at various lags suggests that observations are not independent, which can impact the validity of statistical inferences 10.
📝 An autocorrelation function (ACF) plot of residuals shows significant autocorrelation at lag 1, suggesting that observations are not independent 10.
2.4 Other model considerations
Beyond core assumptions, several other factors can influence the performance and reliability of a logistic regression model, including outliers, high leverage points, and influential observations 11.
- Outliers: Identified by large deviance residuals, indicating observations that do not fit the model well.
- High leverage points: Characterized by large hat values, these observations have predictor values that are extreme compared to others.
- Influential observations: Observations that significantly alter the model's coefficients or predictions, often indicated by large Cook's distance values (typically > 0.5 or > 1).
- Multicollinearity: Assessed by large variance inflation factors (VIFs), typically greater than 4 or 5, indicating high correlation among predictor variables 11.
2.5 Goodness of fit
Assessing goodness of fit determines how well the logistic regression model represents the observed data. Several methods are available, including calibration plots, deviance statistics, and pseudo R-squared measures 12.
- Calibration plot and Hosmer-Lemeshow test: Visualizes the agreement between observed and predicted probabilities, with the Hosmer-Lemeshow test providing a formal statistical assessment 13.
- Deviance and likelihood ratio test: Compares the deviance of the current model to a null model or other nested models to assess improvement in fit 14.
- % Deviance explained / pseudo R²: Measures the proportion of deviance explained by the model relative to a null model, though it does not correct for the number of predictors 15.
2.6 Calibration plot and the Hosmer-Lemeshow test
A calibration plot visually assesses how well the predicted probabilities from the model align with the actual observed outcomes. The Hosmer-Lemeshow test provides a statistical measure of this agreement 13.
- Calibration plot construction: Observed data are grouped, and the probability of the outcome is determined for each group. The plot then displays observed versus predicted probabilities for these groups.
- Ideal calibration: A perfectly calibrated model would show observed probabilities closely matching predicted probabilities, ideally lying on a diagonal line.
- Hosmer-Lemeshow test: This test performs a chi-square comparison of observed and predicted probabilities across deciles of risk, but it is not recommended for small sample sizes 13.

2.7 Deviance and the likelihood ratio test
The deviance statistic is a key component for assessing model fit and comparing nested models. The likelihood ratio test (LRT) leverages deviance to statistically evaluate whether adding predictors significantly improves model fit 14.
- Deviance definition: D=−2(logLcurrent−logLsaturated), where logL is the log-likelihood. A smaller deviance indicates a better fit.
- Likelihood ratio test: Compares the deviance of a null model (D0) to that of a current model (D1). The test statistic D0−D1 follows a chi-square distribution with degrees of freedom equal to the difference in the number of parameters between the models.
- Model comparison: The LRT is used to determine if a more complex model (with more predictors) provides a significantly better fit than a simpler, nested model 14.
2.8 % Deviance explained/pseudo R²
This metric provides an intuitive measure of how much of the total deviance is accounted for by the model, relative to a null model. However, it has limitations regarding overfitting 15.
- Calculation: .
- Interpretation: A higher percentage indicates that the model explains a larger portion of the variability in the outcome compared to a model with only an intercept.
- Limitation: This measure does not penalize for the number of predictors included, making it susceptible to overfitting, especially in models with many variables 15.
2.9 Comparing models: nested vs non-nested models
The method for comparing statistical models depends on whether they are nested or non-nested. Nested models have one model's terms entirely contained within another, while non-nested models do not share this hierarchical relationship 16.
- Nested models: Model A is nested within Model B if all terms in Model A are also present in Model B. For example, a model with only
Ageis nested within a model withAgeandSex. - Non-nested models: Models that do not have a hierarchical relationship, such as comparing a model with
Ageto a model withSexonly, are non-nested 16.
2.10 Comparing nested models
When models are nested, their deviance statistics can be directly compared using the likelihood ratio test to determine if the additional predictors in the larger model significantly improve the fit 17.
- Principle: The addition of predictors to a model is expected to decrease deviance. The LRT assesses whether this decrease is statistically significant.
- Test statistic: The difference in deviances between two nested models, D1−D2, follows a chi-square distribution with degrees of freedom equal to the difference in the number of parameters 17.
2.11 Comparing nested or non-nested models
Information criteria, such as the Akaike Information Criterion (AIC), provide a way to compare both nested and non-nested models by balancing model fit with model complexity 18.
- Akaike Information Criterion (AIC): Calculated as AIC=−2logL+2(k+1), where k is the number of variables in the model. Lower AIC values indicate a preferred model.
- Model selection: The model with the smallest AIC is generally preferred, suggesting a better balance between goodness of fit and parsimony.
- Limitations: Information criteria help select the best model among a set of candidates but do not identify the "correct" model 18.
2.12 Classification and predictive power
Assessing classification and predictive power involves determining how well a logistic regression model can accurately predict the outcome for new observations and discriminate between classes 19.
- Prediction accuracy: Evaluating whether the model can correctly identify which observations will have the outcome and which will not.
- Discrimination: The ability of the model to separate observations into those that will have the outcome versus those that will not.
- Calibration: The accuracy of the predicted probabilities themselves 19.
2.13 Classification
Classification involves assigning observations to a predicted group (e.g., outcome present or absent) based on their predicted probability and a chosen decision threshold 20.
- Prediction of probability: The model's predicted probability of the outcome, p^(Y=1), is calculated using the logistic function.
- Decision threshold: A threshold value (often denoted as τ) is set between 0 and 1. If p^≥τ, the observation is classified into group 1; otherwise, it is classified into group 0.
- Threshold choice: The choice of threshold influences classification outcomes and error rates. A threshold of 0.5 treats false positive and false negative errors equally, which is appropriate for balanced datasets 20.
2.14 Classification and accuracy example
This example demonstrates how to calculate various performance metrics for a logistic regression model using a confusion matrix derived from a specific decision boundary 24.
- Scenario: A logistic regression model for hypertension prediction is used with a decision boundary of 0.3 24.
- Confusion Matrix:
| Observed hypertension | Predicted hypertension |
|---|---|
| Yes | Yes |
| Yes | No |
| No | Yes |
| No | No |
- Metrics to calculate: Accuracy, sensitivity, specificity, positive predictive value, and negative predictive value 24.
📝 A confusion matrix for hypertension prediction with a decision boundary of 0.3 shows 17 true positives, 19 false negatives, 14 false positives, and 102 true negatives 24.
2.15 Model accuracy and classification errors
A confusion matrix is essential for evaluating the performance of a classification model by comparing predicted outcomes to actual observed outcomes. It breaks down correct and incorrect classifications into specific error types 22.
- Confusion Matrix Structure:
| Observed outcome | Model prediction |
|---|---|
| Positive | Positive |
| Positive | Negative |
| Negative | Positive 1 |
| Negative | Negative |
- Definitions:
- True Positives (a): Correctly predicted positive outcomes.
- True Negatives (d): Correctly predicted negative outcomes.
- False Positives (b): Incorrectly predicted positive outcomes (Type I error).
- False Negatives (c): Incorrectly predicted negative outcomes (Type II error).
- Accuracy: The overall proportion of correct classifications: a+b+c+da+d 22.
2.16 Model accuracy and classification errors continued
Beyond overall accuracy, several specific metrics derived from the confusion matrix provide a more nuanced understanding of a model's classification performance, particularly concerning sensitivity and specificity 23.
- Sensitivity (True Positive Rate/Recall): The proportion of actual positive cases that are correctly identified: a+ca.
- Specificity (True Negative Rate): The proportion of actual negative cases that are correctly identified: b+dd.
- Positive Predictive Value (Precision): The proportion of predicted positive cases that are actually positive: a+ba.
- Negative Predictive Value: The proportion of predicted negative cases that are actually negative: d+cd 23.
2.17 The choice of decision boundary affects our model performance
Altering the decision boundary significantly impacts the trade-offs between different types of classification errors, influencing metrics like sensitivity and specificity 26.
- Impact of decreasing threshold: Decreasing the decision threshold generally increases sensitivity (more true positives) but decreases specificity (more false positives).
- Balanced outcomes: When the outcome variable is balanced (equal numbers of 0s and 1s), a threshold of 0.5 aims to minimize overall error and treats false positive and false negative errors equally 26.
2.18 Varying the decision boundary
The selection of the decision boundary is a critical step that directly influences the performance characteristics of a classification model, necessitating an examination of the trade-offs involved 27.
- Sensitivity vs. Specificity: As sensitivity increases with a lower threshold, the false positive rate (1 - specificity) also increases.
- Ideal classifier: A perfect classifier would achieve a sensitivity of 1 (correctly identifying all positive cases) and a false positive rate of 0 (never misclassifying a negative case as positive).
- Performance assessment: Plotting the true positive rate against the false positive rate across a range of decision boundaries provides a comprehensive view of model performance 27.
2.19 ROC curve
The Receiver Operating Characteristic (ROC) curve is a graphical tool that visualizes the performance of a binary classifier across all possible threshold settings, plotting the true positive rate against the false positive rate 29.
- Axes: The y-axis represents the True Positive Rate (TPR), and the x-axis represents the False Positive Rate (FPR) 29.
- Random classifier: A classifier performing no better than random chance would lie on the diagonal line (TPR = FPR).
- Ideal classifier: An ideal classifier would be located at the top-left corner of the plot (TPR = 1, FPR = 0) 30.

2.20 ROC curve continued
The ROC curve provides a comprehensive overview of a classifier's performance across the entire spectrum of decision thresholds. The Area Under the Curve (AUC) is a key metric derived from the ROC curve to quantify overall discriminative ability 30.
- Discriminative ability: The ROC curve illustrates the trade-off between correctly identifying positive cases and incorrectly identifying negative cases as positive.
- Area Under the Curve (AUC): A single scalar value representing the probability that a randomly chosen positive instance will be ranked higher than a randomly chosen negative instance. An AUC closer to 1 indicates better discriminative performance 30.

2.21 Comparing models with AUC ROC
The AUC of the ROC curve serves as a robust metric for comparing the discriminative performance of different logistic regression models. Models with higher AUC values are generally considered superior 31.
- Model comparison: By plotting ROC curves for multiple models and comparing their AUC values, researchers can objectively select the model with the best discriminative power.
- Interpretation of AUC:
- AUC = 1: Perfect classifier.
- AUC > 0.9: Excellent classifier.
- 0.8 < AUC < 0.9: Good classifier.
- 0.7 < AUC < 0.8: Fair classifier.
- AUC = 0.5: Random classifier.
- AUC < 0.5: Worse than random 31.

2.22 For enjoyment: precision-recall curves
Precision-recall curves offer an alternative visualization for classifier performance, particularly useful for imbalanced datasets where the focus is on the accurate identification of positive instances 32.
- Focus: These curves prioritize the performance related to the positive class, showing the trade-off between precision (positive predictive value) and recall (sensitivity).
- Relevance: Especially valuable when the number of negative instances significantly outweighs the number of positive instances, as ROC curves can be misleading in such scenarios 32.
2.23 For enjoyment: precision-recall curves continued
The precision-recall curve plots the positive predictive value against the true positive rate (recall) across various decision thresholds. The Area Under the Precision-Recall Curve (AUCPR) quantifies the model's performance in identifying positive cases 33.
- Curve interpretation: A perfect classifier would achieve a precision of 1 and a recall of 1, resulting in a curve that goes to the top-right corner of the plot.
- AUCPR: Similar to AUC for ROC curves, a higher AUCPR indicates better performance. However, the baseline AUCPR is dependent on the prevalence of the positive class, making direct comparison across datasets with different prevalences challenging 33.

2.24 How to build a logistic regression model
The strategy for building a logistic regression model differs based on its intended purpose: inference or prediction. Each approach requires distinct considerations regarding variable selection and assumption checking 34.
- For inference/causality: Include all identified confounders, regardless of their statistical significance or effect size, and rigorously check model assumptions.
- For prediction: Employ variable selection procedures based on goodness of fit or predictive power to identify the most effective set of predictors for forecasting outcomes 34.
© 2026 Maeve. All rights reserved. This content is protected by copyright.