Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions machine_learning/loss_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,40 @@
return np.sum(kl_loss)


def mean_absolute_percentage_error(

Check failure on line 666 in machine_learning/loss_functions.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F811)

machine_learning/loss_functions.py:666:5: F811 Redefinition of unused `mean_absolute_percentage_error` from line 439
y_true: np.ndarray, y_pred: np.ndarray, epsilon: float = 1e-15
) -> float:
"""
Calculate the Mean Absolute Percentage Error (MAPE) between y_true and y_pred.
MAPE is calculated by dividing the absolute error by the absolute value of
the actual measurement and then averaging.
SMAPE = (1/n) * Σ( |y_true - y_pred| / |y_true|)
Reference:
https://en.wikipedia.org/wiki/Mean_absolute_percentage_error
Parameters:
- y_true: The true values (ground truth)
- y_pred: The predicted values
- epsilon: Small constant to avoid division by zero
>>> true_values = np.array([100, 200, 300, 400])
>>> predicted_values = np.array([110, 190, 310, 420])
>>> float(symmetric_mean_absolute_percentage_error(true_values, predicted_values))

Check failure on line 682 in machine_learning/loss_functions.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

machine_learning/loss_functions.py:682:89: E501 Line too long (90 > 88)
0.058333333333333334
>>> true_labels = np.array([100, 200, 300])
>>> predicted_probs = np.array([110, 190, 310, 420])
>>> symmetric_mean_absolute_percentage_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.")

denominator = np.where(np.abs(y_true) == 0, epsilon, np.abs(y_true))

mape_loss = np.abs(y_true - y_pred) / denominator
return np.mean(mape_loss)


if __name__ == "__main__":
import doctest

Expand Down
Loading