◆ AI All-in-One

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 →
↗ Plan a path here

Read first

Vectors

This leads to

Embeddings and Semantic SearchWord EmbeddingsAttentionk-Means Clusteringk-Nearest NeighboursSupport Vector Machines
The full path from zero — 1 concept before this one
  1. Vectors
  2. 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, 2×2=42 \times 2 = 4 adds a lot. When both dislike one, (−1)×(−2)=2(-1) \times (-2) = 2 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.

2×2+1×2+(−1)(−2)+0×0+2×1=4+2+2+0+2=102 \times 2 + 1 \times 2 + (-1)(-2) + 0 \times 0 + 2 \times 1 = 4 + 2 + 2 + 0 + 2 = 10

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 a\mathbf{a} and look at the shadow that arrow b\mathbf{b} casts on it. The dot product is the length of a\mathbf{a} times the length of that shadow.

Similar direction a · b = 24, cos θ = 0.96 a b = [3, 4] positive: they agree orange: b’s shadow on a (length 4.8) θ At right angles a · c = 0, cos θ = 0 a c = [−3, 4] zero: unrelated no shadow at all Opposite a · d = −25, cos θ = −1 a d = [−4, −3] negative: they disagree the shadow points backwards
Fig. 1 Three pairs of vectors. Pointing a similar way, the dot product is large and positive and b casts a long shadow on a. At right angles it is exactly zero and there is no shadow. Pointing in opposite directions it is negative and the shadow points backwards.

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, a=[a1,…,an]\mathbf{a} = [a_1, \dots, a_n] and b=[b1,…,bn]\mathbf{b} = [b_1, \dots, b_n]:

a⋅b=a1b1+a2b2+⋯+anbn=∑i=1naibi\mathbf{a} \cdot \mathbf{b} = a_1 b_1 + a_2 b_2 + \dots + a_n b_n = \sum_{i=1}^{n} a_i b_i

The ∑\sum ("sigma") means "add up, for ii going from 1 to nn". Note that the result is a single number, a scalar, not a vector. Some books write a⊤b\mathbf{a}^\top \mathbf{b} or ⟨a,b⟩\langle \mathbf{a}, \mathbf{b} \rangle for the same thing. The first form comes from matrix notation.

Take a=[4,3]\mathbf{a} = [4, 3] and b=[3,4]\mathbf{b} = [3, 4]:

a⋅b=4×3+3×4=12+12=24\mathbf{a} \cdot \mathbf{b} = 4 \times 3 + 3 \times 4 = 12 + 12 = 24

Now c=[−3,4]\mathbf{c} = [-3, 4]:   a⋅c=4×(−3)+3×4=−12+12=0\;\mathbf{a} \cdot \mathbf{c} = 4 \times (-3) + 3 \times 4 = -12 + 12 = 0. A dot product of exactly zero means the vectors are at right angles. The technical word is orthogonal.

And d=[−4,−3]\mathbf{d} = [-4, -3], which points exactly opposite to a\mathbf{a}:   a⋅d=−16−9=−25\;\mathbf{a} \cdot \mathbf{d} = -16 - 9 = -25.

Length: the norm

The length of a vector, also called its norm, comes from Pythagoras' theorem. The arrow [4,3][4, 3] goes 4 across and 3 up, so it is the long side of a right-angled triangle with sides 4 and 3:

∥a∥=42+32=25=5\lVert \mathbf{a} \rVert = \sqrt{4^2 + 3^2} = \sqrt{25} = 5

The double bars ∥⋅∥\lVert \cdot \rVert mean "length of". In any number of dimensions:

∥a∥=a12+a22+⋯+an2=a⋅a\lVert \mathbf{a} \rVert = \sqrt{a_1^2 + a_2^2 + \dots + a_n^2} = \sqrt{\mathbf{a} \cdot \mathbf{a}}

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 (∣4∣+∣3∣=7|4| + |3| = 7, 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: [4,3]/5=[0.8,0.6][4, 3] / 5 = [0.8, 0.6]. 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):

d(a,b)=∥a−b∥d(\mathbf{a}, \mathbf{b}) = \lVert \mathbf{a} - \mathbf{b} \rVert

For [4,3][4, 3] and [3,4][3, 4]: the difference is [1,−1][1, -1], so the distance is 1+1≈1.41\sqrt{1 + 1} \approx 1.41. 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 ("theta") is the angle between two vectors:

a⋅b=∥a∥ ∥b∥cos⁡θ\mathbf{a} \cdot \mathbf{b} = \lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert \cos\theta

