1. Learn
  2. /
  3. Courses
  4. /
  5. Introduction to Embeddings with the OpenAI API

Connected

Exercise

Sorting by similarity

Now that you've embedded all of your features, the next step is to compute the similarities. In this exercise, you'll define a function called find_n_closest(), which computes the cosine distances between a query vector and a list of embeddings and returns the n smallest distances and their indexes.

In the next exercise, you'll use this function to enable your semantic product search application.

distance has been imported from scipy.spatial.

Instructions

100 XP
  • Calculate the cosine distance between the query_vector and embedding.
  • Append a dictionary containing dist and its index to the distances list.
  • Sort the distances list by the 'distance' key of each dictionary.
  • Return the first n elements in distances_sorted.