Compute mean absolute error (MAE) in NumPy and compare it with RMSE under an outlier
Quick Overview
Implement mean absolute error with vectorized NumPy so it matches scikit-learn and returns a plain Python float. It also tests why a single large outlier residual raises RMSE much more than MAE, and which inputs make a naive implementation fail.
Compute mean absolute error (MAE) in NumPy and compare it with RMSE under an outlier
Role: Data Scientist
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `compute_mae(y_true, y_pred)` returning `MAE = (1/n) * sum(abs(y_true - y_pred))` as a single `float`. Inputs are 1-D `np.ndarray` of equal length `n`.
Requirements:
- Return a Python `float`, not an array.
- Match `sklearn.metrics.mean_absolute_error` with default `multioutput='uniform_average'`.
- Use vectorized NumPy (`np.abs`, `np.mean`).
- On the fixed length-10 input (one large outlier residual), MAE must be materially smaller than RMSE.
For example:
```python
y_true = np.array([3.0, 5.0, 2.5])
y_pred = np.array([2.5, 5.0, 4.0])
compute_mae(y_true, y_pred) # -> 0.6666666666666666
```
```hint Comparing with RMSE
Write each metric's contribution from a single residual as a function of that residual's size, and compare how fast the two grow.
```
### Constraints & Assumptions
- `y_true` and `y_pred` are 1-D float arrays of the same length `n`.
- The test input is a fixed pair of length-10 arrays with one large outlier residual.
### What a Strong Answer Covers
- Computing the absolute residuals and their mean with vectorized NumPy, returned as a Python `float`.
- Why the result matches scikit-learn's `mean_absolute_error` with uniform averaging.
- Why one large residual raises RMSE much more than MAE.
- The time and space cost, and input checks such as matching shapes and missing values.
### Follow-up Questions
- Why is MAE less sensitive to outliers than RMSE?
- Which constant prediction minimizes MAE, and which minimizes RMSE?
- When would you report RMSE instead of MAE?
Overview: Implement mean absolute error with vectorized NumPy so it matches scikit-learn and returns a plain Python float. It also tests why a single large outlier residual raises RMSE much more than MAE, and which inputs make a naive implementation fail.
Compute mean absolute error (MAE) in NumPy and compare it with RMSE under an outlier
General
Nov 24, 2026
easyData ScientistOtherMachine Learning
0
0
Implement compute_mae(y_true, y_pred) returning MAE = (1/n) * sum(abs(y_true - y_pred)) as a single float. Inputs are 1-D np.ndarray of equal length n.
Requirements:
Return a Python
float
, not an array.
Match
sklearn.metrics.mean_absolute_error
with default
multioutput='uniform_average'
.
Use vectorized NumPy (
np.abs
,
np.mean
).
On the fixed length-10 input (one large outlier residual), MAE must be materially smaller than RMSE.