Level 3 In-Depth AI · Math Foundations
Dot Product, Norms and Similarity
The dot product multiplies two vectors into one number that says how much they point the same way. With lengths and distances, it is how AI measures similarity, from search engines to the attention inside every Transformer.
- Level
- ●●●●● Beginner
- Reading
- 12 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 1 concept →
- Quiz
- 5 questions ↓
Read first
VectorsThe full path from zero — 1 concept before this one
- Vectors
- Dot Product, Norms and Similarity
Read them roughly in this order. See it on the concept map →
Why it matters
Once everything is a vector, the most common question an AI system asks is: how similar are these two vectors?
- A search engine turns your question into an embedding vector and looks for documents whose vectors are most similar. That is Embeddings and Semantic Search, and it is the "retrieval" step in retrieval-augmented generation.
- A recommender scores how well a user vector matches each film vector (see Recommender Systems).
- k-nearest neighbours classifies a new example by finding the training examples closest to it.
- Inside every Transformer, Attention decides which earlier words a word should "look at" by scoring how well their vectors match. GPT-style models compute billions of these scores for every reply they write.
All of these rest on one small operation, the dot product, plus two close relatives: the length of a vector and the distance between two vectors. This chapter builds all three by hand.
The intuition
Imagine two people rating five films from −2 (hated it) to +2 (loved it):
| Film A | Film B | Film C | Film D | Film E | |
|---|---|---|---|---|---|
| Ana | 2 | 1 | −1 | 0 | 2 |
| Ben | 2 | 2 | −2 | 0 | 1 |
How much do they agree? A natural recipe: for each film, multiply their two ratings, then add the results. When both love a film, adds a lot. When both dislike one, also adds, because agreeing on a dislike is still agreeing. When one likes and the other dislikes, the product is negative and subtracts. When either is neutral, the product is 0 and the film doesn't count.
A large positive total means "they agree", near zero means "unrelated tastes", and negative means "opposite tastes". That multiply-and-add recipe is the dot product.
There is a picture too. Think of the two vectors as arrows. The dot product is large when they point the same way, zero when they are at right angles, and negative when they point in opposite directions. You can see it as a shadow: shine a light straight down onto arrow and look at the shadow that arrow casts on it. The dot product is the length of times the length of that shadow.
Key idea The dot product multiplies two vectors component by component and adds up the results. Big and positive means "pointing the same way". It is the basic similarity score of AI.
How it works
The dot product
For two vectors with the same number of components, and :
The ("sigma") means "add up, for going from 1 to ". Note that the result is a single number, a scalar, not a vector. Some books write or for the same thing. The first form comes from matrix notation.
Take and :
Now : . A dot product of exactly zero means the vectors are at right angles. The technical word is orthogonal.
And , which points exactly opposite to : .
Length: the norm
The length of a vector, also called its norm, comes from Pythagoras' theorem. The arrow goes 4 across and 3 up, so it is the long side of a right-angled triangle with sides 4 and 3:
The double bars mean "length of". In any number of dimensions:
So the length is just the square root of a vector's dot product with itself. This everyday length is called the L2 norm or Euclidean norm. You will also meet the L1 norm, the sum of absolute values (, the distance a taxi drives on a grid of streets). Both reappear as penalties on weights in Regularization: L1 and L2.
A vector of length exactly 1 is a unit vector. You can turn any non-zero vector into one by dividing it by its length. This is called normalising: . It keeps the direction and throws away the size.
Distance
The distance between two points is the length of the arrow between them, which is their difference (see Vectors):
For and : the difference is , so the distance is . This straight-line distance is the Euclidean distance. It is what k-Nearest Neighbours and k-Means Clustering use by default.
The geometric meaning: angles
Here is the beautiful fact that connects the multiply-and-add recipe to the arrow picture. If ("theta") is the angle between two vectors:
The cosine, , is a number between −1 and 1 that depends only on the angle. It is 1 when the angle is 0° (same direction), 0 at 90° (right angle), and −1 at 180° (opposite). So the dot product is "length times length times how aligned they are". The shadow picture says the same thing: is the length of 's shadow on .
Check it on our example: , so , and . The two arrows are nearly aligned, as the picture shows.
Cosine similarity
The raw dot product mixes two things: how aligned two vectors are and how long they are. Often you only want the first. A long document might produce a longer embedding vector than a short one on the same topic, and you don't want length to win. Dividing out the lengths leaves only the angle:
Cosine similarity runs from −1 (opposite) through 0 (unrelated) to 1 (same direction). It is the standard similarity score for text embeddings.
A practical trick: if you normalise all your vectors to length 1 in advance, then cosine similarity is the dot product, because the lengths are both 1. That is why vector databases often store normalised embeddings and then rank by plain dot products, which are very fast to compute.
Dot product, cosine or distance?
| Measure | Range | Cares about length? | Typical use |
|---|---|---|---|
| Dot product | any number | yes | attention scores, recommenders, any already-normalised embeddings |
| Cosine similarity | −1 to 1 | no | text embeddings, semantic search |
| Euclidean distance | 0 and up (smaller = more similar) | yes | k-NN, k-means, clustering on raw features |
For unit vectors the three agree on the ranking, because when both lengths are 1. Use whatever your embedding model's documentation recommends. Most text-embedding models are trained with cosine similarity in mind.
How attention uses the dot product
In a Transformer, each word produces a query vector ("what am I looking for?") and a key vector ("what do I contain?"). The score for how much one word should attend to another is their dot product, divided by , where is the vector size, to keep the numbers in a sensible range:
A tiny example with : query and three keys , and . The dot products are , and . Divided by , they are , and . A function called softmax (see Probability Distributions) turns these into weights that add up to 1: about , and . So the word pays most attention to the first one, whose key points the same way as its query. Self-Attention and Multi-Head Attention does exactly this, for every pair of words, with vectors of hundreds of dimensions.
In code
import numpy as np
a = np.array([4.0, 3.0])
b = np.array([3.0, 4.0])
c = np.array([-3.0, 4.0])
print(a @ b, a @ c) # 24.0 0.0 dot products (same as np.dot)
print(np.linalg.norm(a)) # 5.0 length of a
print(np.linalg.norm(a - b)) # 1.4142135623730951 distance from a to b
def cosine(u, v):
return (u @ v) / (np.linalg.norm(u) * np.linalg.norm(v))
print(cosine(a, b), cosine(a, c), cosine(a, -a)) # 0.96 0.0 -1.0
print(np.degrees(np.arccos(cosine(a, b)))) # 16.260204708311967 degrees
# Tiny similarity search over made-up 4-d "embeddings"
docs = {
"how to bake bread": np.array([0.9, 0.1, 0.0, 0.2]),
"sourdough starter tips": np.array([0.7, 0.3, 0.1, 0.1]),
"fixing a flat tyre": np.array([0.0, 0.9, 0.3, 0.1]),
"stock market basics": np.array([0.1, 0.0, 0.9, 0.4]),
}
query = np.array([0.9, 0.1, 0.0, 0.15]) # imagine: "bread recipe"
scores = {title: cosine(query, v) for title, v in docs.items()}
for title, s in sorted(scores.items(), key=lambda kv: -kv[1]):
print(f"{s:.3f} {title}")
# 0.999 how to bake bread
# 0.949 sourdough starter tips
# 0.165 stock market basics
# 0.120 fixing a flat tyre
In PyTorch, normalise once and a single matrix multiplication scores every document against every query at once. This is how real search systems do it on a GPU:
import torch
import torch.nn.functional as F
q = torch.tensor([[0.9, 0.1, 0.0, 0.15]]) # 1 query
D = torch.tensor([[0.9, 0.1, 0.0, 0.2],
[0.0, 0.9, 0.3, 0.1]]) # 2 documents
print(F.cosine_similarity(q, D, dim=1)) # tensor([0.9986, 0.1199])
print(F.normalize(q, dim=1) @ F.normalize(D, dim=1).T) # same scores as a 1 x 2 table
With a million documents, D has a million rows and the last line still works. Beyond that, Vector Databases use approximate search to avoid scoring every row.
Common pitfalls
- Comparing vectors from different models. An embedding from one model and an embedding from another live in unrelated spaces. Their cosine similarity is meaningless, even if the sizes match.
- Forgetting to normalise. Ranking by raw dot product when your vectors have very different lengths lets the longest vectors win everything. Normalise, or use cosine similarity.
- Dividing by zero. The zero vector has no direction, and its cosine similarity is undefined (
nanin NumPy). Libraries add a tiny number to the denominator. Watch for empty inputs that embed to zeros. - Unscaled features. Euclidean distance on raw
[salary, age]is decided almost entirely by salary. Standardise features first (see Data Cleaning and Preparation). - Reading too much into absolute scores. A cosine of 0.8 means "very similar" for one embedding model and "loosely related" for another. Compare scores only within one model and use rankings, or calibrate thresholds on your own data.
Watch out In high dimensions distances bunch together: the nearest and the farthest neighbour of a random point end up at almost the same distance. Similarity search still works on real embeddings, because real data is far from random, but raw Euclidean distance on hundreds of unprocessed features often stops meaning much. See k-Nearest Neighbours on the curse of dimensionality.
Where it leads
- Matrix multiplication is nothing but many dot products at once: every entry of the result is the dot product of a row and a column.
- A single neuron computes the dot product of its weights and its inputs, adds a bias, and applies an activation function.
- Embeddings and Semantic Search, Vector Databases and Retrieval-Augmented Generation are industrial-scale cosine similarity.
- Attention and Self-Attention and Multi-Head Attention are scaled dot products turned into weights.
- Support vector machines and Logistic Regression decide a class by the sign of a dot product: which side of a line, or plane, a point falls on.
- CLIP trains images and captions so that matching pairs have a high cosine similarity.
A bit of history
The dot product grew out of 19th-century work on vectors and quaternions. In the 1880s Josiah Willard Gibbs wrote it with a dot between the two vectors (he called it the "direct product"), alongside the cross product, and the name "dot product" followed from the notation. Pythagoras' theorem, behind the length formula, is far older. Cosine similarity became a workhorse of information retrieval in the 1960s and 1970s in Gerard Salton's SMART system, which represented documents as vectors of word counts and ranked them by the angle to a query vector. The same idea, with learned embeddings instead of word counts, powers today's semantic search. In 2017, the paper Attention Is All You Need made the scaled dot product the central operation of the Transformer, and with it of modern language models.
Try it
- By hand, compute the dot product, both lengths and the cosine similarity of and . Check with NumPy.
- Find a non-zero vector orthogonal to . How many are there?
- Add a fifth document to the code above that you think should rank second. Make up its vector, then check the ranking.
Hint for 2: swap the two components and flip the sign of one: works. Any multiple of it works too.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Essence of Linear Algebra
A visual intuition for vectors, matrices, determinants and eigenvectors. You will see the ideas, not just the rules.
Immersive Linear Algebra
A free linear algebra book whose figures you can drag and rotate. Excellent for seeing vectors, dot products and matrices as geometry.
The Illustrated Word2vec
A gentle, picture-heavy explanation of how words become vectors and why their dot products capture meaning.
Mathematics for Machine Learning
The linear algebra, calculus, probability and optimisation that ML uses, in one free book.
Linear Algebra Review and Reference
A compact 30-page summary of exactly the linear algebra used in machine learning, with ML notation. A good reference once the ideas make sense.
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/dot-product-and-similarity.md