Bayes Minimum Expected Risk Decision Rule
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Given posteriors `posteriors` of shape (n, K) and a K x K `loss` matrix where `loss[k, a]` is the cost of taking action `a` when the true class is `k`, implement `expected_risk(posteriors, loss)` returning the (n, K) matrix `R[i, a] = sum_k P(k | x_i) * loss[k, a]`. Then implement `bayes_decision(posteriors, loss)` returning the risk-minimizing action index per sample as an integer array of shape (n,).
Example:
```text
P = [[0.2, 0.5, 0.3], [0.6, 0.1, 0.3]]
L = [[0, 2, 4], [1, 0, 3], [5, 1, 0]]
expected_risk(P, L) -> [[2.0, 0.7, 2.3], [1.6, 1.5, 2.7]]
bayes_decision(P, L) -> [1, 1]
```
```hint Follow the indices
In the sum, check which axis of `posteriors` and which axis of `loss` the index k runs over. That tells you how to compute every `R[i, a]` at once without a loop.
```
### Constraints & Assumptions
- Rows of `loss` index the true class, columns index the action.
- Exact ties go to the lowest action index.
- Raise `ValueError` if `posteriors` is not 2-D, `loss` is not square, or their class counts disagree (both functions).
- Inputs may be lists or arrays: convert to float. Use NumPy only.
### What a Strong Answer Covers
- A vectorized computation of all risks that respects the orientation of `loss` (true class on rows, action on columns).
- Shape validation that both functions run, with a `ValueError` for each listed case.
- Lowest-index tie breaking and an integer result of shape (n,).
- Why choosing the minimum conditional risk for each sample minimizes the overall expected loss.
- Time and space complexity in terms of n and K.
### Follow-up Questions
- How would you add a reject (abstain) option with a fixed cost?
- Why does 0-1 loss reduce the rule to argmax of the posterior?
- What happens if the posteriors are poorly calibrated?
Overview: Implement the expected risk matrix and the Bayes decision rule for a classifier, given predicted class probabilities and a loss matrix of costs for each true class and action. It tests cost-sensitive decision theory, NumPy matrix products, shape validation and tie handling.