如何在Python中优化MAPE代码? [英] How to optimize MAPE code in Python?

查看:201
本文介绍了如何在Python中优化MAPE代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要具有MAPE功能,但是无法在标准软件包中找到它....,下面,我对该功能的实现.

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)

我不喜欢它,就速度而言,它不是最佳选择.如何以更Pythonic的方式重写代码并提高速度?

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?

推荐答案

这是一种使用

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

在计算division之后,使用masking可能更快一些-

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

运行时测试-

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

这篇关于如何在Python中优化MAPE代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