Linear Algebra Essentials
Vectors, the geometry of dot products and cosine similarity, matrix multiplication as transformation, and why embeddings and neural network layers are linear algebra, with NumPy code for every idea.
In AI Foundations you met embeddings, representations, and a training loop that adjusts parameters. All of those are, underneath, linear algebra. An image is a grid of numbers. A sentence becomes a list of vectors. A neural network layer is a matrix multiplication. Attention in a transformer is a table of dot products. A GPU is, essentially, a machine for multiplying matrices very fast. You do not need to be a mathematician to work in AI, but a geometric intuition for vectors and matrices will make every later topic click. This lesson builds that intuition, with NumPy code you can run for each idea.
Vectors: lists of numbers with meaning
A vector is an ordered list of numbers. Geometrically, picture a 2D vector like [3, 4] as an arrow from the origin to the point (3, 4). In AI, vectors usually describe things:
- A house:
[floor_area, bedrooms, age]such as[120, 3, 15] - A pixel's colour:
[red, green, blue] - A word, sentence, image, or user: an embedding with hundreds or thousands of numbers
The number of entries is the vector's dimension. Humans struggle to picture more than three dimensions, but the arithmetic is identical in 3 or 3,000.
import numpy as np
a = np.array([3.0, 4.0])
b = np.array([1.0, 2.0])
print(a + b) # [4. 6.] element-wise addition: place arrows tip to tail
print(2 * a) # [6. 8.] scaling stretches the arrow
print(np.linalg.norm(a)) # 5.0 length: sqrt(3^2 + 4^2)
A note on notation: we write vectors in bold, like , and their entries with subscripts, . The norm (length) of a vector is the Pythagorean theorem extended to any number of dimensions:
For that is , matching the code. Dividing a vector by its norm gives a unit vector: same direction, length 1. Here . This "normalizing" step shows up constantly, for example before storing embeddings in a vector database.
The dot product: the most important operation in AI
The dot product multiplies matching entries and adds them up:
The symbol (capital sigma) just means "add up the following term for every ". A worked example: .
That single operation has two interpretations, and keeping both in mind is the key to understanding modern AI.
As a weighted sum. If describes a house (area, bedrooms, age) and are learned weights, then
is a score: each feature multiplied by how much it matters, then summed. A linear model is a dot product plus a bias, and every neuron in a network starts with one.
As a measure of alignment. Geometrically:
where is the angle between the arrows. Same direction (): large and positive. Perpendicular, also called orthogonal (): zero. Opposite (): negative. Another way to see it: equals the length of times the length of the projection of onto , the shadow casts along 's direction. So a dot product asks "how much of points along ?"
Cosine similarity versus dot product
Dividing out the lengths gives cosine similarity, which depends only on direction and lies between -1 and 1:
def cosine_similarity(u, v):
return np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v))
print(cosine_similarity(np.array([1, 0]), np.array([1, 0]))) # 1.0 same direction
print(cosine_similarity(np.array([1, 0]), np.array([0, 1]))) # 0.0 orthogonal
print(cosine_similarity(np.array([1, 0]), np.array([-1, 0]))) # -1.0 opposite
Why does the difference matter? Compare a query with two documents and . The dot products are 2.1 and 5.5, so "wins". Now divide by the lengths. For :
and the same calculation gives about 0.999 for : it points almost exactly where the query points, and d2 only wins because it is long. In embedding search, direction usually encodes meaning while length encodes things like frequency or document length, so cosine similarity is the common default. If embeddings are normalized to unit length, dot product and cosine become identical, which is why many systems normalize once and then use the cheaper dot product.
Embeddings: meaning as geometry
An embedding is a vector learned by a model so that items with similar meaning end up close together. Explore the map below: hover a word to see its nearest neighbours.
Here are hand-made 3D "embeddings" to build intuition. Real embeddings are learned and have hundreds or thousands of dimensions, and individual dimensions are rarely this interpretable, but the geometry works the same way.
# Toy dimensions: [royalty, animal, femininity]
emb = {
"king": np.array([0.9, 0.0, 0.1]),
"queen": np.array([0.9, 0.0, 0.9]),
"cat": np.array([0.0, 0.9, 0.5]),
"man": np.array([0.1, 0.0, 0.1]),
"woman": np.array([0.1, 0.0, 0.9]),
}
print(f"king vs queen: {cosine_similarity(emb['king'], emb['queen']):.2f}") # 0.78
print(f"king vs cat: {cosine_similarity(emb['king'], emb['cat']):.2f}") # 0.05
analogy = emb["king"] - emb["man"] + emb["woman"]
candidates = [w for w in emb if w not in ("king", "man", "woman")]
best = max(candidates, key=lambda w: cosine_similarity(analogy, emb[w]))
print("king - man + woman is closest to:", best) # queen
Vector arithmetic works because directions can encode relationships: if "male to female" is roughly a consistent direction, adding it moves "king" toward "queen". This is the basis of semantic search and retrieval-augmented generation: embed a question, embed your documents, and retrieve the documents with the highest cosine similarity.
Note: The famous word-analogy results are real but cherry-picked; many analogies fail, and evaluations usually exclude the input words from the answers, as our code does. Treat them as an intuition, not a law.
Matrices: grids of numbers and transformations
A matrix is a rectangular grid of numbers with shape (rows, columns). Two views are useful:
- A table of data. A dataset of 1,000 houses with 3 features is a
(1000, 3)matrix: one row per example. - A transformation. Multiplying a vector by a matrix produces a new vector, possibly in a different number of dimensions. A matrix is a function that moves space around: rotating, stretching, squashing, projecting.
The second view has a simple key: the columns of a matrix tell you where the basis vectors land. In 2D, the first column is where [1, 0] goes and the second is where [0, 1] goes; every other vector follows along, because the transformation is linear. For example, rotating by an angle sends to and to , so those become the columns:
theta = np.pi / 2
R = np.array([[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]]) # rotate 90 degrees
S = np.array([[2.0, 0.0],
[0.0, 0.5]]) # stretch x, squash y
v = np.array([1.0, 1.0])
print("R @ v :", np.round(R @ v, 3)) # [-1. 1.]
print("S @ (R @ v):", np.round(S @ (R @ v), 3)) # [-2. 0.5]
print("(S @ R) @ v:", np.round((S @ R) @ v, 3)) # same: S @ R is one combined transform
print("R @ S @ v :", np.round(R @ S @ v, 3)) # [-0.5 2. ] order matters
Two lessons hide in that output. First, multiplying matrices composes transformations: S @ R means "rotate, then stretch", packed into one matrix. Second, order matters: in general A @ B is not B @ A.
The matrix multiplication rule
Matrix multiplication A @ B (written in math) takes the dot product of each row of with each column of : the entry in row , column of the result is . A small worked example:
Shapes times give : the inner dimensions must match. Each of the output entries needs multiplications and about additions, so the product costs about floating-point operations (FLOPs). That is why model compute is counted in matrix-multiply FLOPs.
X = np.array([[120, 3, 15],
[ 80, 2, 40],
[200, 5, 5]], dtype=float) # 3 houses, 3 features
w = np.array([2.0, 10.0, -0.5]) # weights
b = 50.0
predictions = X @ w + b # one dot product per house, computed at once
print(predictions) # [312.5 210. 497.5]
One line computes predictions for every house. This vectorization, replacing Python loops with array operations, is cleaner and dramatically faster, and it maps directly onto GPU hardware.
A neural network layer is a matrix
A fully connected layer with 3 inputs and 4 outputs has a weight matrix of shape and a bias vector of length 4. It computes
where ReLU (rectified linear unit) is applied to each entry separately: negatives become 0, positives pass through. A tiny worked example with 2 inputs and 2 outputs:
The diagram traces one layer: a linear transformation (multiply and add bias) followed by a non-linear activation, producing a new representation that feeds the next layer. Each output number is the dot product of one row of with the input, so each row is a learned "pattern detector" and the output says how strongly the input aligns with each pattern.
rng = np.random.default_rng(0)
X = rng.normal(size=(32, 3)) # a batch of 32 inputs, one per row
W = rng.normal(size=(4, 3))
b = np.zeros(4)
H = np.maximum(0, X @ W.T + b) # ReLU(X W^T + b) for the whole batch at once
print(H.shape) # (32, 4)
Why the non-linearity? Because composing linear maps gives a linear map:
Without something like ReLU between them, a hundred layers would be no more expressive than one. With it, stacks of layers can approximate extremely complex functions.
Where you will see this again
- Attention. A transformer computes a query vector and a key vector for each token, then takes the dot product of every query with every key: the matrix (
Q @ K.Tin code). Large dot products mean "this token should pay attention to that one". It is the alignment interpretation, at scale. - Model size. A language model's parameter count is mostly the entries of its weight matrices. Its speed depends on how fast hardware multiplies them.
- Batching. Stacking inputs as rows of a matrix lets one multiplication serve many examples or many users at once, which is why batching is central to efficient inference.
Tip: When AI code breaks, the cause is very often a shape mismatch. Print
.shapeearly and often, and write expected shapes in comments.
A few more operations you will see constantly: the transpose A.T swaps rows and columns; the identity matrix np.eye(n) leaves vectors unchanged; and element-wise multiplication A * B is different from matrix multiplication A @ B.
Common pitfalls
- Confusing
*and@.*multiplies entry by entry (with broadcasting);@is matrix multiplication. Both may run without error and give very different results. - Ignoring vector length. Raw dot products reward long vectors. Normalize or use cosine similarity for similarity search.
- Assuming dimensions are interpretable. In learned embeddings, meaning is spread across many dimensions; directions, not single coordinates, carry concepts.
- Row versus column conventions. Math texts often write with column vectors; code often stores examples as rows and computes
X @ W.T(). Same idea, transposed.
Hands-on exercise
- Compute the dot product of
[2, -1, 3]and[4, 5, 1]by hand, then check withnp.dot. Compute the angle between them in degrees withnp.degrees(np.arccos(cos)). - Add
"dog"and"prince"to the toy embeddings with sensible vectors. Verify that"dog"is closer to"cat"than to"king", and that"prince"is closest to"king". - Build the 2D matrix that reflects vectors across the x-axis (hint: where do
[1, 0]and[0, 1]go?). Apply it twice and explain the result. - Create random matrices
Aof shape(5, 3)andBof shape(3, 2). Predict the shape ofA @ Bbefore computing it. Then tryB @ Aand read the error message. - Time a Python
forloop computing 100,000 dot products of length-3 vectors versus one(100000, 3) @ (3,)multiplication usingtime.perf_counter(). Expect the vectorized version to be tens to hundreds of times faster.
Expected outcome: you can move between the algebraic view (sums of products) and the geometric view (alignment, transformation) and predict shapes before running code.
Key takeaways
- Vectors represent things as lists of numbers; length and direction both carry information.
- The dot product is both a weighted sum and a measure of alignment (); it is everywhere in AI.
- Cosine similarity compares direction only; normalize embeddings and the dot product equals cosine.
- A matrix is a transformation whose columns show where basis vectors land; multiplying matrices composes transformations, and order matters.
- Layers are matrix multiplications plus non-linearities; without the non-linearity, depth collapses.
Next, we look inside matrices: which directions a transformation stretches the most, how the singular value decomposition breaks any matrix into simple pieces, and how that idea gives us PCA for data and LoRA for cheap fine-tuning of large models.
Further reading
- 3Blue1Brown, Essence of Linear Algebra (YouTube series): the best visual introduction to matrices as transformations.
- Gilbert Strang, MIT 18.06 Linear Algebra lectures on MIT OpenCourseWare.
- Deisenroth, Faisal, and Ong, Mathematics for Machine Learning (Cambridge University Press, 2020), free PDF at https://mml-book.github.io/
Save your progress and earn XP
Create a free account to take the quiz, track progress and unlock badges.