Implement weighted MAE, RMSE, R² and MAPE from scratch in NumPy
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement four regression metrics using NumPy only: `mean_absolute_error`, `root_mean_squared_error`, `r2_score` and `mean_absolute_percentage_error`. Each function takes `y_true`, `y_pred` and an optional `sample_weight` (uniform when omitted) and returns a Python `float`. Every average is weighted: `sum(w * x) / sum(w)`.
The functions must follow these rules:
- `r2_score` is `1 - SS_res / SS_tot`, with `SS_tot` taken around the weighted mean of `y_true`. It may be negative. If `SS_tot == 0`, return `1.0` for a perfect fit and `0.0` otherwise.
- `mean_absolute_percentage_error` returns a fraction (0.25 means 25%) and divides by `|y_true|`. Rows with `y_true == 0` are dropped together with their weights.
- MAPE returns `nan` when no rows with a nonzero target remain, or when the weights of the remaining rows sum to zero.
- Raise `ValueError` on a length mismatch between `y_true` and `y_pred`, empty input, a `sample_weight` length mismatch, any negative weight, or a non-positive weight sum.
- Rows with zero weight must have no effect on any metric.
Example:
```python
y_true = [3.0, -0.5, 2.0, 7.0]
y_pred = [2.5, 0.0, 2.0, 8.0]
mean_absolute_error(y_true, y_pred) # 0.5
root_mean_squared_error(y_true, y_pred) # sqrt(0.375) ~ 0.6124
mean_absolute_percentage_error([0.0, 2.0, 4.0], [1.0, 1.0, 5.0]) # 0.375
mean_absolute_percentage_error([0.0, 2.0, 4.0], [1.0, 1.0, 5.0], [10, 1, 3]) # 0.3125
r2_score([1.0, 2.0, 3.0], [3.0, 2.0, 1.0]) # -3.0
```
```hint One helper for every metric
Put the array conversion, the length checks and the weight validation in one function that returns three float arrays. Each metric then reduces to a weighted sum divided by a weight sum.
```
```hint Follow the weights through every term
Check that the mean inside `SS_tot` and the MAPE denominator both use the weights of the rows you actually kept. A zero-weight row or a dropped zero-target row should leave no trace in the result.
```
### Constraints & Assumptions
- Inputs are array-likes (lists or 1-D arrays) of finite floats.
- Use NumPy only inside the functions.
- `mean_absolute_error`, `root_mean_squared_error` and `r2_score` must match `sklearn.metrics` (weighted and unweighted) to `rtol=1e-9` for inputs with at least two rows.
- `mean_absolute_percentage_error` must match sklearn to the same tolerance when every target is nonzero. sklearn divides a zero target by machine epsilon instead of dropping the row, so the drop rule above applies whenever a zero target is present.
### What a Strong Answer Covers
- Input validation that raises `ValueError` for every listed case, shared by the four functions.
- Weighted averages normalized so that zero-weight rows change nothing.
- The weighted mean inside R² and the constant-target rule.
- MAPE's treatment of zero targets, the weights that go with them, and the `nan` result.
- Time and space complexity, and the inputs where the results can differ from sklearn.
### Follow-up Questions
- Why is MAPE problematic when targets are near zero, and what alternatives exist?
- How would you extend these functions to multi-output targets?
- What does a negative R² tell you about a model?
- The constant-target check compares `SS_tot` with exactly zero. What can go wrong with floating-point targets, and would you add a tolerance?
Overview: Implement weighted mean absolute error, RMSE, R² and MAPE from scratch with NumPy, with input validation and optional sample weights. Tests careful handling of zero-weight rows, constant targets in R², zero targets in MAPE, and agreement with scikit-learn.