The cosine, cos⁡θ\cos\theta, 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: ∥b∥cos⁡θ\lVert \mathbf{b} \rVert \cos\theta is the length of b\mathbf{b}'s shadow on a\mathbf{a}.

Check it on our example: 24=5×5×cos⁡θ24 = 5 \times 5 \times \cos\theta, so cos⁡θ=24/25=0.96\cos\theta = 24/25 = 0.96, and θ≈16°\theta \approx 16°. 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(a,b)=a⋅b∥a∥ ∥b∥=cos⁡θ\text{cosine similarity}(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a} \cdot \mathbf{b}}{\lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert} = \cos\theta

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.

how to bake bread baking guide (long) cake decorating car repair q A query and four documents as embeddings blue q = the query “bread recipe”; drawn in 2-D for the picture dashed circle: vectors of length 1 Rank by cosine similarity the cosine of each angle to q 1. how to bake bread +0.98 2. baking guide (long) +0.97 3. cake decorating +0.64 4. car repair -0.50 (pointing away) only the angle counts: the long guide’s bigger arrow does not raise its score
Fig. 2 Similarity search. A query embedding and four document embeddings, drawn in 2-D. Ranking the documents by the cosine of their angle to the query puts the two bread articles first and the car-repair article last, with a negative score. The long article scores no higher just because its vector is longer.

Dot product, cosine or distance?

Measure Range Cares about length? Typical use
Dot product a⋅b\mathbf{a} \cdot \mathbf{b} any number yes attention scores, recommenders, any already-normalised embeddings
Cosine similarity −1 to 1 no text embeddings, semantic search
Euclidean distance ∥a−b∥\lVert \mathbf{a} - \mathbf{b} \rVert 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 ∥a−b∥2=2−2cos⁡θ\lVert \mathbf{a} - \mathbf{b} \rVert^2 = 2 - 2\cos\theta 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 q\mathbf{q} ("what am I looking for?") and a key vector k\mathbf{k} ("what do I contain?"). The score for how much one word should attend to another is their dot product, divided by d\sqrt{d}, where dd is the vector size, to keep the numbers in a sensible range:

score=q⋅kd\text{score} = \frac{\mathbf{q} \cdot \mathbf{k}}{\sqrt{d}}

A tiny example with d=2d = 2: query q=[1,0]\mathbf{q} = [1, 0] and three keys [2,0][2, 0], [0,2][0, 2] and [−1,1][-1, 1]. The dot products are 22, 00 and −1-1. Divided by 2≈1.41\sqrt{2} \approx 1.41, they are 1.411.41, 00 and −0.71-0.71. A function called softmax (see Probability Distributions) turns these into weights that add up to 1: about 0.730.73, 0.180.18 and 0.090.09. 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 (nan in 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

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

  1. By hand, compute the dot product, both lengths and the cosine similarity of [1,2,2][1, 2, 2] and [2,0,1][2, 0, 1]. Check with NumPy.
  2. Find a non-zero vector orthogonal to [2,5][2, 5]. How many are there?
  3. 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: [5,−2][5, -2] works. Any multiple of it works too.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. What is the dot product of [1, 2, 3] and [4, 0, −1]?

  2. Two embedding vectors have a dot product of exactly 0. What does that tell you?

  3. Your search ranks documents by raw dot product with the query, and long documents keep winning even when off-topic. What is the fix?

  4. Vector a = [3, 4]. What is its length, and what unit vector points the same way?

  5. You compare an embedding from model A with an embedding from model B; both have 768 numbers and the cosine similarity is 0.9. What can you conclude?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Essence of Linear Algebra

3Blue1Brown · Beginner · Free

A visual intuition for vectors, matrices, determinants and eigenvectors. You will see the ideas, not just the rules.

Interactive

Immersive Linear Algebra

J. Ström, K. Åström & T. Akenine-Möller · Beginner · Free

A free linear algebra book whose figures you can drag and rotate. Excellent for seeing vectors, dot products and matrices as geometry.

Article

The Illustrated Word2vec

Jay Alammar · 2019 · Beginner · Free

A gentle, picture-heavy explanation of how words become vectors and why their dot products capture meaning.

Book

Mathematics for Machine Learning

Deisenroth, Faisal & Ong · 2020 · Intermediate · Free

The linear algebra, calculus, probability and optimisation that ML uses, in one free book.

Article

Linear Algebra Review and Reference

Zico Kolter (Stanford CS229) · Intermediate · Free

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.

Course

Machine Learning Crash Course

Google · Beginner · Free

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