Matthews Correlation and Cohen's Kappa from Scratch
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `matthews_corrcoef(y_true, y_pred)` (multi-class MCC) and `cohen_kappa_score(y_true, y_pred, weights=None)` using only `numpy`. Build the confusion matrix over the sorted union of labels from both arrays. Both functions return a Python `float` matching `sklearn`.
Example:
```python
y_true = [1, 1, 1, 0, 0, 0, 0, 0]
y_pred = [1, 1, 0, 1, 0, 0, 0, 0]
matthews_corrcoef(y_true, y_pred) # 0.4667 (7/15)
cohen_kappa_score(y_true, y_pred) # 0.4667 (7/15)
```
```hint One matrix for both
Both metrics come from the same confusion matrix. Try writing each one in terms of the row sums, column sums, trace and total of that matrix.
```
```hint Chance agreement
For kappa, ask what the confusion matrix would look like if predictions were independent of the truth but kept the same marginals. One weight matrix can then score both the observed and the chance disagreement.
```
### Constraints & Assumptions
- Labels may be ints or strings. A label appearing only in `y_pred` still counts as a class.
- `weights` is `None`, `"linear"` or `"quadratic"` (distance is the difference of sorted label indices). Any other value, or mismatched shapes, raises `ValueError`.
- MCC with a zero denominator (for example, constant predictions) returns `0.0`.
- Kappa with zero expected (weighted) disagreement returns `nan`.
### What a Strong Answer Covers
- One confusion matrix over the sorted union of labels, so string labels and labels seen only in predictions are handled.
- The multi-class MCC formula in terms of row sums, column sums, trace and total, with the zero-denominator convention.
- The kappa chance matrix built from the marginals, and the unweighted, linear and quadratic disagreement weights.
- Validation of `weights` and input shapes, and the `nan` case for kappa.
- A check of both functions against the binary formulas on a small example.
### Follow-up Questions
- When would you prefer MCC over F1 or accuracy?
- Why do quadratic weights suit ordinal ratings?
- How would you get a confidence interval for kappa?
Overview: Implement the multi-class Matthews correlation coefficient and Cohen's kappa with optional linear or quadratic weights using only NumPy. It tests building a confusion matrix over the union of labels, chance-corrected agreement, and handling the degenerate cases the same way scikit-learn does.