Beginnerโฑ 22 minโšก 80 XP๐Ÿงฉ 5-question quiz

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 a\mathbf{a}, and their entries with subscripts, a1,a2,โ€ฆ,ana_1, a_2, \dots, a_n. The norm (length) of a vector is the Pythagorean theorem extended to any number of dimensions:

โˆฅaโˆฅ=a12+a22+โ‹ฏ+an2\lVert \mathbf{a} \rVert = \sqrt{a_1^2 + a_2^2 + \cdots + a_n^2}

For a=[3,4]\mathbf{a} = [3, 4] that is 9+16=5\sqrt{9 + 16} = 5, matching the code. Dividing a vector by its norm gives a unit vector: same direction, length 1. Here [3,4]/5=[0.6,0.8][3, 4] / 5 = [0.6, 0.8]. 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:

aโ‹…b=a1b1+a2b2+โ‹ฏ+anbn=โˆ‘i=1naibi\mathbf{a} \cdot \mathbf{b} = a_1 b_1 + a_2 b_2 + \cdots + a_n b_n = \sum_{i=1}^{n} a_i b_i

The symbol โˆ‘\sum (capital sigma) just means "add up the following term for every ii". A worked example: [1,2,3]โ‹…[4,0,โˆ’1]=1โ‹…4+2โ‹…0+3โ‹…(โˆ’1)=4+0โˆ’3=1[1, 2, 3] \cdot [4, 0, -1] = 1 \cdot 4 + 2 \cdot 0 + 3 \cdot (-1) = 4 + 0 - 3 = 1.

That single operation has two interpretations, and keeping both in mind is the key to understanding modern AI.

As a weighted sum. If x=[120,3,15]\mathbf{x} = [120, 3, 15] describes a house (area, bedrooms, age) and w=[2.0,10.0,โˆ’0.5]\mathbf{w} = [2.0, 10.0, -0.5] are learned weights, then

wโ‹…x=2.0โ‹…120+10.0โ‹…3+(โˆ’0.5)โ‹…15=240+30โˆ’7.5=262.5\mathbf{w} \cdot \mathbf{x} = 2.0 \cdot 120 + 10.0 \cdot 3 + (-0.5) \cdot 15 = 240 + 30 - 7.5 = 262.5

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:

aโ‹…b=โˆฅaโˆฅโ€‰โˆฅbโˆฅcosโกฮธ\mathbf{a} \cdot \mathbf{b} = \lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert \cos\theta

where ฮธ\theta is the angle between the arrows. Same direction (cosโก0โˆ˜=1\cos 0^\circ = 1): large and positive. Perpendicular, also called orthogonal (cosโก90โˆ˜=0\cos 90^\circ = 0): zero. Opposite (cosโก180โˆ˜=โˆ’1\cos 180^\circ = -1): negative. Another way to see it: aโ‹…b\mathbf{a} \cdot \mathbf{b} equals the length of b\mathbf{b} times the length of the projection of a\mathbf{a} onto b\mathbf{b}, the shadow a\mathbf{a} casts along b\mathbf{b}'s direction. So a dot product asks "how much of a\mathbf{a} points along b\mathbf{b}?"

Cosine similarity versus dot product

Dividing out the lengths gives cosine similarity, which depends only on direction and lies between -1 and 1:

cosโก(a,b)=aโ‹…bโˆฅaโˆฅโ€‰โˆฅbโˆฅ\cos(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a} \cdot \mathbf{b}}{\lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert}
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 q=[1,1]\mathbf{q} = [1, 1] with two documents d1=[1,1.1]\mathbf{d}_1 = [1, 1.1] and d2=[5,0.5]\mathbf{d}_2 = [5, 0.5]. The dot products are 2.1 and 5.5, so d2\mathbf{d}_2 "wins". Now divide by the lengths. For d2\mathbf{d}_2:

cosโก(q,d2)=5.52โ‹…25.25โ‰ˆ5.51.414ร—5.025โ‰ˆ0.774\cos(\mathbf{q}, \mathbf{d}_2) = \frac{5.5}{\sqrt{2} \cdot \sqrt{25.25}} \approx \frac{5.5}{1.414 \times 5.025} \approx 0.774

and the same calculation gives about 0.999 for d1\mathbf{d}_1: 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:

  1. A table of data. A dataset of 1,000 houses with 3 features is a (1000, 3) matrix: one row per example.
  2. 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 ฮธ\theta sends [1,0][1, 0] to [cosโกฮธ,sinโกฮธ][\cos\theta, \sin\theta] and [0,1][0, 1] to [โˆ’sinโกฮธ,cosโกฮธ][-\sin\theta, \cos\theta], so those become the columns:

