Vectors & Spaces
Before you start: the Math Toolkit lesson covers squares, square roots and the sigma sum (adding up a list of terms). That is all the background you need. Every code cell here is plain Python with lists and loops, with no extra libraries.
After this lesson, you will be able to:
- Read a vector two ways: as a list of numbers and as an arrow with a direction and a length
- Compute a dot product by hand and explain what its sign tells you
- Turn the dot product into cosine similarity, and explain why it compares direction while ignoring length
- Measure length and distance with the L1, L2 and L-infinity norms
- Explain basis vectors and span, and why data often uses fewer directions than it has numbers
#What Is a Vector, Really?
Math is not a talent — it is a skill. If you can count, add, and follow directions on a map, you already have everything you need to understand vectors. This lesson starts from zero and builds up one piece at a time. Take it slow and you will surprise yourself.
This lesson begins with numbers you can draw and adds one idea at a time. By the end you will see how data in machine learning is stored, and why.
#Your First Vector
In mathematics, we write a 2D vector as a column of numbers:
Try it! Open the Python REPL (bottom-right of the screen: click Quick Actions, then Python) and typev = [3, 4]yourself.
The top number (3) says "move 3 units along the x-axis." The bottom number (4) says "move 4 units along the y-axis." Together, they define a direction and a distance.
#Magnitude: How Far?
The claim is that this is the Pythagorean theorem in disguise. Here is the check, on a grid. Walk 3 east, then 4 north. The straight line from where you started to where you ended is the vector itself, and it closes a right triangle (a sketch, not to scale):
y
4 | B (3, 4)
| / |
3 | / |
| / | 4 north
2 | / |
| / |
1 | / |
|/ |
0 O-----------------+---- x
0 1 2 3
3 east
Now build a square on each side of that triangle. The square on the 3-side holds 3 × 3 = 9 unit squares. The square on the 4-side holds 4 × 4 = 16. The Pythagorean theorem says the square on the slanted side holds exactly 9 + 16 = 25 unit squares, so each of its sides is √25 = 5. That is the magnitude formula: square the components, add them, take the square root.
#Vectors in Higher Dimensions
Nothing changes when we go from 2 components to 3, or to 100. For [3, 4, 12] you walk 3 along the first axis, 4 along the second and 12 along the third. The length just gets one more term under the root: 9 + 16 + 144 = 169, and √169 = 13.
Why does one more axis mean exactly one more term? Open the derivation to see the 2D right triangle used again and again.
#Vector Operations
#Addition: Chaining Instructions
When you add two vectors, you chain their instructions end to end. Walk east 3, north 4, then walk east 1, south 2. The result: east 4, north 2.
#Scalar Multiplication: Stretching
If you multiply the vector [3, 4] by -0.5, what happens geometrically?
Multiplying by -0.5 does two things: the 0.5 halves the length, and the negative sign flips the direction. The result is [-1.5, -2] — a vector half as long, pointing in the opposite direction.
A vector v has magnitude 10. You multiply it by the scalar -2. What are the magnitude and direction of the result?
#The Dot Product: Measuring Alignment
How alike are two lists of numbers? One small recipe answers that, and you can do it by hand. Take a = [1, 2] and b = [3, 4]. Multiply the first components, multiply the second components, then add the results:
1 × 3 + 2 × 4 = 3 + 8 = 11
- a = [1, 0] and b = [0, 1]: 1 × 0 + 0 × 1 = 0 + 0 = 0. The first arrow runs along the x-axis and the second straight up the y-axis, so they are perpendicular (at a right angle). The dot product is 0.
- a = [3, 4] and b = [1, -2]: 3 × 1 + 4 × (-2) = 3 - 8 = -5. The result is negative.
Three results, three stories. A positive result (11) means the arrows lean broadly the same way. Zero means they are perpendicular. A negative result (-5) means they lean away from each other.
Read the formula as the recipe you just used: a₁ is the first component of a, b₁ the first component of b, and so on up to the n-th. The three dots mean "keep going". The dot product is the single most important operation in all of ML, because "how much do these two lists agree?" is the question it answers.
#Where the Angle Comes In
The dot product also hides an angle. First, the one piece you need: what the cosine measures.
Now the geometric identity:
Check it where the angle comes from geometry, not from the formula. Take a = [1, 0] and b = [3, 4]. The arrow b goes 3 across and 4 up, so it is the long side of the 3-4-5 triangle, and its angle with a has cos = 3 / 5 = 0.6 (side next to the angle over the longest side). The lengths are 1 and 5, so 1 × 5 × 0.6 = 3, and the dot product by hand is 1 × 3 + 0 × 4 = 3. They agree. The perpendicular example agrees too: [1, 0] and [0, 1] both have length 1 and a 90 degree angle, so 1 × 1 × 0 = 0.
Where does a cosine come from in a formula that is only multiply-and-add? Open the derivation to see the law of cosines produce it.
Here is the same idea as a picture: drag the tips of the two arrows, and watch the amber shadow of b on a (the dot product is the length of a times that shadow) shrink to nothing at a right angle and turn negative once b leans away from a.
#Shadow Length and Projection
The amber shadow has a formula. Its signed length is the dot product divided by the length of a, and the shadow as an arrow lying along a is the projection of b onto a:
Open the derivation to see where the stretch factor comes from.
#Normalising and Cosine Similarity
Take a = [3, 4], whose length is 5. Normalised, it is [3/5, 4/5] = [0.6, 0.8]. Check its length: 0.36 + 0.64 = 1. Take b = [4, 3], also of length 5, which normalises to [0.8, 0.6].
- The raw dot product is 3 × 4 + 4 × 3 = 24.
- The dot product of the two normalised vectors is 0.6 × 0.8 + 0.8 × 0.6 = 0.48 + 0.48 = 0.96.
- The formula above gives cos θ = 24 / (5 × 5) = 0.96.
In two or three dimensions the cosine of a real angle cannot leave -1 to 1. In 768 dimensions there is no angle to look at, and the ratio itself is what defines the angle, so we need a proof that it never leaves that range. Open the derivation to see one that uses only a square that cannot be negative.
In a transformer, the attention step starts by taking a dot product between a query vector and each key vector. The Transformers track explains why. The arithmetic is exactly the multiply-and-add you just did.
Let us try it with numbers. Here are made-up 5-number vectors for "king", "queen" and "car". This is a toy: the numbers are not from a real model, they only show the mechanics.
- king = [0.8, 0.2, -0.1, 0.9, 0.3]
- queen = [0.7, 0.3, -0.2, 0.85, 0.35]
- car = [-0.1, 0.8, 0.7, -0.3, 0.1]
The dot product of king and queen, one component at a time: 0.8 × 0.7 = 0.56, 0.2 × 0.3 = 0.06, (-0.1) × (-0.2) = 0.02, 0.9 × 0.85 = 0.765, 0.3 × 0.35 = 0.105. Add them: 0.56 + 0.06 + 0.02 + 0.765 + 0.105 = 1.51. The lengths come out as about 1.261 for king and 1.210 for queen, so the cosine similarity is 1.51 / (1.261 × 1.210) ≈ 0.989. Doing the same for king and car gives a dot product of -0.23 and a cosine of about -0.164. In this toy, king and queen point almost the same way, and car points slightly away.
Now compute it for real. The playground below runs plain Python in your browser, with no setup and no install. Edit the vectors, click Run, and watch the dot product, lengths and cosine similarity update.
#Norms and Distances
- L1 norm: add the absolute values of the components (the absolute value drops a minus sign). 3 + 4 = 7. Think of city blocks, where you can only walk along streets.
- L2 norm: the straight-line length we already used. √(3² + 4²) = √25 = 5.
- L-infinity norm: the largest absolute component. The larger of 3 and 4 is 4.
So the same arrow has size 7, 5 or 4, depending on the question you are asking. L2 is the default when people say "length".
Drag the point in the next picture to see all three sizes of the same arrow with the arithmetic written out, and watch the shape formed by every point whose size is exactly 1: a diamond, a circle or a square.
#Two Facts About Norms
The picture shows the diamond sitting inside the circle, and the circle inside the square. For [3, 4] the three sizes were 7, 5 and 4, always in that order. The first derivation says this order holds for every vector, and it is why the diamond is the smallest shape.
The second fact is what makes distance behave like distance: going somewhere by a detour is never shorter than going straight. Take any two vectors a and b. Walking a and then b ends at a + b. The straight-line length of a + b cannot exceed the two legs added. The same holds for L1 and L-infinity: it follows component by component from the one-number fact that |x + y| is at most |x| + |y|. Open the derivation for L2.
A later lesson meets L1 and L2 again as penalties that keep a model's numbers small, and L2 distance is one way nearest-neighbour search measures "closest".
#How Vectors Power Machine Learning
#Step 1: Raw Data
Everything starts as raw data: image pixels, text, audio samples, or spreadsheet rows. At this stage, the data is not yet in a form that any ML model can work with. A 28x28 grayscale image is just a grid of brightness values. A sentence is just a sequence of characters.
#Step 2: Convert to Vectors
#Step 3: Vector Operations
#Step 4: ML Model Uses Vectors
The model processes these vectors through layers of transformations. In a transformer, query and key vectors are compared via dot products to compute attention. In a recommendation system, user and item vectors are compared via cosine similarity. In RAG (retrieval-augmented generation, where a system looks up relevant documents before answering), document and query vectors are compared to find relevant context. Every one of these steps is built from the vector math in this lesson.
#Vector Spaces and Basis Vectors
#Basis Vectors: The Building Blocks
The standard basis is not the only one. With [1, 1] and [1, -1] you can also reach [3, 4]: 3.5 × [1, 1] + (-0.5) × [1, -1] = [3.5 - 0.5, 3.5 + 0.5] = [3, 4]. Different building blocks, same destination, different stretch amounts.
Slide the two stretch amounts in the next picture to walk to different points, then make the second arrow parallel to the first and watch the reachable plane collapse onto a line.
To test two arrows, ask whether some stretch of the first cancels the second. Take [1, 2] and [2, 4]. Twice the first is [2, 4], so 2 × [1, 2] - [2, 4] = [0, 0]. They are dependent, and they span only a line. Now take [1, 2] and [3, 4]. For a × [1, 2] + b × [3, 4] to be [0, 0] we need a + 3b = 0 and 2a + 4b = 0. The first gives a = -3b. Put that in the second: -6b + 4b = -2b = 0, so b = 0 and a = 0. Only the trivial combination works, so they are independent and span the whole plane. A basis is a set of independent arrows that spans the space, and in 2D that is always exactly two.
You have three vectors in 3D: v1 = [1, 0, 0], v2 = [0, 1, 0], v3 = [2, 3, 0]. What is the dimension of their span?
#Try It Yourself
Time to build the lesson's tools in code. You will write the dot product, the length, cosine similarity and normalising from scratch in plain Python, then check them against the numbers worked by hand above. The toy king, queen and car vectors are provided.
Tests: Verify dot(king, queen) is 1.51 and dot(king, car) is -0.23, cosine(king, queen) is 0.9894 and cosine(king, car) is -0.1638, the dot product of the two normalised vectors equals the cosine (0.9894), length(normalise(king)) is 1.0, tripling king triples the dot product (4.77 against 1.59) while the cosine stays at 1.0.
When you run the solution you should see dot(king, queen) = 1.51 and dot(king, car) = -0.23, and cosines of 0.9894 and -0.1638. The normalised dot product matches the cosine at 0.9894, and the normalised king has length 1.0. In the stretch step, tripling king triples the dot product (4.77 against 1.59 for king with itself) but the cosine stays at 1.0. The dot product feels the length, and the cosine does not.
Real embedding vectors have hundreds to thousands of numbers instead of 5. The code is identical, just with longer lists.
#Key Takeaways
- A vector is a list of numbers, and you can also picture it as an arrow with direction and magnitude. Every data point in ML is represented as a vector
- Dot product measures alignment. Multiply matching components and add: it is positive when vectors lean the same way, zero when perpendicular, negative when they lean apart
- Cosine similarity normalizes for magnitude. By dividing the dot product by both vector lengths, it measures pure directional alignment regardless of scale, which is why it powers embedding-based search
- Norms measure size. For [3, 4] the L1, L2 and L-infinity norms are 7, 5 and 4, and the norm of a difference is a distance
- Basis vectors and span define the space. Any vector can be built from linear combinations of basis vectors, and data often uses fewer independent directions than it has numbers
- High dimensions work the same way. The math for 2D vectors extends identically to 768D or higher; you cannot visualize it, but the operations are unchanged
#Quick Check
u = [2, -1] and v = [1, k]. For which value of k are u and v perpendicular?
An ordered list of numbers that describes one thing, such as a point or a displacement; you can also picture it as an arrow with a direction and a magnitude.
One entry of a vector. [3, 4] has two components, 3 and 4.
The number of components in a vector. [3, 4] is 2-dimensional; a 28x28 image flattened into a list is 784-dimensional.
A single real number with no direction. Multiplying a vector by a scalar stretches or shrinks it without changing the line it points along (a negative scalar also flips it).
The size of a vector. The usual L2 norm is the square root of the sum of its squared components, written ||v||. L1 adds absolute values and L-infinity takes the largest absolute component.
A single number computed by multiplying corresponding components of two vectors and summing them. Measures how aligned two vectors are.
The dot product divided by both vector magnitudes, giving a value in [-1, 1] that measures only angular alignment, ignoring length.
Divide every component of a vector by its own length, so the result has length 1 and points the same way.
A list of numbers a model has learned to describe a word, image or other item, so that similar items get similar lists.
Two vectors are orthogonal (perpendicular) when their dot product is zero. In ML, orthogonal (mean-centred) features are uncorrelated: neither linearly predicts the other. Uncorrelated is weaker than independent.
A smallest set of vectors that can build every vector in a space by linear combinations (none of them can be built from the others).
The set of all vectors you can produce by linear combinations of a given set of vectors. In 2D, two non-parallel vectors span the entire plane.
Semantic Search
An embedding model turns documents and queries into vectors with hundreds to thousands of numbers, so a retrieval system can rank results by cosine similarity instead of keyword overlap. (Semantic means about meaning.)
Finds results by meaning, not only by shared words
Music Recommendations
Recommendation systems commonly describe tracks and listeners with vectors, so 'songs like this' becomes 'find the vectors closest to this one'.
Turns taste into a nearest-neighbour search
Visual Search
A vision model encodes each image as a vector, and 'visually similar' lookups are nearest-neighbour searches in that vector space.
Lets you search with a picture instead of a keyword