A gentle tour of vectors: arrows, lists, length and the dot product
Before this lesson: lesson 02 (the notation , indices and ) and lesson 03 (NumPy arrays). From school you need the theorem of Pythagoras and the cosine of an angle. Time: about 55 minutes, plus the notebook.
Why this matters #
- Data are vectors. A data set with features stores each sample as a vector . An grey image is a vector in . A language model stores each word piece (token) as an embedding, a vector with hundreds or thousands of entries (768 in BERT-base).
- Models are dot products. A linear model, and every neuron of a neural network, computes before its activation function. In a transformer, the attention score of a query and a key is the dot product , scaled by .
- Similarity is geometry. -nearest neighbours uses the distance . Retrieval for chatbots (RAG), recommendation and face recognition compare embeddings with cosine similarity.
- Size is a norm. Weight decay and ridge regression add to the loss, so they keep the weights short.
This lesson is a first look. The Linear Algebra track starts where it ends.
1. Predict first #
2. The picture #
Two views of one vector #
The vector is a list of two numbers. Draw it as an arrow: start at the origin, go 3 to the right and 1 up. The numbers are the entries (or components) and .
The two views help in different ways. The arrow gives intuition in 2-D and 3-D. The list works in any number of dimensions. A house with area 120 m², 3 rooms and age 15 years is the vector . An image is a list of 64 grey values, so it is a vector in . We cannot draw . But every operation in this lesson is defined by the entries, so it works for any . We draw the 2-D case only as a guide.
Adding, subtracting and scaling #
- Addition is entry by entry: . As arrows: put the tail of at the tip of ("tip to tail"). The sum goes from the origin to the new tip. It is the diagonal of the parallelogram with sides and .
- Scalar multiplication multiplies every entry by one number (a scalar): . The arrow gets 2 times longer. A negative flips the arrow to the opposite direction.
- Subtraction is . As arrows, goes from the tip of to the tip of , because .
Drag the tips of (blue) and (orange). The violet arrow is the result, and the panel writes it entry by entry. Switch to : the violet arrow now runs from the tip of to the tip of (its dashed copy starts at the origin). In , move the slider below 0 and watch the arrow flip.
A sum of scaled vectors, such as , is a linear combination of and . Linear combinations are the main object of Linear Algebra lesson 1.
Because the operations work entry by entry, they work on data too. Mixing two images, , is one scaling of each image and one addition:
Move the slider from 0 to 1. The mix fades from
image to image . Below the images, is written as
64 numbers, one row of the image per line. Each pixel is one entry, so each entry of the mix is the same mix of two numbers.
The images are real samples from scikit-learn's load_digits (grey values 0 to 16).
Length and distance #
The arrow is the long side (hypotenuse) of a right triangle with the sides 3 and 4. By Pythagoras, its length is . We write the length of as (the norm of ).
In 3-D, use Pythagoras twice. For , the shadow of on the floor is , with length . The vertical part has length 2, and it is at a right angle to the floor. So . The same pattern continues in any dimension: square the entries, add them, take the square root.
The distance between two points and is the length of the arrow between them, . For and : , so the distance is 5.
The dot product as a shadow #
The dot product of and multiplies the entries pair by pair and adds the products: . For and : .
There is a second way to get the same number. Let be the angle between the two arrows. Drop straight down (at a right angle) onto the line of . The result is the shadow, or projection, of on . Its signed length is . Then
In words: is the length of times the signed length of the shadow of .
Drag the tips of and and compare the two readouts: the sum of products and are always equal. The thick segment is the shadow of on the line of : aqua when , magenta when . Press right angle: the shadow disappears and the dot product is 0.
So the sign of the dot product tells you the type of angle:
| angle | the two arrows | |
|---|---|---|
| (acute) | point roughly the same way | |
| (right) | are orthogonal (perpendicular) | |
| (obtuse) | point roughly opposite ways |
The table assumes that and are not the zero vector. For the zero vector the angle is not defined.
What is the length of , and what is the distance between and ?
. The distance is the length of the difference: , so it is also 5. Adding the entries () is not a length, and is the squared length: do not forget the square root.
and . What is , and what kind of angle do and make?
, so the angle is acute. With and , , so . A common slip is to forget the minus sign of and get .
3. Definitions and main results #
Vectors and their operations #
A vector is an ordered list of real numbers . We write it as a column, and (the transpose) is the same numbers as a row:
In running text we write ; it still means a column. The zero vector has all entries 0. For and a scalar :
Both operations work entry by entry, so they follow the rules of ordinary numbers: , , , and . Only vectors of the same size can be added.
Norm, unit vector, distance #
Definition. The norm (Euclidean length) of is
Other norms exist (the Linear Algebra lesson on norms compares them). In this track, always means this one, also written . Do not confuse it with , the absolute value of one number.
Two properties follow directly from the definition.
- , and only for . A sum of squares is zero only if every square is zero.
- . Proof: , because (for example ).
A unit vector has norm 1. For , the vector is a unit vector in the direction of : by property 2, . For example . Dividing by the norm is called normalizing.
The (Euclidean) distance between and is .
The dot product #
Definition. The dot product (or inner product) of is the number
Books also write or . The notation is "row times column": a
row times an column gives a result, one number. In NumPy it is
x @ y or np.dot(x, y).
Rules. For vectors and a scalar :
- symmetric: ;
- linear in each vector: and ;
- length: .
Each rule follows from the same rule for numbers, applied to every term of the sum.
Expanding a squared length. The rules give a formula that we use again and again:
Proof (for the minus sign; the plus sign is the same with replaced by ).
- Use the length rule: .
- Use linearity to multiply out, like for numbers: .
- Use symmetry, , and the length rule: .
It is the vector version of .
The geometric formula #
Theorem. Let be nonzero, and let be the angle between them. Then
Why this is true, in one picture. The arrows , and form a triangle. The expansion above gives the length of the third side from the dot product. The law of cosines gives the length of the same side from the angle. The two formulas must agree, and that forces .
Proof with the law of cosines
- Draw the triangle with corners , and . Its sides have the lengths and , and the side from the tip of to the tip of is the arrow , with length . The angle at the corner is .
- The law of cosines (school geometry; it is Pythagoras when ) says , that is, .
- The expansion of the previous section says .
- The left sides of steps 2 and 3 are equal. Subtract from both right sides and divide by : .
If and lie on one line, the "triangle" is flat ( or ). The formula still holds: for with , , and the case is the same with .
In with we cannot measure the angle with a protractor. There, we turn the theorem around and use it to define the angle:
This is a valid definition because the fraction is always between and (the Cauchy–Schwarz inequality, in the folded block below).
Consequences.
- , or exactly when the angle is acute, right or obtuse (for nonzero , ), because and has the same sign as .
- and are orthogonal (perpendicular) when . Then : this is Pythagoras in .
- The scalar projection of on the direction of is , and the projection vector is . This is the "shadow" of the figure.
For two nonzero vectors, , and . What is the angle between them?
, so . The negative sign means an obtuse angle; has . You do not need the entries: the lengths and the dot product are enough.
Cosine similarity #
Definition. The cosine similarity of two nonzero vectors is
It is 1 when and point in the same direction, 0 when they are orthogonal, and when they point in opposite directions. It ignores length: for , .
This is why it is used for texts and embeddings. A long article and a short note about the same topic have word-count vectors that point the same way but have different lengths. Cosine similarity calls them similar. The distance calls them far apart, because it also compares the lengths.
Drag the query (blue). Each orange point is a document, written as the counts of two words. The left table ranks the documents by cosine similarity and the right table by distance. The best match by cosine has a violet ring, and the best match by distance has an aqua ring. D1 and D2 point in the same direction: cosine gives them the same score, distance does not. Drag far out along that direction and watch only the distance ranking change.
For unit vectors the two measures agree. If , the expansion gives
So a smaller distance means a larger cosine. This is why many systems normalize all embeddings to length 1 first and then use either measure.
A linear model is a dot product #
A linear model predicts a number from the feature vector with weights and a bias :
Each weight says how much feature counts: if grows by 1 and the other features stay the same, changes by . For a house with (area in 100 m², rooms) and , (prices in 100 000 CHF): .
The geometric formula gives a second reading. For a fixed length of , the score is largest when points in the direction of . So a neuron "looks for" inputs that point like its weight vector.
Cauchy–Schwarz, and angles in high dimension
Cauchy–Schwarz inequality. For all : .
Proof. If both sides are 0. Otherwise, for every number , a squared length is not negative: . Choose (the that makes the right side smallest). This gives , so . Take square roots.
So always lies in , and the definition of the angle above makes sense. It does not need a picture, so it works for every .
Random vectors in high dimension are almost orthogonal. Draw two vectors with independent standard normal entries. In their angle can be anything from 0° to 180°. In it is almost always close to 90°: in a simulation with 2000 pairs, the angles had mean 90.0° and standard deviation 1.8°. The dot product is a sum of random terms with mean 0, so it grows like , while grows like . The notebook draws the histogram. Linear Algebra lesson 18 uses this fact.
Answers to section 1. (1) : . (2) ; directly, . (3) Exactly 1: cosine similarity ignores length, and points in the same direction as .
4. Worked example #
Take and .
(a) Operations.
(b) Lengths and distance.
The unit vector in the direction of is .
(c) Dot product and angle.
so .
(d) Check with the expansion. . This matches (b): . ✓
(e) Projection. The projection of on the direction of is
with scalar projection . The rest, , is orthogonal to : . ✓
(f) Cosine versus distance. The query is compared with two documents of the figure: D2 and D6 .
- D2 : and , so . The difference is , so the distance is .
- D6 : and , so . The difference is , so the distance is .
Cosine similarity prefers D2 (same direction: ). Distance prefers D6 (close to the tip of ).
5. In code #
NumPy checks the hand computations above. The notebook for this lesson has these cells and the exercises.
import numpy as np
x = np.array([2., 1.])
y = np.array([1., 3.])
print(x + y, x - y, 2 * x) # [3. 4.] [ 1. -2.] [4. 2.]
print(np.linalg.norm(x), np.linalg.norm(y)) # 2.236... 3.162...
print(np.linalg.norm(x - y)) # 2.236... (distance)
print(x / np.linalg.norm(x)) # [0.894 0.447] (unit vector)
dot = x @ y # same as np.dot(x, y) and np.sum(x * y)
cos = dot / (np.linalg.norm(x) * np.linalg.norm(y))
print(dot, cos, np.degrees(np.arccos(cos))) # 5.0 0.7071... 45.0...
# the expansion ||x - y||^2 = ||x||^2 + ||y||^2 - 2 x.y
print(np.isclose(np.sum((x - y)**2), x @ x + y @ y - 2 * (x @ y))) # True
# projection of y on the direction of x, and the orthogonal rest
p = (x @ y) / (x @ x) * x
print(p, (y - p) @ x) # [2. 1.] 0.0
# cosine similarity versus distance
q, D2, D6 = np.array([2., 1.]), np.array([8., 4.]), np.array([1., 1.])
cosine = lambda a, b: a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
print(cosine(q, D2), cosine(q, D6)) # 1.0 0.9486...
print(np.linalg.norm(q - D2), np.linalg.norm(q - D6)) # 6.708... 1.0
The angle may print as 45.00000000000001: floats are not exact (lesson 03). Compare floats with np.isclose.
6. Where it shows up #
- Features and embeddings. A row of a data matrix is a feature vector . Word embeddings place words with similar meaning at similar directions, so cosine similarity finds related words. Sentence embeddings and vector databases do the same for whole texts; this is the retrieval step of RAG.
- Nearest neighbours. -NN classification and clustering with -means compute distances between feature vectors. The notebook finds the nearest neighbour of a digit image by cosine similarity.
- Neurons and attention. A neuron computes . Scaled dot-product attention computes for every query and key, then a softmax (lesson 05). A large dot product means "this key matches this query".
- Regularization. Ridge regression and weight decay add to the loss.
- ML for science. A molecule or a material is often stored as a fingerprint vector, and similar compounds are found with a similarity of these vectors. A wind field is a 2-D or 3-D vector at each grid point, and the speed is its norm.
7. Common mistakes #
- Adding the entries to get a length. , not . Square, add, then take the square root.
- Forgetting the square root. , not .
- Confusing and . is the length of a vector. is the absolute value of a number. They agree only for .
- Thinking that the dot product is a vector. is one number. The entrywise product
x * yin NumPy is a vector; its sum is the dot product. - Asking for the angle with the zero vector. divides by 0. The zero vector has no direction.
- Using cosine similarity when length matters. Two shopping baskets with 1 apple and 100 apples point in the same direction, so their cosine similarity is 1. If the amount matters, use a distance (or compare the norms too).
8. Check yourself #
- Compute , and for and .
Answer
, , . - Find the unit vector in the direction of .
Answer
, so the unit vector is . - For which number are and orthogonal?
Answer
, so . Check: . - , and . What is ?
Answer
, so (Pythagoras). - Two embeddings are normalized to length 1, and their distance is . What is their cosine similarity, and what is the angle?
Answer
gives , so and . - A linear model has and . Compute for . Which change of increases fastest, for a step of length 1?
Answer
. A step changes by . For this is largest when points along : , and grows by . Lesson 07 uses the same argument for the gradient.
What is the norm (length) of ?
, the theorem of Pythagoras applied entry by entry.
Compute and the unit vector in its direction.
; the unit vector is .
Give the two formulas for the dot product .
Algebra: . Geometry: , with the angle between and .
What does mean for two nonzero vectors?
They are orthogonal: the angle between them is .
Expand with dot products.
.
What is the cosine similarity of and , and what range does it have?
, a number in (for nonzero , ).
Why is the cosine similarity of and equal to 1?
Cosine similarity ignores length: scaling a vector by multiplies and by the same , which cancels.
How are distance and cosine similarity related for unit vectors?
, so a smaller distance means a larger cosine similarity.
Compute .
.
Write a linear model as a dot product. What does the weight mean?
. If feature grows by 1 and the others stay fixed, changes by .
9. Interview angle #
- "What is the difference between cosine similarity and Euclidean distance? When do you use which?" — Cosine compares directions and ignores length; distance compares positions. Use cosine for texts and embeddings where length reflects size, not meaning. For unit vectors they give the same ranking, because .
- "Why is the dot product ?" — Expand and compare with the law of cosines on the triangle .
- "Why does attention divide by ?" — For random vectors with independent entries of variance 1, is a sum of terms with variance 1 each, so its standard deviation is . Dividing keeps the scores in a range where the softmax is not saturated.
- "Two random vectors in 1000 dimensions: what angle do you expect?" — Close to ; the cosine is of size .
10. Practice #
The notebook for this lesson runs in Colab or in your browser. Four exercises, each with a check cell and a folded solution:
- Write
norm,dotandangle_degwith a loop ornp.sum, and check them againstnp.linalg.normand@. - Check on random vectors.
- Build the cosine-similarity matrix of the rows of a matrix with broadcasting, and find the nearest neighbour of a
digit image from
load_digits. - Draw random vectors in dimensions and plot the histogram of their angles.
11. Watch and read #
- Boyd and Vandenberghe, Introduction to Applied Linear Algebra (VMLS), free PDF: chapter 1 (vectors, addition, inner product) and chapter 3 (norm, distance, angle).
- Deisenroth, Faisal and Ong, Mathematics for Machine Learning, free PDF: §3.1–3.4 (norms, inner products, lengths and distances, angles and orthogonality).
- Next step: Linear Algebra lesson 1 (matrices as maps, span and basis).
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.