開始使用免費開始

將使用者歷史加入推薦引擎

在許多推薦情境(例如電影或購物推薦)中,只根據單一資料點來產生下一次推薦通常不夠充分。這些情況下,你需要為使用者的全部或部分歷史紀錄建立嵌入向量(embedding),才能得到更精準、也更相關的推薦。

在本練習中,你會擴充產品推薦系統,將使用者先前瀏覽過的所有產品納入考量。這些產品以字典所組成的清單 user_history 儲存。

你可以使用以下自訂函式:create_embeddings(texts)create_product_text(product)、以及 find_n_closest(query_vector, embeddings, n=3)numpy 也已匯入為 np

本練習屬於課程

Introduction to Embeddings with the OpenAI API

檢視課程

練習說明

  • user_history 中每個產品的文字特徵合併、對合併後的字串建立嵌入向量,並使用 numpy 計算其平均嵌入向量。
  • 將出現在 user_history 的產品自 products 中過濾移除。
  • products_filtered 中每個產品的特徵合併,並對合併後的字串建立嵌入向量。

動手互動練習

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

# Prepare and embed the user_history, and calculate the mean embeddings
history_texts = [____ for article in user_history]
history_embeddings = ____
mean_history_embeddings = ____

# Filter products to remove any in user_history
products_filtered = ____

# Combine product features and embed the resulting texts
product_texts = ____
product_embeddings = ____

hits = find_n_closest(mean_history_embeddings, product_embeddings)

for hit in hits:
  product = products_filtered[hit['index']]
  print(product['title'])
編輯並執行程式碼