numpy二维& 3-D矩阵“行"乘法 [英] Numpy 2-D & 3-D matrix "row"-wise multiplication

查看:140
本文介绍了numpy二维& 3-D矩阵“行"乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习numpy,并尝试在2维和3维矩阵之间进行一种奇怪的矩阵乘法.我有一个功能可以满足我的需求,但是我很好奇是否有更好的方法.

I started learning numpy and I'm trying to do a kind of strange matrix multiplication between a 2-dimensional and a 3-dimensional matrices. I have a function that does what I need, but I'm curious if there's a better way of doing it.

让我们考虑一下,我们有一个矩阵(M1)具有(KxN)个维,还有另一个矩阵(M2)具有(KxNxN)个维.我正在尝试将M1的每(1xN)行与M2的相应(NxN)矩阵相乘.这是我的带有示例矩阵的代码:

Let's consider we have a matrix M1 with (KxN) dimensions, and have another matrix M2 with (KxNxN) dimensions. I'm trying to multiply each (1xN) rows of M1 with the corresponding (NxN) matrix of M2. Here's my code with sample matrices:

a = [[1., 2., 3.],
     [0., 9., 8.]]
a = np.array(a)
b = [[[.5, .5, .5],
      [.5, .5, .5],
      [.5, .5, .5]],
     [[.25, .25, .25],
      [.25, .25, .25],
      [.25, .25, .25]]]
b = np.array(b)

c = [[5., 5., 5., 5., 5.]]
c = np.array(c)
d = [[[.1, .1, .1, .1, .1],
      [.2, .2, .2, .2, .2],
      [.3, .3, .3, .3, .3],
      [.4, .4, .4, .4, .4],
      [.5, .5, .5, .5, .5]]]
d = np.array(d)


def mul(x, y):
    result = []
    for i in range(len(x)):
        result.append(x[i] @ y[i])
    return np.array(result)


print(mul(a, b))
[[3.   3.   3.  ]
 [4.25 4.25 4.25]]
print(mul(c, d))
[[7.5 7.5 7.5 7.5 7.5]]

我认为这很清楚.我敢肯定有更好的方法可以做到这一点,但是到目前为止,我还无法提出一种方法.我一直在尝试apply_along_axis并乘以,但是我可能完全偏离了轨道.

I think that makes it clear. I'm sure there is a better way of doing it, but so far I was unable to come up with one. I've been trying with apply_along_axis and multiply but I might be completely off track.

推荐答案

您可以使用 np.einsum -

You can use np.einsum -

np.einsum('ij,ijk->ik',array1,array2)

或在Python 3.x上使用np.matmul@运算符-

np.matmul(array1[:,None,:],array2)[:,0]
(array1[:,None,:] @ array2)[:,0]

这篇关于numpy二维& 3-D矩阵“行"乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