NumPy: Dot Product of two Arrays
In this tutorial, you will learn how to find the dot product of two arrays using NumPy's numpy.dot()
function.
For two scalars (or 0 Dimensional Arrays), their dot product is equivalent to simple multiplication; you can use either numpy.multiply()
or plain *
. Below is the dot product of $2$ and $3$.
import numpy as np
dotproduct = np.dot(2,3)
print(dotproduct)
The script will print
6
1 Dimensional Arrays
Consider two two-dimensional vectors, $\mathbf{a} = a_{x}\mathbf{i} + a_{y}\mathbf{j}$ and $\mathbf{b} = b_{x}\mathbf{i} + b_{y}\mathbf{j}$. Their dot product (also called scalar product) is defined by
$$ \mathbf{a}\cdot\mathbf{b} = a_{x}b_{x} + a_{y}b_{y} $$
So, given the vectors $\mathbf{u} = 2\mathbf{i} - 5\mathbf{j}$ and $\mathbf{v} = \mathbf{i} + 3\mathbf{j}$ their dot product is
$$ \mathbf{u} \cdot \mathbf{v} = 2 \times 1 + (-5) \times3 = -13 $$
NumPy has the numpy.dot()
function to find the dot product of two arrays. Representing the vectors $u$ and $v$ as 1D arrays, we write the script below to compute their dot product.
import numpy as np
u = [2,-5]
v = [1,3]
dotproduct = np.dot(u,v)
print(dotproduct)
On running the script, it will result in
-13
2 Dimensional Arrays
Now if the arrays are two-dimensional, numpy.dot()
will result in matrix multiplication. As an example, consider the below two two-dimensional arrays
$$ \mathbf{u} = [[2,-3],[1,9]] \\ \mathbf{v} = [[0,1],[1,-4]] $$
We find their dot product in NumPy,
import numpy as np
u = [[2,-3],[1,9]]
v = [[0,1],[1,-4]]
dotproduct = np.dot(u,v)
print(dotproduct)
and this script results in
[[ -3 14]
[ 9 -35]]
The above operation actually is matrix multiplication. We can use numpy.matmul()
for the above two arrays and arrive at the same result. The below script
import numpy as np
u = [[2,-3],[1,9]]
v = [[0,1],[1,-4]]
matrixproduct = np.matmul(u,v)
print(matrixproduct)
also results in the same array
[[ -3 14]
[ 9 -35]]