Numpy is the best python module for array creation and its manipulation. It has many functions that help it in manipulation. Numpy dot is one of them. In this entire tutorial of “how to”, you will know how to perform NumPy dot product on arrays step by step.
Steps to calculate dot products for Numpy Array
Step 1: Import all the necessary libraries.
Here in this tutorial, I am using only the NumPy array. Let’s import them.
import numpy as np
Step 2: Create a Numpy array
Let’s create both the one dimensional and two- dimensional NumPy array to perform dot product on it. You can create a NumPy array using the numpy.array() method. Please note that you have to pass two arrays for performing dot product inside the numpy.dot() method.
1D Numpy array creation
array([2, 3, 4]/pre>
array([2, 2, 2])
2D Numpy array creation
array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
array([[2, 2, 2], [2, 2, 2], [2, 2, 2]])
Step 3: Calculate Numpy dot product of Array
Now the last step is to perform dot product on both arrays. To do so you have to pass two arrays inside the dot() method. Let’s see them
Calculate dot product on 1D Array
You have to just pass both 1D NumPy arrays inside the dot() method. It will return a single result.
Dot Product of 2D Numpy array
Here you have to be careful. It is a 2D array and you have to follow rules on dot product. In mathematics, dot product is only possible and valid when the number of columns of matrix_1 is equal to the number of rows of matrix_2. Here for the sake of simplicity, my array is both the square matrix or array. The square matrix is called when the number of rows and number of columns is equal.
Let’s perform dot product on 2D Array.
The output will also be a 2D Numpy array with the shape n x p. Here n is the number of columns of the matrix or array1 and p is the number of rows of the matrix or array 2.
Calculate Numpy dot product using 1D and 2D array
The above examples were calculating products using the same 1D and 2D Numpy array. In this example, I will show you to find the dot product of a 1D array using a 2D array. Just execute the following lines of code to find the product.
array_1d_1= np.array([2,3,4]) array_2d_1= np.array([[1,2,3],[4,5,6],[7,8,9]]) np.dot(array_1d_1,array_2d_1)
If you reverse the placement of the array, then you will get a different output.
Numpy dot is a very useful method for implementing many machine learning algorithms. The examples that I have mentioned here will give you a basic understanding of how to do dot products in NumPy. Hope you have liked this tutorial. If you have any questions then you can contact us.
Numpy dot method Documentation
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.