Show how balanced class weights shift a logistic regression intercept
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `reweighting_shifts_intercept(X: np.ndarray, y: np.ndarray) -> dict`. On an imbalanced binary dataset, fit `LogisticRegression(solver='lbfgs', max_iter=5000, tol=1e-8, C=1.0, penalty='l2', random_state=0)` twice, changing only `class_weight`: (a) `None` (unweighted) and (b) `'balanced'`. Return the intercept and slope differences plus the theoretical intercept shift.
The returned dict must have exactly the keys `'intercept_delta'`, `'slope_abs_delta'` and `'theoretical_shift'`:
- `'intercept_delta'` is `balanced.intercept_[0] - unweighted.intercept_[0]`, as a float.
- `'slope_abs_delta'` is `np.abs(balanced.coef_.ravel() - unweighted.coef_.ravel())`, a 1-D float ndarray of shape `(n_features,)`.
- `'theoretical_shift'` is `log(w1/w0)` as a float, using the balanced weights `n_samples/(2*np.bincount(y))`.
```hint Hold everything else fixed
Put the pinned hyperparameters in one place and pass them to both estimators, so `class_weight` is the only thing that differs between the two fits.
```
```hint Think in log-odds
Ask what multiplying every positive example's loss by $w_1$ and every negative example's loss by $w_0$ does to the odds the model is trying to match.
```
### Constraints & Assumptions
- `y` is binary with labels `{0, 1}`, and both classes are present.
- `X` is a numeric array of shape `(n_samples, n_features)`.
- All three values are graded with `assert_allclose(rtol=1e-5)` against reference fits pinned the same way, so the hyperparameters must match exactly.
### What a Strong Answer Covers
- Two fits that share every hyperparameter and differ only in `class_weight`, with each output in the requested type and shape.
- The balanced weights computed from the class counts, and the theoretical shift `log(w1/w0)` expressed in terms of those counts.
- Why reweighting moves the intercept while leaving the slopes nearly unchanged.
- Why the match between `intercept_delta` and `theoretical_shift` is only approximate on real data.
### Follow-up Questions
- Why does the intercept absorb almost all of the reweighting effect?
- How does L2 regularization (`C`) perturb the clean `log(w1/w0)` relationship?
- After training with balanced weights, how would you recover probabilities that match the true base rate?
Overview: Fit a pinned scikit-learn logistic regression with and without balanced class weights, then compare the intercepts and slopes with the theoretical shift log(w1/w0). It tests how class weights relate to prior odds in a logistic model and when that theoretical shift holds only approximately.