NumPy – Dot Product
The dot product is one of the most important operations in linear algebra and is widely used in:
- Machine learning
- Deep learning
- Data science
- Physics and engineering
In Python, NumPy provides an efficient way to compute the dot product using np.dot().
What is Dot Product?
The dot product is a mathematical operation that takes two vectors (or matrices) and returns a single value or a matrix.
It is used to measure:
How much two vectors point in the same direction.
Dot Product Formula
For two vectors:
A = [a1, a2, a3]
B = [b1, b2, b3]
The dot product is:
A · B = a1b1 + a2b2 + a3b3
Import NumPy
import numpy as np
1. Dot Product of Vectors
import numpy as np
A = np.array([1, 2, 3])
B = np.array([4, 5, 6])
result = np.dot(A, B)
print(result)
Output:
32
Explanation:
1×4 + 2×5 + 3×6 = 4 + 10 + 18 = 32
2. Dot Product of Matrices
import numpy as np
A = np.array([[1, 2],
[3, 4]])
B = np.array([[5, 6],
[7, 8]])
result = np.dot(A, B)
print(result)
Output:
[[19 22]
[43 50]]
3. Using @ Operator (Modern Way)
import numpy as np
A = np.array([[1, 2],
[3, 4]])
B = np.array([[5, 6],
[7, 8]])
result = A @ B
print(result)
4. Dot Product vs Element-wise Multiplication
❌ Element-wise multiplication:
A * B
✅ Dot product:
np.dot(A, B)
Difference Table
| Operation | Symbol | Meaning |
|---|---|---|
| Element-wise | * | Multiply each element |
| Dot product | np.dot() or @ | Linear algebra multiplication |
5. Dot Product with Higher Dimensions
import numpy as np
A = np.array([[1, 2, 3],
[4, 5, 6]])
B = np.array([[7, 8],
[9, 10],
[11, 12]])
result = np.dot(A, B)
print(result)
Output:
[[ 58 64]
[139 154]]
6. Geometric Meaning of Dot Product
The dot product also relates to the angle between two vectors:
- If result > 0 → same direction
- If result = 0 → perpendicular
- If result < 0 → opposite direction
Real-World Applications
Dot product is used in:
1. Machine Learning
- Neural network computations
- Weight multiplication
2. Computer Graphics
- Lighting calculations
- 3D transformations
3. Data Science
- Similarity measurement
- Feature analysis
4. Physics
- Work = Force · Distance
- Vector projections
Why Use NumPy for Dot Product?
- Fast C-based computation
- Easy syntax
- Handles large datasets
- Supports multi-dimensional arrays
- Essential for AI/ML workflows
Common Error
❌ Shape mismatch error:
ValueError: shapes not aligned
Solution:
Ensure:
- Columns of first matrix = Rows of second matrix
Summary
The dot product in NumPy is a fundamental operation used to multiply vectors and matrices efficiently.
It is widely used in AI, ML, and scientific computing built with Python.
Conclusion
Understanding the dot product is essential for mastering linear algebra and machine learning. With NumPy, you can perform these operations easily and efficiently using np.dot() or the @ operator.


0 Comments