使用 Python、Numpy 更快地做到这一点? [英] Faster way to do this using Python, Numpy?

查看:40
本文介绍了使用 Python、Numpy 更快地做到这一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中有一个函数.我想让它快很多?有人有什么建议吗?

I have a function in Python. I would like to make it a lot faster? Does anyone have any tips?

def garchModel(e2, omega=0.01, beta=0.1, gamma=0.8 ):

    sigma    = np.empty( len( e2 ) )
    sigma[0] = omega

    for i in np.arange(  1, len(e2) ):

        sigma[i] = omega + beta * sigma[ i-1 ] + gamma * e2[ i-1 ]

    return sigma

推荐答案

以下代码有效,但有太多的诡计,我不确定它是否依赖于一些最终可能会崩溃的未记录的实现细节:/p>

The following code works, but there's too much trickery going on, I am not sure it is not depending on some undocumented implementation detail that could eventually break down:

from numpy.lib.stride_tricks import as_strided
from numpy.core.umath_tests import inner1d

def garch_model(e2, omega=0.01, beta=0.1, gamma=0.8):
    n = len(e2)
    sigma = np.empty((n,))
    sigma[:] = omega
    sigma[1:] += gamma * e2[:-1]
    sigma_view = as_strided(sigma, shape=(n-1, 2), strides=sigma.strides*2)
    inner1d(sigma_view, [beta, 1], out=sigma[1:])
    return sigma

In [75]: e2 = np.random.rand(1e6)

In [76]: np.allclose(garchModel(e2), garch_model(e2))
Out[76]: True

In [77]: %timeit garchModel(e2)
1 loops, best of 3: 6.93 s per loop

In [78]: %timeit garch_model(e2)
100 loops, best of 3: 17.5 ms per loop

这篇关于使用 Python、Numpy 更快地做到这一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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