DS Multiple Regression
Multiple regression uses several explanatory variables at once:
rides = b0 + b1 × temp_c + b2 × rain_mm + b3 × weekend + errorYou already fitted such a model in the Linear Regression Case. This lesson looks at why it's more than "several simple regressions glued together", and at the pitfalls that come with more variables.
"Holding the others fixed"
Each coefficient in a multiple regression is the change in the prediction when its variable rises by one unit while all other variables in the model stay the same. That can differ a lot from the simple, one-variable slope, because the simple slope also picks up the effects of every variable correlated with it.
Recall the sunglasses puzzle from Correlation vs Causality: sunglasses sales and rides were both driven by temperature. Let's see what regression makes of it:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(7)
temp = rng.uniform(4, 30, 60).round(1)
sunglasses = (2 + 0.8 * temp + rng.normal(0, 3, 60)).round().clip(0).astype(int)
rides = (150 + 12 * temp + rng.normal(0, 40, 60)).round().astype(int)
df = pd.DataFrame({"temp_c": temp, "sunglasses": sunglasses, "rides": rides})
simple = smf.ols("rides ~ sunglasses", data=df).fit()
multiple = smf.ols("rides ~ sunglasses + temp_c", data=df).fit()
print("simple: sunglasses coef =", round(simple.params["sunglasses"], 2),
" p =", f"{simple.pvalues['sunglasses']:.1e}")
print("multiple: sunglasses coef =", round(multiple.params["sunglasses"], 2),
" p =", round(multiple.pvalues["sunglasses"], 3))
print("multiple: temp_c coef =", round(multiple.params["temp_c"], 2))simple: sunglasses coef = 12.59 p = 3.1e-20
multiple: sunglasses coef = 1.0 p = 0.612
multiple: temp_c coef = 11.33
Alone, sunglasses look like a strong predictor (about +12.6 rides per pair sold, p ≈ 10⁻²⁰). Once temperature is in the model, the sunglasses coefficient shrinks to about 1 and loses its significance (p ≈ 0.61), while temperature keeps a slope close to the true +12. Multiple regression controls for the confounder — as long as you measured it and put it in.
Omitted-variable bias
The flip side: leaving out an important variable that correlates with an included one biases the included coefficient. In Riverside Bikes, warmer days happen to fall slightly more often on weekends (correlation 0.18), so the temperature-only model gives temperature a bit of the weekend's credit:
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
for f in ["rides ~ temp_c", "rides ~ temp_c + weekend", "rides ~ temp_c + weekend + rain_mm"]:
m = smf.ols(f, data=bikes).fit()
lo, hi = m.conf_int().loc["temp_c"]
print(f"{f:36} temp slope={m.params['temp_c']:6.2f} 95% CI [{lo:5.2f}, {hi:5.2f}]")rides ~ temp_c temp slope= 12.54 95% CI [10.52, 14.57]
rides ~ temp_c + weekend temp slope= 11.78 95% CI [10.03, 13.53]
rides ~ temp_c + weekend + rain_mm temp slope= 11.49 95% CI [10.33, 12.66]
As variables are added, the temperature slope moves from 12.54 towards the true value 12, and the confidence interval narrows a lot: the other variables "soak up" variation that used to be noise.
Multicollinearity
When two predictors are strongly correlated with each other, the model can't tell their effects apart. The coefficients become unstable and their standard errors balloon — although predictions may still be fine. The variance inflation factor (VIF) measures it: values above about 5–10 signal a problem.
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from statsmodels.stats.outliers_influence import variance_inflation_factor
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
# a second thermometer in the shade: almost the same information as temp_c
bikes["shade_temp"] = (bikes["temp_c"] - 2 + np.random.default_rng(3).normal(0, 0.8, 60)).round(1)
m = smf.ols("rides ~ temp_c + shade_temp + rain_mm + weekend", data=bikes).fit()
print(m.summary2().tables[1][["Coef.", "Std.Err.", "P>|t|"]].round(3))
X = m.model.exog
names = m.model.exog_names
print()
for i, name in enumerate(names[1:], start=1):
print(f"VIF {name:10} {variance_inflation_factor(X, i):6.1f}") Coef. Std.Err. P>|t|
Intercept 174.903 14.626 0.000
temp_c 2.598 4.841 0.594
shade_temp 8.884 4.800 0.070
rain_mm -8.943 1.048 0.000
weekend 64.200 9.434 0.000
VIF temp_c 74.8
VIF shade_temp 74.8
VIF rain_mm 1.0
VIF weekend 1.0
With both thermometers in the model, the two temperature coefficients get large standard errors: the model can shift weight between them almost freely. The VIFs of temp_c and shade_temp are far above 10. The cure is to keep only one of them (or combine them into one feature).
Choosing variables
- Start from domain knowledge: which variables plausibly affect the target?
- Include known confounders, even if their own coefficients aren't interesting.
- Avoid variables that are consequences of the target (e.g. "bikes needing repair", which rises because of many rides).
- Compare candidate models with adjusted R², AIC, and above all performance on held-out data (next lessons).
Test yourself
In a multiple regression, what does the temp_c coefficient describe?
- The correlation between temp and rides
- The change in predicted rides per degree, holding the other variables fixed
- The average temperature
- The R² of temperature
After adding temperature to the model, the sunglasses coefficient drops to near zero. Why?
- Sunglasses data was wrong
- Temperature was a confounder; controlling for it removes the spurious association
- Adding variables always sets others to zero
- The intercept absorbed it
Two predictors have VIFs of 40. What is the likely problem?
- Missing values
- They are strongly correlated with each other (multicollinearity)
- The intercept is missing
- The target is skewed