Adjust Posteriors for Class Prior Shift
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `adjust_for_prior_shift(posteriors, train_priors, test_priors, classes=None)`. Re-weight each row as `p_new(k|x) ∝ p_old(k|x) * test[k] / train[k]`, renormalize per row, and return `(adjusted_posteriors, predictions)`.
- Normalize both prior vectors to sum to 1 before use (unnormalized priors give identical results).
- A row whose re-weighted mass is exactly 0 becomes the normalized test priors.
- Predictions are the row argmax (ties go to the lowest column index), mapped through `classes` when given, else integer indices.
- Raise `ValueError` if: `posteriors` is not 2-D or has negatives, prior or `classes` length ≠ columns, any train prior ≤ 0, or test priors have a negative or a non-positive sum.
Example:
```text
posteriors = [[0.5, 0.3, 0.2], [0.8, 0.1, 0.1]]
train_priors = [0.5, 0.25, 0.25]
test_priors = [0.25, 0.25, 0.5]
classes = ["cat", "dog", "fox"]
Output: adjusted = [[5/19, 6/19, 8/19], [4/7, 1/7, 2/7]]
preds = ["fox", "cat"]
```
```hint Start from Bayes' rule
Write $p(k \mid x)$ as likelihood times prior over evidence. Ask which factor changes when only the class priors move, and which factor is shared by every class in a row.
```
```hint Watch the zero rows
Dividing by the row sum fails for a row whose re-weighted mass is 0, for example when all of its probability sits on classes whose test prior is 0. Find those rows before you divide.
```
### Constraints & Assumptions
- `posteriors` has shape `(n, c)`. The returned array has the same shape, with rows summing to 1.
- Inputs may be lists or NumPy arrays. Output arrays are NumPy.
### What a Strong Answer Covers
- Why multiplying each class column by the prior ratio and renormalizing gives the exact posterior under the new priors.
- Validation that covers every `ValueError` case in the spec, with both prior vectors normalized before use.
- A vectorized re-weighting with per-row renormalization and the fallback to the test priors for zero-mass rows.
- Predictions with lowest-index tie breaking, mapped through `classes` when it is given.
- Time and space cost for an `(n, c)` input.
### Follow-up Questions
- How would you estimate the test priors when they are unknown?
- Why does this correction assume calibrated posteriors?
- How would you handle numerical underflow with very small probabilities?
Overview: Implement a function that re-weights a classifier's predicted class probabilities when the class priors differ between training and test data, then renormalizes each row and returns label predictions. It tests Bayes' rule, NumPy broadcasting, input validation and edge cases such as rows with zero mass.