NumPy中的累积交叉加法/乘法

时间:2018-03-25 18:40:11

标签: python numpy matrix matrix-multiplication scientific-computing

a = [1,2,3]
b = [2,4,6]

c = [1*2, 1*4 + 2*2, 1*6 + 2*4 + 3*2]

我通过创建Toeplitz矩阵使用了dot产品,但我正在寻找一个更快的版本,因为我正在处理一个巨大的数据集。使用循环也会减慢计算速度。

1 个答案:

答案 0 :(得分:4)

This output is the first half of a convolution of a and b:

numpy.convolve(a, b)[:len(a)]

If your arrays are big enough, you may be able to save time with an FFT-based convolution:

scipy.signal.fftconvolve(a, b)[:len(a)]

An FFT convolution has runtime O(n log n) where n is the length of the input arrays, in contrast to the O(n^2) runtime of a straightforward nested-loop convolution. However, it has a worse constant factor, and it requires floating-point arithmetic, so results may have a small amount of numerical error.

On a sufficiently recent version of SciPy (at least 0.19.0, released March 09, 2017), you can use scipy.signal.convolve to automatically pick between a direct or FFT convolution based on an estimate of which would be faster. Prior to 0.19.0, scipy.signal.convolve would always use a direct computation.