gpt4 book ai didi

python - numpy dot() 和 Python 3.5+ 矩阵乘法之间的区别@

转载 作者:IT老高 更新时间:2023-10-28 21:10:11 33 4
gpt4 key购买 nike

我最近迁移到 Python 3.5 并注意到 new matrix multiplication operator (@)有时行为与 numpy dot 不同运算符(operator)。例如,对于 3d 数组:

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)

@ 操作符返回一个形状数组:

c.shape
(8, 13, 13)

np.dot() 函数返回时:

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

如何使用 numpy dot 重现相同的结果?还有其他显着差异吗?

最佳答案

@ 运算符调用数组的__matmul__ 方法,而不是dot。该方法在 API 中也以函数 np.matmul 的形式出现。 .

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

来自文档:

matmul differs from dot in two important ways.

  • Multiplication by scalars is not allowed.
  • Stacks of matrices are broadcast together as if the matrices were elements.

最后一点清楚地表明,dotmatmul 方法在传递 3D(或更高维)数组时表现不同。从文档中引用更多内容:

对于matmul:

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 :

For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b

关于python - numpy dot() 和 Python 3.5+ 矩阵乘法之间的区别@,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34142485/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com