gpt4 book ai didi

python - 矩阵-矩阵乘法的函数 numpy.dot()、@ 和方法 .dot() 之间有什么区别?

转载 作者:行者123 更新时间:2023-12-05 08:51:37 31 4
gpt4 key购买 nike

有区别吗?如果不是,按惯例首选什么?性能似乎几乎相同。

a=np.random.rand(1000,1000)
b=np.random.rand(1000,1000)
%timeit a.dot(b) #14.3 ms ± 374 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit np.dot(a,b) #14.7 ms ± 315 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit a @ b #15.1 ms ± 779 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

最佳答案

除了少数异常(exception),它们几乎相同。

a.dot(b)np.dot(a, b) 完全一样。参见 numpy.dotndarray.dot .

但是,查看numpy.dot的文档:

If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.

a@b对应numpy.matmul(a, b) . dotmatmul 的区别如下:

matmul differs from dot in two important ways:

  • Multiplication by scalars is not allowed, use * instead.
  • Stacks of matrices are broadcast together as if the matrices were elements, respecting the signature (n,k),(k,m)->(n,m):
>>> a = np.ones([9, 5, 7, 4])
>>> c = np.ones([9, 5, 4, 3])
>>> np.dot(a, c).shape (9, 5, 7, 9, 5, 3)
>>> np.matmul(a, c).shape (9, 5, 7, 3)
>>> # n is 7, k is 4, m is 3

关于python - 矩阵-矩阵乘法的函数 numpy.dot()、@ 和方法 .dot() 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59416178/

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