Show that balanced class weights, a class weight dict and sample weights fit the same logistic regression
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `weighting_equivalence(X: np.ndarray, y: np.ndarray) -> dict`. It fits three logistic regression models on imbalanced binary data, each expressing the same re-weighting, and returns their learned parameters. Every fit uses `LogisticRegression(solver='lbfgs', max_iter=1000, tol=1e-6, C=1.0, penalty='l2', random_state=0)` and varies only the weighting scheme:
- (a) `class_weight='balanced'`.
- (b) `class_weight={0: w0, 1: w1}`, where `w0, w1` are entries 0 and 1 of `n_samples / (2 * np.bincount(y))`.
- (c) `class_weight=None` with `fit(X, y, sample_weight=sw)`, where `sw = np.where(y == 1, w1, w0)`.
Return a dict with these keys:
- `'balanced_coef'`, `'dict_coef'` and `'sample_weight_coef'`: each model's `coef_.ravel()`, a 1-D float array of shape `(n_features,)`.
- `'intercepts'`: a 1-D float ndarray of the three `intercept_[0]` values in the order (a), (b), (c).
Then explain why the three fits must give the same parameters.
```hint Write the objective once
Write the L2-regularized log loss with a weight on every sample. Then work out, for each of the three settings, which weight each sample ends up with.
```
```hint Check the label dtype
`np.bincount` only accepts non-negative integers. Make sure `y` has an integer dtype before you count classes with it.
```
### Constraints & Assumptions
- `y` contains only the labels 0 and 1, and both are present.
- The classes are imbalanced, so `w0` and `w1` differ.
- The three coefficient vectors and the three intercepts must agree to `rtol=1e-5`.
### What a Strong Answer Covers
- Fits the three models with identical pinned settings, changing only the weighting.
- Computes the balanced weights as `n_samples / (2 * counts)` and maps each sample to its class weight with the classes the right way round.
- Shows that all three settings give the same per-sample weights, hence the same objective and the same unique optimum.
- Returns the coefficients as 1-D float arrays and the intercepts in the order (a), (b), (c).
- Describes what balanced weights do to each class's total weight and to the meaning of `C`.
### Follow-up Questions
- Why does the balanced formula use `n_samples / (2 * np.bincount(y))`?
- What happens if `sample_weight` and `class_weight` are both supplied?
- Would this equivalence still hold exactly with a stochastic solver like `solver='saga'`?
- How do balanced weights change the predicted probabilities, and how would you recover probabilities calibrated to the true base rate?
Overview: Fit a scikit-learn logistic regression three ways on imbalanced binary data, with balanced class weights, an explicit class weight dict and per-sample weights, and show the learned parameters agree. Tests how class weights enter the weighted log loss and why the regularized optimum is unique.