Embeddings and cosine similarity
Embeddings represent objects as vectors
An embedding is a numerical representation of an input such as a sentence, image or document. A dense text embedding usually contains many real-valued coordinates, not one coordinate per vocabulary word. A trained encoder maps inputs to a space in which its training objective encourages useful relationships. These relationships are imperfect: a high score need not mean factual agreement, relevance or identical meaning. Unlike a generative model that produces new tokens, an embedding interface returns vectors; some architectures can support both tasks with different heads. Here we use invented two-dimensional vectors, not a learned encoder. The vector [1, 0] and [1, 1] have dot product 1, cosine 1/sqrt(2), and Euclidean distance 1.
import math
def measures(a, b): # Teaching domain: nonempty integer vectors, entries at most 1000. if not a or len(a) != len(b): raise ValueError("equal positive dimensions required") if any(type(x) is not int or abs(x) > 1000 for x in (*a, *b)): raise ValueError("bounded integer entries required") aa = sum(x*x for x in a) bb = sum(y*y for y in b) if aa == 0 or bb == 0: raise ValueError("cosine undefined for zero norm") dot = sum(x*y for x, y in zip(a, b)) distance = math.sqrt(sum((x-y)**2 for x, y in zip(a, b))) return dot, dot / math.sqrt(aa*bb), distance
for b in ([1, 1], [3, 0], [-1, 0]): dot, cosine, distance = measures([1, 0], b) print(f"{dot} {cosine:.3f} {distance:.3f}")Calculate three different measures
For equal-length vectors a and b, the dot product is the sum of corresponding products. Their L2 norms are square roots of sums of squared coordinates. Cosine divides the dot by the product of those norms; the mathematical range is -1 to 1 for nonzero vectors. Euclidean distance is the square root of the sum of squared differences and is nonnegative. Larger cosine or dot scores indicate more similarity under those respective rules; smaller distance means closer. In the example [3, 0] has cosine 1 but distance 2, whereas [1, 1] has cosine about 0.707 but distance 1. Thus cosine prefers the same direction while Euclidean distance prefers [1, 1]. Opposite directions yield cosine -1. Zero vectors have no defined cosine; this example rejects them rather than manufacturing a zero score. Dot and distance alone could still be computed for zero vectors. Python floats approximate real arithmetic, so round only for display. The input bound keeps the teaching example numerically simple.
Normalization and deterministic ranking
L2 normalization divides each coordinate by its vector norm. A unit vector has norm 1. For unit vectors u and v, dot(u,v) equals cosine(u,v), and squared Euclidean distance equals 2 - 2dot(u,v); hence the three give the same mathematical ordering (with distance ascending). Without normalization they may disagree. Choose the measure recommended for the encoder and verified for the task; normalizing can discard useful magnitude information. For integer fixtures, we can rank cosine without floating-point ties: with fixed nonzero query q, write d = dot(q,v) and s = dot(v,v). The signed square dabs(d)/s is a strictly increasing transformation of cosine up to a shared positive query factor. Fractions compare it exactly, even for negative values. Sort descending by this key, then ascending by unique document ID. The output is a, b, d, c: the first two are tied despite different lengths. This exact rational method is for bounded teaching fixtures, not a general production float index.
from fractions import Fraction
def rank_cosine(query, records): # Nonzero, equal-length bounded integer vectors; unique string IDs. def checked(v): if (not v or len(v) != len(query) or any(type(x) is not int or abs(x) > 1000 for x in v) or not any(v)): raise ValueError("invalid vector") return sum(x*x for x in v) checked(query) seen = set() scores = [] for key, vector in records: if not isinstance(key, str) or not key or key in seen: raise ValueError("unique nonempty string IDs required") seen.add(key) norm2 = checked(vector) dot = sum(x*y for x, y in zip(query, vector)) # Signed square is monotonic in cosine; query norm is constant. signed = Fraction(dot*abs(dot), norm2) scores.append((key, signed)) return [key for key, _ in sorted(scores, key=lambda row: (-row[1], row[0]))]
records = [("b", [1, 0]), ("a", [3, 0]), ("c", [-1, 0]), ("d", [1, 1])]print(rank_cosine([1, 0], records))Common mistakes
Do not sort cosine distance or Euclidean distance in descending order by accident. Do not rank cosine by the unsigned squared dot: opposite vectors would look identical. Check dimensions before using zip, which otherwise silently truncates. A cosine score of 0.8 is not an 80 percent probability of relevance; choose any threshold using labeled validation examples for that model and task. Avoid rounding scores before ranking. Reject invalid or zero vectors explicitly; a library may define a zero-vector convention that differs from this lesson. In a real system consider finite-number checks, overflow-safe normalization, approximate floating-point ties and consistent deterministic secondary keys.
Practice and next step
Calculate all three measures for [1, 0] versus [0, 1] and [2, 0] (answers: dot 0, cosine 0, distance sqrt(2); dot 2, cosine 1, distance 1). Reverse the record input order and verify identical ranks. Add an opposite-direction vector and a zero vector separately; the former ranks last and the latter is rejected. Then explain why dimension equality is necessary but not sufficient before comparing embeddings. The next lesson establishes that contract.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Embeddings and cosine similarity quiz
Apply embedding similarity and retrieval contracts.
What does a dense text embedding represent?
What is cosine for [1,0] and [1,1]?
Which statement about unit vectors is correct?
What should the example do with a zero vector?
Why use signed rather than unsigned squared dot in the integer ranking?