typestar

Predicting with intervals in Python

get_prediction gives the mean and both intervals, which predict alone does not.

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(5)
frame = pd.DataFrame({"practice": np.arange(1, 51)})
frame["tpm"] = 72 + 0.65 * frame["practice"] + rng.normal(0, 3, size=50)

model = smf.ols("tpm ~ practice", data=frame).fit()
future = pd.DataFrame({"practice": [60, 90]})

print(model.predict(future).round(2).tolist())

prediction = model.get_prediction(future).summary_frame(alpha=0.05)
print(prediction.columns.tolist())
print(prediction[["mean", "mean_ci_lower", "obs_ci_upper"]].round(2))

How it works

  1. predict on new data needs the same column names.
  2. conf_int on the prediction is the interval for the mean.
  3. obs_ci is the wider interval for a single new observation.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
555
Tokens
180
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 98 seconds.

Type this snippet

Step 3 of 3 in Model design, step 6 of 19 in Statistics with statsmodels.

← Previous Next →