TExcelTAD
Home › Linear Algebra & Matrix Theory › Embeddings and Cosine Similarity

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, u⋅v=∥u∥∥v∥cos⁡θ\mathbf{u} \cdot \mathbf{v} = \lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert \cos \theta. The cosine similarity is

cos⁡(u,v)=u⋅v∥u∥∥v∥∈[−1,1]\cos(\mathbf{u}, \mathbf{v}) = \frac{\mathbf{u} \cdot \mathbf{v}}{\lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert} \in [-1, 1]

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 [−1,1][-1, 1]). Length often reflects things like word frequency or text length rather than meaning, which is why cosine is the default. The cosine distance is 1−cos⁡1 - \cos.

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: ∥u−v∥2=2−2 u⋅v\lVert \mathbf{u} - \mathbf{v} \rVert^2 = 2 - 2\, \mathbf{u} \cdot \mathbf{v}. Most vector databases normalize once at insert time and then use plain dot products.

python · try it yourself
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 S=UUTS = UU^T 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 UU (N×dN \times d), all NN scores come from a single matrix-vector product UqU\mathbf{q}, then a top-kk selection:

python · try it yourself
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 "king−man+woman≈queen\text{king} - \text{man} + \text{woman} \approx \text{queen}" pattern: the difference car−bicycle\text{car} - \text{bicycle} 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 N⋅dN \cdot d 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:

python · try it yourself
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 vocab×d\text{vocab} \times d matrix), and attention scores are scaled dot products between token vectors.

Exercises

Exercise 1: Cosine by hand

Compute the cosine similarity of u=(1,2,2)\mathbf{u} = (1, 2, 2) and v=(2,0,1)\mathbf{v} = (2, 0, 1).

Answer

435≈0.5963\frac{4}{3\sqrt{5}} \approx 0.5963.

Solution

u⋅v=2+0+2=4\mathbf{u} \cdot \mathbf{v} = 2 + 0 + 2 = 4, ∥u∥=3\lVert \mathbf{u} \rVert = 3, ∥v∥=5\lVert \mathbf{v} \rVert = \sqrt{5}, so cos⁡=435≈0.5963\cos = \frac{4}{3\sqrt{5}} \approx 0.5963.

Exercise 2: Length does not matter

Show that cos⁡(3u,v)=cos⁡(u,v)\cos(3\mathbf{u}, \mathbf{v}) = \cos(\mathbf{u}, \mathbf{v}), and say what happens for −u-\mathbf{u}.

Answer

Positive scaling cancels; cos⁡(−u,v)=−cos⁡(u,v)\cos(-\mathbf{u}, \mathbf{v}) = -\cos(\mathbf{u}, \mathbf{v}).

Solution

cos⁡(cu,v)=c(u⋅v)∣c∣∥u∥∥v∥=sign⁡(c)⋅cos⁡(u,v)\cos(c\mathbf{u}, \mathbf{v}) = \frac{c(\mathbf{u} \cdot \mathbf{v})}{\lvert c \rvert \lVert \mathbf{u} \rVert \lVert \mathbf{v} \rVert} = \operatorname{sign}(c) \cdot \cos(\mathbf{u}, \mathbf{v}).

Exercise 3: Distance and cosine

Two unit vectors have cosine similarity 0.8. What is their Euclidean distance?

Answer

0.4≈0.6325\sqrt{0.4} \approx 0.6325.

Solution

∥u−v∥2=∥u∥2+∥v∥2−2u⋅v=2−1.6=0.4\lVert \mathbf{u} - \mathbf{v} \rVert^2 = \lVert \mathbf{u} \rVert^2 + \lVert \mathbf{v} \rVert^2 - 2\mathbf{u} \cdot \mathbf{v} = 2 - 1.6 = 0.4.

Exercise 4: Rank documents (code)

Three documents have embeddings d1=(1,0,1)\mathbf{d}_1 = (1, 0, 1), d2=(0,1,1)\mathbf{d}_2 = (0, 1, 1), d3=(1,1,0)\mathbf{d}_3 = (1, 1, 0). Rank them for the query q=(2,1,0)\mathbf{q} = (2, 1, 0).

Answer

d3\mathbf{d}_3 (0.9487), then d1\mathbf{d}_1 (0.6325), then d2\mathbf{d}_2 (0.3162).

Solution

All documents have length 2\sqrt{2} and ∥q∥=5\lVert \mathbf{q} \rVert = \sqrt{5}, so the ranking follows the dot products 3, 2, 1 for d3\mathbf{d}_3, d1\mathbf{d}_1, d2\mathbf{d}_2.

python · try it yourself
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…

  1. 0
  2. 1
  3. −1
  4. undefined

Why do vector databases often normalize embeddings when inserting them?

  1. To save disk space
  2. So cosine similarity becomes a plain dot product
  3. Because embeddings must be integers
  4. To make them orthogonal

With all embeddings normalized as rows of U, how do you get all pairwise cosine similarities at once?

  1. UTUU^T U
  2. UUTUU^T
  3. U+UTU + U^T
  4. U−1U^{-1}