Confidence vs Prediction Interval at x0 with statsmodels OLS
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `def ci_and_pi(x: np.ndarray, y: np.ndarray, x0: float) -> tuple` that fits an OLS regression of `y` on `x` with an intercept (`sm.add_constant`) and returns, at `x0`, the 95% confidence interval for the mean response and the 95% prediction interval for a new observation, as `(mean_lower, mean_upper, obs_lower, obs_upper)`.
Requirements:
- Call `get_prediction` on a design row that includes the constant, such as `[1, x0]`, with `alpha=0.05`.
- Take the mean-response interval from `conf_int(obs=False)`, or from the `mean_ci_lower` and `mean_ci_upper` columns of the summary frame.
- Take the prediction interval from `conf_int(obs=True)`, or from the `obs_ci_lower` and `obs_ci_upper` columns.
- Return a flat tuple of four floats. A test checks that `obs_upper - obs_lower > mean_upper - mean_lower`.
```hint Design row
The fitted model has two columns, the constant and `x`. The new point has to be passed with the same columns in the same order, and calling `sm.add_constant` on a single value can quietly skip the constant.
```
```hint Two sources of uncertainty
Ask what each interval is uncertain about: the height of the fitted line at `x0`, or one new `y` drawn at `x0`.
```
### Constraints & Assumptions
- `x` and `y` are 1-D arrays of the same length. The tests use a fixed `x` of shape `(10,)`, a fixed `y` and a fixed `x0`.
- Both intervals are two-sided at the 95% level (`alpha=0.05`).
### What a Strong Answer Covers
- Fitting OLS with an explicit intercept and passing a new-point row whose columns match the fitted design matrix.
- Reading the mean-response and new-observation intervals from one prediction object at `alpha=0.05` and returning them in the requested order as plain floats.
- The variance behind each interval, and why the prediction interval is wider at every `x0`.
- Edge cases such as a constant `x`, a perfect fit, too few points, or `x0` far outside the observed range.
### Follow-up Questions
- Why is the prediction interval always wider than the confidence interval?
- How do both intervals behave as `x0` moves far from the mean of `x`?
- Which assumptions matter more for the prediction interval than for the confidence interval?
- What happens to the width of each interval as the sample size grows?
Overview: Implement a Python function that fits an ordinary least squares regression with statsmodels and returns the 95% confidence interval for the mean response and the 95% prediction interval for a new observation at a given point. It tests regression inference and how the two intervals differ.