且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:Numpy将数组的每一行与另一个数组的每一行相乘

更新时间:2022-06-03 18:05:01

您需要展开第二个轴以创建两个 4D 版本,并使其乘以彼此-

You need to spread out that second axis to create two 4D versions and let them multiply against each other -

matrix[:,None,:,:]*matrix[:,:,None,:]

或者简单地--

matrix[:,None]*matrix[...,None,:]



外部操作



示意图说明:

Outer-operation

Explanation with schematic :

我们希望沿彼此进行外元素相乘第二轴。因此,我们需要扩展轴并创建两个4D数组版本,以使单例(length = 1的轴)对应于另一个的全轴长版本。我们使用 np.newaxis / None 进行尺寸扩展。

We are looking to perform outer-elementwise multiplication against each other along the second axis. So, we need to extend axes and create two 4D array versions such that there's singleton(axis with length=1) corresponding to a full-axis-length version in another. We are doing this dimension-extension with np.newaxis/None.

考虑形状为(3,5):

matrix : 3 x 5

让我们沿着第二个轴进行外元素乘法。因此,数组的扩展将是-

Let's do outer-elementwise multiplication along the second axis. So, the extension of arrays would be -

matrix-version1 : 3 x 1 x 5
matrix-version2 : 3 x 5 x 1

类似地,为了沿第一个轴执行外元素乘法, -

Similarly, for performing outer-elementwise multiplication along the first axis, it would be -

matrix-version1 : 1 x 3 x 5
matrix-version2 : 3 x 1 x 5

因此,将其扩展到我们的 3D 情况下,沿第二轴进行元素逐次乘法,并假设形状为(m,n,r),则应为-

Thus, extending this to our 3D case for outer-elementwise multiplication along the second axis and assuming a shape of (m,n,r), it would be -

matrix-version1 : m x 1 x n x r # [:,None,:,:]
matrix-version2 : m x n x 1 x r # [:,:,None,:]

因此,在元素相乘后得出:

Hence, after elementwise multiplication resulting in :

output          : m x n x n x r