英文:
Element-wise multiply of two numpy array of different shapes
问题
我有两个numpy数组F和C,它们的维度分别为NxM和MxB。如何以高效的方式获得元素为Result[n,m,b] = F[n,m]*C[m,b]的矩阵,其维度为NxMxB?
英文:
I have two numpy arrays F and C of dimensions NxM and MxB. How can I get a matrix with elements Result[n,m,b] = F[n,m]*C[m,b] with dimensions NxMxB in an efficient manner?
答案1
得分: 1
代码示例中提到的翻译部分如下:
"While the solution by @Nick Odell comments works and is fast, it is perhaps not very readable. Another option is to use numpy.einsum, which allows you to explicitely state which dimensions have to be multiplied and which ones must be summed. In your case, you could do"
"在这里,@Nick Odell 提到的解决方案有效且速度快,但可能不太易读。另一种选择是使用 numpy.einsum,它允许您明确指定哪些维度需要相乘,哪些需要相加。在您的情况下,您可以这样做:"
import numpy as np
N = 20
M = 40
B = 10
F = np.random.rand(N,M)
C = np.random.rand(M,B)
Result = np.einsum('nm,mb->nmb', F, C)
print(Result.shape) # (20,40,10)
在这段代码中,'nm,mb->nmb' 的含义如下:
nm:第一个矩阵具有分别带有下标n和m的维度,mb:第二个矩阵具有分别带有下标m和b的维度,-->nmb:相乘nxmxb,不对任何下标求和。
英文:
While the solution by @Nick Odell comments works and is fast, it is perhaps not very readable. Another option is to use numpy.einsum, which allows you to explicitely state which dimensions have to be multiplied and which ones must be summed. In your case, you could do
import numpy as np
N = 20
M = 40
B = 10
F = np.random.rand(N,M)
C = np.random.rand(M,B)
Result = np.einsum('nm,mb->nmb', F, C)
print(Result.shape) # (20,40,10)
Here 'nm,mb->nmb' means:
nm: first matrix has dimensions with subscriptsnandmrespectively,mb: second matrix has dimenisons with subscriptsmandbrespectively,-->nmb: multiplynxmxb, do not sum over any subscript.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论