セマンティック検索とエンリッチ埋め込み

OpenAI API ではじめる Embeddings 入門

Emmanuel Pire

Senior Software Engineer, DataCamp

セマンティック検索

  • 埋め込みを使用して検索クエリに最も類似した結果を返す
  • : オンラインニュースサイトのセマンティック検索

セマンティック検索の仕組み:検索テキストが埋め込みモデルで埋め込まれ、埋め込まれた検索テキストと見出しの距離が評価され、最も近い見出しが返される。

OpenAI API ではじめる Embeddings 入門

セマンティック検索

セマンティック検索の仕組み:検索テキストが埋め込みモデルで埋め込まれ、埋め込まれた検索テキストと見出しの距離が評価され、最も近い見出しが返される。

  1. 検索クエリと各テキストを埋め込む
  2. コサイン距離を計算する
  3. コサイン距離が_最小_のテキストを抽出する
OpenAI API ではじめる Embeddings 入門

エンリッチ埋め込み

articles = [
    {"headline": "Economic Growth Continues Amid Global Uncertainty",
     "topic": "Business",
     "keywords": ["economy", "business", "finance"]},
    ...
    {"headline": "1.5 Billion Tune-in to the World Cup Final",
     "topic": "Sport",
     "keywords": ["soccer", "world cup", "tv"]}
]
Headline: Economic Growth Continues Amid Global Uncertainty
Topic: Business
Keywords: economy, business, finance
OpenAI API ではじめる Embeddings 入門

F文字列による特徴量の結合

articles = [..., {"headline": "1.5 Billion Tune-in to the World Cup ",
                  "topic": "Sport",
                  "keywords": ["soccer", "world cup", "tv"]}]


def create_article_text(article):
return f"""Headline: {article['headline']} Topic: {article['topic']} Keywords: {', '.join(article['keywords'])}"""
print(create_article_text(articles[-1]))
Headline: 1.5 Billion Tune-in to the World Cup Final
Topic: Sport
Keywords: soccer, world cup, tv
OpenAI API ではじめる Embeddings 入門

エンリッチ埋め込みの作成

article_texts = [create_article_text(article) for article in articles]

article_embeddings = create_embeddings(article_texts)
print(article_embeddings)
[[-0.019609929993748665, -0.03331860154867172, ...],
 ...,
 [..., -0.014373429119586945, -0.005235843360424042]]
OpenAI API ではじめる Embeddings 入門

距離の計算

from scipy.spatial import distance

def find_n_closest(query_vector, embeddings, n=3):

distances = [] for index, embedding in enumerate(embeddings): dist = distance.cosine(query_vector, embedding) distances.append({"distance": dist, "index": index})
distances_sorted = sorted(distances, key=lambda x: x["distance"])
return distances_sorted[0:n]
OpenAI API ではじめる Embeddings 入門

検索結果の返却

query_text = "AI"

query_vector = create_embeddings(query_text)[0]
hits = find_n_closest(query_vector, article_embeddings)
for hit in hits: article = articles[hit['index']] print(article['headline'])
Tech Giant Buys 49% Stake In AI Startup
Tech Company Launches Innovative Product to Improve Online Accessibility
India Successfully Lands Near Moon's South Pole
OpenAI API ではじめる Embeddings 入門

練習しましょう!

OpenAI API ではじめる Embeddings 入門

Preparing Video For Download...