Skip to content

statsmodels

statsmodels fits the classical models and prints the tables a reviewer asks for: coefficients, standard errors, confidence intervals, and p-values. Reach for it when the question is about an effect size rather than a prediction score. The formula interface reads like R, so expression ~ treatment + batch means the same thing in both. Every block below ran with statsmodels 0.15, which still parses formulas with patsy by default. Set the environment variable SM_FORMULA_ENGINE=formulaic to switch engines.

Task Call
Linear model smf.ols("y ~ a + b", data=df).fit()
Coefficient table model.summary().tables[1]
Confidence intervals model.conf_int()
Prediction intervals model.get_prediction(new).summary_frame()
Robust standard errors smf.ols(...).fit(cov_type="HC3")
ANOVA table anova_lm(model, typ=2)
Nested model test anova_lm(reduced, full)
Pairwise comparisons pairwise_tukeyhsd(y, groups)
QQ plot sm.qqplot(model.resid, line="45", fit=True)
Logistic regression smf.logit("y ~ x", data=df).fit(disp=0)
Poisson GLM smf.glm(..., family=sm.families.Poisson(), offset=...)
Negative binomial smf.negativebinomial("y ~ x", data=df, offset=...)
Random intercept smf.mixedlm("y ~ x", data=df, groups=df["id"])
Kaplan-Meier sm.SurvfuncRight(time, status)
Log-rank test sm.duration.survdiff(time, status, group)
Cox model smf.phreg("time ~ x", data=df, status=status)
Sample size TTestIndPower().solve_power(effect_size=0.8, power=0.8)
FDR correction multipletests(p, method="fdr_bh")
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from statsmodels.stats.anova import anova_lm
from statsmodels.stats.multicomp import pairwise_tukeyhsd
from statsmodels.stats.multitest import multipletests
from statsmodels.stats.power import TTestIndPower
rng = np.random.default_rng(42)
Path("outputs").mkdir(exist_ok=True)
pd.set_option("display.width", 100)

The example models one gene in 60 samples, with a treatment effect of 1.5 and three batches. The first level in alphabetical order becomes the reference, so Control and B1 sit in the intercept.

