Click4Ai

59.

Easy

Implement the **Mean Absolute Error (MAE)** loss function.

Formula:

MAE = (1/n) * sum(|y_true - y_pred|)

Write a function mae(y_true, y_pred) that takes two arrays and returns the MAE value.

Example:

y_true = [3, 5, 2, 7]

y_pred = [2.5, 5.5, 2, 8]

Absolute errors: [0.5, 0.5, 0, 1]

MAE = (0.5 + 0.5 + 0 + 1) / 4 = 0.5

**Explanation:** MAE measures the average of the absolute differences between predictions and actual values. Unlike MSE, it treats all errors linearly (no squaring), making it more robust to outliers.

Constraints:

  • y_true and y_pred are 1D numpy arrays of equal length
  • Return a single float value
  • Do not use sklearn; implement from scratch
  • Test Cases

    Test Case 1
    Input: y_true=[3,5,2,7], y_pred=[2.5,5.5,2,8]
    Expected: 0.5
    Test Case 2
    Input: y_true=[1,2,3], y_pred=[1,2,3]
    Expected: 0.0
    Test Case 3
    Input: y_true=[0,0,0], y_pred=[1,-1,2]
    Expected: 1.3333333333333333
    + 2 hidden test cases