Skip to content

Logistic Regression

When the outcome is yes or no, responder or not, alive or dead, a straight line is the wrong model, because it predicts probabilities below zero and above one. Logistic regression models the log-odds of the outcome, so every predicted probability stays between zero and one, and it reports each effect as an odds ratio. This page predicts treatment response from a biomarker in R and Python.

Use it when the outcome is binary and each row is one independent experimental unit, here one patient. The model writes the log-odds of the outcome as a linear function of the predictors. The exponential of a coefficient is an odds ratio: the factor by which the odds change when that predictor rises by one unit.

Download logistic.csv into your working directory. The invented table has 120 rows, one per patient, and two columns. biomarker is a continuous measurement taken before treatment, and responder is 1 for a patient who responded and 0 for a patient who did not.

library(ggplot2)
trial <- read.csv("logistic.csv")
dir.create("outputs", showWarnings = FALSE)
cat(sprintf("%d patients: %d responders, %d non-responders\n", nrow(trial),
sum(trial$responder == 1), sum(trial$responder == 0)))
cat(sprintf("Biomarker from %.2f to %.2f\n", min(trial$biomarker),
max(trial$biomarker)))
120 patients: 70 responders, 50 non-responders
Biomarker from 0.21 to 10.37

glm() with family = binomial fits the model in R, and smf.logit() fits it in statsmodels. Both maximize the same likelihood. statsmodels prints a message from its optimizer unless you pass disp=False.

fit <- glm(responder ~ biomarker, data = trial, family = binomial)
estimates <- coef(summary(fit))
cat(sprintf("%-11s %8s %7s %6s %8s\n", "term", "estimate", "SE", "z", "p"))
cat(sprintf("%-11s %8.4f %7.4f %6.2f %8.2g\n", rownames(estimates),
estimates[, "Estimate"], estimates[, "Std. Error"],
estimates[, "z value"], estimates[, "Pr(>|z|)"]), sep = "")
term estimate SE z p
(Intercept) -4.6123 0.8917 -5.17 2.3e-07
biomarker 1.0587 0.1925 5.50 3.8e-08

The biomarker coefficient is 1.0587, so each additional unit of biomarker adds 1.0587 to the log-odds of response. Its p-value, 3.8e-08, says that a slope of zero fits these 120 patients poorly. It says nothing about the size of the effect, and a change in log-odds is hard to picture. The intercept, -4.6123, is the log-odds of response at a biomarker of zero, just below the lowest observed value of 0.21. R and statsmodels agree on every digit shown.

Exponentiate the coefficient to get the odds ratio, and exponentiate the limits of its confidence interval to get the interval of the odds ratio. R offers two intervals for a glm. confint.default() returns the Wald interval, the estimate plus or minus 1.96 standard errors on the log-odds scale. confint() returns the profile likelihood interval, which keeps every value of the coefficient that a likelihood ratio test does not reject at the 5% level. While it works, confint() prints the message “Waiting for profiling to be done…”.

odds_ratio <- exp(coef(fit)[["biomarker"]])
wald_ci <- exp(confint.default(fit)["biomarker", ])
profile_ci <- exp(confint(fit)["biomarker", ])
cat(sprintf("Odds ratio per unit of biomarker: %.2f\n", odds_ratio))
cat(sprintf("Wald 95%% CI: %.2f to %.2f\n", wald_ci[1], wald_ci[2]))
cat(sprintf("Profile 95%% CI: %.2f to %.2f\n", profile_ci[1], profile_ci[2]))
Odds ratio per unit of biomarker: 2.88
Wald 95% CI: 1.98 to 4.20
Profile 95% CI: 2.05 to 4.39

The odds ratio is 2.88: each one-unit rise in the biomarker multiplies the odds of response by 2.88. Read the interval as the range of odds ratios that are compatible with the data. By the Wald interval, that range runs from 1.98 to 4.20. A doubling and a quadrupling of the odds per unit are both plausible, and an odds ratio of 1, which means no association, is not.

conf_int() in statsmodels returns the Wald interval, and it matches confint.default() in R. The profile likelihood interval, 2.05 to 4.39, sits higher at both ends. The Wald interval is symmetric around the coefficient on the log-odds scale, which is exact only when the log-likelihood is a parabola. The profile interval follows the actual shape of the log-likelihood.

In a large sample the two intervals agree. They move apart when the sample is small, when one outcome class has few patients, or when the coefficient is large, and the profile interval is the one to prefer there. With 50 patients in the smaller class, the upper limits already differ in the first decimal. State which interval you report: confint() in R and conf_int() in statsmodels are the default calls, and they return different limits for the same model.

