0
0
NumPydata~5 mins

np.dot() for dot product in NumPy

Choose your learning style9 modes available
Introduction

We use np.dot() to multiply arrays in a way that combines rows and columns. It helps us find relationships between data points.

To calculate the total sales by multiplying price and quantity arrays.
To find the angle between two vectors in physics or machine learning.
To combine features in data for predictions using linear algebra.
To compute weighted sums in neural networks or statistics.
Syntax
NumPy
np.dot(a, b)

a and b can be numbers, 1D or 2D arrays.

For 1D arrays, it calculates the sum of products (like a scalar product).

Examples
This multiplies corresponding elements and sums them: 1*4 + 2*5 + 3*6 = 32.
NumPy
import numpy as np

# Dot product of two 1D arrays
v1 = np.array([1, 2, 3])
v2 = np.array([4, 5, 6])
result = np.dot(v1, v2)
print(result)
This multiplies matrices: rows of m1 with columns of m2.
NumPy
import numpy as np

# Dot product of 2D arrays (matrices)
m1 = np.array([[1, 2], [3, 4]])
m2 = np.array([[5, 6], [7, 8]])
result = np.dot(m1, m2)
print(result)
Here, the 1D array acts like a row vector multiplied by the matrix.
NumPy
import numpy as np

# Dot product of 1D and 2D array
v = np.array([1, 2])
m = np.array([[3, 4], [5, 6]])
result = np.dot(v, m)
print(result)
Sample Program

This program calculates the dot product of two simple vectors. It multiplies each pair of elements and sums them up.

NumPy
import numpy as np

# Define two vectors
vector_a = np.array([2, 3, 4])
vector_b = np.array([1, 0, -1])

# Calculate dot product
dot_product = np.dot(vector_a, vector_b)

print(f"Dot product of {vector_a} and {vector_b} is {dot_product}")
OutputSuccess
Important Notes

If arrays have incompatible shapes, np.dot() will raise an error.

For 2D arrays, np.dot() performs matrix multiplication.

For higher dimensions, consider using np.matmul() or the @ operator.

Summary

np.dot() multiplies arrays to find sums of products.

It works for vectors (1D) and matrices (2D).

Useful for combining data, physics calculations, and machine learning.