两个不同形状的NumPy数组的逐元素相乘

huangapple go评论89阅读模式
英文:

Element-wise multiply of two numpy array of different shapes

问题

我有两个numpy数组FC,它们的维度分别为NxMMxB。如何以高效的方式获得元素为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:第一个矩阵具有分别带有下标 nm 的维度,
  • mb:第二个矩阵具有分别带有下标 mb 的维度,
  • -->nmb:相乘 n x m x b,不对任何下标求和。
英文:

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 subscripts n and m respectively,
  • mb: second matrix has dimenisons with subscripts m and b respectively,
  • -->nmb: multiply n x m x b, do not sum over any subscript.

huangapple
  • 本文由 发表于 2023年6月8日 05:10:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定