← back

Calculate Mean Absolute Error (MAE)

#93 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the Mean Absolute Error (MAE) between predicted values and actual values. MAE measures the average magnitude of errors in a set of predictions without considering their direction.

Solution

1
2
3
4
5
6
def mean_absolute_error(y_true: list[float], y_pred: list[float]) -> float:
    n = len(y_true)
    if n == 0:
        return 0.0
    mae = sum(abs(t - p) for t, p in zip(y_true, y_pred)) / n
    return round(mae, 4)

Explanation

  1. For each pair of true and predicted values, compute the absolute difference |y_true_i - y_pred_i|.
  2. Sum all absolute differences.
  3. Divide by the total number of samples to get the mean.

MAE is robust to outliers compared to MSE since it does not square the errors. A MAE of 0 means perfect predictions.

Complexity

  • Time: O(n) where n is the number of samples
  • Space: O(1)