lea*_*ner 9 python arrays numpy convolution
我有 2 个二维数组。我试图沿轴 1 进行卷积。np.convolve
没有提供axis
参数。这里的答案是,使用 1 个 2D 数组与 1D 数组进行卷积np.apply_along_axis
。但它不能直接应用于我的用例。这里的问题没有答案。
MWE如下。
import numpy as np
a = np.random.randint(0, 5, (2, 5))
"""
a=
array([[4, 2, 0, 4, 3],
[2, 2, 2, 3, 1]])
"""
b = np.random.randint(0, 5, (2, 2))
"""
b=
array([[4, 3],
[4, 0]])
"""
# What I want
c = np.convolve(a, b, axis=1) # axis is not supported as an argument
"""
c=
array([[16, 20, 6, 16, 24, 9],
[ 8, 8, 8, 12, 4, 0]])
"""
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用 来完成此操作np.fft.fft
,但这似乎是完成简单事情的不必要的步骤。有没有一种简单的方法可以做到这一点?谢谢。
为什么不直接使用 进行列表理解zip
呢?
>>> np.array([np.convolve(x, y) for x, y in zip(a, b)])
array([[16, 20, 6, 16, 24, 9],
[ 8, 8, 8, 12, 4, 0]])
>>>
Run Code Online (Sandbox Code Playgroud)
或者与scipy.signal.convolve2d
:
>>> from scipy.signal import convolve2d
>>> convolve2d(a, b)[[0, 2]]
array([[16, 20, 6, 16, 24, 9],
[ 8, 8, 8, 12, 4, 0]])
>>>
Run Code Online (Sandbox Code Playgroud)