開始使用免費開始

評論情感分類

你已經算出嵌入向量,接下來要計算 cosine 距離並取出最相近的標籤。

你會定義一個名為 find_closest() 的函式,用來比較一個向量與多個向量之間的嵌入向量,並回傳最近的距離及其索引。然後你會迴圈遍歷所有評論,使用 find_closest() 找出每則評論最接近的距離,並用該索引取出分類後的標籤。

上一個練習建立的 class_embeddingsreview_embeddings 物件都可供你使用,reviewssentiments 也已備妥。

本練習屬於課程

Introduction to Embeddings with the OpenAI API

檢視課程

練習說明

  • 定義名為 find_closest() 的函式,回傳與 query_vector 最相似之嵌入向量的距離與索引。
  • 使用 find_closest() 找出每個評論的嵌入向量與 class_embeddings 之間最接近的距離。
  • 使用 closest'index' 來子集 sentiments,並取出 'label'

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Define a function to return the minimum distance and its index
def find_closest(query_vector, embeddings):
  distances = []
  for index, embedding in enumerate(embeddings):
    dist = distance.cosine(____, ____)
    distances.append({"distance": dist, "index": index})
  return ____(distances, key=lambda x: x["distance"])

for index, review in enumerate(reviews):
  # Find the closest distance and its index using find_closest()
  closest = ____(review_embeddings[____], ____)
  # Subset sentiments using the index from closest
  label = ____
  print(f'"{review}" was classified as {label}')
編輯並執行程式碼