Machine Learning from Scratch · Data as Numbers
Vectors and the Dot Product
Describe a film and a viewer as lists of numbers, then multiply and add to measure how well they match: the dot product behind recommendations and neural networks.
dot_product.py
# A film described by numbers: how much action, comedy and romance it has, from 0 to 1.
film = [0.9, 0.2, 0.1]
# A viewer described the same way: how much they like each.
viewer = [0.8, 0.5, 0.0]
score = 0
for f, v in zip(film, viewer):
score = score + f * v
print("action film:", round(score, 2))
romance = [0.1, 0.3, 0.9]
score2 = sum([f * v for f, v in zip(romance, viewer)])
print("romance film:", round(score2, 2))
Step by step
- A film as three numbers: 0.9 action, 0.2 comedy, 0.1 romance. A list of numbers like this is called a vector; each position always means the same thing.
- The viewer as a vector in the same order: loves action (0.8), likes comedy (0.5), does not care for romance (0.0).
- The match score starts at 0.
- Pair up the first number of each: the film's action (0.9) with how much the viewer likes action (0.8).
- 0 + 0.9 × 0.8 = 0.72. A lot of action, for someone who loves action: a big contribution.
- Comedy: the film has 0.2, the viewer likes it 0.5.
- 0.72 + 0.2 × 0.5 = 0.82. A little comedy, liked a little: a small addition.
- Romance: the film has 0.1, the viewer likes it 0.0.
- 0.82 + 0.1 × 0.0 = 0.82. Anything times 0 is 0: the viewer does not care about romance, so it adds nothing.
- All three pairs are done: the loop ends.
- The dot product: multiply each pair, add them up. 0.82 is a strong match.
- A romance film: little action, some comedy, lots of romance.
- The same calculation in one line: 0.1 × 0.8 + 0.3 × 0.5 + 0.9 × 0.0 = 0.23.
- A much lower score: 0.23 against 0.82. A recommender would suggest the action film. That one multiply-and-add is the heart of recommendations, search and neural networks.