Statistical modeling with Python · Lesson 9 of 16
Multiple regression and categorical variables
Add several predictors to a regression, read each coefficient 'holding the others fixed', use text columns with C(), reference levels and interactions.
Real outcomes depend on several things at once. Multiple regression puts them all in one model: score ~ hours + absences. Each coefficient then answers a sharper question than in Linear regression in Python with statsmodels: how much does the score change with one more hour, for students with the same number of absences?
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
simple = smf.ols("score ~ hours", data=df).fit()
multi = smf.ols("score ~ hours + absences", data=df).fit()
print("hours alone:", round(simple.params["hours"], 3))
print(multi.params.round(3))
print(f"R-squared: {simple.rsquared:.3f} -> {multi.rsquared:.3f}")hours alone: 3.512 Intercept 38.844 hours 3.542 absences -2.218 dtype: float64 R-squared: 0.430 -> 0.510
How to read it: with absences in the model, each extra hour goes with about 3.5 more points and each missed class with about 2.2 fewer points, holding the other one fixed. R-squared rises from 0.43 to 0.51: absences explain part of what hours alone could not.
Text columns: C() and the reference level
prep (yes / no) and course (math / biology / history) are categories. Inside a formula, C(course) turns a category into dummy columns, one 0/1 column per level except one. The level left out is the reference level (by default the first in alphabetical order, here biology), and every other level is compared with it.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.ols("score ~ hours + absences + C(prep) + C(course)", data=df).fit()
print(model.params.round(2))Intercept 28.86 C(prep)[T.yes] 11.05 C(course)[T.history] 10.15 C(course)[T.math] -5.51 hours 3.89 absences -2.15 dtype: float64
Text columns are turned into categories automatically, but writing C() makes it clear.
C(prep)[T.yes](11.05): students who took the prep course score about 11 points more than those who did not, at the same hours, absences and course.C(course)[T.history]andC(course)[T.math]: the difference from biology, the reference level. History students score about 10 points more than biology students, math students about 5.5 fewer, again at the same hours, absences and prep.[T.…]stands for treatment coding, the name of this 0/1 scheme.
To compare everything with math instead, name the reference level with Treatment. The model is the same (same predictions, same R-squared); only the comparisons printed change.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.ols('score ~ hours + absences + C(prep) + C(course, Treatment("math"))',
data=df).fit()
for name, value in model.params.round(2).items():
print(f"{name:<40}{value:>7}")
print(f"R-squared: {model.rsquared:.3f}")Intercept 23.35
C(prep)[T.yes] 11.05
C(course, Treatment("math"))[T.biology] 5.51
C(course, Treatment("math"))[T.history] 15.65
hours 3.89
absences -2.15
R-squared: 0.676Are the course differences real? Check their p-values and intervals as in the last lesson. A single test for the whole course variable (all levels at once) is an F-test: model.f_test(...) or comparing models, which Comparing models: AIC and cross-validation shows.
Interactions: when one effect depends on another
Maybe study hours pay off more for students who took the prep course. An interaction hours * C(prep) lets the slope of hours differ by group. The * adds both main effects and their product hours:C(prep)[T.yes].
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.ols("score ~ hours * C(prep) + absences", data=df).fit()
print(model.params.round(3))
p = model.pvalues["hours:C(prep)[T.yes]"]
print(f"interaction p-value: {p:.3f}")Intercept 31.998 C(prep)[T.yes] 8.972 hours 3.664 hours:C(prep)[T.yes] 0.364 absences -2.071 dtype: float64 interaction p-value: 0.618
How to read it: the slope of hours is the hours coefficient for students without prep, and hours + hours:C(prep)[T.yes] for students with prep. Here the interaction is small with a large p-value, so the data give no reason to think hours work differently with prep. The simpler model without the interaction is a reasonable choice.
a + b main effects; a:b only the product; a * b both plus the product; np.log(x) or I(x ** 2) transform a column inside the formula (import numpy as np first).✎ Exercise
Fit score ~ hours + absences + C(prep) and print the coefficients rounded to 2 decimals, then print the predicted score for a student with 10 hours, 2 absences and the prep course (1 decimal).
Hint: Give predict() a DataFrame with the raw columns hours, absences and prep; the formula does the rest.
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
# your code here
Expected output:
Intercept 30.64 C(prep)[T.yes] 11.75 hours 3.82 absences -2.07 dtype: float64 76.5
Show a solution
import pandas as pd
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.ols("score ~ hours + absences + C(prep)", data=df).fit()
print(model.params.round(2))
new = pd.DataFrame({"hours": [10], "absences": [2], "prep": ["yes"]})
print(round(float(model.predict(new).iloc[0]), 1))Intercept 30.64 C(prep)[T.yes] 11.75 hours 3.82 absences -2.07 dtype: float64 76.5
Check yourself
1. In score ~ hours + absences, what does the hours coefficient measure?
In multiple regression each coefficient holds the other predictors fixed.
2. C(course) has three levels. How many coefficients does it add?
One level is the reference; each of the other two gets a coefficient comparing it with the reference.
3. What does hours * C(prep) add compared with hours + C(prep)?
The * operator adds the product term hours:C(prep)[T.yes].