Embedding Similarity: Top-K Retrieval and Evaluation
Machine LearningModel answerLast updated
Implement cosine-similarity ranking over a set of candidate embeddings, handle edge cases explicitly, and reason through how you would evaluate whether the results are actually useful.
Embedding Similarity: Top-K Retrieval and Evaluation
You are building a feature that surfaces related items to a user based on vector embeddings. Each item is represented as a dense numeric vector of fixed dimension d. Given a single query embedding and a collection of candidate embeddings (each paired with a unique identifier), your task is to return the top k most similar candidates using cosine similarity.
What You Are Expected to Do
- Clarify the setup — before writing code, ask the questions you would ask an interviewer to nail down the representation and success criteria.
- Implement
top_k_similar— a Python function with the signature below. Handle all edge cases explicitly; do not silently swallow them. - Discuss scaling — explain how your approach changes as the candidate set grows from thousands to hundreds of millions.
- Describe evaluation — explain how you would measure, offline and online, whether the similarity is actually good.
def top_k_similar(
query: list[float],
candidates: dict[str, list[float]],
k: int,
) -> list[tuple[str, float]]:
"""
Return the top-k candidates most similar to the query,
ranked by cosine similarity, descending.
Parameters
----------
query : 1-D numeric vector (the reference embedding)
candidates : mapping of unique id -> embedding vector
k : number of results to return
Returns
-------
List of (id, similarity_score) tuples, length min(k, eligible candidates),
sorted by score descending; ties broken alphabetically by id.
"""
Constraints and Edge-Case Rules
- All valid embeddings share the same dimension
d. - If the query embedding itself appears among the candidates (matched by value or by a special sentinel id), exclude it from results.
- Zero vectors: a zero-norm vector has undefined cosine similarity — return a score of
0.0for any such candidate, and if the query is a zero vector raise aValueError. - Missing or non-numeric values: skip any candidate whose vector contains
None,NaN, or non-numeric entries, but do not crash. - Dimension mismatch: skip candidates whose vector length differs from the query's.
- Invalid
k: raise aValueErrorfork ≤ 0; ifkexceeds the number of eligible candidates, return all eligible candidates. - Ties: break deterministically by candidate id, ascending alphabetically.
Clarifying Questions Worth Raising
Think about — and briefly address — the following before diving into code:
- What does the embedding encode? Visual appearance, behavioral co-engagement, text semantics, or a blend?
- Is "similar" defined by human judgment, by downstream click or save behavior, or both?
- How large is the candidate pool, and is exact nearest-neighbor search acceptable?
- What is the deployment latency budget, and does it affect whether retrieval must be approximate?
Hints
Hint 1
Cosine similarity is a dot product divided by the product of the two L2 norms. Compute each piece separately so you can catch the zero-norm case before dividing.
Hint 2
Sort a list of (score, id) tuples in a single pass using a compound sort key — primary: score descending, secondary: id ascending — rather than sorting twice.
Hint 3
For offline evaluation, think in two layers: does the ranked list match human or behavioral ground truth (NDCG, MRR, precision@k), and does the similarity generalize across meaningful slices (topic, modality, popularity tier)?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying Questions and Framing
Before writing a single line of code, a strong candidate establishes what the embedding actually encodes. If the vector captures visual style, cosine similarity in that space measures visual relatedness — which may be exactly right or completely wrong depending on the product goal. If the embedding was trained on co-engagement (users who interacted with both items), similarity means behavioral affinity, not appearance. This matters because a mismatch between the embedding space and the product definition of "similar" will produce a system that passes unit tests but fails in production.
Worth confirming up front: whether the candidate pool is thousands (exact search is fine) or hundreds of millions (approximate search is required), and whether there is a labeled evaluation set or only implicit behavioral signals.
Implementation
Core logic
Cosine similarity between vectors u and v is:
cos(u, v) = (u · v) / (||u|| * ||v||)
The key failure modes are a zero-norm vector (division by zero) and mismatched dimensions. Handle both explicitly.
import math
def top_k_similar(
query: list[float],
candidates: dict[str, list[float]],
k: int,
) -> list[tuple[str, float]]:
if k <= 0:
raise ValueError(f"k must be a positive integer, got {k}")
# Validate query
if not _is_valid_vector(query):
raise ValueError("Query contains missing or non-numeric values.")
query_norm = _l2_norm(query)
if query_norm == 0.0:
raise ValueError("Query is a zero vector; cosine similarity is undefined.")
d = len(query)
scored = []
for cid, vec in candidates.items():
# Skip malformed or mismatched candidates
if not _is_valid_vector(vec) or len(vec) != d:
continue
# Exclude the query itself if it appears in candidates
if vec == query:
continue
cand_norm = _l2_norm(vec)
if cand_norm == 0.0:
score = 0.0
else:
score = _dot(query, vec) / (query_norm * cand_norm)
scored.append((score, cid))
# Sort: score descending, id ascending for ties
scored.sort(key=lambda x: (-x[0], x[1]))
return [(cid, score) for score, cid in scored[:k]]
def _is_valid_vector(v) -> bool:
try:
for x in v:
if x is None or (isinstance(x, float) and math.isnan(x)):
return False
float(x) # catches non-numeric types
return len(v) > 0
except (TypeError, ValueError):
return False
def _l2_norm(v) -> float:
return math.sqrt(sum(x * x for x in v))
def _dot(a, b) -> float:
return sum(x * y for x, y in zip(a, b))
Complexity: O(n · d) time to score all candidates, O(n log n) to sort. Space is O(n) for the scored list.
Common mistakes
- Forgetting to normalize before the dot product, then returning raw dot products and calling them cosine similarities.
- Catching the zero-norm case after dividing (ZeroDivisionError) rather than before.
- Using a stable sort on score only and assuming tie order is deterministic — it is not across Python versions or platforms.
Scaling to Large Candidate Sets
Pure Python loops become the bottleneck well before the math does. The natural progression:
-
Vectorize with NumPy — represent all candidate vectors as an (n × d) matrix, pre-normalize each row to unit length, then the entire score computation is a single matrix–vector multiply. This is 50–200× faster than a Python loop for n in the tens of thousands.
-
Approximate nearest-neighbor (ANN) — at n ≥ 1M, even a vectorized exact search is too slow for real-time queries. Libraries like FAISS (IVF or HNSW indexes), ScaNN, or Annoy trade a small recall loss (typically 1–5% at the top-10 level) for sub-millisecond latency at scale. The right index type depends on d and the query-per-second requirement.
-
Pre-filtering — if items have categorical attributes (topic, language, format), a coarse filter before the ANN search reduces the effective n without touching recall for in-category queries.
Evaluation
Offline
You need a ground truth. Two common sources:
- Human labels: annotators rate pairs as relevant / not relevant. Compute NDCG@k or MRR against the ranked list. NDCG is preferable when relevance is graded rather than binary.
- Behavioral signals: treat a save, long dwell, or close-up interaction as a positive; a scroll-past as a weak negative. Compute precision@k or recall@k using held-out interactions.
Slice the results. Aggregate NDCG hides failures on rare topics, low-engagement items, or specific modalities. A model that looks fine overall may be poor for niche content where users have few behavioral signals.
Leakage check: if the embeddings were trained on engagement data, make sure the evaluation positives come from a time window after the embedding training cutoff. Using future interactions to train and past interactions to evaluate inverts causality.
Online
The offline metric is a proxy. The real question is whether surfacing similar items changes user behavior in the direction the product wants. A clean A/B test compares a control (e.g., popularity-based related items) to the embedding-based ranking on a metric like saves, follows, or session depth. Guardrail metrics — diversity of topics seen, time spent — prevent optimizing one number at the expense of user experience.
Diversity is a common follow-up: top-k by cosine similarity alone can return near-duplicate items from the same cluster. A reranking step (maximal marginal relevance or determinantal point processes) can balance relevance and variety.