使用卷积定理和 FFT 不会导致与 scipy.convolve 函数相同的结果

Using the convolution theorem and FFT does not lead to the same result as the scipy.convolve function

我想熟悉基于傅里叶的卷积。因此,我使用 numpy.fftscipy.signal.convolve 创建了一个小示例。但是,这两种操作的结果是不同的 我不知道为什么。 有人有想法吗?

我已经尝试使用scipy.signal.convolve的不同模式。

例子:

import numpy as np
from scipy.signal import convolve

# Generate example data
data = np.array([1, 1, 1, 1, 1, 1])
kernel = np.array([0, 1, 2, 1, 0, 0])

# Using scipy.signal.convolve
A = convolve(kernel, data, mode='full')
B = convolve(kernel, data, mode='valid')
C = convolve(kernel, data, mode='same')

# Using the convolution theorem 
D = np.fft.ifft(np.fft.fft(kernel) * np.fft.fft(data))

结果是:

A = array([0, 1, 3, 4, 4, 4, 4, 3, 1, 0, 0])
B = array([4])
C = array([3, 4, 4, 4, 4, 3])

D = array([4.+0.j, 4.+0.j, 4.+0.j, 4.+0.j, 4.+0.j, 4.+0.j])

您需要用 N-1 个零填充 datakernel 以避免循环卷积...

import numpy as np
from scipy.signal import convolve

# Generate example data
data = np.array([1, 1, 1, 1, 1, 1])
kernel = np.array([0, 1, 2, 1, 0, 0])

# Using scipy.signal.convolve
A = convolve(kernel, data, mode='full')

# Using the convolution theorem - need to pad with N-1 zeroes
data = np.array([1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0])
kernel = np.array([0, 1, 2, 1, 0, 0, 0, 0, 0, 0, 0])

D = np.fft.ifft(np.fft.fft(kernel) * np.fft.fft(data))

print (A)
print (D)

Result:

[0 1 3 4 4 4 4 3 1 0 0]
[2.4e-16+0.j 1.0e+00+0.j 3.0e+00+0.j 4.0e+00+0.j 4.0e+00+0.j 4.0e+00+0.j
 4.0e+00+0.j 3.0e+00+0.j 1.0e+00+0.j 3.2e-16+0.j 1.6e-16+0.j]