Statistical modeling with Python · Lesson 8 of 16

Linear regression in Python with statsmodels

Fit a simple linear regression with statsmodels' formula API and read every number: slope, R-squared, p-values, confidence intervals, predictions.

About 18 minutes · code runs in your browser, nothing to install

Linear regression draws the straight line that best fits a cloud of points and tells you how sure it is about that line. It is the base of almost every model in this course, so this lesson reads each number slowly.

The data: 100 students, how many hours a week they studied (hours), how many classes they missed (absences), whether they took a prep course, their course, their exam score (0–100) and whether they passed (score 55 or more). The file students.csv is ready on this page; reading CSV files is covered in Reading a CSV file and a first look.

Pythoneditable
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")

print(df.head())
print(df.shape)
print(df[["hours", "score"]].describe().round(2))
Output
   hours  absences prep   course  score  passed
0    3.6         8   no  biology     33       0
1    1.5         5   no  biology     13       0
2   13.2         0  yes  biology     99       1
3    1.2         7   no  biology     18       0
4    4.5         3  yes  history     45       0
(100, 6)
        hours   score
count  100.00  100.00
mean     7.78   57.26
std      3.97   21.25
min      1.00   12.00
25%      4.30   41.75
50%      8.00   60.50
75%     11.30   72.25
max     14.00   99.00

Fit the line

smf.ols("score ~ hours", data=df).fit() finds the intercept and slope that make the squared distances from the points to the line as small as possible (ordinary least squares).

Pythoneditable
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")

model = smf.ols("score ~ hours", data=df).fit()
print(model.params.round(3))
print(model.bse.round(3))
print(f"R-squared: {model.rsquared:.3f}")
print(f"n = {int(model.nobs)}")
Output
Intercept    29.936
hours         3.512
dtype: float64
Intercept    3.560
hours        0.408
dtype: float64
R-squared: 0.430
n = 100

params = coefficients, bse = their standard errors.

  • Intercept (29.9): the predicted score for a student who studies 0 hours. Often not interesting by itself; it anchors the line.
  • Slope of hours (3.5): each extra hour of study a week goes with about 3.5 more points, on average. This is the number you usually care about.
  • Standard error (0.41): how much the slope would wobble from sample to sample. Roughly, the slope is 3.5 give or take 2 × 0.41.
  • R-squared (0.43): hours explain 43% of the differences in scores between students. The other 57% is everything else (absences, talent, luck).

Next, the p-values and the 95% confidence intervals. The p-value of a coefficient tests the null hypothesis "this coefficient is 0", that is, no straight-line link.

Pythoneditable
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")

model = smf.ols("score ~ hours", data=df).fit()

def show_p(p):
    return "< 0.001" if p < 0.001 else f"{p:.3f}"

for name in model.params.index:
    print(f"{name:<10} p {show_p(model.pvalues[name])}")
ci = model.conf_int(alpha=0.05)
ci.columns = ["2.5%", "97.5%"]
print(ci.round(2))
Output
Intercept  p < 0.001
hours      p < 0.001
            2.5%  97.5%
Intercept  22.87  37.00
hours       2.70   4.32

The slope's interval runs from about 2.7 to 4.3 points per hour: we cannot pin the effect to one number, but it is clearly positive and clearly not tiny. That sentence is the honest summary of this regression.

Watch out: The slope describes an association in this data, not a promise. Students who study more may also differ in other ways (motivation, free time). Only an experiment shows that studying causes the higher score.

Predictions with intervals

get_prediction gives the predicted score for new hours, with two intervals: mean_ci for the average student with those hours (narrow) and obs_ci for one student (wide, because single students vary a lot). Notice the upper limit 111.6 for 14 hours: a straight line knows nothing about the 100-point maximum, one reason other models exist for limited outcomes.

Pythoneditable
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")

model = smf.ols("score ~ hours", data=df).fit()
new = pd.DataFrame({"hours": [2, 8, 14]})
pred = model.get_prediction(new).summary_frame(alpha=0.05)
print(pred[["mean", "mean_ci_lower", "mean_ci_upper"]].round(1))
print(pred[["obs_ci_lower", "obs_ci_upper"]].round(1))
Output
   mean  mean_ci_lower  mean_ci_upper
0  37.0           31.3           42.6
1  58.0           54.8           61.2
2  79.1           73.1           85.1
   obs_ci_lower  obs_ci_upper
0           4.5          69.4
1          25.9          90.2
2          46.6         111.6
Pythoneditable
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")

import numpy as np
import matplotlib.pyplot as plt

model = smf.ols("score ~ hours", data=df).fit()
b0, b1 = model.params["Intercept"], model.params["hours"]
print(f"score = {b0:.1f} + {b1:.2f} × hours")

x = np.linspace(1, 14, 50)
plt.scatter(df["hours"], df["score"], color="steelblue", alpha=0.6)
plt.plot(x, b0 + b1 * x, color="crimson", linewidth=2)
plt.title("Exam score and study hours")
plt.xlabel("Hours of study per week")
plt.ylabel("Score")
plt.show()
Output
score = 29.9 + 3.51 × hours
Chart drawn by this code
The full summary table
model = smf.ols("score ~ hours", data=df).fit()
print(model.summary())

On your own computer: the classic table with all of the numbers above, plus F-statistic, AIC and residual checks.

✎ Exercise

Fit score ~ absences on the same data. Print the coefficients and R-squared, both rounded to 3 decimals. Does each missed class go with a higher or lower score?

Hint: Same as for hours: smf.ols("score ~ absences", data=df).fit(), then model.params.round(3).

Your codewrite your answer, then Run
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")

# your code here

Expected output:

Intercept    65.979
absences     -2.116
dtype: float64
R-squared: 0.072
Show a solution
Solutioneditable
import pandas as pd
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")

model = smf.ols("score ~ absences", data=df).fit()
print(model.params.round(3))
print(f"R-squared: {model.rsquared:.3f}")
Output
Intercept    65.979
absences     -2.116
dtype: float64
R-squared: 0.072

Check yourself

1. The slope of hours is 3.5. What does it mean?

2. R-squared is 0.43. What does it say?

3. Why is obs_ci wider than mean_ci?

Spotted a mistake on this page? Tell us