AI & prompting

Cosine Similarity Explained (with Worked Python Examples)

Cosine similarity is the cosine of the angle between two vectors: the dot product divided by the product of their lengths. It runs from 1 (same direction) through 0 (unrelated) to -1 (opposite), and because it ignores length, it compares what two vectors point at rather than how big they are.

cosine_similarity(a, b) = (a · b) / (|a| × |b|)

It is the standard way to compare text embeddings in semantic search and RAG. If you're new to embeddings themselves, start with what are embeddings; this article is about the measure.

A worked example by hand

Take two 2-dimensional vectors, a = [3, 4] and c = [4, 3].

  1. Dot product: multiply matching entries and add them. 3 × 4 + 4 × 3 = 24.
  2. Lengths: |a| = √(3² + 4²) = √25 = 5. |c| = √(4² + 3²) = 5.
  3. Divide: 24 / (5 × 5) = 0.96.

A cosine of 0.96 corresponds to an angle of about 16 degrees: the two vectors point in nearly the same direction.

The same calculation in Python

import math

def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))

def euclidean(a, b):
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

a = [3, 4]
for v in ([6, 8], [4, 3], [4, -3], [-3, -4]):
    print(v, round(cosine(a, v), 4), round(euclidean(a, v), 4))

Output (Python 3.12):

[6, 8] 1.0 5.0
[4, 3] 0.96 1.4142
[4, -3] 0.0 7.0711
[-3, -4] -1.0 10.0

The table below reads those rows together with the plain dot product of each pair:

Compared with a = [3, 4]Cosine similarityEuclidean distanceDot productWhat it shows
[6, 8]1.05.050Same direction, twice as long. Cosine says identical; distance says far apart.
[4, 3]0.961.414224Slightly different direction, same length.
[4, -3]0.07.07110Perpendicular: no shared direction.
[-3, -4]-1.010.0-25Exactly opposite.

The first row is the whole point of cosine similarity. [6, 8] is just [3, 4] scaled up, and cosine treats them as identical, while Euclidean distance puts them 5 units apart. SciPy's documentation shows the same property: the cosine distance between [1, 0, 0] and [0, 1, 0] is 1.0, and so is the distance between [100, 0, 0] and [0, 1, 0]. Scale doesn't matter.

Why ignoring length is useful for text

A quick way to see this without an embedding model is to count words. Each sentence becomes a vector with one entry per vocabulary word:

from collections import Counter

docs = {
    "A": "the cat sat on the mat",
    "B": "the cat lay on the rug",
    "C": "stock prices fell sharply today",
}
vocab = sorted(set(" ".join(docs.values()).split()))
vec = {k: [Counter(v.split())[w] for w in vocab] for k, v in docs.items()}
print(round(cosine(vec["A"], vec["B"]), 4), round(cosine(vec["A"], vec["C"]), 4))

Output:

0.75 0.0

A and B share "the" (twice each), "cat" and "on", giving 0.75. A and C share no words, giving exactly 0. If you pasted sentence A ten times into one document, its counts would all multiply by ten but its cosine similarity to B would stay 0.75. Longer documents don't automatically look more similar, which is what you want when comparing a short query with long passages.

Word counts can't tell that "cat" and "kitten" are related, which is why real systems use embeddings. An embedding model maps text to a vector where related meanings point in similar directions, and cosine similarity is then computed exactly as above, only over hundreds or thousands of dimensions. OpenAI's text-embedding-3-small returns 1,536 numbers per text by default and text-embedding-3-large returns 3,072.

Cosine similarity vs dot product vs Euclidean distance

For vectors of length 1 (unit vectors), the three measures agree on ranking. Divide a and c by their length of 5 and you get [0.6, 0.8] and [0.8, 0.6]. Their dot product is 0.48 + 0.48 = 0.96, the same as the cosine similarity, because the denominator is now 1 × 1. For unit vectors, squared Euclidean distance is also tied to cosine by a fixed formula:

|u - v|² = 2 - 2 × cosine(u, v)

For our pair: 2 - 2 × 0.96 = 0.08, and computing the squared distance between [0.6, 0.8] and [0.8, 0.6] directly gives 0.04 + 0.04 = 0.08. Higher cosine always means smaller distance, so sorting by either gives the same order.

This is why OpenAI's embeddings guide says the choice of distance function "typically doesn't matter much". Its embeddings are normalised to length 1, so cosine similarity can be computed slightly faster with just a dot product, and cosine similarity and Euclidean distance give identical rankings. scikit-learn's documentation makes the same point from the other side: on L2-normalised data, its cosine_similarity is equivalent to a plain dot product (linear_kernel).

If your vectors are not normalised, the measures disagree, as the [6, 8] row shows. Either normalise them first or use cosine similarity explicitly.

Computing it with NumPy, scikit-learn or SciPy

import numpy as np
a = np.array([3, 4], dtype=float)
c = np.array([4, 3], dtype=float)
print(a @ c / (np.linalg.norm(a) * np.linalg.norm(c)))   # 0.96
  • scikit-learn: sklearn.metrics.pairwise.cosine_similarity(X, Y) takes two lists of vectors and returns a matrix with one row per vector in X and one column per vector in Y.
  • SciPy: scipy.spatial.distance.cosine(u, v) returns the cosine distance, 1 minus the similarity. By that formula, [3, 4] and [4, 3] give 1 - 0.96 = 0.04, not 0.96. Mixing the two up reverses your search results.
  • Vector databases usually let you choose cosine, dot product or Euclidean when you create an index. With normalised embeddings, any of the three ranks results the same way. See what is a vector database.

Pitfalls

  • Zero vectors. A vector of all zeros has no direction, and the formula divides by zero. The plain Python function above raises ZeroDivisionError. scikit-learn returns 0 for such pairs: its documented example compares [0, 0, 0] with other vectors and gets 0. Decide what your code should do, for example when an empty document is embedded.
  • Scores aren't comparable across models. 0.8 from one embedding model doesn't mean the same as 0.8 from another. Re-tune any threshold when you switch.
  • Don't compare vectors from different models. An embedding from model A and one from model B live in different spaces, even when they have the same number of dimensions. The cosine between them is meaningless. Re-embed everything when you change models.
  • High similarity isn't relevance. Two passages can be close in meaning and still not answer the question. In RAG, retrieval quality also depends on how documents were split; see chunking documents for RAG.

Frequently asked questions

What is a good cosine similarity score?
There is no universal threshold. Typical scores for related and unrelated texts differ from one embedding model to another. Pick a cutoff by testing on pairs from your own data that you have labelled as related or unrelated, and re-test whenever you change models.
Can cosine similarity be negative?
Yes. It ranges from -1 (vectors pointing in opposite directions) through 0 (perpendicular, no shared direction) to 1 (same direction). With word-count vectors, which have no negative entries, it can't go below 0. With embeddings, whose entries can be negative, it can.
What is the difference between cosine similarity and cosine distance?
Cosine distance is 1 minus cosine similarity. SciPy's scipy.spatial.distance.cosine returns the distance, so identical directions give 0 and perpendicular vectors give 1. Check which one a library returns before sorting results, because the order is reversed.
Is cosine similarity the same as the dot product?
Only when both vectors have length 1. Cosine similarity is the dot product divided by the two lengths. OpenAI's embeddings are already normalised to length 1, so for them the dot product gives the same number and is slightly cheaper to compute.

Sources