numpy dot()和Python 3.5+矩阵乘法之间的区别@ [英] Difference between numpy dot() and Python 3.5+ matrix multiplication @

查看:79
本文介绍了numpy dot()和Python 3.5+矩阵乘法之间的区别@的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近转向Python 3.5,并注意到新矩阵乘法运算符(@)有时的行为与 numpy点不同运算符.例如,对于3d数组:

I recently moved to Python 3.5 and noticed the new matrix multiplication operator (@) sometimes behaves differently from the numpy dot operator. In example, for 3d arrays:

import numpy as np

a = np.random.rand(8,13,13)
b = np.random.rand(8,13,13)
c = a @ b  # Python 3.5+
d = np.dot(a, b)

@运算符返回一个形状数组:

The @ operator returns an array of shape:

c.shape
(8, 13, 13)

,而np.dot()函数返回:

d.shape
(8, 13, 8, 13)

如何用numpy点重现相同的结果?还有其他重大区别吗?

How can I reproduce the same result with numpy dot? Are there any other significant differences?

推荐答案

@运算符调用数组的__matmul__方法,而不是dot.此方法在API中也以 np.matmul 的形式存在.

The @ operator calls the array's __matmul__ method, not dot. This method is also present in the API as the function np.matmul.

>>> a = np.random.rand(8,13,13)
>>> b = np.random.rand(8,13,13)
>>> np.matmul(a, b).shape
(8, 13, 13)

从文档中:

matmuldot在两个重要方面不同.

matmul differs from dot in two important ways.

  • 不允许标量相乘.
  • 将矩阵堆栈一起广播,就好像矩阵是元素一样.

最后一点很清楚,当传递3D(或更高维)数组时,dotmatmul方法的行为会有所不同.从文档中引用更多内容:

The last point makes it clear that dot and matmul methods behave differently when passed 3D (or higher dimensional) arrays. Quoting from the documentation some more:

对于matmul:

如果任一自变量为N-D,N> 2,则将其视为位于最后两个索引中并相应广播的一组矩阵.

If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.

对于 np.dot :

对于2-D数组,它等效于矩阵乘法,对于1-D数组,其等效于向量的内积(无复共轭). 对于N个维度,它是a的最后一个轴与b的倒数第二个之和的乘积

这篇关于numpy dot()和Python 3.5+矩阵乘法之间的区别@的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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