Numpy Dot Function

PythonPythonBeginner
Practice Now

Introduction

In this lab, we will explore the dot() function of the Numpy library, which is mainly used to calculate the dot product of two vectors. We will also see how this function can handle 2D arrays as matrices and perform matrix multiplication.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Understand the Syntax of numpy.dot()

The syntax required for using the dot() function is as follows:

numpy.dot(a, b, out=None)

Where:

  • a is the first parameter. If "a" is complex, then its complex conjugate is used for the calculation of the dot product.
  • b is the second parameter. If "b" is complex, then its complex conjugate is used for the calculation of the dot product.
  • out is the output argument. If it is not used, then it must have the exact kind that would be returned. Otherwise, it must be C-contiguous and its dtype must be the dtype that would be returned for dot(a, b).

Calculate the Dot Product of Scalars and 1D Arrays

In this step, we will use the dot() function to calculate the dot product of scalars and 1D arrays.

import numpy as np

## Calculate the dot product of scalar values
a = np.dot(8, 4)
print("The dot product of the above given scalar values is: ")
print(a)

## Calculate the dot product of two 1D arrays
vect_a = 4 + 3j
vect_b = 8 + 5j

dot_product = np.dot(vect_a, vect_b)
print("The dot product of two 1D arrays is: ")
print(dot_product)

Perform Matrix Multiplication with 2D Arrays

In this step, we will use the dot() function to perform matrix multiplication with 2D arrays.

import numpy as np

a = np.array([[50,100],[12,13]])
print("Matrix a is:")
print(a)

b = np.array([[10,20],[12,21]])
print("Matrix b is:")
print(b)

dot = np.dot(a, b)
print("The dot product of matrices a and b is:")
print(dot)

Error Handling

In this step, we will explore the ValueError that is raised when the last dimension of a is not the same size as the second-to-last dimension of b.

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8], [9, 10], [11, 12], [13, 14]])

## Error handling
error = np.dot(a, b)
print(error)

Summary

In this lab, we covered the dot() function of the Numpy library. We learned how to use this function with its syntax, and the values returned by the function were explained with the help of code examples. We also explored the error handling of the function.

Other Python Tutorials you may like