用於分類任務的 Embeddings

Introduction to Embeddings with the OpenAI API

Emmanuel Pire

Senior Software Engineer, DataCamp

分類任務

 

為項目指派標籤

  • 分類
    • 範例:將標題歸入主題
  • 情感分析

 

可用來將文章分類的主題表。

Introduction to Embeddings with the OpenAI API

分類任務

 

為項目指派標籤

  • 分類
    • 範例:將標題歸入主題
  • 情感分析
    • 範例:將評論分類為正面或負面

 

Embeddings 擷取「語意」意涵

 

包含笑臉與哭臉的表格,可用於依情感分類。

Introduction to Embeddings with the OpenAI API

用 embeddings 做分類

  • Zero-shot 分類
    • 不用標註資料

 

流程:

  1. 將類別描述做嵌入

在向量空間中的類別描述嵌入。

Introduction to Embeddings with the OpenAI API

用 embeddings 做分類

  • Zero-shot 分類
    • 不用標註資料

 

流程:

  1. 將類別描述做嵌入
  2. 將待分類項目做嵌入
  3. 計算 cosine 距離

在向量空間中的類別描述嵌入,並顯示未知向量。

Introduction to Embeddings with the OpenAI API

用 embeddings 做分類

  • Zero-shot 分類
    • 不用標註資料

 

流程:

  1. 將類別描述做嵌入
  2. 將待分類項目做嵌入
  3. 計算 cosine 距離
  4. 指派最相近的標籤

在向量空間中的類別描述嵌入,將未知向量指派為 Tech 標籤。

Introduction to Embeddings with the OpenAI API

為類別描述建立嵌入

topics = [
  {'label': 'Tech'},
  {'label': 'Science'},
  {'label': 'Sport'},
  {'label': 'Business'},
]

class_descriptions = [topic['label'] for topic in topics]
class_embeddings = create_embeddings(class_descriptions)
Introduction to Embeddings with the OpenAI API

為待分類項目建立嵌入

article = {"headline": "How NVIDIA GPUs Could Decide Who Wins the AI Race",
           "keywords": ["ai", "business", "computers"]}

def create_article_text(article): return f"""Headline: {article['headline']} Keywords: {', '.join(article['keywords'])}""" article_text = create_article_text(article)
article_embeddings = create_embeddings(article_text)[0]
Introduction to Embeddings with the OpenAI API

計算 cosine 距離

def find_closest(query_vector, embeddings):
  distances = []
  for index, embedding in enumerate(embeddings):
    dist = distance.cosine(query_vector, embedding)
    distances.append({"distance": dist, "index": index})
  return min(distances, key=lambda x: x["distance"])

closest = find_closest(article_embeddings, class_embeddings)
Introduction to Embeddings with the OpenAI API

取出最相似的標籤

label = topics[closest['index']]['label']

print(label)
Business
article = {"headline": "How NVIDIA GPUs Could Decide Who Wins the AI Race",
           "keywords": ["ai", "business", "computers"]}

限制

  • 類別描述細節不足
Introduction to Embeddings with the OpenAI API

更完整的描述

topics = [
  {'label': 'Tech', 'description': 'A news article about technology'},
  {'label': 'Science', 'description': 'A news article about science'},
  {'label': 'Sport', 'description': 'A news article about sports'},
  {'label': 'Business', 'description': 'A news article about business'},
]

class_descriptions = [topic['description'] for topic in topics] class_embeddings = create_embeddings(class_descriptions)
[...] label = topics[closest['index']]['label'] print(label)
Tech
Introduction to Embeddings with the OpenAI API

一起來練習吧!

Introduction to Embeddings with the OpenAI API

Preparing Video For Download...