开始使用免费开始使用

评论情感分类

现在您已经计算好了嵌入向量,接下来要计算余弦距离并提取最相似的标签。

您将定义一个名为 find_closest() 的函数,用于将一个向量的嵌入与多个其他向量进行比较,并返回最近的距离及其索引。随后,您会遍历所有评论,并使用 find_closest() 为每条评论找到最近的距离,再根据该索引提取分类后的标签。

上一练习中创建的 class_embeddingsreview_embeddings 已可直接使用,同时还提供了 reviewssentiments

本练习是课程的一部分

使用 OpenAI API 的 Embeddings 入门

查看课程

练习说明

  • 定义函数 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}')
编辑并运行代码