分類タスクへの埋め込みの活用

OpenAI API で学ぶ埋め込み入門

Emmanuel Pire

Senior Software Engineer, DataCamp

分類タスク

項目にラベルを割り当てる

  • 分類
    • : 見出しをトピックごとに分類
  • 感情分析

A table of topics that we could use to categorize articles.

OpenAI API で学ぶ埋め込み入門

分類タスク

項目にラベルを割り当てる

  • 分類
    • : 見出しをトピックごとに分類
  • 感情分析
    • : レビューをポジティブ/ネガティブに分類

埋め込みはセマンティックな意味を捉える

A table containing a smiley and a sad face, which could be used to categorize by sentiment.

OpenAI API で学ぶ埋め込み入門

埋め込みを用いた分類

  • ゼロショット分類:
    • ラベル付きデータを使用しない

プロセス:

  1. クラスの説明を埋め込む

Embedded class descriptions in the vector space.

OpenAI API で学ぶ埋め込み入門

埋め込みを用いた分類

  • ゼロショット分類:
    • ラベル付きデータを使用しない

プロセス:

  1. クラスの説明を埋め込む
  2. 分類する項目を埋め込む
  3. コサイン距離を計算する

Embedded class descriptions in the vector space, with an unknown vector shown.

OpenAI API で学ぶ埋め込み入門

埋め込みを用いた分類

  • ゼロショット分類:
    • ラベル付きデータを使用しない

プロセス:

  1. クラスの説明を埋め込む
  2. 分類する項目を埋め込む
  3. コサイン距離を計算する
  4. 最も近いラベルを割り当てる

Embedded class descriptions in the vector space, with an unknown vector assigned the Tech label.

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)
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]
OpenAI API で学ぶ埋め込み入門

コサイン距離を計算する

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)
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"]}

アプローチの限界

  • クラスの説明が十分ではない
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
OpenAI API で学ぶ埋め込み入門

練習しましょう!

OpenAI API で学ぶ埋め込み入門

Preparing Video For Download...