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
predicton new data needs the same column names.conf_inton the prediction is the interval for the mean.obs_ciis the wider interval for a single new observation.
Keywords and builtins used here
asprint
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.
Step 3 of 3 in Model design, step 6 of 19 in Statistics with statsmodels.