本文介绍了快速累积和和运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个预测算法,它使用以下代码来处理时间序列在给定范围内的趋势:

I have a forecast algorithm that works the trend of time series up to a given horizon using the following code:

import numpy as np
horizon = 91
phi = 0.2
trend = -0.004
trend_up_to_horizon = np.cumsum(phi ** np.arange(horizon) + 1) * self.trend

在此示例中,前两个 trend_up_horizo​​n 值是:

In this example the first two trend_up_horizon values are:

array([-0.008 , -0.0128])

是否有一种计算上更快的方法来实现这一目标?目前,我估计使用 np.cumsum 方法和 ** 运算符会花费很长时间.

Is there a computationally faster way to achieve this? At the moment this takes a long time as I guess using the np.cumsum method and ** operator are expensive.

感谢您的帮助

推荐答案

您可以使用Cython使其速度更快一点,但这并不多

you could use Cython to make it a tiny bit faster, but it's not much

在基本 np.cumsum(phi ** np.arange(horizo​​n)+ 1)*趋势上运行%timeit ,说我的笔记本电脑需要17.5µs,没什么

running %timeit on your basic np.cumsum(phi ** np.arange(horizon) + 1) * trend says it takes 17.5µs on my laptop, which isn't much

与之等效的Cython版本是:

a Cython version that does the equivalent is:

import numpy as np
cimport numpy as np
cimport cython

@cython.boundscheck(False)
def do_cumsum(size_t horizon, double phi, double trend):
    cdef np.ndarray[double, ndim=1] out = np.empty(horizon, dtype=np.float)
    cdef double csum = 0
    cdef int i

    for i in range(horizon):
        csum += phi ** i + 1
        out[i] = csum * trend

    return out

可以将 do_cumsum(水平,水平线,趋势)的时间降低到6.9µs,而如果我切换到单精度/32位浮点,则可以降低到4.5µs

which reduces the time of do_cumsum(horizon, p trend) down to 6.9µs, while if I switch to single precision/32bit floats this goes down to 4.5µs

那是说,微秒并不多,您最好将精力集中在其他地方

that said, microseconds aren't much and you're probably better off focusing your efforts elsewhere

这篇关于快速累积和和运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 09:53