Multiple Regression & Diagnostics
Most outcomes depend on more than one variable. Multiple regression puts several predictors into one model, and each coefficient then estimates the change in the outcome per unit of its predictor with the other predictors held fixed. This page fits a confounded effect, adjusts for the confounder, and runs three diagnostics on the adjusted model, in R and Python.
When to use multiple regression
Section titled “When to use multiple regression”Use it when several variables can influence the outcome, and above all when the predictor you care about is correlated with another cause of the outcome. A model that leaves out that other cause assigns part of its effect to your predictor.
Get the data
Section titled “Get the data”Download multi_regression.csv into your working directory. The invented table has 80 rows, one per independent sample, and three columns: expression, the log2 expression of one gene, age in years, and viability, the percentage of viable cells.
The values come from a simulation with a known answer. Expression rises with age. Viability falls by 2.5 points per unit of expression and by 0.5 points per year of age. Age is a confounder, because it raises expression and lowers viability on its own.
The Python code numbers the rows from 1, as R does, so that both tabs name a sample by the same row number.
library(car)library(ggplot2)
multi <- read.csv("multi_regression.csv")dir.create("outputs", showWarnings = FALSE)cat(sprintf("%d samples, columns: %s\n", nrow(multi), paste(names(multi), collapse = ", ")))cat(sprintf("Correlation of expression and age: r = %.3f\n", cor(multi$expression, multi$age)))80 samples, columns: expression, age, viabilityCorrelation of expression and age: r = 0.616from pathlib import Path
import matplotlib.pyplot as pltimport pandas as pdimport statsmodels.formula.api as smffrom statsmodels.stats.outliers_influence import variance_inflation_factor
multi = pd.read_csv("multi_regression.csv")multi.index = multi.index + 1output = Path("outputs")output.mkdir(exist_ok=True)print(f"{len(multi)} samples, columns: {', '.join(multi.columns)}")print("Correlation of expression and age: " f"r = {multi['expression'].corr(multi['age']):.3f}")80 samples, columns: expression, age, viabilityCorrelation of expression and age: r = 0.616Expression and age correlate at r = 0.616. Samples with high expression are, on average, the older samples.
The confounded simple model
Section titled “The confounded simple model”First fit viability on expression alone.
simple <- lm(viability ~ expression, data = multi)simple_ci <- confint(simple)["expression", ]cat(sprintf("Simple model, expression: %.3f, 95%% CI [%.3f, %.3f]\n", coef(simple)["expression"], simple_ci[1], simple_ci[2]))Simple model, expression: -5.595, 95% CI [-7.010, -4.180]simple = smf.ols("viability ~ expression", data=multi).fit()simple_ci = simple.conf_int().loc["expression"]print(f"Simple model, expression: {simple.params['expression']:.3f}, " f"95% CI [{simple_ci[0]:.3f}, {simple_ci[1]:.3f}]")Simple model, expression: -5.595, 95% CI [-7.010, -4.180]Each unit of expression goes with 5.6 fewer points of viability, and the interval, -7.01 to -4.18, excludes the simulated effect of -2.5. The interval describes the association in the table correctly. It answers the wrong question for anyone who wants the effect of expression, because the samples with high expression are also older and this model cannot tell the two apart.
The adjusted model
Section titled “The adjusted model”Add age, and the model estimates each coefficient with the other predictor held fixed. The code prints the coefficient table with 95% confidence intervals, the residual standard error, and adjusted R-squared.
full <- lm(viability ~ expression + age, data = multi)coef_table <- cbind(coef(summary(full)), confint(full))print(coef_table, digits = 3)cat(sprintf("Residual standard error %.3f on %d degrees of freedom\n", sigma(full), df.residual(full)))cat(sprintf("Adjusted R-squared %.3f\n", summary(full)$adj.r.squared)) Estimate Std. Error t value Pr(>|t|) 2.5 % 97.5 %(Intercept) 100.856 2.7457 36.73 1.45e-50 95.388 106.323expression -2.247 0.6646 -3.38 1.14e-03 -3.570 -0.923age -0.535 0.0654 -8.18 4.65e-12 -0.665 -0.405Residual standard error 5.535 on 77 degrees of freedomAdjusted R-squared 0.694full = smf.ols("viability ~ expression + age", data=multi).fit()limits = full.conf_int()coef_table = pd.DataFrame({ "estimate": full.params, "std_error": full.bse, "t": full.tvalues, "p": full.pvalues, "ci_low": limits[0], "ci_high": limits[1],})print(coef_table.to_string(float_format="{:.4g}".format))print(f"Residual standard error {full.mse_resid**0.5:.3f} " f"on {full.df_resid:.0f} degrees of freedom")print(f"Adjusted R-squared {full.rsquared_adj:.3f}") estimate std_error t p ci_low ci_highIntercept 100.9 2.746 36.73 1.454e-50 95.39 106.3expression -2.247 0.6646 -3.38 0.001139 -3.57 -0.9233age -0.5349 0.06541 -8.176 4.651e-12 -0.6651 -0.4046Residual standard error 5.535 on 77 degrees of freedomAdjusted R-squared 0.694With age in the model, the expression coefficient is -2.25, with a 95% interval from -3.57 to -0.92 that includes the simulated -2.5. Each year of age goes with 0.535 fewer points of viability, and that interval, -0.665 to -0.405, includes the simulated -0.5. Both tabs print the same fit.
The value -2.25 is the estimate of the expression effect under this model. It estimates the causal effect here only because the simulation made age the single confounder and gave both predictors straight-line effects. In a real study, a confounder that nobody measured would bias the adjusted coefficient in the same way that age biased the simple one, and no line of the output would show it.
Adjusted R-squared is 0.694. Plain R-squared rises whenever you add a predictor, even a useless one, so compare models of different size with the adjusted value.
Seeing the adjustment
Section titled “Seeing the adjustment”The figure draws the expression coefficient of each model with its 95% interval.
full_ci <- confint(full)["expression", ]comparison <- data.frame( model = factor(c("Simple", "Adjusted for age"), levels = c("Simple", "Adjusted for age")), estimate = c(coef(simple)["expression"], coef(full)["expression"]), ci_low = c(simple_ci[1], full_ci[1]), ci_high = c(simple_ci[2], full_ci[2]))comparison_plot <- ggplot(comparison, aes(model, estimate)) + geom_hline(yintercept = 0, linetype = "dashed", color = "grey50") + geom_errorbar(aes(ymin = ci_low, ymax = ci_high), width = 0.15, color = "#1f4e5f") + geom_point(size = 3, color = "#1f4e5f") + labs(x = NULL, y = "Expression coefficient (points per unit)") + theme_classic(base_size = 12)ggsave("outputs/confounding-r.png", comparison_plot, width = 5, height = 4, dpi = 150)
full_ci = full.conf_int().loc["expression"]comparison = pd.DataFrame({ "model": ["Simple", "Adjusted for age"], "estimate": [simple.params["expression"], full.params["expression"]], "ci_low": [simple_ci[0], full_ci[0]], "ci_high": [simple_ci[1], full_ci[1]],})figure, axes = plt.subplots(figsize=(5, 4))axes.axhline(0, linestyle="--", color="grey")axes.errorbar( comparison["model"], comparison["estimate"], yerr=[comparison["estimate"] - comparison["ci_low"], comparison["ci_high"] - comparison["estimate"]], fmt="o", color="#1f2a44", markersize=8, capsize=5)axes.set_xlim(-0.5, 1.5)axes.set_ylabel("Expression coefficient (points per unit)")figure.tight_layout()figure.savefig(output / "confounding-python.png", dpi=150)plt.close(figure)
The estimate moves from -5.6 to -2.25 when age enters the model, and the two intervals do not overlap. More than half of the simple coefficient came from age.
Diagnostics
Section titled “Diagnostics”The adjusted model rests on the same assumptions as a simple regression, and it adds one new way to fail: predictors that carry nearly the same information. Three checks follow.
Variance inflation factors
Section titled “Variance inflation factors”The variance inflation factor (VIF) of a predictor is 1 / (1 - R²), where R² comes from a regression of that predictor on the other predictors. Collinearity multiplies the variance of the coefficient by this factor, so its square root multiplies the standard error. vif() from car computes it in R. In statsmodels, variance_inflation_factor() takes the design matrix and a column number, so the code loops over the columns and skips the intercept.
inflation <- vif(full)cat(sprintf("%s: VIF = %.3f, standard error factor = %.3f\n", names(inflation), inflation, sqrt(inflation)), sep = "")expression: VIF = 1.612, standard error factor = 1.270age: VIF = 1.612, standard error factor = 1.270design = full.model.exogfor column, name in enumerate(full.model.exog_names): if name != "Intercept": inflation = variance_inflation_factor(design, column) print(f"{name}: VIF = {inflation:.3f}, " f"standard error factor = {inflation**0.5:.3f}")expression: VIF = 1.612, standard error factor = 1.270age: VIF = 1.612, standard error factor = 1.270With two predictors the two factors are equal, and both follow from the correlation printed at the top: 1 / (1 - 0.616²) is 1.612. The standard error of each coefficient is 1.27 times what it would be with uncorrelated predictors. That cost is modest, and the interval for expression still excludes zero. A correlation of 0.95 between the predictors would push the VIF above 10, and the model could then no longer separate expression from age.
Residuals against fitted values
Section titled “Residuals against fitted values”Plot the residuals of the adjusted model against its fitted values. A curve points to a predictor whose effect is not a straight line, or to a missing interaction. A funnel points to a spread that changes with the fitted value.
residuals_table <- data.frame(fitted = fitted(full), residual = resid(full))residual_plot <- ggplot(residuals_table, aes(fitted, residual)) + geom_point(color = "#69b3a2", alpha = 0.8, size = 2) + geom_hline(yintercept = 0, linetype = "dashed", color = "#1f4e5f") + labs(x = "Fitted viability (%)", y = "Residual (%)") + theme_classic(base_size = 12)ggsave("outputs/multiple-regression-resid-r.png", residual_plot, width = 5, height = 4, dpi = 150)
figure, axes = plt.subplots(figsize=(5, 4))axes.scatter(full.fittedvalues, full.resid, alpha=0.8, color="#4c72b0")axes.axhline(0, linestyle="--", color="#1f2a44")axes.set_xlabel("Fitted viability (%)")axes.set_ylabel("Residual (%)")figure.tight_layout()figure.savefig(output / "multiple-regression-resid-python.png", dpi=150)plt.close(figure)
The residuals scatter around zero over the whole range of fitted values, with no curve and no funnel, so the plot gives no reason to doubt the straight-line terms or the constant spread. It is compatible with the model and does not prove it. A few samples lie more than 10 points from zero, and the next check asks whether any of them moves the estimate.
Influential observations
Section titled “Influential observations”Cook’s distance measures how far the fitted values of all samples move when one sample is left out of the fit. It grows with the residual of that sample and with its leverage, which is high when the sample has an unusual combination of predictor values. The code lists the three samples with the largest distance, then fits the model again without the first of them.
cooks <- cooks.distance(full)top <- order(cooks, decreasing = TRUE)[1:3]influence_table <- cbind(multi[top, ], residual = round(resid(full)[top], 2), leverage = round(hatvalues(full)[top], 3), cooks_distance = round(cooks[top], 3))print(influence_table)refit <- lm(viability ~ expression + age, data = multi[-top[1], ])refit_ci <- confint(refit)["expression", ]cat(sprintf("All samples, expression: %.3f, 95%% CI [%.3f, %.3f]\n", coef(full)["expression"], full_ci[1], full_ci[2]))cat(sprintf("Without row %d, expression: %.3f, 95%% CI [%.3f, %.3f]\n", top[1], coef(refit)["expression"], refit_ci[1], refit_ci[2])) expression age viability residual leverage cooks_distance35 3.016 33.3 65.02 -11.25 0.063 0.09955 0.648 40.1 88.74 10.79 0.060 0.08662 3.970 62.3 42.64 -15.97 0.024 0.071All samples, expression: -2.247, 95% CI [-3.570, -0.923]Without row 35, expression: -2.037, 95% CI [-3.346, -0.729]influence = full.get_influence()cooks = pd.Series(influence.cooks_distance[0], index=multi.index)leverage = pd.Series(influence.hat_matrix_diag, index=multi.index)top = cooks.nlargest(3)influence_table = multi.loc[top.index].assign( residual=full.resid.loc[top.index].round(2), leverage=leverage.loc[top.index].round(3), cooks_distance=top.round(3))print(influence_table.to_string())refit = smf.ols("viability ~ expression + age", data=multi.drop(index=top.index[0])).fit()refit_ci = refit.conf_int().loc["expression"]print(f"All samples, expression: {full.params['expression']:.3f}, " f"95% CI [{full_ci[0]:.3f}, {full_ci[1]:.3f}]")print(f"Without row {top.index[0]}, expression: " f"{refit.params['expression']:.3f}, " f"95% CI [{refit_ci[0]:.3f}, {refit_ci[1]:.3f}]") expression age viability residual leverage cooks_distance35 3.016 33.3 65.02 -11.25 0.063 0.09955 0.648 40.1 88.74 10.79 0.060 0.08662 3.970 62.3 42.64 -15.97 0.024 0.071All samples, expression: -2.247, 95% CI [-3.570, -0.923]Without row 35, expression: -2.037, 95% CI [-3.346, -0.729]Row 35 has the largest distance, 0.099. It is a 33-year-old sample with an expression of 3.016, an unusual pair in a table where expression rises with age, so its leverage is 0.063 against an average of 3/80, or 0.0375, for this model. Its viability sits 11.25 points below the fitted value. Row 62 has the largest residual of the three, -15.97, with a leverage of only 0.024 and a smaller distance: a large residual moves the fit less when the predictor values are ordinary.
Leaving row 35 out moves the expression coefficient from -2.247 to -2.037. The shift of 0.21 is about a third of the standard error of 0.665, and the interval still excludes zero, so the most influential sample does not decide the conclusion. The second fit is a sensitivity check. Keep row 35 in the analysis unless the lab record shows that the measurement is wrong.
Limits of adjustment
Section titled “Limits of adjustment”Adjust for a confounder, and do not adjust for a mediator. If expression lowered viability by first raising a stress marker, a model with that marker as a predictor would hold fixed the path that carries the effect, and the expression coefficient would shrink toward zero for the wrong reason.
A coefficient holds the other predictors fixed only in the form the model gives them. Here age enters as a straight line. If viability dropped sharply after 60 and changed little before, a straight-line term for age would leave part of the confounding in the expression coefficient.
The model also treats the 80 rows as independent samples. Several samples from one donor share that donor’s age and much of its biology, and they belong in a mixed model.
Scientific references
Section titled “Scientific references”Fox and Weisberg, 2019, describe the car functions in An R Companion to Applied Regression.
Cook, 1977 introduces the distance that measures the influence of one observation on a least-squares fit.
Further reading
Section titled “Further reading”The R linear model reference documents the formula interface for several predictors. The R influence measures reference defines Cook’s distance, leverage, and the other leave-one-out statistics that lm supports.
The statsmodels OLS example shows model construction in Python and a case of collinear predictors. The statsmodels regression diagnostics example lists the diagnostic tests and influence statistics of a fitted model.
An Introduction to Statistical Learning explains in its third chapter why a simple and a multiple regression coefficient differ, and it covers collinearity and high-leverage points. Continue with Logistic Regression when the outcome has two classes.