Python中的无环3D矩阵乘法 [英] A loopless 3D matrix multiplication in python

查看:65
本文介绍了Python中的无环3D矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在python(numpy)中执行以下操作.

I am looking to do the following operation in python (numpy).

Matrix A is M x N x R
Matrix B is N x 1 x R

矩阵乘以AB = C,其中C是M x 1 x R矩阵. 本质上说,A的每个M x N层(其中的R个)都是矩阵分别乘以B中的每个N x 1向量.我确信这是单线的.我一直在尝试使用tensordot(),但是我似乎给了我意想不到的答案.

Matrix multiply AB = C, where C is a M x 1 x R matrix. Essentially each M x N layer of A (R of them) is matrix multiplied independently by each N x 1 vector in B. I am sure this is a one-liner. I have been trying to use tensordot(), but I that seems to be giving me answers that I don't expect.

我已经在Igor Pro中编程了将近10年,现在我正尝试将其页面转换为python.

I have been programming in Igor Pro for nearly 10 years, and I am now trying to convert pages of it over to python.

推荐答案

抱歉,关于死灵法术,但是使用宝贵的np.einsum可以大大改善这个答案.

Sorry for the necromancy, but this answer can be substantially improved upon, using the invaluable np.einsum.

import numpy as np

D,M,N,R = 1,2,3,4
A = np.random.rand(M,N,R)
B = np.random.rand(N,D,R)

print np.einsum('mnr,ndr->mdr', A, B).shape

请注意,它具有几个优点:首先,它的速度很快.通常,np.einsum的优化程度很高,但是np.einsum足够聪明,可以避免创建MxNxR临时数组,但是可以直接在N上执行收缩.

Note that it has several advantages: first of all, its fast. np.einsum is well-optimized generally, but moreover, np.einsum is smart enough to avoid the creation of an MxNxR temporary array, but performs the contraction over N directly.

但也许更重要的是,它非常可读.毫无疑问,该代码是正确的.并且可以使它变得更加复杂而没有任何麻烦.

But perhaps more importantly, its very readable. There is no doubt that this code is correct; and you could make it a lot more complicated without any trouble.

请注意,如果需要,可以简单地从B和einsum语句中删除虚拟"D"轴.

Note that the dummy 'D' axis can simply be dropped from B and the einsum statement if you wish.

这篇关于Python中的无环3D矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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