Vectors & the dot product
Step 3 of 18 in Foundations · Concept · Easy
A vector is a list of numbers that can represent a point, a direction, or a data example. The dot product measures how aligned two vectors are; it is the single most used operation in ML.
The lesson
A vector is an ordered list of numbers. It can be a point, an arrow, or one example in a dataset: a movie as [action, comedy, romance] scores, say.
The dot product multiplies matching entries and adds them up: a·b = a₁b₁ + a₂b₂ + … + aₙbₙ. Two vectors in, one number out.
Geometrically, a·b = |a| |b| cos θ, where θ is the angle between them. Positive means they point the same way, zero means perpendicular, negative means opposed. The length of a is |a| = √(a·a). Divide the dot product by both lengths and you get cosine similarity, a number from −1 to 1 that compares direction and ignores size.
- a·b = 1·2 + 2·0 + 2·1 = 4
- |a| = √(1 + 4 + 4) = 3 and |b| = √(4 + 0 + 1) ≈ 2.236
- cosine = 4 / (3 × 2.236) ≈ 0.596: fairly aligned
This is the most used operation in ML. A neuron computes w·x + b. A linear model's prediction is a dot product. Search ranks documents by the cosine similarity of their embeddings.
Common mistake. A big dot product does not mean two vectors are similar. Long vectors give big dot products whatever their direction. To compare direction, use cosine similarity.
Check yourself
a = [3, 4] and b = [2, −1]. What is a·b?
Show the answer
2. 3·2 + 4·(−1) = 6 − 4 = 2.
What is the cosine similarity of [1, 0] and [1, 1]? Two decimals.
Show the answer
0.7071. Dot product 1. Lengths 1 and √2. 1 / √2 ≈ 0.71, the cosine of 45°.
Two non-zero vectors have a dot product of 0. They are:
- pointing the same way
- perpendicular
- pointing opposite ways
Show the answer
perpendicular. a·b = |a||b|cos θ. With non-zero lengths, the product is zero only when cos θ = 0, that is θ = 90°.
Build it
Similarity by hand
Write dot(a, b), norm(a) and cosine(a, b) in plain Python. Represent 5 movies as genre vectors and find the most similar pair.
Done when: Matches NumPy; the most similar pair makes intuitive sense.
Runs in your browser: write the code on the map and the tests mark it.
Resources
Earn this star
On the map, your answers are marked and you log what you built. Finish the step and its star lights.
Open this step on the map