MAPE calculation in python

Both solutions are not working with zero values. This is working form me:

def percentage_error(actual, predicted):
    res = np.empty(actual.shape)
    for j in range(actual.shape[0]):
        if actual[j] != 0:
            res[j] = (actual[j] - predicted[j]) / actual[j]
        else:
            res[j] = predicted[j] / np.mean(actual)
    return res

def mean_absolute_percentage_error(y_true, y_pred): 
    return np.mean(np.abs(percentage_error(np.asarray(y_true), np.asarray(y_pred)))) * 100

I hope it helps.


In Python for compare by not equal need !=, not <>.

So need:

def mape_vectorized_v2(a, b): 
    mask = a != 0
    return (np.fabs(a - b)/a)[mask].mean()

Another solution from stats.stackexchange:

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

The new version of scikit-learn (v0.24) has a function that will calculate MAPE. sklearn.metrics.mean_absolute_percentage_error

All what you need is two array-like variables: y_true storing the actual/real values, and y_pred storing the predicted values.

You can refer to the official documentation here.