← Math
Math

Similarity and distance

Does the mix find listeners like you, or listeners who listen as much?

Choose a vector comparison that matches the meaning of “listeners like you”.

Outcome

Say which question distance and cosine each answer, relate them on unit vectors, handle a listener with no plays, and check that the index returns the ranking the promise needs.

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).

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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);
}
Which candidate should the taste mix choose?

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.

What a vector index ranks by
MetricVectors storedRanks by
l2raw minutessimilar volume and mix together
ipraw minuteswhoever listens most in shared genres
l2unit vectorstaste (same order as cosine)
ipunit vectorstaste (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

The index uses ip on raw minutes. A rock-heavy listener plays (200, 10). Where do they rank for the seed (40, 30)?

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.

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.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// "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
Two unit vectors have cosine 0.5. What is the distance between them?
Why does a normalising index skip all-zero vectors?
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.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.