How to optimize MAPE code in Python?

后端 未结 2 766
小蘑菇
小蘑菇 2020-12-30 12:43

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, predic         


        
相关标签:
2条回答
  • 2020-12-30 13:03

    Another similar way of doing it using masked_Arrays to mask division by zero is:

    import numpy.ma as ma
    masked_actual = ma.masked_array(actual, mask=actual==0)
    MAPE = (np.fabs(masked_actual - predict)/masked_actual).mean()
    
    0 讨论(0)
  • 2020-12-30 13:04

    Here's one vectorized approach with masking -

    def mape_vectorized(a, b): 
        mask = a <> 0
        return (np.fabs(a[mask] - b[mask])/a[mask]).mean()
    

    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() 
    

    Runtime test -

    In [217]: a = np.random.randint(-10,10,(10000))
         ...: b = np.random.randint(-10,10,(10000))
         ...: 
    
    In [218]: %timeit mape(a,b)
    100 loops, best of 3: 11.7 ms per loop
    
    In [219]: %timeit mape_vectorized(a,b)
    1000 loops, best of 3: 273 µs per loop
    
    In [220]: %timeit mape_vectorized_v2(a,b)
    1000 loops, best of 3: 220 µs per loop
    
    0 讨论(0)
提交回复
热议问题