Lesson 2 · Unit 01
The dot product
Multiply matching entries, add: one number for alignment
What you practise
- Multiply matching entries and add
- It measures alignment
- Cosine similarity
- Perpendicular means zero
- A weighted sum is a dot product
Try a question from this lesson
Pick one
Apples cost 2 coins and pears cost 5. You buy 3 apples and 4 pears. What do you pay?
Correct answer
26
Why
3 × 2 + 4 × 5 = 26. You multiplied matching entries of [3, 4] and [2, 5] and added the results. That operation is the dot product, and it is everywhere in ML.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The dot product
Take two vectors of the same size. Multiply the first entries, the second entries, and so on. Add the products. Two vectors go in, one number comes out.
It is written a · b. In NumPy it is a @ b or np.dot(a, b).
Any weighted sum is a dot product: quantities with prices, features with weights, grades with credits.
import numpy as np
qty = np.array([3, 4])
price = np.array([2, 5])
print(qty @ price) # 26
print(np.dot(qty, price)) # 26Concept
Cosine similarity
The dot product grows with alignment, but also with length: a long arrow scores high against almost anything.
To compare direction only, divide the dot product by both lengths. The result is the cosine similarity: 1 for the same direction, 0 for perpendicular, -1 for opposite.
Search engines and language models use it to ask "do these two vectors mean the same thing?".
import numpy as np
def cosine(a, b):
na = np.linalg.norm(a)
nb = np.linalg.norm(b)
return (a @ b) / (na * nb)
a = np.array([1, 0])
print(cosine(a, np.array([5, 0]))) # 1.0
print(cosine(a, np.array([0, 2]))) # 0.010 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.