Topic 1 of 5 · 4 min read
Vectors, matrices and their shapes
Goal: Predict the output shape of a matrix product and compute a dot product to compare two vectors.
A vector is a list of numbers that places one thing as a point in space, and a matrix is a machine that moves points to new places; almost every model is a stack of such machines. Most day-to-day bugs here are shape bugs, not hard math.
Check yourself · 1 of 3
What is the dot product of a = [2, 3] and b = [4, 1]?
Why it matters
A sentence embedding from an API is a vector of, say, 768 numbers. A neural network layer is a matrix multiplied by a vector. Retrieval, search and attention all reduce to the same operation: compare vectors with a dot product. If you can read shapes and a dot product, you can read most ML code.
How to do it
- Dot product. Multiply two vectors position by position, then add. For
a = [3, 4]andb = [4, 3]: 34 + 43 = 24. A large dot product means the vectors point the same way. - Cosine similarity. Divide the dot product by both lengths so size does not count. Here each vector has length 5, so 24 / (5*5) = 0.96, nearly the same direction. Vectors at right angles score 0, opposite ones score -1.
- Matrix times vector. Each output number is one row of the matrix dotted with the input. A layer with 128 outputs and 784 inputs holds a 128 by 784 matrix.
- Shape rule. The inner sizes must match and the outer sizes survive: (m, k) @ (k, n) gives (m, n). A batch of 32 inputs with 784 features, shape (32, 784), times weights (784, 128) gives (32, 128): one 128-number result per example.
Before and after
import numpy as np
X = np.zeros((32, 784)) # batch of 32 images
W = np.zeros((128, 784)) # weights stored the wrong way round
out = X @ W # ValueError: 784 does not match 128
The fix is to transpose or store the weights as (784, 128):
out = X @ W.T # (32, 784) @ (784, 128) -> (32, 128)
What goes wrong
- Silent broadcasting. NumPy and PyTorch stretch a (32, 1) array against a (32,) array into a (32, 32) one. The code runs, the loss is wrong. Print shapes after every step.
- Swapped axes. (batch, features) versus (features, batch). Fix the convention once and write it in comments.
- Comparing unnormalised vectors. A long vector wins a dot-product search because it is long, not because it is similar. Normalise first or use cosine similarity.
Examples
Shapes through one layer
x = np.random.randn(32, 784) # 32 examples, 784 features
W = np.random.randn(784, 128)
b = np.random.randn(128)
h = x @ W + b # (32, 128); b is added to every row
print(h.shape) # (32, 128)
The bias has shape (128,) and is broadcast across the 32 rows, which is the intended use of broadcasting.
Dot product versus cosine
a = np.array([3.0, 4.0]); b = np.array([6.0, 8.0])
print(a @ b) # 50.0
print(a @ b / (np.linalg.norm(a) * np.linalg.norm(b))) # 1.0
The vectors point the same way, so cosine is exactly 1, but the raw dot product only reflects that b is twice as long.
Key points
- A dot product multiplies two vectors position by position and sums the results; larger means more aligned.
- Cosine similarity divides the dot product by both vector lengths, so it measures direction only and lies between -1 and 1.
- A matrix times a vector gives one dot product per matrix row, which is what one network layer computes before its activation.
- For a matrix product (m, k) @ (k, n), the inner k must match and the result has shape (m, n).
- Broadcasting can hide shape bugs by running without error, so check shapes after each operation.
Common mistakes
- Multiplying with * when you mean @, which multiplies element by element instead of doing a matrix product.
- Assuming that code that runs has the right shapes; broadcasting accepts many wrong ones.
- Ranking search results by raw dot product on vectors that were never normalised.
- Mixing up the (batch, features) and (features, batch) conventions between libraries.
Check yourself · 2 of 3
A batch X has shape (64, 300) and a weight matrix W has shape (300, 10). What is the shape of X @ W?
Check yourself · 3 of 3
Two embeddings have cosine similarity 0.02. What does that tell you?
Practice items, not counted towards your mastery.
Start here
- Mathematics for Machine Learning (Deisenroth, Faisal, Ong) (opens in a new tab)BookFree
The free book that covers linear algebra, calculus and probability in the order machine learning needs them.
- 3Blue1Brown: Essence of linear algebra (opens in a new tab)VideoFree
Vectors, dot products and matrix multiplication drawn as geometry, the fastest way to build intuition.
- 3Blue1Brown: Essence of calculus (opens in a new tab)VideoFree
Derivatives and the chain rule as pictures of change, without heavy algebra.
More for this topic
- NumPy: the absolute basics for beginners (opens in a new tab)DocsFree
Array shapes, broadcasting and matrix products in the library every ML stack uses.