Guide 1 · Mathematics of Artificial Intelligence
Unit 1: Linear algebra
1-1 Vectors: Data as numbers
A model does not read a word or see a picture. Everything you feed into it becomes a list of numbers we call a vector, and every group of vectors becomes a table we call a matrix.
What matters in a vector is its direction. When two vectors point in roughly the same direction, the two things they represent are close in meaning. We measure this closeness with cosine similarity: when the value gets close to 1, the meanings are close, and when it gets close to 0, there is no connection.

Try it
We have represented three cards using three numbers each. The first and second cards talk about the same topic, while the third talks about something else.
import numpy as np
card_a = np.array([0.9, 0.1, 0.3])
card_b = np.array([0.8, 0.2, 0.4])
card_c = np.array([0.1, 0.9, 0.2])
def cosine(u, v):
return u @ v / (np.linalg.norm(u) * np.linalg.norm(v))
print(round(cosine(card_a, card_b), 3)) # 0.984
print(round(cosine(card_a, card_c), 3)) # 0.271The result is 0.984 between the first and the second, and 0.271 between the first and the third. That is how a search engine finds the text closest to your question.
Where you meet it
Embeddings in language models are vectors made up of hundreds or thousands of numbers, and semantic search rests entirely on this measure. Every layer in a neural network multiplies a matrix by a vector.
Exercises
- Calculate by hand the cosine similarity between (1,0) and (1,1).
- Multiply card_a by 2 and recalculate. Does its similarity with card_b change?
Solutions
- 0.707, which is the cosine of 45 degrees.
- It does not change, because similarity measures direction rather than length.
1-2 Matrices: A machine that transforms vectors
A matrix is a table of numbers, though it is more useful to see it as a machine: you feed a vector into it and it outputs another vector. When you multiply a matrix by a vector, you multiply each row in the matrix by the vector and add the results up, giving one number per row.
What a matrix does to a single vector, it does to the entire space: it stretches it, rotates it, or tilts it. To see what a matrix does, look at where it sends the vectors (1,0) and (0,1): its first column sets the new position for the first, and its second column sets the new position for the second.

When you multiply two matrices, you apply two transformations one after the other. The order changes the outcome: rotating and then stretching gives a different result from stretching and then rotating. As for the determinant, it tells you by what factor the matrix multiplies areas. If it equals zero, the matrix has squashed the space down into a line, losing information that cannot be recovered, which is why it has no inverse.
Try it
Matrix A stretches and tilts, while matrix R rotates by a quarter turn. We apply both to the vector (1,1) and then swap their order.
import numpy as np
A = np.array([[2.0, 1.0],
[0.0, 1.0]])
R = np.array([[0.0, -1.0],
[1.0, 0.0]])
x = np.array([1.0, 1.0])
print(A @ x) # [3. 1.]
print(R @ A @ x) # [-1. 3.] A first, then R
print(A @ R @ x) # [-1. 1.] R first, then A
print(round(np.linalg.det(A), 2)) # 2.0Matrix A moved the vector (1,1) to (3,1). When we applied A and then R, we got (-1,3), and when we applied R and then A, we got (-1,1). Swapping the order changed the answer. The determinant equals 2, meaning every area is doubled.
Where you meet it
Every layer in a neural network multiplies a weight matrix by a vector and then adds an offset. A deep network consists of a chain of such transformations separated by non-linear functions; without those functions, the entire chain would collapse into a single matrix.
Exercises
- Multiply by hand the matrix [[1,2],[3,4]] by the vector (1,1).
- What matrix doubles the length of every vector without changing its direction?
- A matrix has a second column that is double its first column. What is its determinant and why?
Solutions
- (3,7).
- [[2,0],[0,2]].
- Zero, because the two columns lie on the same line, so the area is squashed flat.
1-3 Least squares: The closest line to the points
You have a set of points and you want a line that passes through them. Once you have more than two points, a single line will rarely pass through all of them. So we change the question: which line gets closest to all of them?
We measure closeness like this: we take the vertical distance between each point and the line, which we call the residual, square it, and add them all up. The best line makes this sum as small as possible. We square the residuals so that positive and negative values do not cancel each other out, and so that large errors cost us more.

We write the problem using matrices: we put the inputs into a matrix X, the weights we are looking for into a vector w, and the target values we want into y. We want Xw to get as close to y as possible. This problem has a direct solution called the normal equation. Geometrically, this means the residual sits at right angles to the columns of X, leaving nothing in the data that the line can still capture.
Try it
We have five students, and we know how many hours each studied and what score they achieved. We look for the best line, and then predict the score for someone who studies for six hours.
import numpy as np
hours = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
score = np.array([52.0, 57.0, 66.0, 70.0, 79.0])
X = np.column_stack([np.ones_like(hours), hours])
w, *_ = np.linalg.lstsq(X, score, rcond=None)
print(np.round(w, 1)) # [44.7 6.7]
print(round(float(w[0] + w[1] * 6), 1)) # 84.9
residual = score - X @ w
print(np.round(X.T @ residual, 6)) # [0. 0.]The line is: score = 44.7 + 6.7 × hours. Each hour of study corresponds to roughly 6.7 marks, and for someone who studies six hours we predict 84.9. The final line prints two zeros: the residual is indeed at right angles to the columns of X, just as we said.
Where you meet it
Linear regression is this exact problem, and it is the very first model you learn in machine learning. When the data grows large, we do not solve the equation directly; instead, we reach the very same weights through gradient descent.
Exercises
- Change the last student’s score from 79 to 95 and solve again. What happened to the slope and why?
- Why did we add a column of ones to X?
- Does the line prove that studying causes the higher score?
Solutions
- The slope rose from 6.7 to 9.9. A single distant point pulled the line towards itself, because squaring magnifies large errors.
- So the line can learn where to cross the vertical axis. Without it, we force the line to pass through zero.
- No. The line shows that the two rise together, not which one causes the other.
1-4 Eigenvalues: The axes that do not rotate
When you multiply a matrix by a vector, its direction usually changes. Yet almost every matrix has special vectors whose direction it does not change, only stretching or shrinking them. We call these eigenvectors, and we call the amount of stretch the eigenvalue. We write the relationship like this: Av = λv.

