Statistical modeling with Python · Lesson 12 of 16
Logistic regression in Python (GLM)
Run a logistic regression as a GLM with statsmodels, turn coefficients into odds ratios, read them in plain words and predict probabilities.
Logistic regression models a yes/no outcome: passed or failed, bought or not, sick or healthy. It is a GLM (GLMs explained: family and link function) with a Binomial family and a logit link. It predicts the probability of "yes", always between 0 and 1.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
print(df["passed"].value_counts())
print(df.groupby("prep")["passed"].mean().round(3))
print(df.groupby("passed")[["hours", "absences"]].mean().round(2))passed
1 57
0 43
Name: count, dtype: int64
prep
no 0.537
yes 0.609
Name: passed, dtype: float64
hours absences
passed
0 5.27 4.79
1 9.68 3.61The same 100 students as before, now with the 0/1 column passed: counts, pass rate by prep course, averages by result.
Fit the model
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours + absences + C(prep)", data=df,
family=sm.families.Binomial()).fit()
print(model.params.round(3))
def show_p(p):
return "< 0.001" if p < 0.001 else f"{p:.3f}"
for name, p in model.pvalues.items():
print(f"{name:<15} p {show_p(p)}")Intercept -2.569 C(prep)[T.yes] 1.254 hours 0.457 absences -0.274 dtype: float64 Intercept p 0.003 C(prep)[T.yes] p 0.034 hours p < 0.001 absences p 0.010
Write the formula as for a linear regression, use smf.glm and pass family=sm.families.Binomial(). The outcome must be 0/1 (or True/False).
The coefficients are on the log-odds scale, which nobody thinks in. Signs are easy to read (hours and prep push the chance of passing up, absences push it down), but the sizes need one more step.
Odds ratios: the numbers to report
Odds are p / (1 − p): a 75% chance is odds of 3 (3 to 1). np.exp(coefficient) gives the odds ratio (OR): the factor by which the odds are multiplied for one more unit of the predictor. Take the exponential of the confidence interval too.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours + absences + C(prep)", data=df,
family=sm.families.Binomial()).fit()
table = pd.DataFrame({
"odds_ratio": np.exp(model.params),
"ci_low": np.exp(model.conf_int()[0]),
"ci_high": np.exp(model.conf_int()[1]),
})
print(table.round(2))odds_ratio ci_low ci_high Intercept 0.08 0.01 0.41 C(prep)[T.yes] 3.50 1.10 11.20 hours 1.58 1.32 1.89 absences 0.76 0.62 0.94
- hours, OR 1.58: each extra hour of study a week multiplies the odds of passing by 1.58, that is 58% higher odds, at the same absences and prep. Two extra hours: 1.58 × 1.58 ≈ 2.5 times the odds.
- absences, OR 0.76: each missed class multiplies the odds by 0.76, that is 24% lower odds.
- C(prep)[T.yes], OR 3.50: students who took the prep course have 3.5 times the odds of passing of those who did not, at the same hours and absences. The interval is wide (about 1.1 to 11), so the size is uncertain, but it is above 1.
- An OR of 1 means no effect. If the interval contains 1, the data are compatible with no effect.
Predicted probabilities. model.predict(new_data) returns the probability of passing for each new row. This is the easiest way to explain a model to anyone: compare a few typical people.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours + absences + C(prep)", data=df,
family=sm.families.Binomial()).fit()
new = pd.DataFrame({
"hours": [4, 8, 8, 12],
"absences": [3, 3, 3, 3],
"prep": ["no", "no", "yes", "no"],
})
new["p_pass"] = model.predict(new).round(3)
print(new)hours absences prep p_pass 0 4 3 no 0.173 1 8 3 no 0.565 2 8 3 yes 0.820 3 12 3 no 0.890
Same 3 absences: going from 4 to 8 hours lifts the chance of passing from about 17% to 57%; adding the prep course at 8 hours lifts it to 82%. The effect on the probability depends on where you start, which is exactly what odds ratios hide.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours + absences + C(prep)", data=df,
family=sm.families.Binomial()).fit()
import matplotlib.pyplot as plt
grid = pd.DataFrame({"hours": np.linspace(1, 14, 60), "absences": 3})
for prep, color in [("no", "steelblue"), ("yes", "darkorange")]:
p = model.predict(grid.assign(prep=prep))
plt.plot(grid["hours"], p, color=color, label=f"prep: {prep}")
print("Hours for a 50% chance, no prep:",
round(float(grid["hours"][(model.predict(grid.assign(prep="no")) >= 0.5).idxmax()]), 1))
plt.axhline(0.5, color="grey", linestyle="--")
plt.title("Chance of passing (3 absences)")
plt.xlabel("Hours of study per week")
plt.ylabel("Probability of passing")
plt.legend()
plt.show()Hours for a 50% chance, no prep: 7.6

The S-shaped curve of logistic regression: probabilities never leave 0 to 1.
The same model with smf.logit. statsmodels also has smf.logit, a dedicated logistic regression. It gives the same coefficients. Pass disp=0 to fit(), or it prints the steps of its optimiser.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
logit = smf.logit("passed ~ hours + absences + C(prep)", data=df).fit(disp=0)
print(logit.params.round(3))
print(f"pseudo R-squared: {logit.prsquared:.3f}")Intercept -2.569 C(prep)[T.yes] 1.254 hours 0.457 absences -0.274 dtype: float64 pseudo R-squared: 0.342
McFadden's pseudo R-squared: 0 = no better than the pass rate alone. As a rough rule of thumb, values of 0.2-0.4 already mean a good fit; it is not the R-squared of linear regression.
✎ Exercise
Fit a logistic GLM with hours only (passed ~ hours). Print the odds ratio for hours (3 decimals) and the predicted probability of passing for 6 and 10 hours (3 decimals).
Hint: np.exp(model.params["hours"]) for the odds ratio; model.predict(pd.DataFrame({"hours": [6, 10]})) for probabilities.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
# your code here
Expected output:
odds ratio for hours: 1.424 0 0.446 1 0.768 dtype: float64
Show a solution
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
df = pd.read_csv("students.csv")
model = smf.glm("passed ~ hours", data=df, family=sm.families.Binomial()).fit()
print(f"odds ratio for hours: {np.exp(model.params['hours']):.3f}")
new = pd.DataFrame({"hours": [6, 10]})
print(model.predict(new).round(3))odds ratio for hours: 1.424 0 0.446 1 0.768 dtype: float64
Check yourself
1. A predictor has an odds ratio of 1.6. What does it mean?
Odds ratios act on odds, p / (1 − p), not directly on probabilities.
2. The 95% interval of an odds ratio is 0.8 to 2.4. What can you say?
An OR of 1 means no change in the odds; it lies inside this interval.
3. How do you get the odds ratios from a fitted model?
Coefficients are log odds ratios; the exponential turns them into odds ratios.