3

I've tried working with both of these functions, and they seem to be the same. But why would numpy have 2 different functions for the same operation? I just wanted to be sure.

I've so far found that they work the same for 2D arrays, but didn't find any difference at anywhere.

Fahim
  • 308
  • 1
  • 3
  • 10
  • This has already answer here: https://stackoverflow.com/questions/34142485/difference-between-numpy-dot-and-python-3-5-matrix-multiplication Try to search before asking a question. – Zabir Al Nazi May 01 '20 at 20:49
  • It's largely a matter of history. `np.dot` has been part of `numpy` for a long time. `matmul` with its operator `@` is new, with a different way of handling 3d (and larger) arrays. For 2d and 1d arrays they are basically the same. – hpaulj May 01 '20 at 20:49
  • I actually found that post before posting here. Just the heading mislead me, as I didn't know that '@' works the same as 'np.matmul' – Fahim May 01 '20 at 23:19

1 Answers1

3

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)

From the documentation:

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.

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:

For 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. For 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

For more information please check out: Difference between numpy dot() and Python 3.5+ matrix multiplication @

Hereby I cite the top answer as it's very clear what the difference is. Please say if You need some more help.

bindas
  • 33
  • 5