Why do they matter to us? Because they reveal the natural axes of the transformation. Along those axes, the matrix becomes nothing more than multiplication by a number. If the matrix is symmetric, its eigenvectors sit at right angles to one another and its eigenvalues are real numbers, which is the case for the covariance matrix we will meet in the next lesson.
Eigenvalues tell you what happens when you repeat the transformation: any direction with a value greater than 1 grows larger each time, while any direction with a value below 1 fades away.
Try it
We take a small symmetric matrix. We ask for its eigenvalues and eigenvectors, and then check the equation for ourselves.
import numpy as np
np.set_printoptions(precision=3, suppress=True)
S = np.array([[2.0, 1.0],
[1.0, 2.0]])
values, vectors = np.linalg.eigh(S)
print(values) # [1. 3.]
print(vectors) # [[-0.707 0.707]
# [ 0.707 0.707]]
v = vectors[:, 1]
print(S @ v, values[1] * v) # [2.121 2.121] [2.121 2.121]The two eigenvalues are 1 and 3. The first eigenvector points along (-1,1) and stays as it is, while the second points along (1,1) and stretches threefold. The last line prints the same vector twice: Av truly does equal λv.
Where you meet it
Principal component analysis is built on them. The PageRank algorithm that Google used to rank web pages looks for an eigenvector. And in deep networks, eigenvalues help us understand why gradients explode or vanish as layers repeat.
Exercises
- What are the eigenvalues of the matrix [[2,0],[0,5]], and what are its eigenvectors?
- A matrix has one eigenvalue equal to zero. What do you know about its determinant?
- In the lesson’s example, work out the sum and the product of the two eigenvalues, and compare them with the sum of the matrix’s diagonal and its determinant.
Solutions
- 2 and 5, and its eigenvectors are (1,0) and (0,1).
- Its determinant equals zero, because the determinant is the product of the eigenvalues.
- The sum is 4, which equals the sum of the diagonal, and the product is 3, which equals the determinant. This holds true for every square matrix.
1-5 Singular value decomposition and principal components
Eigenvectors belong to square matrices. Data, however, rarely arrives square: it might have a thousand rows and twenty columns, for example. Singular value decomposition, or SVD, works on any matrix, breaking it down into three steps: we rotate it, stretch it along the axes, and rotate it once more. We write it like this: A = UΣVᵀ.
We call the numbers along the diagonal of Σ singular values, and they are ordered from largest to smallest. Each one tells you how much of the data its axis carries. If you keep the large values and drop the small ones, you get a smaller version of the data that loses almost nothing.
That is principal component analysis, or PCA: we subtract the mean from each column and then apply SVD. The rows of Vᵀ give the new axes, and the square of each singular value sets its axis’s share of the variance.

Try it
We take two hundred points, each with two numbers, where the second number roughly follows the first. We ask: how many axes do we actually need?
import numpy as np
np.set_printoptions(precision=3, suppress=True)
rng = np.random.default_rng(0)
t = rng.normal(size=200)
data = np.column_stack([t, 0.5 * t + 0.2 * rng.normal(size=200)])
data = data - data.mean(axis=0)
U, s, Vt = np.linalg.svd(data, full_matrices=False)
print(Vt[0]) # [-0.893 -0.45 ]
print(s**2 / np.sum(s**2)) # [0.972 0.028]
one_number = data @ Vt[0]
rebuilt = np.outer(one_number, Vt[0])
print(round(float(np.mean((data - rebuilt) ** 2)), 4)) # 0.0168The first axis points roughly along (0.89, 0.45) and carries 97% of the variance, leaving only 3% to the second. The minus sign in the output changes nothing, since an axis is a line with two ends. When we compressed each point into a single number and reconstructed it, the mean squared error came out at just 0.017.
Where you meet it
We compress embeddings this way to plot or store them. And LoRA, which we use to fine-tune large language models, rests on a closely related idea: a low-rank matrix is enough to make the adjustment the model needs.
Exercises
- Change the noise from 0.2 to 1.0 and run the code again. What happened to the first axis’s share?
- Why do we subtract the mean before applying PCA?
- You have embeddings of 768 numbers, and you find that the first 50 axes carry 90% of the variance. What do you gain and what do you lose if you keep only those?
Solutions
- Its share dropped from 97% to roughly 70%. The more noise there is, the weaker the relationship between the two numbers becomes, and the more we need both axes.
- Because PCA looks for the direction of spread around the centre of the data. If we do not subtract the mean, the first axis points towards the position of the centre itself.
- You gain smaller storage size and faster search, and you lose 10% of the variance, which may hold fine details. Test it on your task before you decide.
Tip: use ← → to move between sections.

