Matrix multiplication
Quick answer
Matrix multiplication combines rows of the left matrix with columns of the right matrix. If A has shape (m, n) and B has shape (n, p), their product has shape (m, p). The shared inner dimension must match. Each output entry is a dot product. For a feature matrix X with m samples and n features, a weight vector w of length n gives m predictions using Xw; adding a scalar intercept shifts every prediction.
Predict a batch by hand and in Python
For three parcels, the first row [2, 1] produces 2 × 3 + 1 × 2 = 8 before adding the intercept. A list comprehension collects one result per sample. The fixture has two features in every row.
X = [[2, 1], [5, 3], [4, 2]]w = [3, 2]b = 4assert all(len(row) == len(w) for row in X)predictions = [sum(x * weight for x, weight in zip(row, w)) + b for row in X]print(predictions)Expected output:
[12, 25, 20]Three sample rows produce three durations, in minutes. These weights are supplied, not learned from this fixture.
Matrix product versus elementwise product
NumPy local lab: @ computes the matrix product for two 2-D arrays; * multiplies corresponding elements for arrays of the same shape. Matrix multiplication is generally not commutative. The second example catches the dimension error and prints a stable message instead of a version-dependent traceback.
import numpy as npA = np.array([[1, 2], [3, 4]])B = np.array([[2, 0], [1, 3]])print((A @ B).tolist())print((A * B).tolist())print((B @ A).tolist())try: A @ np.array([1, 2, 3])except ValueError: print("incompatible dimensions")Expected output:
[[4, 6], [10, 12]][[2, 0], [3, 12]][[2, 4], [10, 14]]incompatible dimensionsThe top-left entry of A @ B is 1 × 2 + 2 × 1 = 4. The same entry of A * B is 1 × 2 = 2. A 2-by-2 matrix cannot multiply a length-three vector.
Common mistakes
Transposing a matrix merely to make a multiplication run can change the intended operation. Decide which axis contains features and match the weights to that axis. NumPy broadcasting may make elementwise operations legal even when the matrix multiplication you intended is not.
Practice and next steps
Predict the shape of (4, 3) @ (3, 2), then compute the first entry for a row [1, 0, 2] and a column [3, 4, 5]. Next, reverse the question: can we recover weights from outputs?
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Matrix multiplication — knowledge check
Apply linear algebra to small numerical fixtures.
What shape results from (5,2) @ (2,4)?
Which pair cannot be multiplied in the stated order?
A row [2,3] has weights [4,1] and intercept 2. What is the prediction?
For same-shaped 2-D NumPy arrays, what does * compute?
Why not automatically transpose an incompatible feature matrix?