My Coding > Programming language > Python > Python FAQ > Python: How to calculate MAPE – Mean Absolute Percentage Error

# Python: How to calculate MAPE – Mean Absolute Percentage Error

Mean absolute percentage error (MAPE) is a metric to calculate the distance between two datasets. This metric often used, when it is necessary to estimate the distance (or cost) between predicted and target values of some functions.

MAPE = (100%/n)*Σni=1(|(yi-y’i)/yi|)

where y is our target value and y' - our predicted value.

This function have few disadvantages. First of all, if or target value is equal to 0, then we will have division to 0, which is not very easy to do. Second disadvantage – is percent value. In some calculations, it is very easy to forget that this is per cent values and make a mistake. Also different function can calculate this value with or without per cents. So it is necessary to be very accurate.

### Test data set

Let’s make a simple dataset for calculation MAE value

 y 5 3 6 7 5 6 3 45 6 8 -3 4 5 y' 4 3 6 6 6 4 4 38 5 7 -4 4 3

and we can transfer these data to python numpy array

y_data = np.array([5, 3,6,7,5,6,3,45,6,8,-3,4,5])
y_pred = np.array([4,3,6,6,6,4,4,38,5,7,-4,4,3])

### Calculating MAPE with pure numpy

We will implement the above equation with Numpy mathematical operations

def MAPE(y_validate, y_predict):
return np.mean(np.abs((y_validate – y_predict)/y_validate)) * 100

And the final code at one go

import numpy as np
def MAPE(y_validate, y_predict):
return np.mean(np.abs((y_validate – y_predict)/y_validate)) * 100
y_data = np.array([5, 3,6,7,5,6,3,45,6,8,-3,4,5])
y_pred = np.array([4,3,6,6,6,4,4,38,5,7,-4,4,3])
print(MAPE(y_data, y_pred))
# 18.385225885225882

### Sklearn MAPE function

Sclean library (Scikit-learn is a free software machine learning library for the Python) have MAPE procedure within its tools. But it is necessary to pay attention – it calculate Mean absolute percentage error without applying per cents, which is necessary to remember.

import numpy as np
from sklearn.metrics import mean_absolute_percentage_error as mape
y_data = np.array([5, 3,6,7,5,6,3,45,6,8,-3,4,5])
y_pred = np.array([4,3,6,6,6,4,4,38,5,7,-4,4,3])
print(mape(y_data, y_pred)) # 0.18385225885225884
print(mape(y_data, y_pred) * 100) # 18.385225885225884

Published: 2022-06-18 00:52:35

### 9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.