NumPy Dot Product – numpy.dot()

NumPy Dot Product

To compute dot product of numpy nd arrays, you can use numpy.dot() function.

numpy.dot() function accepts two numpy arrays as arguments, computes their dot product, and returns the result.

Syntax

The syntax of numpy.dot() function is

numpy.dot(a, b, out=None)
ParameterDescription
a[mandatory] First argument for dot product operation.
b[mandatory] Second argument for dot product operation.
out[optional] This argument is used for performance. This has to be a C-contiguous array, and the dtype must be the dtype that would be returned for dot(a,b).

Behavior of numpy.dot() based on Input Array Dimensions

The following table specifies the type of operation done based on the dimensions of input arrays: a and b.

Dimension of ‘a’ and ‘b’Output
Zero-Dimension (Scalar)Multiplication of two scalars, a and b.
One-Dimensional Arrays (Vector)Inner product of vectors.
Two-Dimensional Arrays (Matrix)Matrix Multiplication.
a: N-Dimensional Array
b: 1-D Array
Sum product over the last axis of a and b.
a: N-Dimensional Array
b: M-Dimensional Array (M>=2)
Sum product over the last axis of a and second-to-last axis of b.

Examples

1. Dot Product of Scalars

In this example, we take two scalars and calculate their dot product using numpy.dot() function. Dot product using numpy.dot() with two scalars as arguments return multiplication of the two scalars.

Python Program

import numpy as np

a = 3 
b = 4
output = np.dot(a,b)
print(output)
Run Code Copy

Output

12

Explanation

output = a * b
       = 3 * 4
       = 12

2. Dot Product of 1D Arrays (Vectors)

In this example, we take two numpy one-dimensional arrays and calculate their dot product using numpy.dot() function. We already know that, if input arguments to dot() method are one-dimensional, then the output would be inner product of these two vectors (since these are 1D arrays).

Python Program

import numpy as np

# Initialize arrays
A = np.array([2, 1, 5, 4])
B = np.array([3, 4, 7, 8])

# Dot product
output = np.dot(A, B)

print(output)
Run Code Copy

Output

77

Dot Product

output = [2, 1, 5, 4].[3, 4, 7, 8]
       = 2*3 + 1*4 + 5*7 + 4*8
       = 77

3. Dot Product of 2-D Arrays (Matrix)

In this example, we take two two-dimensional numpy arrays and calculate their dot product. Dot product of two 2-D arrays returns matrix multiplication of the two input arrays.

Python Program

import numpy as np

# Initialize arrays
A = np.array([[2, 1], [5, 4]])
B = np.array([[3, 4], [7, 8]])

# Dot product
output = np.dot(A, B)

print(output)
Run Code Copy

Output

[[13 16]
 [43 52]]

Dot Product

output = [[2, 1], [5, 4]].[[3, 4], [7, 8]]
       = [[2*3+1*7, 2*4+1*8], [5*3+4*7, 5*4+4*8]]
       = [[13, 16], [43, 52]]

Summary

In this NumPy Tutorial, we learned how to calculate the dot product of numpy arrays, with the help of well detailed example programs.

Related Tutorials

Code copied to clipboard successfully 👍