How to Calculate MAPE in Python?

How to Calculate MAPE in Python?

The Mean Absolute Percentage Error (MAPE) is a common metric used to determine the accuracy of forecasting methods. It's calculated as the average of the absolute percentage errors of predictions.

The formula for MAPE is:

MAPE=n1​∑i=1n​∣∣​Ai​Ai​−Fi​​∣∣​×100

Where:

  • n is the number of data points.
  • Ai​ is the actual value for the i-th data point.
  • Fi​ is the forecasted value for the i-th data point.

Let's implement MAPE in Python:

def mean_absolute_percentage_error(y_true, y_pred): # Ensure lists are numpy arrays to use element-wise operations y_true, y_pred = np.array(y_true), np.array(y_pred) # Avoid division by zero by adding a small constant # Note: Handle this as you see fit based on your use case y_true = y_true + 1e-10 return np.mean(np.abs((y_true - y_pred) / y_true)) * 100 # Example usage: import numpy as np y_true = [100, 200, 300, 400, 500] y_pred = [110, 190, 290, 410, 490] mape = mean_absolute_percentage_error(y_true, y_pred) print(f"MAPE: {mape:.2f}%") 

Note: The division by zero issue is something you should be careful about when calculating MAPE, especially if the actual values can be zero. The above implementation adds a very small constant to avoid the division by zero, but depending on your use case, you might want to handle this differently.


More Tags

gps powershell-1.0 ecmascript-6 android-mediascanner pixel semantic-ui-react php-7.3 .net-5 rendering shuffle

More Programming Guides

Other Guides

More Programming Examples