Skip to content

Instantly share code, notes, and snippets.

@amanahuja
Last active October 1, 2020 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amanahuja/6315882 to your computer and use it in GitHub Desktop.
Save amanahuja/6315882 to your computer and use it in GitHub Desktop.
Mean Absolute Percentage Error (MAPE) metric for python sklearn. Written in response to a question on Cross Validated: http://stats.stackexchange.com/questions/58391/mean-absolute-percentage-error-mape-in-scikit-learn/62511#62511
from sklearn.utils import check_arrays
def mean_absolute_percentage_error(y_true, y_pred):
"""
Use of this metric is not recommended; for illustration only.
See other regression metrics on sklearn docs:
http://scikit-learn.org/stable/modules/classes.html#regression-metrics
Use like any other metric
>>> y_true = [3, -0.5, 2, 7]; y_pred = [2.5, -0.3, 2, 8]
>>> mean_absolute_percentage_error(y_true, y_pred)
Out[]: 24.791666666666668
"""
y_true, y_pred = check_arrays(y_true, y_pred)
## Note: does not handle mix 1d representation
#if _is_1d(y_true):
# y_true, y_pred = _check_1d_array(y_true, y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
@acondori
Copy link

This doesn't work, is too old, any have a new version o this? thanks a lot!

@RamzanShahidkhan
Copy link

The new version is here to calculate the MAPE
import numpy as np

def mean_absolute_percentage_error(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100

@HudaBou
Copy link

HudaBou commented Jan 17, 2020

I've used the same code part and I have this problem: ValueError: operands could not be broadcast together with shapes (7947,) (18545,) any idea?

@ashutosh1919
Copy link

MAPE is releasing in update 0.23 in sklearn by PR #15007.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment