Skip to content

Mean absolute error #10927

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 26, 2023
43 changes: 43 additions & 0 deletions machine_learning/loss_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,49 @@ def mean_squared_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
return np.mean(squared_errors)


def mean_absolute_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""
Calculates the Mean Absolute Error (MAE) between ground truth (observed)
and predicted values.

MAE measures the absolute difference between true values and predicted values.

Equation:
MAE = (1/n) * Σ(abs(y_true - y_pred))

Reference: https://en.wikipedia.org/wiki/Mean_absolute_error

Parameters:
- y_true: The true values (ground truth)
- y_pred: The predicted values

>>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
>>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2])
>>> np.isclose(mean_absolute_error(true_values, predicted_values), 0.16)
True
>>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
>>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2])
>>> np.isclose(mean_absolute_error(true_values, predicted_values), 2.16)
False
>>> true_labels = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
>>> predicted_probs = np.array([0.3, 0.8, 0.9, 5.2])
>>> mean_absolute_error(true_labels, predicted_probs)
Traceback (most recent call last):
...
ValueError: Input arrays must have the same length.
"""
if len(y_true) != len(y_pred):
raise ValueError("Input arrays must have the same length.")

if isinstance(y_true, np.ndarray) and isinstance(y_pred, np.ndarray):
return np.mean(abs(y_true - y_pred))
else:
try:
return np.mean(abs(np.asarray(y_true) - np.asarray(y_pred)))
except ValueError as error:
raise ValueError("Could not convert input to NumPy array.") from error


def mean_squared_logarithmic_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""
Calculate the mean squared logarithmic error (MSLE) between ground truth and
Expand Down