Solving tips
- MAE is the mean of the absolute errors — build it inside-out: differences, absolute value, mean.
- Vectorize with NumPy: y_pred - y_true is an elementwise array, then np.abs and np.mean, no Python loop needed.
- Guard the empty-input case so you don't divide by zero.
Implement mean absolute error (MAE) from scratch with NumPy, without using a library metric function. MAE is a standard regression metric, and interviewers ask for it to check that you can turn a formula into clean vectorized code.
Definition
For n paired values, MAE is the average absolute difference between prediction and truth:
MAE = (1/n) * sum_i |y_pred[i] - y_true[i]|
Task
Complete mae(y_true, y_pred) so it returns the MAE as a float. Both inputs are 1-D NumPy arrays of the same length. Do not call sklearn or any built-in MAE helper.
Example
y_true = np.array([3.0, 5.0, 2.5, 7.0])
y_pred = np.array([2.5, 5.0, 4.0, 8.0])
mae(y_true, y_pred) # -> 0.75
The absolute errors are [0.5, 0.0, 1.5, 1.0], and their mean is 3.0 / 4 = 0.75.
Constraints
1 <= n <= 10^6; use vectorized NumPy, not a Python loop.- Values fit in float64.