n = 60
df = pd.DataFrame({
"treatment": np.tile(["Control", "Treated"], n // 2),
"batch": np.repeat(["B1", "B2", "B3"], n // 3),
})
batch_shift = df["batch"].map({"B1": 0.0, "B2": 0.8, "B3": -0.5})
df["expression"] = (
10 + 1.5 * (df["treatment"] == "Treated") + batch_shift
+ rng.normal(scale=1.5, size=n)
)
model = smf.ols("expression ~ treatment + batch", data=df).fit()
print(model.summary().tables[1])
print(f"R-squared = {model.rsquared:.3f}, AIC = {model.aic:.1f}")
========================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------
Intercept 10.0378 0.310 32.359 0.000 9.416 10.659
treatment[T.Treated] 1.3257 0.310 4.274 0.000 0.704 1.947
batch[T.B2] 1.0136 0.380 2.668 0.010 0.253 1.775
batch[T.B3] -0.2716 0.380 -0.715 0.478 -1.033 0.489
========================================================================================
R-squared = 0.356, AIC = 196.2

print(model.summary()) gives the full report with the F-test and residual checks. To pick another reference level, write the term as C(batch, Treatment(reference="B2")).

The fitted model holds every number in the summary as a pandas object, ready to join or export.

conf_int = model.conf_int()
coef_table = pd.DataFrame({
"estimate": model.params,
"ci_low": conf_int[0],
"ci_high": conf_int[1],
"p_value": model.pvalues,
})
print(coef_table.round(4))
estimate ci_low ci_high p_value
Intercept 10.0378 9.4164 10.6592 0.0000
treatment[T.Treated] 1.3257 0.7042 1.9471 0.0001
batch[T.B2] 1.0136 0.2525 1.7747 0.0100
batch[T.B3] -0.2716 -1.0327 0.4895 0.4776

get_prediction takes new rows in the same columns as the data. In summary_frame, the mean_ci columns bound the average expression for that group, and the wider obs_ci columns bound a single new sample.

new_samples = pd.DataFrame({
"treatment": ["Control", "Treated"],
"batch": ["B1", "B1"],
})
pred = model.get_prediction(new_samples).summary_frame(alpha=0.05)
print(pred.round(3))
mean mean_se mean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper
0 10.038 0.31 9.416 10.659 7.552 12.523
1 11.363 0.31 10.742 11.985 8.878 13.849

fit(cov_type="HC3") keeps the coefficients and replaces the standard errors with ones that stay valid when the residual variance differs between samples. Here the simulated noise has one variance, so HC3 moves each standard error by less than 10%.

robust = smf.ols("expression ~ treatment + batch", data=df).fit(cov_type="HC3")
se_table = pd.DataFrame({"classic_se": model.bse, "hc3_se": robust.bse})
print(se_table.round(4))
classic_se hc3_se
Intercept 0.3102 0.3316
treatment[T.Treated] 0.3102 0.3211
batch[T.B2] 0.3799 0.4066
batch[T.B3] 0.3799 0.3958

anova_lm with typ=2 tests each term after the others, which suits an unbalanced design. The default, typ=1, is sequential and depends on the order of terms in the formula.

print(anova_lm(model, typ=2).round(4))
sum_sq df F PR(>F)
treatment 26.3603 1.0 18.2628 0.0001
batch 18.3526 2.0 6.3575 0.0032
Residual 80.8296 56.0 NaN NaN

This F-test asks whether treatment improves a model that already has batch.

reduced = smf.ols("expression ~ batch", data=df).fit()
print(anova_lm(reduced, model).round(4))
df_resid ssr df_diff ss_diff F Pr(>F)
0 57.0 107.1899 0.0 NaN NaN NaN
1 56.0 80.8296 1.0 26.3603 18.2628 0.0001

pairwise_tukeyhsd tests every pair of batches and holds the family-wise error rate at 0.05.

tukey = pairwise_tukeyhsd(df["expression"], df["batch"], alpha=0.05)
print(tukey.summary())
Multiple Comparison of Means - Tukey HSD, FWER=0.05
====================================================
group1 group2 meandiff p-adj lower upper reject
----------------------------------------------------
B1 B2 1.0136 0.0587 -0.03 2.0571 False
B1 B3 -0.2716 0.8063 -1.3152 0.7719 False
B2 B3 -1.2852 0.0121 -2.3287 -0.2417 True
----------------------------------------------------

Residuals against fitted values should show no trend or funnel. In the QQ plot, fit=True standardizes the residuals so the 45 degree line is the right reference.

fig, axes = plt.subplots(1, 2, figsize=(9, 3.8))
axes[0].scatter(model.fittedvalues, model.resid, s=15, alpha=0.7)
axes[0].axhline(0, color="tab:red", linestyle="--")
axes[0].set(xlabel="fitted values", ylabel="residuals",
title="Residuals vs fitted")
sm.qqplot(model.resid, line="45", fit=True, ax=axes[1])
axes[1].set_title("Normal QQ plot of residuals")
fig.tight_layout()
fig.savefig("outputs/statsmodels-diagnostics.png", dpi=150)
plt.close(fig)

Two diagnostic panels for the linear model. Left, residuals of the 60 samples sit in six vertical bands at fitted values between about 9.8 and 12.4, one band per treatment and batch combination, spread evenly around zero within about plus or minus 3. Right, the standardized residuals follow the 45 degree line from about -2.6 to 2.6.

The model relates disease status in 300 patients to age and carrier status. fit(disp=0) stops the optimizer from printing its convergence message. Exponentiate the coefficients and their confidence limits to get odds ratios.

n_pat = 300
patients = pd.DataFrame({
"age": rng.normal(55, 10, n_pat).round(),
"carrier": rng.integers(0, 2, n_pat),
})
logit_p = -6 + 0.08 * patients["age"] + 0.9 * patients["carrier"]
patients["disease"] = rng.binomial(1, 1 / (1 + np.exp(-logit_p)))
logit_fit = smf.logit("disease ~ age + carrier", data=patients).fit(disp=0)
odds = np.exp(pd.concat([logit_fit.params, logit_fit.conf_int()], axis=1))
odds.columns = ["odds_ratio", "ci_low", "ci_high"]
print(odds.round(3))
odds_ratio ci_low ci_high
Intercept 0.002 0.000 0.011
age 1.095 1.061 1.130
carrier 1.570 0.893 2.758

The data are counts of one gene in 24 samples whose library sizes range from 1.5 to 3.9 million reads. The offset log(lib_size) turns the model into a model of rate per read, which is how sequencing depth enters a count model. Library size as an ordinary covariate is a common mistake.

lib_size = rng.integers(15, 40, size=24) * 100_000
group = np.repeat(["Control", "Treated"], 12)
mean_count = 50 * lib_size / 1e6 * np.where(group == "Treated", 2.0, 1.0)
size = 1 / 0.1
count_df = pd.DataFrame({
"group": group,
"lib_size": lib_size,
"counts": rng.negative_binomial(size, size / (size + mean_count)),
})
pois_fit = smf.glm(
"counts ~ group", data=count_df, family=sm.families.Poisson(),
offset=np.log(count_df["lib_size"]),
).fit()
print(pois_fit.summary().tables[1])
print(f"Pearson chi2 / df = {pois_fit.pearson_chi2 / pois_fit.df_resid:.2f}")
====================================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------------
Intercept -9.8439 0.024 -405.036 0.000 -9.891 -9.796
group[T.Treated] 0.5671 0.030 18.917 0.000 0.508 0.626
====================================================================================
Pearson chi2 / df = 14.34

A Pearson chi-square to degrees of freedom ratio far above 1 means the counts vary more than a Poisson model allows, and its standard errors are too small.

smf.negativebinomial estimates the dispersion alpha along with the coefficients. The family sm.families.NegativeBinomial() inside smf.glm fixes alpha at 1.0 unless you pass a value, and statsmodels warns when it does.

nb_fit = smf.negativebinomial(
"counts ~ group", data=count_df, offset=np.log(count_df["lib_size"])
).fit(disp=0)
print(nb_fit.summary().tables[1])
fold = np.exp(nb_fit.params["group[T.Treated]"])
print(f"fold change, Treated vs Control = {fold:.2f}")
====================================================================================
coef std err z P>|z| [0.025 0.975]
------------------------------------------------------------------------------------
Intercept -9.8785 0.074 -132.660 0.000 -10.024 -9.733
group[T.Treated] 0.5877 0.104 5.669 0.000 0.385 0.791
alpha 0.0587 0.019 3.162 0.002 0.022 0.095
====================================================================================
fold change, Treated vs Control = 1.80

Twenty patients are measured at four time points, half on a drug and half on placebo. A random intercept per patient absorbs the baseline differences between people. The time:arm term asks whether the slope over time differs between arms.

patient = np.repeat([f"P{i:02d}" for i in range(1, 21)], 4)
arm = np.repeat(["Drug", "Placebo"], 40)
time = np.tile(np.arange(4), 20)
baseline = np.repeat(rng.normal(scale=1.0, size=20), 4)
slope = np.where(arm == "Drug", 1.0, 0.3)
long_df = pd.DataFrame({
"patient": patient,
"arm": arm,
"time": time,
"expression": 5 + baseline + slope * time + rng.normal(scale=0.5, size=80),
})
mixed_fit = smf.mixedlm(
"expression ~ time * arm", data=long_df, groups=long_df["patient"]
).fit()
print(mixed_fit.summary().tables[1])
Coef. Std.Err. z P>|z| [0.025 0.975]
Intercept 5.326 0.326 16.350 0.000 4.687 5.964
arm[T.Placebo] -0.316 0.461 -0.685 0.493 -1.218 0.587
time 1.008 0.062 16.238 0.000 0.887 1.130
time:arm[T.Placebo] -0.654 0.088 -7.452 0.000 -0.827 -0.482
Group Var 0.926 0.847

Group Var is the variance of the patient intercepts. Add re_formula="~time" to give each patient a random slope as well.

statsmodels covers Kaplan-Meier curves, the log-rank test, and Cox regression without an extra package. The lifelines package is the common alternative when you need more plots or parametric models.

Eighty patients are split into two arms, and follow-up is censored between 10 and 40 months. status is 1 for an event and 0 for a censored time.

surv_arm = np.repeat(["Control", "Treated"], 40)
event_time = rng.exponential(scale=np.where(surv_arm == "Treated", 30, 15))
censor_time = rng.uniform(10, 40, size=80)
surv_df = pd.DataFrame({
"arm": surv_arm,
"time": np.minimum(event_time, censor_time).round(1),
"status": (event_time <= censor_time).astype(int),
})
km_fits = {}
for arm_name, arm_rows in surv_df.groupby("arm"):
km_fits[arm_name] = sm.SurvfuncRight(arm_rows["time"], arm_rows["status"])
median = km_fits[arm_name].quantile(0.5)
print(f"{arm_name}: {arm_rows['status'].sum()} events, "
f"median survival {median:.1f} months")
print(km_fits["Control"].summary().head(4))
Control: 31 events, median survival 14.1 months
Treated: 23 events, median survival 21.7 months
Surv prob Surv prob SE num at risk num events
Time
0.7 0.975 0.024686 40 1.0
1.0 0.950 0.034460 39 1.0
1.2 0.925 0.041646 38 1.0
3.7 0.900 0.047434 37 1.0

Each fit stores its step function in surv_times and surv_prob. Add the starting point at time 0 so both curves begin at 1.

fig, ax = plt.subplots(figsize=(5.5, 3.8))
for arm_name, km in km_fits.items():
times = np.concatenate([[0], km.surv_times])
probs = np.concatenate([[1], km.surv_prob])
ax.step(times, probs, where="post", label=arm_name)
ax.set(xlabel="months", ylabel="survival probability", ylim=(0, 1.02),
title="Kaplan-Meier estimate by arm")
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig("outputs/statsmodels-kaplan-meier.png", dpi=150)
plt.close(fig)

Kaplan-Meier step curves for 40 Control and 40 Treated patients. The Control curve drops below 0.5 at about 14 months and reaches 0 near 32 months. The Treated curve stays above it from about 4 months on, crosses 0.5 near 22 months, and ends near 0.27 at about 32 months.

chi2, p_value = sm.duration.survdiff(
surv_df["time"], surv_df["status"], surv_df["arm"]
)
print(f"log-rank chi2 = {chi2:.2f}, p = {p_value:.4f}")
log-rank chi2 = 10.13, p = 0.0015

The hazard ratio is the exponentiated coefficient, and the summary table reports its confidence limits on the same scale. A value below 1 means a lower event rate than the reference arm, here Control.

cox_fit = smf.phreg("time ~ arm", data=surv_df,
status=surv_df["status"].to_numpy()).fit()
cox_table = cox_fit.summary().tables[1]
print(cox_table[["HR", "[0.025", "0.975]", "P>|t|"]].round(4))
HR [0.025 0.975] P>|t|
arm[T.Treated] 0.413 0.2357 0.7236 0.002

solve_power solves for whichever argument is left out. The effect size is Cohen’s d, the difference in means divided by the pooled standard deviation.

power_calc = TTestIndPower()
n_per_group = power_calc.solve_power(
effect_size=0.8, alpha=0.05, power=0.8, ratio=1.0,
alternative="two-sided",
)
power_at_10 = power_calc.solve_power(
effect_size=0.8, nobs1=10, alpha=0.05, ratio=1.0,
alternative="two-sided",
)
print(f"n per group for d = 0.8 and 80% power: {np.ceil(n_per_group):.0f}")
print(f"power with 10 per group: {power_at_10:.2f}")
n per group for d = 0.8 and 80% power: 26
power with 10 per group: 0.40

method="fdr_bh" returns Benjamini-Hochberg adjusted p-values and a reject flag at alpha.

raw_p = np.array([0.001, 0.008, 0.012, 0.03, 0.04, 0.15, 0.25, 0.5, 0.8])
reject, p_adj, _, _ = multipletests(raw_p, alpha=0.05, method="fdr_bh")
print(f"adjusted: {p_adj.round(3)}")
print(f"reject: {reject}")
adjusted: [0.009 0.036 0.036 0.068 0.072 0.225 0.321 0.562 0.8 ]
reject: [ True True True False False False False False False]
Method Controls
bonferroni family-wise error rate, the most conservative
holm family-wise error rate, uniformly more power than Bonferroni
fdr_bh false discovery rate, the standard for gene lists
fdr_by false discovery rate under any dependence between tests

Seabold and Perktold, 2010 describe statsmodels for econometric and statistical modeling in Python.