依相似度排序
現在你已經為所有特徵建立了嵌入向量(embedding),下一步是計算相似度。在本練習中,你將定義一個名為 find_n_closest() 的函式,用來計算查詢向量與一組嵌入向量之間的 cosine 距離,並回傳距離最小的 n 個值及其索引。
在下一個練習中,你會使用這個函式來建立語意產品搜尋應用。
distance 已從 scipy.spatial 匯入。
本練習屬於課程
Introduction to Embeddings with the OpenAI API
練習說明
- 計算
query_vector與embedding的 cosine 距離。 - 將包含
dist與其index的字典加入distances清單。 - 依每個字典的
'distance'鍵排序distances清單。 - 回傳
distances_sorted的前n個元素。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def find_n_closest(query_vector, embeddings, n=3):
distances = []
for index, embedding in enumerate(embeddings):
# Calculate the cosine distance between the query vector and embedding
dist = ____
# Append the distance and index to distances
distances.append({"distance": ____, "index": ____})
# Sort distances by the distance key
distances_sorted = ____
# Return the first n elements in distances_sorted
return ____