Skip to content

Commit 2c8c49c

Browse files
megpaypre-commit-ci[bot]tianyizheng02
authored andcommitted
Mean absolute error (TheAlgorithms#10927)
* added mean absolute error to loss_functions.py * added doctest to mean absolute error to loss_functions.py * fixed long line in loss_functions.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fixed error in MAE * Update machine_learning/loss_functions.py Co-authored-by: Tianyi Zheng <[email protected]> --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Tianyi Zheng <[email protected]>
1 parent 7533f3a commit 2c8c49c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Diff for: machine_learning/loss_functions.py

+37
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,43 @@ def mean_squared_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
261261
return np.mean(squared_errors)
262262

263263

264+
def mean_absolute_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
265+
"""
266+
Calculates the Mean Absolute Error (MAE) between ground truth (observed)
267+
and predicted values.
268+
269+
MAE measures the absolute difference between true values and predicted values.
270+
271+
Equation:
272+
MAE = (1/n) * Σ(abs(y_true - y_pred))
273+
274+
Reference: https://en.wikipedia.org/wiki/Mean_absolute_error
275+
276+
Parameters:
277+
- y_true: The true values (ground truth)
278+
- y_pred: The predicted values
279+
280+
>>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
281+
>>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2])
282+
>>> np.isclose(mean_absolute_error(true_values, predicted_values), 0.16)
283+
True
284+
>>> true_values = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
285+
>>> predicted_values = np.array([0.8, 2.1, 2.9, 4.2, 5.2])
286+
>>> np.isclose(mean_absolute_error(true_values, predicted_values), 2.16)
287+
False
288+
>>> true_labels = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
289+
>>> predicted_probs = np.array([0.3, 0.8, 0.9, 5.2])
290+
>>> mean_absolute_error(true_labels, predicted_probs)
291+
Traceback (most recent call last):
292+
...
293+
ValueError: Input arrays must have the same length.
294+
"""
295+
if len(y_true) != len(y_pred):
296+
raise ValueError("Input arrays must have the same length.")
297+
298+
return np.mean(abs(y_true - y_pred))
299+
300+
264301
def mean_squared_logarithmic_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
265302
"""
266303
Calculate the mean squared logarithmic error (MSLE) between ground truth and

0 commit comments

Comments
 (0)