1. Learn
  2. /
  3. 课程
  4. /
  5. 使用 OpenAI API 的 Embeddings 入门

Connected

道练习

产品推荐系统

在本练习中,您将为一家销售多种商品的在线零售商构建一个推荐系统。该系统会基于用户最后浏览但未购买的商品,为其推荐 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_vector 与 embeddings 之间距离最小的 n 个值及其索引。

说明

100 XP
  • 使用 create_product_text() 合并 last_product 的文本特征,并对 products 中的每个产品执行相同操作。
  • 使用 create_embeddings() 对 last_product_text 和 product_texts 进行嵌入,确保 last_product_embeddings 为单个列表。
  • 使用 find_n_closest() 找到最小的 3 个余弦距离及其索引。