文字相似度

Introduction to Embeddings with the OpenAI API

Emmanuel Pire

Senior Software Engineer, DataCamp

重點回顧…

 

  • 語意相近的文字會在向量空間中被嵌入得更靠近
  • 量測距離即可量化相似度
  • 促成多種 embeddings 應用:
    • 語意搜尋
    • 推薦
    • 分類

 

一張 2D 向量空間的圖,顯示同情緒與主題的評論在向量空間中彼此更接近。

Introduction to Embeddings with the OpenAI API

量測相似度

 

Cosine distance

from scipy.spatial import distance

distance.cosine([0, 1], [1, 0])
1.0
  • 範圍為 0 到 2
  • 數值越小=相似度越高

 

兩個向量,中間以一直線相連。

Introduction to Embeddings with the OpenAI API

範例:比較新聞標題相似度

包含標題與其 embeddings 的字典清單。

Introduction to Embeddings with the OpenAI API

範例:比較新聞標題相似度

def create_embeddings(texts):
  response = client.embeddings.create(
    model="text-embedding-3-small",
    input=texts
  )
  response_dict = response.model_dump()

  return [data['embedding'] for data in response_dict['data']]
print(create_embeddings(["Python is the best!", "R is the best!"]))

print(create_embeddings("DataCamp is awesome!")[0])
[[0.0050565884448587894, ..., , -0.04000323638319969],
 [-0.0018890155479311943, ..., -0.04085670784115791]]

[0.00037010075175203383, ..., -0.021759100258350372]
Introduction to Embeddings with the OpenAI API

範例:比較新聞標題相似度

from scipy.spatial import distance
import numpy as np

search_text = "computer"
search_embedding = create_embeddings(search_text)[0]
distances = []
for article in articles:
dist = distance.cosine(search_embedding, article["embedding"])
distances.append(dist)
min_dist_ind = np.argmin(distances)
print(articles[min_dist_ind]['headline'])
Tech Company Launches Innovative Product to Improve Online Accessibility
Introduction to Embeddings with the OpenAI API

一起來練習吧!

Introduction to Embeddings with the OpenAI API

Preparing Video For Download...