如何为两个形状相似的numpy数组向量化< x(t-lag),y(t)>?

5n0oy7gb  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(68)

我有两个相同维度的numpy数组xy。对于不同的滞后值,我想计算<x(t-lag>,y(t)>如下。下面的代码是通过我想知道是否有一个矢量化的实现,可以更快。

def foo(x, y, lags):
    T = x.shape[0]
    res_list = []
    for lag in lags:
        res_list.append(np.mean(x[lag:]*y[:(T - lag)]))
    return res_list

if __name__ == '__main__':
    T = 1000
    N = 10
    lags = np.arange(0, 40)
    x = np.random.randn(T, N)
    y = np.random.randn(T, N)
    res = foo(x, y, lags)
    print("done")
jaql4c8m

jaql4c8m1#

如果你使用einsum来避免创建大型中间数组,这会更快一些:

def foo(x, y, lags):
    T = x.shape[0]
    res_list = []
    for lag in lags:
        res_list.append(np.einsum('ij,ij', x[lag:], y[:(T - lag)]) / x[lag:].size)
    return res_list

时间:

Original
876 µs ± 10.1 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
Einsum
502 µs ± 2.81 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

这最终会快43%。
我不确定是否有一个完全矢量化的解决方案。

相关问题