Command Palette

Search for a command to run...

Hectal
Phase 14: Working with Data: NumPy and pandas
Python · Exercise 3 of 6 PreviousNext
Intermediate

Find the most similar items

Write top_k(embeddings, query, k). embeddings is a 2-D array with one item per row (each row is that item's embedding, a list of numbers describing it). query is a 1-D vector. Return a plain Python list of the row numbers of the k rows most similar to the query, best first. For the example below it should print [0, 1, 4].

"Most similar" means the highest cosine similarity (how closely two vectors point the same way, Topic 14.5). The plan: divide every row and the query by their lengths, use @ to get one score per row, then np.argsort to put the best first.

What Check tests

  1. The three closest to row 0 are rows 0, 1, 4
  2. A query near the 'car' row ranks row 3 first
  3. Vector length does not matter (cosine)
  4. It returns a plain list of Python ints
  5. The embeddings are not changed
  6. It returns exactly k items

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.