開始使用免費開始

產品推薦系統

在這個練習中,你將為一家販售多樣商品的線上零售商打造一套推薦系統。當使用者瀏覽了產品頁但未購買時,系統會根據他最後瀏覽的產品,推薦 3 個相似的商品。

你已獲得網站可用產品的字典清單:

products = [
    {
        "title": "Smartphone X1",
        "short_description": "The latest flagship smartphone with AI-powered features and 5G connectivity.",
        "price": 799.99,
        "category": "Electronics",
        "features": [
            "6.5-inch AMOLED display",
            ...
            "Fast wireless charging"
        ]
    },
    ...
]

以及使用者最後瀏覽產品的字典,已存於 last_product

課程先前定義的下列自訂函式也可供你使用:

  • create_embeddings(texts) → 回傳 texts 中每個文字的嵌入向量(embedding)清單。
  • create_product_text(product) → 將 product 的各項特徵合併為單一字串以供嵌入。
  • find_n_closest(query_vector, embeddings, n=3) → 依餘弦距離,回傳 query_vectorembeddings 之間最接近的 n 個距離與其索引。

本練習屬於課程

Introduction to Embeddings with the OpenAI API

檢視課程

練習說明

  • 使用 create_product_text(),將 last_product 的文字特徵合併,並對 products 中的每個產品也進行合併。
  • 使用 create_embeddings()last_product_textproduct_texts 進行嵌入,並確保 last_product_embeddings 為單一串列。
  • 使用 find_n_closest() 找出最小的 3 個餘弦距離及其索引。

動手互動練習

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

# Combine the features for last_product and each product in products
last_product_text = ____
product_texts = ____

# Embed last_product_text and product_texts
last_product_embeddings = ____
product_embeddings = ____

# Find the three smallest cosine distances and their indexes
hits = ____(____, product_embeddings)

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