v9.1.1
Menu

Embedding Nearest Neighbors

mediumFREEWord EmbeddingsNLP 1: Foundations

Find the k nearest neighbors of a query word in an embedding space using cosine similarity.

Implement nearest_neighbors(query, k, embeddings):

  • query: the query word (a string that is a key of embeddings)
  • k: the number of neighbors to return
  • embeddings: a dict mapping each word to its embedding vector (a list of floats; all vectors have the same length)

Output: Return a list of the k nearest words (excluding the query), sorted by descending cosine similarity to the query's vector.

Example

Input
cat 2
4
cat 0.9 0.1
dog 0.8 0.2
car 0.1 0.9
kitten 0.85 0.15
Output
['kitten', 'dog']
Reasoning
  • The inputs are a query word (cat), a count k = 2, and a vocabulary where every word owns a 2-dimensional vector. cat is (0.9,0.1)(0.9, 0.1).
  • Cosine similarity compares directions only: cos⁡(q,v)=q⋅v∥q∥ ∥v∥\cos(q, v) = \frac{q \cdot v}{\lVert q \rVert \, \lVert v \rVert}. Here ∥cat∥=0.82≈0.9055\lVert \text{cat} \rVert = \sqrt{0.82} \approx 0.9055.
  • dog (0.8,0.2)(0.8, 0.2): q⋅v=0.72+0.02=0.74q \cdot v = 0.72 + 0.02 = 0.74, ∥v∥=0.68≈0.8246\lVert v \rVert = \sqrt{0.68} \approx 0.8246, so cos⁡≈0.74/0.7467≈0.9910\cos \approx 0.74 / 0.7467 \approx 0.9910.
  • kitten (0.85,0.15)(0.85, 0.15): q⋅v=0.765+0.015=0.78q \cdot v = 0.765 + 0.015 = 0.78, ∥v∥=0.745≈0.8631\lVert v \rVert = \sqrt{0.745} \approx 0.8631, so cos⁡≈0.78/0.7816≈0.9980\cos \approx 0.78 / 0.7816 \approx 0.9980.
  • car (0.1,0.9)(0.1, 0.9): q⋅v=0.18q \cdot v = 0.18 and ∥v∥=0.9055\lVert v \rVert = 0.9055, so cos⁡=0.18/0.82≈0.2195\cos = 0.18 / 0.82 \approx 0.2195.
  • cat itself would score exactly 1, but the query is never its own neighbour. Ranking the rest gives kitten, dog, car; the top 2 yields ['kitten', 'dog'].
  • Notice that kitten and dog differ by under 0.007: cosine ignores vector length, so only the angle decides.

Constraints

  • Exclude the query word itself from results
  • Sort by cosine similarity (highest first)
  • k is always <= number of non-query words
  • Use cosine similarity

Learn this in

More from NLP 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.