추천 시스템

OpenAI API로 시작하는 임베딩 Introduction

Emmanuel Pire

Senior Software Engineer, DataCamp

임베딩을 활용한 추천 시스템

 

  • 시맨틱 검색과 매우 유사합니다!

 

프로세스:

  1. 추천 후보와 데이터 포인트를 임베딩

벡터 공간에서 파란색 데이터 포인트 하나와 여러 개의 빨간색 데이터 포인트.

OpenAI API로 시작하는 임베딩 Introduction

임베딩을 활용한 추천 시스템

 

  • 시맨틱 검색과 매우 유사합니다!

 

프로세스:

  1. 추천 후보와 데이터 포인트를 임베딩
  2. 코사인 거리 계산

벡터 공간에서 파란색 데이터 포인트 하나와 여러 개의 빨간색 데이터 포인트. 코사인 거리를 나타내는 선이 각 빨간색 포인트와 파란색 포인트 사이에 표시됨.

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

current_article = {"headline": "How NVIDIA GPUs Could Decide Who Wins the AI Race", "topic": "Tech", "keywords": ["ai", "business", "computers"]}
OpenAI API로 시작하는 임베딩 Introduction

특성 결합

def create_article_text(article):
  return f"""Headline: {article['headline']}
Topic: {article['topic']}
Keywords: {', '.join(article['keywords'])}"""
article_texts = [create_article_text(article) for article in articles]
current_article_text = create_article_text(current_article)
print(current_article_text)
Headline: How NVIDIA GPUs Could Decide Who Wins the AI Race
Topic: Tech
Keywords: ai, business, computers
OpenAI API로 시작하는 임베딩 Introduction

임베딩 생성

def create_embeddings(texts):
  response = openai.Embedding.create(
    model="text-embedding-3-small",
    input=texts
  )
  response_dict = response.model_dump()

  return [data['embedding'] for data in response_dict['data']]
current_article_embeddings = create_embeddings(current_article_text)[0]
article_embeddings = create_embeddings(article_texts)
OpenAI API로 시작하는 임베딩 Introduction

가장 유사한 기사 찾기

def find_n_closest(query_vector, embeddings, n=3):
  distances = []
  for index, embedding in enumerate(embeddings):
    dist = spatial.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]
hits = find_n_closest(current_article_embeddings, article_embeddings)

for hit in hits: article = articles[hit['index']] print(article['headline'])
OpenAI API로 시작하는 임베딩 Introduction

가장 유사한 기사 찾기

Tech Giant Buys 49% Stake In AI Startup
Tech Company Launches Innovative Product to Improve Online Accessibility
Scientists Make Breakthrough Discovery in Renewable Energy
OpenAI API로 시작하는 임베딩 Introduction

사용자 히스토리 추가

user_history = [
    {"headline": "How NVIDIA GPUs Could Decide Who Wins the AI Race",
     "topic": "Tech",
     "keywords": ["ai", "business", "computers"]},
    {"headline": "Tech Giant Buys 49% Stake In AI Startup",
     "topic": "Tech",
     "keywords": ["business", "AI"]}
]
OpenAI API로 시작하는 임베딩 Introduction

다중 데이터 포인트 기반 추천

임베딩된 기사를 나타낸 플롯. 사용자가 읽은 기사는 파란색, 읽지 않은 기사는 빨간색으로 표시됨.

OpenAI API로 시작하는 임베딩 Introduction

다중 데이터 포인트 기반 추천

 

프로세스:

  • 여러 벡터를 평균으로 결합
  • 코사인 거리 계산

두 벡터의 평균으로 계산된 포인트가 두 점 사이에 추가됨.

OpenAI API로 시작하는 임베딩 Introduction

다중 데이터 포인트 기반 추천

 

프로세스:

  • 여러 벡터를 평균으로 결합
  • 코사인 거리 계산
  • 가장 가까운 벡터 추천

추천을 위해 가장 가까운 빨간색 포인트가 강조 표시됨.

OpenAI API로 시작하는 임베딩 Introduction

다중 데이터 포인트 기반 추천

 

프로세스:

  • 여러 벡터를 평균으로 결합
  • 코사인 거리 계산
  • 가장 가까운 벡터 추천

이미 읽은 기사를 제외해야 함을 강조하기 위해 가장 가까운 포인트가 파란색으로 표시됨.

OpenAI API로 시작하는 임베딩 Introduction

다중 데이터 포인트 기반 추천

 

프로세스:

  • 여러 벡터를 평균으로 결합
  • 코사인 거리 계산
  • 가장 가까운 벡터 추천
    • 읽지 않은 항목인지 확인

이번에는 더 먼 곳에 있는 가장 가까운 빨간색 포인트가 강조 표시됨.

OpenAI API로 시작하는 임베딩 Introduction

다중 데이터 포인트 기반 추천

def create_article_text(article):
  return f"""Headline: {article['headline']}
Topic: {article['topic']}
Keywords: {', '.join(article['keywords'])}"""

history_texts = [create_article_text(article) for article in user_history]
history_embeddings = create_embeddings(history_texts)

mean_history_embeddings = np.mean(history_embeddings, axis=0)
articles_filtered = [article for article in articles if article not in user_history]
article_texts = [create_article_text(article) for article in articles_filtered] article_embeddings = create_embeddings(article_texts)
OpenAI API로 시작하는 임베딩 Introduction

다중 데이터 포인트 기반 추천

hits = find_n_closest(mean_history_embeddings, article_embeddings)

for hit in hits: article = articles_filtered[hit['index']] print(article['headline'])
Tech Company Launches Innovative Product to Improve Online Accessibility
New Social Media Platform Has Everyone Talking!
Scientists Make Breakthrough Discovery in Renewable Energy
OpenAI API로 시작하는 임베딩 Introduction

연습해 봅시다!

OpenAI API로 시작하는 임베딩 Introduction

Preparing Video For Download...