Overview

5 Fitting a logistic regression

This chapter presents logistic regression as a practical, supervised approach for predicting binary outcomes. It explains how a linear combination of predictors is transformed by the sigmoid function into probabilities between 0 and 1, which are then thresholded (commonly at 0.5) to yield class labels. The discussion highlights how coefficients quantify effects on the log-odds of the outcome, contrasts logistic and linear regression, and sets the stage for a complete workflow: data exploration, model fitting, interpretation, and performance evaluation using standard classification metrics.

To ground the ideas, the chapter analyzes a raisin dataset with morphological features and a binary class indicating variety. After importing and cleaning the data (including mapping class labels to 0/1), the authors perform exploratory analysis: class-wise descriptive statistics, paired histograms to assess class separation, and correlation heat maps to probe relationships among predictors. Strong correlations motivate a multicollinearity check via Variance Inflation Factors (VIFs), revealing several problematic predictors. A full multiple logistic model identifies some insignificant variables, and a reduced model focusing on MinorAxisLength and Perimeter is fit to mitigate collinearity while preserving predictive signal.

The reduced model shows strong statistical significance (LLR p-value ≈ 0) and good fit (McFadden’s pseudo R² ≈ 0.50). The chapter demonstrates turning fitted coefficients into probabilities and then class predictions, builds a confusion matrix, and computes key metrics: sensitivity ≈ 85.3%, specificity ≈ 88.2%, false positive rate ≈ 11.8%, false negative rate ≈ 14.7%, and accuracy ≈ 86.8%. The area under the ROC curve is ≈ 0.868, consistent with the accuracy and indicating solid discrimination. The end-to-end example illustrates best practices—thorough EDA, handling multicollinearity, careful model interpretation, and robust evaluation—applicable to a wide range of binary classification problems.

A graphical illustration of the sigmoid function. The sigmoid function is characterized by its S-shaped curve, compared to a linear function which is characterized by a straight line.
A grid of histograms that displays the data distributions of each numeric variable in the raisins data frame further segmented by the binary variable Class.
A pair of correlation heat maps, one for each variety of raisin.
A Receiver Operating Characteristic, or ROC, curve. The false positive rate is plotted along the x-axis and the true positive rate is plotted along the y-axis. When the curve, represented by the solid line, hugs the upper-left quadrant of the plot, as it does here, it thereby increases the area under it. The dashed line represents an AUC equal to 0.5, or otherwise the equivalent of random guessing.

Summary

  • Logistic regression is a statistical method used to model the relationship between a binary outcome variable and one or more predictors. Unlike linear regression, which predicts continuous outcomes, logistic regression predicts the probability that an observation belongs to one class versus the other. Logistic regression applies the logistic function, or sigmoid function, to transform the linear combination of predictors into probabilities, which are then used to make binary predictions. Logistic regression models are regularly fit in many fields, including medicine, finance, marketing, and the social sciences.
  • Goodness of fit should be evaluated from at least a trio of measures: McFadden’s pseudo R2, which represents a model’s ability to explain variation in the binary dependent variable above and beyond a null model that contains just an intercept term; the LLR p-value, which measures a model’s statistical significance; and the p-values for the individual predictors, which indicate whether or not the relationship between a predictor and the binary outcome variable is statistically significant.
  • Classification metrics—true and false positive rates, true and false negative rates, accuracy and misclassification rates, and the area under the receiver operating characteristic curve—are essential for evaluating the performance of a logistic regression and its ability to accurately predict binary outcomes. By analyzing these metrics, you can draw conclusions around a model’s strengths and weaknesses, identify opportunities for improvement, and make informed decisions about model optimization and deployment.
  • Data exploration, which typically involves a mix of computing basic statistics and creating graphical displays of the data, should scale with the length and width of the data set. The value proposition of data exploration, when done correctly and thoroughly, lies in its ability to identify patterns, outliers, and potential issues with the data that could drive variable selection and other model development decisions.

FAQ

What is logistic regression, and when should I use it instead of linear regression?Use logistic regression when your dependent variable is binary (0/1). It models the probability of the positive class using the logistic (sigmoid) function, ensuring outputs are between 0 and 1. Unlike linear regression (which predicts continuous outcomes), logistic regression predicts class probabilities and class labels for classification tasks.
How does the sigmoid function turn a linear combination of predictors into a probability?The model forms a linear predictor η = β0 + β1X1 + … + βkXk, then applies the sigmoid: p = 1/(1 + e^(−η)). This maps any real value to (0, 1), which can be interpreted as the probability of the positive class.
Why do we code the target as 0/1 and what does the 0.5 threshold mean?Coding classes as 0 and 1 lets the model estimate P(Y=1|X). A common default is to predict class 1 when p ≥ 0.5 and class 0 otherwise. The threshold can be moved (e.g., 0.3 or 0.7) to trade off sensitivity and specificity depending on costs of false positives vs. false negatives.
How do I fit a multiple logistic regression in Python with statsmodels?Use the formula API: import statsmodels.formula.api as smf; model = smf.logit('Y ~ X1 + X2 + ...', data=df).fit(); print(model.summary()). The summary includes coefficients, standard errors, z-scores, p-values, and goodness-of-fit statistics.
How do I interpret logistic regression coefficients?Each coefficient is the change in log-odds of the positive class per one-unit increase in the predictor (holding others constant). Positive means higher odds of class 1; negative means lower odds. You can exponentiate coefficients to get odds ratios: OR = exp(β). For example, OR=1.5 means a 50% increase in odds per unit increase.
What is McFadden’s pseudo R-squared and how do I read it?It’s 1 − (log-likelihood of the fitted model / log-likelihood of the null model). Higher is better and it’s useful for comparing models on the same data. Rough guide: around 0.2–0.4 indicates a good fit; values near 0.5 (as in the chapter’s reduced model) indicate an excellent fit for many applications.
How do I detect and handle multicollinearity in logistic regression?Detect it via correlation heat maps and Variance Inflation Factors (VIF). A VIF ≥ 10 suggests problematic collinearity. Remedies include removing or combining correlated predictors, feature engineering, or using regularization or dimensionality reduction. The chapter resolves issues by fitting a reduced model with fewer, stronger predictors.
What exploratory steps help before fitting the model?- Compute grouped descriptive stats by class to compare distributions. - Plot paired histograms for each predictor split by class to assess separation and overlap. - Plot correlation heat maps (and consider by-class heat maps) to spot strong predictor–predictor correlations that may signal multicollinearity.
How do I convert predicted probabilities into class labels and build a confusion matrix?Apply a threshold (e.g., 0.5) to probabilities to get predictions 0/1. Then cross-tabulate actual vs. predicted labels to obtain TN, FP, FN, TP. These counts power all standard classification metrics.
Which classification metrics should I report and how do I interpret them?- Sensitivity (Recall for class 1): TP/(TP+FN). - Specificity (TNR for class 0): TN/(TN+FP). - False Positive Rate: FP/(FP+TN). - False Negative Rate: FN/(TP+FN). - Accuracy: (TP+TN)/N; Misclassification rate: (FP+FN)/N. - AUC and ROC: threshold-independent discrimination; higher AUC (closer to 1) is better. Choose metrics based on context (e.g., prioritize sensitivity when missing positives is costly).

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Statistics Every Programmer Needs ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Statistics Every Programmer Needs ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Statistics Every Programmer Needs ebook for free