探索向量空间

使用 OpenAI API 的 Embeddings 入门

Emmanuel Pire

Senior Software Engineer, DataCamp

示例:为标题生成嵌入

articles = [
    {"headline": "Economic Growth Continues Amid Global Uncertainty", "topic": "Business"},
    {"headline": "Interest rates fall to historic lows", "topic": "Business"},
    {"headline": "Scientists Make Breakthrough Discovery in Renewable Energy", "topic": "Science"},
    {"headline": "India Successfully Lands Near Moon's South Pole", "topic": "Science"},
    {"headline": "New Particle Discovered at CERN", "topic": "Science"},
    {"headline": "Tech Company Launches Innovative Product to Improve Online Accessibility", "topic": "Tech"},
    {"headline": "Tech Giant Buys 49% Stake In AI Startup", "topic": "Tech"},
    {"headline": "New Social Media Platform Has Everyone Talking!", "topic": "Tech"},
    {"headline": "The Blues get promoted on the final day of the season!", "topic": "Sport"},
    {"headline": "1.5 Billion Tune-in to the World Cup Final", "topic": "Sport"}
]
使用 OpenAI API 的 Embeddings 入门

示例:为标题生成嵌入

包含标题及其嵌入的字典列表。

使用 OpenAI API 的 Embeddings 入门

为多个输入生成嵌入

headline_text = [article['headline'] for article in articles]
headline_text
["Economic Growth Continues Amid Global Uncertainty",
 ...,
 "1.5 Billion Tune-in to the World Cup Final"]
response = client.embeddings.create(
  model="text-embedding-3-small",
  input=headline_text
)
response_dict = response.model_dump()
  • 批量处理比多次 API 调用更高效
使用 OpenAI API 的 Embeddings 入门
[...]

'data': [
    {
      "embedding": [-0.017142612487077713, ..., -0.0012911480152979493],
      "index": 0,
      "object": "embedding"
    },
    {
      "embedding": [-0.032995883375406265, ..., -0.0028605300467461348],
      "index": 1,
      "object": "embedding"
    },
    ...
  ]

[...]
使用 OpenAI API 的 Embeddings 入门

为多个输入生成嵌入

articles = [
    {"headline": "Economic Growth Continues Amid Global Uncertainty", "topic": "Business"},
     ...
]
for i, article in enumerate(articles):

article['embedding'] = response_dict['data'][i]['embedding']
print(articles[:2])
[{'headline': 'Economic Growth Continues Amid Global Uncertainty',
  'topic': 'Business',
  'embedding': [-0.017142612487077713, ..., -0.0012911480152979493]}
 {'headline': 'Interest rates fall to historic lows',
  'topic': 'Business',
  'embedding': [-0.032995883375406265, ..., -0.0028605300467461348]}]
使用 OpenAI API 的 Embeddings 入门

嵌入向量有多长?

  • "在全球不确定性中,经济增长持续"
len(articles[0]['embedding'])
1536
  • "科技公司推出创新产品以提升可访问性"
len(articles[5]['embedding'])
1536
  • 始终返回 1536 个数!
使用 OpenAI API 的 Embeddings 入门

降维与 t-SNE

 

  • 多种技术可用于_降维_
  • t-SNE(t 分布随机邻域嵌入)
1 https://www.datacamp.com/tutorial/introduction-t-sne
使用 OpenAI API 的 Embeddings 入门

实现 t-SNE

from sklearn.manifold import TSNE
import numpy as np


embeddings = [article['embedding'] for article in articles]
tsne = TSNE(n_components=2, perplexity=5)
embeddings_2d = tsne.fit_transform(np.array(embeddings))
  • n_components:输出维度数
  • perplexity:算法参数,须小于数据点数量
  • 会产生信息损失
1 https://www.datacamp.com/tutorial/introduction-t-sne
使用 OpenAI API 的 Embeddings 入门

可视化嵌入

import matplotlib.pyplot as plt

plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1])

topics = [article['topic'] for article in articles] for i, topic in enumerate(topics): plt.annotate(topic, (embeddings_2d[i, 0], embeddings_2d[i, 1])) plt.show()
使用 OpenAI API 的 Embeddings 入门

可视化嵌入

 

  • _相似_文章会聚在一起!
  • 模型捕捉到_语义_含义

 

  • 接下来:计算相似度

 

一个二维向量空间图,显示同一情感和主题的评论在向量空间中更接近。

使用 OpenAI API 的 Embeddings 入门

开始练习吧!

使用 OpenAI API 的 Embeddings 入门

Preparing Video For Download...