简体   繁体   English

numpy.dot 的意外结果

[英]Unexpected result with numpy.dot

I have two matrices:我有两个矩阵:

>>> a.shape
(100, 3, 1)
>>> b.shape
(100, 3, 3)

I'd like to perform a dot product such that my end result is (100, 3, 1).我想执行一个点积,这样我的最终结果是 (100, 3, 1)。 However, currently I receive:但是,目前我收到:

>>> c = np.dot(b, a)
>>> c.shape
(100, 3, 100, 1)

Could somebody explain what is happening?有人可以解释发生了什么吗? I'm reading thedocs and can't figure it out.我正在阅读文档,但无法弄清楚。

Edit:编辑:

So per the docs (overlooked it):所以根据文档(忽略它):

If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.如果 a 和 b 都是二维数组,则是矩阵乘法,但首选使用 matmul 或 a @ b。

And that gives the desired result, but I'm still curious, what is taking place here?这给出了想要的结果,但我仍然很好奇,这里发生了什么? What rule of the np.dot function is being applied to yield a result of (100, 3, 100, 1) ?应用np.dot函数的什么规则来产生(100, 3, 100, 1)

This is how dot works in your case:这就是 dot 在您的情况下的工作方式:

dot(b, a)[i,j,k,m] = sum(b[i,j,:] * a[k,:,m])

Your output shape is exactly how the docs specify it:您的输出形状正是文档指定的方式:

(b.shape[0], b.shape[1], a.shape[0], a.shape[2])

If it's not what you expected, you might be looking for another matrix multiplication.如果这不是您所期望的,您可能正在寻找另一个矩阵乘法。

dot will return all the possible products of the matrices stored in the last two dimensions of your arrays. dot将返回存储在数组最后两个维度中的矩阵的所有可能乘积。 Use matmul aka the @ operator to broadcast the leading dimensions instead of combining them:使用matmul aka @运算符来广播前导维度而不是组合它们:

np.matmul(b, a)

Or或者

b @ a

The Swiss Army knife of sum-products is einsum , so you can use that too: sum-products 的einsumeinsum ,所以你也可以使用它:

np.einsum('aij,ajk->aik', b, a)

Or或者

np.einsum('ajk,aij->aik', a, b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM