开始使用免费开始使用

产品推荐系统

在本练习中,您将为一家销售多种商品的在线零售商构建一个推荐系统。该系统会基于用户最后浏览但未购买的商品,为其推荐 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 中每个文本对应的嵌入向量列表。
  • create_product_text(product) → 将 product 的各项特征合并为一个用于嵌入的字符串。
  • find_n_closest(query_vector, embeddings, n=3) → 基于余弦距离,返回 query_vectorembeddings 之间距离最小的 n 个值及其索引。

本练习是课程的一部分

使用 OpenAI API 的 Embeddings 入门

查看课程

练习说明

  • 使用 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'])
编辑并运行代码