Odds Ratio Confidence Intervals From a Fitted Logistic Regression
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `fitted_odds_ratio_ci(X: np.ndarray, y: np.ndarray, alpha: float = 0.05) -> np.ndarray`. Fit a logistic regression and return the odds-ratio confidence interval for each coefficient (including the intercept). Build the interval on the log-odds scale (`beta +/- z_{1-alpha/2} * se`), then exponentiate, so it is not symmetric about `exp(beta)`.
Requirements:
- Fit `sm.Logit(y, sm.add_constant(X)).fit(method='newton', maxiter=200, tol=1e-10, disp=0)`.
- Take `res.conf_int(alpha=alpha)` and exponentiate both endpoints.
- Return a float64 `np.ndarray` of shape `(p+1, 2)`: column 0 is the lower bound, column 1 the upper bound.
- Coverage is `1-alpha` (`alpha=0.05` gives 95%, `alpha=0.01` gives 99%).
```hint Which scale is normal
Think about the scale on which the Wald normal approximation for a logistic regression coefficient is stated, and what a strictly increasing function does to the endpoints of an interval.
```
```hint Return type
Check what `res.conf_int` returns for NumPy inputs and for pandas inputs, and make sure your function returns the same kind of object either way.
```
### Constraints & Assumptions
- `X` has shape `(n, p)` with no intercept column, and `y` is a 1-D array of 0/1 integers.
- The grader uses a fixed, non-separable dataset with `n = 60` and `p = 2`, so the expected return shape is `(3, 2)`.
- It calls the function with `alpha=0.05` and `alpha=0.01` and asserts that the 99% interval strictly contains the 95% one.
- Results are checked with `numpy.testing.assert_allclose(rtol=1e-6)`.
### What a Strong Answer Covers
- Fitting the model with an intercept and the specified Newton settings, so there are `p+1` coefficients in a known order.
- Building the interval on the log-odds scale and only then applying `exp`, with a reason for that order.
- Why the resulting interval is asymmetric about `exp(beta)` and why the 99% interval contains the 95% interval.
- The output's shape, dtype and column order, and what can go wrong with the fit.
### Follow-up Questions
- Why not exponentiate `beta` and its `se` and build a symmetric interval on the odds-ratio scale?
- How would you get a confidence interval for a predicted probability instead of the odds ratio?
- What happens to these intervals when one feature perfectly separates the classes, and what would you do about it?
Overview: Fit a logistic regression with statsmodels and return a confidence interval for the odds ratio of every coefficient, intercept included. It tests which scale the Wald interval belongs on, why the odds-ratio interval is asymmetric, and how coverage changes with alpha.