Embeddings and Cosine Similarity
An embedding turns a word, sentence, image or product into a vector, chosen so that similar things get vectors pointing in similar directions. Comparing them is then pure linear algebra: dot products, norms and angles. This is how semantic search, recommendation and retrieval-augmented generation find "related" items.
Vectors that carry meaning
Real embedding models (word2vec, sentence transformers, the embedding endpoints of LLM APIs) output vectors with hundreds or thousands of entries, learned from data; individual coordinates rarely mean anything on their own. To see the mechanics we use tiny made-up 4-dimensional embeddings whose axes we pretend mean (animal, vehicle, size, speed):
| item | animal | vehicle | size | speed |
|---|---|---|---|---|
| cat | 0.9 | 0.0 | 0.2 | 0.4 |
| dog | 0.9 | 0.0 | 0.4 | 0.5 |
| horse | 0.8 | 0.3 | 0.8 | 0.7 |
| bicycle | 0.0 | 0.8 | 0.3 | 0.4 |
| car | 0.0 | 1.0 | 0.5 | 0.8 |
| truck | 0.0 | 0.9 | 0.9 | 0.5 |
Cosine similarity
From The Dot Product, . The cosine similarity is
It is 1 for vectors pointing the same way, 0 for orthogonal ones and −1 for opposite ones, and it ignores length (by Cauchy–Schwarz from Inner Products it always lies in ). Length often reflects things like word frequency or text length rather than meaning, which is why cosine is the default. The cosine distance is .
If all vectors are normalized to length 1 first, cosine similarity is just the dot product, and for unit vectors the Euclidean distance carries the same information: . Most vector databases normalize once at insert time and then use plain dot products.
import numpy as np
names = ["cat", "dog", "horse", "bicycle", "car", "truck"]
E = np.array([[0.9, 0.0, 0.2, 0.4], [0.9, 0.0, 0.4, 0.5], [0.8, 0.3, 0.8, 0.7],
[0.0, 0.8, 0.3, 0.4], [0.0, 1.0, 0.5, 0.8], [0.0, 0.9, 0.9, 0.5]])
def cosine(u, v):
return float(u @ v / (np.linalg.norm(u) * np.linalg.norm(v)))
print("cos(cat, dog) =", round(cosine(E[0], E[1]), 4))
print("cos(cat, car) =", round(cosine(E[0], E[4]), 4))
print("cos(horse, car) =", round(cosine(E[2], E[4]), 4))
U = E / np.linalg.norm(E, axis=1, keepdims=True) # normalize rows once
S = U @ U.T # all pairwise cosines in one product
print("similarity matrix:")
for name, row in zip(names, S):
print(f" {name:8s}", " ".join(f"{x:5.2f}" for x in row))cos(cat, dog) = 0.9819
cos(cat, car) = 0.304
cos(horse, car) = 0.672
similarity matrix:
cat 1.00 0.98 0.85 0.23 0.30 0.28
dog 0.98 1.00 0.92 0.31 0.40 0.40
horse 0.85 0.92 1.00 0.59 0.67 0.72
bicycle 0.23 0.31 0.59 1.00 0.98 0.92
car 0.30 0.40 0.67 0.98 1.00 0.93
truck 0.28 0.40 0.72 0.92 0.93 1.00
The similarity matrix is a Gram matrix: symmetric and positive semidefinite, with ones on the diagonal.
Nearest neighbours
Search is "embed the query, then find the stored vectors with the highest cosine". With normalized rows in a matrix (), all scores come from a single matrix-vector product , then a top- selection:
import numpy as np
names = ["cat", "dog", "horse", "bicycle", "car", "truck"]
E = np.array([[0.9, 0.0, 0.2, 0.4], [0.9, 0.0, 0.4, 0.5], [0.8, 0.3, 0.8, 0.7],
[0.0, 0.8, 0.3, 0.4], [0.0, 1.0, 0.5, 0.8], [0.0, 0.9, 0.9, 0.5]])
U = E / np.linalg.norm(E, axis=1, keepdims=True)
def top_k(query, k=3):
q = query / np.linalg.norm(query)
scores = U @ q
idx = np.argsort(-scores)[:k]
return [(names[i], round(float(scores[i]), 3)) for i in idx]
print("query 'big fast animal':", top_k(np.array([0.8, 0.1, 0.9, 0.9])))
print("query 'small vehicle' :", top_k(np.array([0.0, 0.9, 0.1, 0.3])))
analogy = E[4] - E[3] + E[0] # car - bicycle + cat
print("car - bicycle + cat ->", top_k(analogy, 2))query 'big fast animal': [('horse', 0.983), ('dog', 0.919), ('cat', 0.832)]
query 'small vehicle' : [('bicycle', 0.967), ('car', 0.907), ('truck', 0.805)]
car - bicycle + cat -> [('dog', 0.966), ('horse', 0.948)]
The last line is a vector-arithmetic analogy, the famous "" pattern: the difference is roughly "bigger and faster", and adding it to cat lands nearest to dog. With real learned embeddings such analogies work only sometimes, but the arithmetic is the same.
Note: Exact search costs multiplications per query. For millions of vectors, vector databases use approximate nearest-neighbour indexes (HNSW graphs, IVF clustering, product quantization) that trade a little accuracy for a lot of speed (Vector Search).
Reducing dimension
Embeddings are often compressed before storage or plotted in 2D. Projecting onto the top principal directions (PCA, or a truncated SVD) keeps most of the geometry. Here two dimensions already separate animals from vehicles:
import numpy as np
names = ["cat", "dog", "horse", "bicycle", "car", "truck"]
E = np.array([[0.9, 0.0, 0.2, 0.4], [0.9, 0.0, 0.4, 0.5], [0.8, 0.3, 0.8, 0.7],
[0.0, 0.8, 0.3, 0.4], [0.0, 1.0, 0.5, 0.8], [0.0, 0.9, 0.9, 0.5]])
Ec = E - E.mean(axis=0)
U, s, Vt = np.linalg.svd(Ec, full_matrices=False)
coords = Ec @ Vt[:2].T
print("variance kept by 2 components:", round(float((s[:2]**2).sum() / (s**2).sum()), 4))
for n, (a, b) in zip(names, coords):
print(f"{n:8s} {abs(a):.3f} side {'A' if a > 0 else 'B'} second coord {b:+.3f}")variance kept by 2 components: 0.9602
cat 0.734 side B second coord -0.227
dog 0.695 side B second coord -0.013
horse 0.341 side B second coord +0.397
bicycle 0.467 side A second coord -0.352
car 0.664 side A second coord -0.033
truck 0.638 side A second coord +0.228
(The sign of a principal component is arbitrary, so we report which side of 0 each item falls on.)
In software
- Semantic search and RAG. Documents are chunked, embedded and stored; a question is embedded and its nearest chunks are pasted into the LLM prompt (Embeddings, RAG).
- Recommendation. Users and items get embeddings; the score of an item for a user is a dot product (the mini project builds one with SVD).
- Deduplication and clustering. Near-duplicate detection is "cosine above 0.95"; k-means on normalized embeddings groups topics.
- Inside LLMs. The first layer is an embedding lookup (a row of a matrix), and attention scores are scaled dot products between token vectors.
Exercises
Exercise 1: Cosine by hand
Compute the cosine similarity of and .
Answer
.
Solution
, , , so .
Exercise 2: Length does not matter
Show that , and say what happens for .
Answer
Positive scaling cancels; .
Solution
.
Exercise 3: Distance and cosine
Two unit vectors have cosine similarity 0.8. What is their Euclidean distance?
Answer
.
Solution
.
Exercise 4: Rank documents (code)
Three documents have embeddings , , . Rank them for the query .
Answer
(0.9487), then (0.6325), then (0.3162).
Solution
All documents have length and , so the ranking follows the dot products 3, 2, 1 for , , .
import numpy as np
D = np.array([[1, 0, 1], [0, 1, 1], [1, 1, 0]], dtype=float)
q = np.array([2.0, 1.0, 0.0])
s = D @ q / (np.linalg.norm(D, axis=1) * np.linalg.norm(q))
print(np.round(s, 4), "order:", [f"d{i + 1}" for i in np.argsort(-s)])[0.6325 0.3162 0.9487] order: ['d3', 'd1', 'd2']
Test yourself
Cosine similarity of two vectors pointing in exactly opposite directions is…
- 0
- 1
- −1
- undefined
Why do vector databases often normalize embeddings when inserting them?
- To save disk space
- So cosine similarity becomes a plain dot product
- Because embeddings must be integers
- To make them orthogonal
With all embeddings normalized as rows of U, how do you get all pairwise cosine similarities at once?