我有两个相同维度的numpy数组x
和y
。对于不同的滞后值,我想计算<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")
1条答案
按热度按时间jaql4c8m1#
如果你使用einsum来避免创建大型中间数组,这会更快一些:
时间:
这最终会快43%。
我不确定是否有一个完全矢量化的解决方案。