如何在Python中优化MAPE代码?

时间:2017-02-15 13:38:32

标签: python numpy machine-learning statistics data-science

我需要一个MAPE函数,但是我无法在标准软件包中找到它......下面,我实现了这个函数。

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方式并提高速度?

2 个答案:

答案 0 :(得分:6)

这是masking -

的一种矢量化方法
def mape_vectorized(a, b): 
    mask = a <> 0
    return (np.fabs(a[mask] - b[mask])/a[mask]).mean()

在计算masking之后division可能是一个速度更快的

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

答案 1 :(得分:0)

使用def customReduce[CC1[A] <: Iterable[A], CC2[A] <: Iterable[A]](foos: CC1[Foo[CC2]])(implicit factory: Factory[Int, CC1[Int]] ): Foo[CC1] = Foo(foos.flatMap(_.foo).to(factory)) println(customReduce(Seq(Foo(Seq(1))))) // Foo(List(1)) 掩盖被零除的另一种类似方法是:

masked_Arrays