시맨틱 검색과 풍부한 임베딩

OpenAI API로 시작하는 임베딩 Introduction

Emmanuel Pire

Senior Software Engineer, DataCamp

시맨틱 검색

  • 임베딩을 사용해 검색 쿼리와 가장 유사한 결과 반환
  • 예시: 온라인 뉴스 사이트의 시맨틱 검색

시맨틱 검색 작동 방식: 검색 텍스트가 임베딩 모델에 의해 임베딩되고, 임베딩된 검색 텍스트와 임베딩된 헤드라인 사이의 거리가 계산됩니다. 가장 가까운 헤드라인이 반환됩니다.

OpenAI API로 시작하는 임베딩 Introduction

시맨틱 검색

시맨틱 검색 작동 방식: 검색 텍스트가 임베딩 모델에 의해 임베딩되고, 임베딩된 검색 텍스트와 임베딩된 헤드라인 사이의 거리가 계산됩니다. 가장 가까운 헤드라인이 반환됩니다.

  1. 검색 쿼리와 텍스트를 임베딩
  2. 코사인 거리 계산
  3. 코사인 거리가 가장 작은 텍스트 추출
OpenAI API로 시작하는 임베딩 Introduction

풍부한 임베딩

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로 시작하는 임베딩 Introduction

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로 시작하는 임베딩 Introduction

풍부한 임베딩 생성

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로 시작하는 임베딩 Introduction

거리 계산

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로 시작하는 임베딩 Introduction

검색 결과 반환

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로 시작하는 임베딩 Introduction

연습해 봅시다!

OpenAI API로 시작하는 임베딩 Introduction

Preparing Video For Download...