Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In linear algebra, machine learning (neural networks, linear regression), and 3D computer graphics, matrix multiplication is the foundational building block.
One of the most frequent points of confusion for newcomers to NumPy is distinguishing between element-wise multiplication (*) and formal linear algebraic matrix multiplication (@ or matmul()).
@ or np.matmul): Computes row-by-column inner dot products according to formal linear algebra rules:$$C_{ij} = \sum_{k=1}^K A_{ik} B_{kj}$$
For matrices $A$ of shape $(M, K)$ and $B$ of shape $(K, N)$, the inner dimensions ($K$) must match exactly, and the resulting matrix $C$ has shape $(M, N)$.
np.dot() and np.matmul()NumPy provides both np.dot() and np.matmul() (or the @ operator). For 2D matrices, they produce identical results. However, their behaviors diverge on 1D vectors and higher-order tensors:
For 1D vectors, both compute the standard scalar inner product:
This is where matmul() / @ shines and is the standard for deep learning:
np.matmul() treats trailing 2 dimensions as matrices and broadcasts over leading batch dimensions.np.dot() computes a sum-product over the last axis of $A$ and second-to-last axis of $B$, which is not batch matrix multiplication!When multiplying a 1D vector $v$ with a 2D matrix $M$:
v @ M), NumPy temporarily promotes $v$ to a row matrix $(1, K)$, performs multiplication, and squeezes the output back to a 1D vector.M @ v), NumPy promotes $v$ to a column matrix $(K, 1)$, performs multiplication, and squeezes back:np.matmul and np.dot on 3D tensors?a = np.array([1, 2]) and b = np.array([3, 4]), what is a * b?A @ B raise a ValueError?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.