How to Calculate MAPE in Python
Published on Aug. 22, 2023, 12:16 p.m.
There are different ways to calculate the Mean Absolute Percentage Error (MAPE) in Python, but here are two common methods:
Method 1: Using the numpy package
import numpy as np
def MAPE(actual, predicted):
mask = actual != 0
return (np.fabs(actual - predicted)/actual)[mask].mean() * 100
Method 2: Without using any package
def MAPE(actual, predicted):
mask = actual != 0
return (sum(np.abs((actual - predicted) / actual)[mask]) / len(actual)) * 100
In both methods, actual
is a list or NumPy array of the actual (observed) values, and predicted
is also a list or NumPy array of the predicted values. The MAPE is calculated by finding the average of the absolute differences between the actual and predicted values, divided by the actual values, and then multiplying by 100 to express it as a percentage.
You can use either of these functions to calculate the MAPE for your data by passing in the actual
and predicted
arrays as arguments, as shown below:
actual = [10, 20, 30, 40]
predicted = [12, 22, 32, 42]
mape = MAPE(actual, predicted)
print(mape)
This will output the MAPE value for the given data.