Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Euclidean distance
- The straight-line distance √Σ(aᵢ − bᵢ)²; it grows with differences in size as well as direction.
- Cosine similarity
- a · b ÷ (‖a‖ ‖b‖): how closely two vectors point the same way, ignoring their lengths.
- Unit vector
- A vector divided by its length, so its length is 1; on unit vectors ‖â − b̂‖² = 2 − 2 cos θ.
- Vector index
- A database structure that returns the nearest stored vectors to a query under a configured metric, such as pgvector or FAISS.
- Inner product metric Also ip
- Ranking by the largest dot product; on unit vectors it is the same as ranking by cosine.
Why this matters
A recommendation, search or deduplication feature often asks “which stored vectors are nearest?”. Nearest depends on the metric, and the metric is often a setting on a vector index chosen once and forgotten. Pick the one that answers the product’s question, and make sure the index stores vectors the way that metric needs.
This lesson assumes vectors, dot products and square roots.
What nearest means
Distance asks how far apart two profiles are, counting every minute. Cosine asks whether they point the same way: the same mix of genres, whatever the total. Euclidean distance takes the square root of the sum of squared component differences, so differences in each genre contribute to the result.
A vector index ranks stored profiles against a query using its configured measure. The metric and the representation must answer the same product question: raw minutes preserve listening volume, while a direction comparison focuses on proportions.
01Two questions, two measures
Two questions, two measures
A music app’s weekly “listeners like you” mix finds neighbours for each listener from their minutes per genre. The neighbour search runs in a vector index. In testing, a listener who plays rock and jazz in a 4 to 3 ratio got a mix built from people who play similar minutes in individual genres, and a listener with no plays appeared as a possible neighbour.
The two-genre probe isolates the ranking before we inspect the index configuration. Predict what this program prints for the seed (40, 30).
const seed = [40, 30]; // weekly minutes of rock and jazz
const others: [string, number[]][] = [
["heavy", [80, 60]],
["near", [30, 40]],
["newbie", [0, 0]]
];
const dot = (a: number[], b: number[]) => a.reduce((sum, x, i) => sum + x * b[i]!, 0);
for (const [id, v] of others) {
const distance = Math.hypot(...seed.map((x, i) => x - v[i]!));
const cosine =
dot(v, v) === 0
? "none"
: (dot(seed, v) / Math.sqrt(dot(seed, seed) * dot(v, v))).toFixed(3);
console.log(id, distance.toFixed(1), cosine);
}
02On unit vectors they agree
On unit vectors they agree
Raw distance selected the wrong neighbour for this promise. To preserve a distance-based search, divide each nonzero profile by its length. Expand the squared distance: (â − b̂) · (â − b̂) = â · â + b̂ · b̂ − 2â · b̂ = 1 + 1 − 2 cos θ. Thus ‖â − b̂‖² = 2 − 2 cos θ: the closer the directions, the smaller the distance, and ranking by distance is ranking by cosine. The heavy listener’s unit distance from the seed is 0; near’s is √(2 − 1.92) = 0.283.
03No plays, no direction
No plays, no direction
A listener with no plays this week has the profile (0, 0). Its length is 0, so cosine divides by zero and has no value, and it cannot be normalised. On raw distance it sits 50 from the seed, exactly as close as the heavy listener, so a distance ranking can include it despite having no evidence of taste. Skip zero profiles for a taste comparison. If the seed is zero, offer a general mix until there is listening history.
04The index decides
The index decides
The unit-vector identity gives us a configuration check: normalise stored profiles and queries, then either L2 or inner product can rank by taste. A normalising index must skip zero profiles. The lab models exact rankings; an approximate index can also miss neighbours, which this calculation does not assess.
| Metric | Vectors stored | Ranks by |
|---|---|---|
| l2 | raw minutes | similar volume and mix together |
| ip | raw minutes | whoever listens most in shared genres |
| l2 | unit vectors | taste (same order as cosine) |
| ip | unit vectors | taste (equal to cosine) |
With pgvector, the SQL operator picks the metric: <-> is L2 distance, <#> negative inner product and <=> cosine distance, and the index must use the matching operator class.
05Match the metric to the promise
Match the metric to the promise
06Build the listener mix
Build the listener mix
First repair the profile comparison. Then use it to select a taste neighbour and report the distance between unit vectors. Finally audit the index’s actual top results against that taste ranking, including raw settings that deliberately disagree.
A listeners-like-you mix
Distance and cosine, the nearest by taste, then what the index returns.
In the frontend “Fans also like” in Next.js and Svelte Optional
An artist page can rank related artists in the browser: normalise each vector, take the dot product, and leave out artists with no listening yet.
// "Fans also like" on an artist page: rank by cosine on normalised vectors, skip empty ones.
type Artist = { name: string; vector: number[] };
const norm = (v: number[]) => Math.sqrt(v.reduce((sum, x) => sum + x * x, 0));
const unit = (v: number[]) => v.map((x) => x / norm(v));
const dot = (a: number[], b: number[]) => a.reduce((sum, x, i) => sum + x * b[i]!, 0);
export function FansAlsoLike({ artist, others }: { artist: Artist; others: Artist[] }) {
if (norm(artist.vector) === 0) return null; // a new artist has no listening yet
const query = unit(artist.vector);
const similar = others
.filter((other) => norm(other.vector) > 0)
.map((other) => ({ other, score: dot(query, unit(other.vector)) }))
.sort((a, b) => b.score - a.score)
.slice(0, 5);
return (
<ul>
{similar.map(({ other }) => (
<li key={other.name}>{other.name}</li>
))}
</ul>
);
}
Check this idea later
Sources
Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The listeners and their profiles are a worked model.
Sign in to keep your read marks on every device. Sign in
Was this helpful?