0 votes
1 view
in Data Science by (17.6k points)

I need to have a MAPE function, however I was not able to find it in standard packages ... Below, my implementation of this function.

def mape(actual, predict):

    tmp, n = 0.0, 0

    for i in range(0, len(actual)):

        if actual[i] <> 0:

            tmp += math.fabs(actual[i]-predict[i])/actual[i]

            n += 1

    return (tmp/n)

I don't like it, it's super not optimal in terms of speed. How to rewrite the code to be more Pythonic way and boost the speed?

1 Answer

0 votes
by (38.5k points)

For making the code optimal, here is a  vectorized approach with masking -

 

def mape_vectorized(a, b): 

    mask = a <> 0

    return (np.fabs(a[mask] - b[mask])/a[mask]).mean()

This is probably a faster one with masking after division computation -

 

def mape_vectorized_v2(a, b): 

    mask = a <> 0

    return (np.fabs(a - b)/a)[mask].mean() 

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...