Historical Context & Motivation
Much of classical statistics was designed around continuous outcomes — predicting a person's height, a stock's price, or the yield of a chemical reaction. Yet many of the most consequential questions in computer science and data science involve binary outcomes: Will the user click? Will the email be spam? Will the patient be readmitted? Ordinary least squares regression is a poor fit for such problems because it can produce predicted values outside the [0, 1] interval and violates the assumptions of normally distributed errors. Logistic regression was developed precisely to address this gap, providing a principled probabilistic framework for modeling dichotomous response variables.
glm() function becomes a first-class citizen in R's stats package, making logistic regression accessible with a single function call.The central question logistic regression addresses is deceptively simple: given a set of predictor variables, how do we estimate the probability that a binary outcome equals 1 while respecting the constraint that probabilities must lie between 0 and 1? R's glm(..., family=binomial) syntax provides an elegant, one-line answer rooted in over 180 years of mathematical development.
Core Principles & Definitions
Logistic regression belongs to the broader family of Generalized Linear Models (GLMs). A GLM extends ordinary linear regression by allowing the response variable to follow any distribution in the exponential family (binomial, Poisson, gamma, etc.) and by connecting the expected value of the response to a linear predictor through a link function. For logistic regression the response is binomial and the link function is the logit. Understanding four foundational ideas will anchor everything that follows.
Binary Response Variable
The Logit Link Function
Maximum Likelihood Estimation
Odds and Odds Ratios
The Logistic (Sigmoid) Curve
The defining visual of logistic regression is the sigmoid curve, which maps any real-valued linear predictor to a probability between 0 and 1. The diagram below contrasts a naive linear fit (which can exceed [0, 1]) with the logistic curve, and annotates the critical inflection point at p = 0.5 where the model's decision boundary typically lies.
Observe that the sigmoid curve is nearly flat in the tails and steepest at the center. This behavior means that changes in the predictor Xβ near zero have the largest impact on the predicted probability, while extreme predictor values shift probability very little. This is a fundamental property of the nonlinear relationship between predictors and probability in logistic regression, and it has direct implications for how we interpret coefficients: a one-unit change in a predictor does not correspond to a constant change in probability.
Mathematical Framework
The mathematical core of logistic regression involves three related representations: the logit form (log-odds), the probability form (inverse logit), and the log-likelihood that is maximized to estimate coefficients. Understanding all three is essential for interpreting glm() output in R.
glm() maximizes this function via IRLS (Iteratively Reweighted Least Squares). The deviance reported in the output equals −2ℓ(β) and serves as the GLM analogue of the residual sum of squares.lm(). Three problems arise: (1) predicted values can fall outside [0, 1], (2) the error variance is heteroscedastic (it depends on p), and (3) the relationship between predictors and probability is fundamentally S-shaped, not linear. The logit link and binomial likelihood jointly resolve all three.The glm() Function — Syntax & Output Anatomy
In R, logistic regression is fit with a single call to glm() by specifying family = binomial (which defaults to the logit link). The function signature mirrors lm(), accepting a formula and a data frame, but internally it uses IRLS rather than QR decomposition. Below is a detailed anatomy of the function call and its output components.
glm() call into its four arguments (formula, data, family, output object) and shows the key components of the summary() output: the coefficients table, deviance information, AIC, and commonly used extractor and interpretation functions.| Output Component | Meaning | R Accessor |
|---|---|---|
Estimate | Coefficient β̂ on the log-odds scale | coef(model) |
Std. Error | Standard error of β̂, derived from the Fisher information matrix | summary(model)$coefficients[,2] |
z value | Wald statistic: β̂ / SE(β̂), analogous to the t-statistic in OLS | summary(model)$coefficients[,3] |
Pr(>|z|) | Two-sided p-value for the Wald test H₀: βⱼ = 0 | summary(model)$coefficients[,4] |
| Null Deviance | −2 × log-likelihood of the intercept-only model | model$null.deviance |
| Residual Deviance | −2 × log-likelihood of the fitted model; drop = improvement | model$deviance |
| AIC | Akaike Information Criterion: −2ℓ + 2k; lower is better | AIC(model) |
Worked Example — Predicting Spam Emails
Suppose we have a data frame email_df with 1000 emails, a binary column spam (1 = spam, 0 = not spam), and two numeric predictors: num_links (count of hyperlinks in the email body) and caps_pct (percentage of uppercase characters). We will fit a logistic regression model, examine the output, and make a prediction.
glm() with the formula spam ~ num_links + caps_pct and family = binomial. The R code is:
spam_model <- glm(spam ~ num_links + caps_pct, data = email_df, family = binomial)summary(spam_model) yields (hypothetical output):
(Intercept) -3.20 0.45 -7.11 <0.001 ***
num_links 0.52 0.08 6.50 <0.001 ***
caps_pct 0.10 0.03 3.33 0.0009 ***
Null deviance: 1200.5 on 999 df. Residual deviance: 850.3 on 997 df. AIC: 856.3.exp(coef(spam_model)):
• exp(0.52) ≈ 1.68 — each additional link multiplies the odds of spam by 1.68 (68% increase).
• exp(0.10) ≈ 1.11 — each 1 percentage-point increase in uppercase characters multiplies the odds by 1.11 (11% increase).predict(spam_model, newdata = data.frame(num_links=5, caps_pct=15), type='response')1 - pchisq(350.2, df=2) ≈ 0, confirming that the predictors collectively improve the model. We can also compute McFadden's pseudo-R²: 1 − (850.3 / 1200.5) ≈ 0.292, indicating a moderate fit.Strengths, Limitations & When to Use Logistic Regression
Logistic regression occupies a sweet spot in the modeling toolkit: it is powerful enough to reveal statistically significant relationships and produce calibrated probability estimates, yet simple enough to be fully interpretable. However, like any model, it comes with trade-offs that every practitioner must understand.
| Strengths | Limitations |
|---|---|
| Produces well-calibrated probabilities, not just class labels — critical for risk scoring and decision-making under uncertainty. | Assumes a linear relationship between predictors and the log-odds; cannot automatically capture nonlinear patterns or interactions. |
| Coefficients have a direct odds-ratio interpretation, making results transparent and explainable to stakeholders. | Sensitive to multicollinearity — highly correlated predictors inflate standard errors and destabilize coefficient estimates. |
| Computationally efficient; IRLS typically converges in under 25 iterations even on moderately large data sets. | Can suffer from complete or quasi-complete separation when a predictor perfectly predicts the outcome, causing coefficients to diverge. |
| Well-studied statistical properties — asymptotic normality of MLEs, Wald tests, likelihood-ratio tests, and confidence intervals are all readily available. | Basic form handles only binary outcomes; ordinal or multinomial responses require extensions (ordinal logistic, multinomial logistic). |
| Acts as a strong baseline model in ML pipelines; outperforms complex models when the true decision boundary is approximately linear. | No built-in regularization in base R's glm(); use glmnet for L1/L2 penalties when p is large relative to n. |
Connection to Advanced Methods
Logistic regression via glm() is the starting point for a family of increasingly flexible models. Understanding how it connects to these extensions helps you know when to graduate to more powerful tools and what you trade away when you do.
| Feature | glm() Logistic Regression | Advanced Extension |
|---|---|---|
| Regularization | No penalty; MLE only | glmnet: L1 (Lasso), L2 (Ridge), Elastic Net for variable selection and shrinkage |
| Nonlinear effects | Linear in log-odds; manually add polynomials or interactions | GAMs (mgcv::gam) fit smooth splines for each predictor automatically |
| Response categories | Binary (0/1) only | nnet::multinom for multinomial; MASS::polr for ordinal outcomes |
| Random effects | Fixed effects only; no grouping structure | lme4::glmer for mixed-effects logistic regression with hierarchical/clustered data |
| Prediction power | Strong baseline; linear decision boundary | Random forests, gradient boosting (xgboost), neural nets — nonlinear boundaries, higher capacity, less interpretability |
A key insight is that logistic regression's loss function — the negative log-likelihood — is identical to the binary cross-entropy loss used in neural networks. When you train a neural network for binary classification with a single sigmoid output unit and no hidden layers, you are literally fitting logistic regression. This equivalence means that every concept you learn here — odds ratios, log-likelihood, deviance — transfers directly into deep learning diagnostics. Mastering glm() is therefore not just a statistics exercise; it is building foundational intuition for modern machine learning.
Practice Problems
m1 <- glm(admit ~ gre, data=grad, family=binomial)
m2 <- glm(admit ~ gre + gpa + rank, data=grad, family=binomial)
Model m1 has residual deviance 486.1 (df = 398) and m2 has residual deviance 458.5 (df = 394). Perform a likelihood-ratio test to determine whether the additional predictors (gpa, rank) significantly improve the model. Show the R code and interpret the result.churn_mod <- glm(churned ~ tenure_months + support_tickets + plan_tier, data=customers, family=binomial), you obtain: β_tenure_months = −0.08, β_support_tickets = 0.35, and for plan_tier (reference = 'free'): β_basic = −0.50, β_premium = −1.20. Interpret each coefficient in business terms. Then write the R code to predict churn probability for a premium-tier customer with 18 months of tenure and 3 support tickets.Lesson Summary
Logistic regression models binary outcomes by applying the logit link function — log(p / (1 − p)) — to map a linear predictor Xβ to probabilities in (0, 1) via the sigmoid function. Coefficients are estimated through maximum likelihood estimation (IRLS) rather than OLS, and the primary interpretation tool is the odds ratio: exp(βⱼ) gives the multiplicative change in odds for a one-unit increase in xⱼ.
In R, the entire workflow fits into glm(y ~ x, data, family = binomial). The summary() output reports the coefficients table (Wald z-tests), null and residual deviance for assessing overall fit, and AIC for model comparison. Predictions on the probability scale require predict(..., type = 'response'). This model serves as the interpretable, efficient baseline classifier from which all more complex binary classification methods — regularized regression, GAMs, tree ensembles, and neural networks — depart.