Embedding 的奇妙世界!

Introduction to Embeddings with the OpenAI API

Emmanuel Pire

Senior Software Engineer, DataCamp

什麼是 embeddings?

  • 來自 Natural Language Processing(NLP)的概念
  • 文字的數值化表示

將單字輸入到 embedding 模型,輸出為文字的數值表示。

Introduction to Embeddings with the OpenAI API

什麼是 embeddings?

 

  • 將文字映射到「多維」的向量空間
  • 模型輸出的數字為文字在空間中的位置
  • 相似的詞會彼此「更靠近」
  • 不相似的詞會「更遠離」

以數值表示文字;越相似者距離越近。

Introduction to Embeddings with the OpenAI API

為什麼 embeddings 有用?

  • Embeddings 能捕捉「語義」
  • 語義:文字的脈絡與意圖

 

  • 範例
    • 「請問超市在哪個方向?」
    • 「可以告訴我去商店的路嗎?」

以數值表示文字;越相似者距離越近。

Introduction to Embeddings with the OpenAI API

語義式搜尋引擎

 

  • 傳統搜尋引擎
    • 使用關鍵字樣式比對
    • 可能忽略真正意圖
    • 會漏掉詞形變化

 

傳統搜尋引擎顯示無關結果。

Introduction to Embeddings with the OpenAI API

語義式搜尋引擎

  • 使用 embeddings 理解意圖與脈絡

將「comfortable running shoes」進行嵌入。

Introduction to Embeddings with the OpenAI API

語義式搜尋引擎

  • 使用 embeddings 理解意圖與脈絡

嵌入後的文字顯示於多維空間中。

Introduction to Embeddings with the OpenAI API

推薦系統

 

  • 範例:職缺推薦
    • 依你已查看的職缺描述推薦相似職缺
    • 減少職稱差異的影響

以 embeddings 呈現的職缺推薦。

Introduction to Embeddings with the OpenAI API

分類

 

分類任務:

  • 情緒分類
  • 群聚觀測值
  • 類別歸納

 

範例

  • 新聞標題分類

 

將未知新聞標題以 embeddings 呈現以進行分類。

Introduction to Embeddings with the OpenAI API

建立 Embeddings 請求

  • Embeddings 端點
from openai import OpenAI


client = OpenAI(api_key="<OPENAI_API_KEY>")
response = client.embeddings.create(
model="text-embedding-3-small",
input="Embeddings are a numerical representation of text that can be used to measure the relatedness between two pieces of text."
)
response_dict = response.model_dump() print(response_dict)
1 https://platform.openai.com/docs/api-reference/embeddings
Introduction to Embeddings with the OpenAI API

Embeddings 回應

{'object': 'list',
 'data': [
    {
      "embedding": [0.0023064255, ..., -0.0028842222],
      "index": 0,
      "object": "embedding"
    }
  ],
 'model': 'text-embedding-3-small',
 'usage': {
  "prompt_tokens": 24,
  "total_tokens": 24
  }
}
Introduction to Embeddings with the OpenAI API

擷取 embeddings

print(response_dict['data'][0]['embedding'])
[0.0023064255, ...., -0.0028842222]
Introduction to Embeddings with the OpenAI API

一起來練習吧!

Introduction to Embeddings with the OpenAI API

Preparing Video For Download...