Downsample and Upweight the Majority Class
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `downsample_and_upweight(X, y, factor, seed)`. Randomly keep `max(1, floor(n_maj / factor))` rows of the majority class, keep all rows of the other classes, and give each kept majority row weight `factor` (all other rows get `1.0`). Return `(X_res, y_res, sample_weight, kept_indices)`.
Example:
```python
X = np.arange(16).reshape(8, 2)
y = np.array([3, 7, 3, 7, 3, 7, 3, 7])
X_res, y_res, sample_weight, kept_indices = downsample_and_upweight(X, y, factor=2, seed=0)
# counts tie at 4, so the majority is 3 (the lower label)
# y_res keeps 2 rows of label 3 (weight 2.0) and all 4 rows of label 7 (weight 1.0)
```
```hint Ties
Think about the order in which `np.unique` returns labels, and which index `np.argmax` picks when several counts are equal.
```
### Constraints & Assumptions
- The majority is the most frequent label, and ties go to the lowest label. Only the majority class is downsampled, and `y` may have more than two classes.
- Select the majority rows as `maj_idx[np.random.default_rng(seed).permutation(n_maj)[:n_keep]]`, where `maj_idx` holds the majority row indices in ascending order.
- `kept_indices` is strictly increasing, with `X_res = X[kept_indices]` and `y_res = y[kept_indices]`.
- `sample_weight` is a float array aligned with `y_res`. `factor` may be a non-integer.
- A `factor` below 1 raises `ValueError`.
### What a Strong Answer Covers
- Majority detection with the lowest-label tie rule, with only that class downsampled.
- The exact seeded selection of majority rows and the `max(1, ...)` floor on the kept count.
- Kept indices in increasing original order, with float weights aligned to `y_res`.
- Why weighting the kept majority rows by `factor` restores the original class ratio, and when it does so only approximately.
- Validation and edge cases such as a non-integer factor, `factor = 1`, and a factor larger than the majority count.
### Follow-up Questions
- How do the predicted probabilities of a model trained this way compare with one trained on downsampled data without the weights?
- How would you choose `factor`?
- Why use this instead of training on all rows, and how should you evaluate the resulting model?
Overview: Implement a function that downsamples the majority class with a seeded permutation and upweights the kept rows so a weighted loss still sees the original class ratio. It tests tie-breaking, reproducible sampling, index bookkeeping, and how upweighting affects predicted probabilities.