An odds ratio is constant along the biomarker, and the change in probability is not. Predict the probability of response at three biomarker values, and again one unit higher.

grid <- data.frame(biomarker = c(2, 4, 7))
one_higher <- data.frame(biomarker = grid$biomarker + 1)
grid$probability <- predict(fit, grid, type = "response")
grid$one_unit_higher <- predict(fit, one_higher, type = "response")
grid$difference <- grid$one_unit_higher - grid$probability
grid$ratio <- grid$one_unit_higher / grid$probability
print(round(grid, 3), row.names = FALSE)
biomarker probability one_unit_higher difference ratio
2 0.076 0.192 0.116 2.521
4 0.407 0.664 0.257 1.633
7 0.943 0.979 0.037 1.039

At a biomarker of 2, the predicted probability of response is 0.076, and one more unit raises it to 0.192, a gain of 0.116. At 4, the same unit takes the probability from 0.407 to 0.664, a gain of 0.257. At 7, almost every patient already responds, and the unit adds only 0.037. The odds ratio is 2.88 at all three starting points.

No single change in probability describes the model. When the audience needs a risk, quote the predicted probability at a named biomarker value.

Predict over a grid of biomarker values to draw the fitted curve. The band is a 95% Wald interval computed on the log-odds scale and then transformed to a probability, so it cannot leave the range from zero to one. get_prediction() in statsmodels builds its interval the same way.

curve_data <- data.frame(
biomarker = seq(min(trial$biomarker), max(trial$biomarker), length.out = 200)
)
log_odds <- predict(fit, curve_data, type = "link", se.fit = TRUE)
margin <- qnorm(0.975) * log_odds$se.fit
curve_data$probability <- plogis(log_odds$fit)
curve_data$lower <- plogis(log_odds$fit - margin)
curve_data$upper <- plogis(log_odds$fit + margin)
curve_plot <- ggplot(curve_data, aes(biomarker, probability)) +
geom_ribbon(aes(ymin = lower, ymax = upper), fill = "#1f4e5f",
alpha = 0.2) +
geom_line(color = "#1f4e5f", linewidth = 1) +
geom_point(data = trial, aes(y = responder), alpha = 0.3,
color = "#69b3a2") +
labs(x = "Biomarker", y = "Probability of response") +
theme_minimal(base_size = 13)
ggsave("outputs/logistic-curve-r.png", curve_plot, width = 5, height = 4,
dpi = 150)

Fitted logistic curve from ggplot2. The probability of response rises in an S shape from near 0 at low biomarker values to near 1 at high values, inside a 95% band, with one point per patient at 0 or 1.

The points at 0 and 1 are the patients. The curve is steepest where the predicted probability is 0.5 and flattens toward both ends, which is why the same odds ratio moved the probability by different amounts in the table above.

  • An odds ratio is not a risk ratio. From a biomarker of 4 to 5, the odds of response multiply by 2.88 while the probability multiplies by 1.633, the ratio column above. Write “the odds of response are 2.88 times higher”, not “response is 2.88 times more likely”. The two ratios come close only where the outcome is rare, as in the first row.
  • A perfect split breaks the fit. When one biomarker value separates every responder from every non-responder, the likelihood has no finite maximum. R warns that fitted probabilities are numerically 0 or 1, statsmodels warns that the optimization did not converge and for some tables also raises a PerfectSeparationWarning, and both return a huge coefficient with a larger standard error. Small tables and rare outcomes are prone to it.
  • The smaller outcome class limits the model. This table has 50 non-responders, and that count, not the 120 patients, sets how many predictors the model can support. A common rule of thumb asks for at least ten patients in the smaller class for each coefficient.
  • An odds ratio belongs to its unit. The value 2.88 is per one unit of this biomarker. Record the biomarker in a unit ten times smaller, and the odds ratio per unit moves toward 1 while the fitted probabilities stay the same.
  • Logistic regression models the log-odds of a binary outcome, so every predicted probability stays between zero and one.
  • The exponential of a coefficient is the odds ratio per unit of the predictor. Report it with its interval, and read the interval as the range of odds ratios compatible with the data.
  • confint() in R returns a profile likelihood interval. confint.default() in R and conf_int() in statsmodels return a Wald interval.
  • One odds ratio changes the probability by different amounts along the curve, so show predicted probabilities at the values that matter.
  • An odds ratio approximates a risk ratio only when the outcome is rare.

The R generalized linear model reference explains the family, link, and formula arguments used by the binomial model. An Introduction to Statistical Learning places logistic regression within classification and provides R and Python labs.

The ROC Curves and AUC lesson examines how a model’s scores distinguish the two outcome classes.