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
- The three closest to row 0 are rows 0, 1, 4
- A query near the 'car' row ranks row 3 first
- Vector length does not matter (cosine)
- It returns a plain list of Python ints
- The embeddings are not changed
- 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.
Output
Press Run to see what your program prints.