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

查看:16
本文介绍了如何在 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天全站免登陆