Rฮธ=[cosโกฮธโˆ’sinโกฮธsinโกฮธcosโกฮธ],R90โˆ˜[11]=[0โˆ’110][11]=[โˆ’11]R_\theta = \begin{bmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{bmatrix}, \qquad R_{90^\circ} \begin{bmatrix} 1 \\ 1 \end{bmatrix} = \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} \begin{bmatrix} 1 \\ 1 \end{bmatrix} = \begin{bmatrix} -1 \\ 1 \end{bmatrix}
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 ABAB in math) takes the dot product of each row of AA with each column of BB: the entry in row ii, column jj of the result is (AB)ij=โˆ‘kAikBkj(AB)_{ij} = \sum_k A_{ik} B_{kj}. A small worked example:

[1234][5678]=[1โ‹…5+2โ‹…71โ‹…6+2โ‹…83โ‹…5+4โ‹…73โ‹…6+4โ‹…8]=[19224350]\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix} \begin{bmatrix} 5 & 6 \\ 7 & 8 \end{bmatrix} = \begin{bmatrix} 1 \cdot 5 + 2 \cdot 7 & 1 \cdot 6 + 2 \cdot 8 \\ 3 \cdot 5 + 4 \cdot 7 & 3 \cdot 6 + 4 \cdot 8 \end{bmatrix} = \begin{bmatrix} 19 & 22 \\ 43 & 50 \end{bmatrix}

Shapes (mร—n)(m \times n) times (nร—p)(n \times p) give (mร—p)(m \times p): the inner dimensions must match. Each of the mโ‹…pm \cdot p output entries needs nn multiplications and about nn additions, so the product costs about 2mnp2mnp 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 WW of shape (4ร—3)(4 \times 3) and a bias vector b\mathbf{b} of length 4. It computes

h=ReLU(Wx+b),ReLU(z)=maxโก(0,z)\mathbf{h} = \mathrm{ReLU}(W\mathbf{x} + \mathbf{b}), \qquad \mathrm{ReLU}(z) = \max(0, z)

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:

W=[1โˆ’10.52],x=[23],b=[0โˆ’1]โ€…โ€Šโ‡’โ€…โ€ŠWx+b=[2โˆ’3+01+6โˆ’1]=[โˆ’16]โ€…โ€Šโ‡’โ€…โ€Šh=[06]W = \begin{bmatrix} 1 & -1 \\ 0.5 & 2 \end{bmatrix}, \quad \mathbf{x} = \begin{bmatrix} 2 \\ 3 \end{bmatrix}, \quad \mathbf{b} = \begin{bmatrix} 0 \\ -1 \end{bmatrix} \;\Rightarrow\; W\mathbf{x} + \mathbf{b} = \begin{bmatrix} 2 - 3 + 0 \\ 1 + 6 - 1 \end{bmatrix} = \begin{bmatrix} -1 \\ 6 \end{bmatrix} \;\Rightarrow\; \mathbf{h} = \begin{bmatrix} 0 \\ 6 \end{bmatrix}
Rendering diagramโ€ฆ

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 WW 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:

W2(W1x)=(W2W1)โ€‰x=Wโ€ฒxW_2 (W_1 \mathbf{x}) = (W_2 W_1)\,\mathbf{x} = W' \mathbf{x}

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 QKโŠคQK^\top (Q @ K.T in 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 .shape early 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 WxW\mathbf{x} with column vectors; code often stores examples as rows and computes X @ W.T (XWโŠคXW^\top). Same idea, transposed.

Hands-on exercise

  1. Compute the dot product of [2, -1, 3] and [4, 5, 1] by hand, then check with np.dot. Compute the angle between them in degrees with np.degrees(np.arccos(cos)).
  2. 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".
  3. 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.
  4. Create random matrices A of shape (5, 3) and B of shape (3, 2). Predict the shape of A @ B before computing it. Then try B @ A and read the error message.
  5. Time a Python for loop computing 100,000 dot products of length-3 vectors versus one (100000, 3) @ (3,) multiplication using time.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 (aโ‹…b=โˆฅaโˆฅโˆฅbโˆฅcosโกฮธ\mathbf{a} \cdot \mathbf{b} = \lVert \mathbf{a} \rVert \lVert \mathbf{b} \rVert \cos\theta); 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.