Consider the following code.
import numpy as np
array1 = np.random.random((3,3,3))
array2 = np.random.random((3,3,3))
array3 = array1@array2
What does array3 contain? I know it also has shape (3,3,3). If array1 and array2 were two-dimensional, then array3 would be the matrix multiplication of the arrays. Has the @ operation a mathematical meaning?
CodePudding user response:
This is explained in PEP 465:
For inputs with more than 2 dimensions, we treat the last two dimensions as being the dimensions of the matrices to multiply, and ‘broadcast’ across the other dimensions. This provides a convenient way to quickly compute many matrix products in a single operation. For example,
arr(10, 2, 3) @ arr(10, 3, 4)performs 10 separate matrix multiplies, each of which multiplies a 2x3 and a 3x4 matrix to produce a 2x4 matrix, and then returns the 10 resulting matrices together in an array with shape (10, 2, 4).
So for your code array3[0, :, :] contains the result of the matrix-matrix multiplication array1[0, :, :] @ array2[0, :, :], and so on.
CodePudding user response:
In numpy @ does matrix multiplication
While * does element wise multiplication or Hadamard product
