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.
When to use logistic regression
Section titled “When to use logistic regression”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.
Get the data
Section titled “Get the data”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-respondersBiomarker from 0.21 to 10.37from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport statsmodels.formula.api as smf
trial = pd.read_csv("logistic.csv")output = Path("outputs")output.mkdir(exist_ok=True)print(f"{len(trial)} patients: {(trial['responder'] == 1).sum()} responders, " f"{(trial['responder'] == 0).sum()} non-responders")print(f"Biomarker from {trial['biomarker'].min():.2f} to " f"{trial['biomarker'].max():.2f}")120 patients: 70 responders, 50 non-respondersBiomarker from 0.21 to 10.37Fit the model
Section titled “Fit the model”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-07biomarker 1.0587 0.1925 5.50 3.8e-08model = smf.logit("responder ~ biomarker", data=trial).fit(disp=False)print(f"{'term':<11} {'estimate':>8} {'SE':>7} {'z':>6} {'p':>8}")for term in model.params.index: print(f"{term:<11} {model.params[term]:8.4f} {model.bse[term]:7.4f} " f"{model.tvalues[term]:6.2f} {model.pvalues[term]:8.2g}")term estimate SE z pIntercept -4.6123 0.8917 -5.17 2.3e-07biomarker 1.0587 0.1925 5.50 3.8e-08The 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.
Read the odds ratio and its interval
Section titled “Read the odds ratio and its interval”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.88Wald 95% CI: 1.98 to 4.20Profile 95% CI: 2.05 to 4.39odds_ratio = np.exp(model.params["biomarker"])wald_ci = np.exp(model.conf_int().loc["biomarker"])print(f"Odds ratio per unit of biomarker: {odds_ratio:.2f}")print(f"Wald 95% CI: {wald_ci[0]:.2f} to {wald_ci[1]:.2f}")Odds ratio per unit of biomarker: 2.88Wald 95% CI: 1.98 to 4.20The 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.
Turn the fit into probabilities
Section titled “Turn the fit into probabilities”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$probabilitygrid$ratio <- grid$one_unit_higher / grid$probabilityprint(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.039grid = pd.DataFrame({"biomarker": [2, 4, 7]})one_higher = pd.DataFrame({"biomarker": grid["biomarker"] + 1})grid["probability"] = model.predict(grid)grid["one_unit_higher"] = model.predict(one_higher)grid["difference"] = grid["one_unit_higher"] - grid["probability"]grid["ratio"] = grid["one_unit_higher"] / grid["probability"]print(grid.round(3).to_string(index=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.039At 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.
Draw the logistic curve
Section titled “Draw the logistic curve”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.fitcurve_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)
curve_data = pd.DataFrame({ "biomarker": np.linspace(trial["biomarker"].min(), trial["biomarker"].max(), 200),})band = model.get_prediction(curve_data).summary_frame()
figure, axes = plt.subplots(figsize=(5, 4))axes.fill_between(curve_data["biomarker"], band["ci_lower"], band["ci_upper"], color="#1f2a44", alpha=0.2)axes.plot(curve_data["biomarker"], band["predicted"], color="#1f2a44")axes.scatter(trial["biomarker"], trial["responder"], alpha=0.3, color="#4c72b0")axes.set_xlabel("Biomarker")axes.set_ylabel("Probability of response")figure.tight_layout()figure.savefig(output / "logistic-curve-python.png", dpi=150)plt.close(figure)
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.
Pitfalls
Section titled “Pitfalls”- 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
ratiocolumn 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.
Key points
Section titled “Key points”- 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 andconf_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.
Further reading
Section titled “Further reading”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.