Embedding Model
A model that converts text into vectors
A model that converts text into vectors
An Embedding Model is an AI model that converts unstructured data such as text, images, and audio into fixed-length numeric vectors (embeddings). These vectors mathematically encode the semantic characteristics of the original data, enabling computers to perform similarity calculation, search, classification, and more.
Early on, static embeddings such as Word2Vec and GloVe were mainstream, but after BERT appeared in 2018, Transformer-based models became dominant. Today, commercial APIs such as OpenAI text-embedding-3, Cohere Embed v3, and Google Gecko compete with open-source models such as BGE, E5, and GTE.
An embedding model takes text as input and typically outputs a real-valued vector of 256 to 3072 dimensions. Texts with similar meaning are placed close together in the vector space, and different texts far apart. Thanks to this property, semantic similarity can be quantified with cosine similarity or Euclidean distance.
In practice, the Embedding Model is a core component of RAG (Retrieval-Augmented Generation), semantic search, recommendation systems, duplicate detection, and clustering. Combined with a Vector Database (Pinecone, Weaviate, Milvus), it finds relevant information among hundreds of millions of documents within milliseconds.
# Embedding Model 활용 예제
from openai import OpenAI
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
client = OpenAI()
# 1. OpenAI text-embedding-3-small 사용 ($0.02/1M tokens)
def get_embedding(text: str, model="text-embedding-3-small"):
response = client.embeddings.create(input=text, model=model)
return response.data[0].embedding
# 임베딩 생성
texts = [
"Python은 데이터 분석에 많이 사용됩니다",
"파이썬은 머신러닝 분야에서 인기가 높습니다",
"자바스크립트는 웹 개발에 필수입니다",
"오늘 날씨가 좋네요"
]
embeddings = [get_embedding(t) for t in texts]
# 2. 유사도 계산
similarity_matrix = cosine_similarity(embeddings)
print("텍스트 유사도 행렬:")
print(np.round(similarity_matrix, 2))
# Python-파이썬: 0.92 (높음), Python-날씨: 0.31 (낮음)
# 3. 시맨틱 검색 구현
query = "데이터 사이언스 프로그래밍 언어"
query_emb = get_embedding(query)
scores = cosine_similarity([query_emb], embeddings)[0]
ranked_results = sorted(zip(texts, scores), key=lambda x: x[1], reverse=True)
print("\n검색 결과:")
for text, score in ranked_results:
print(f" {score:.3f}: {text}")
# 4. 오픈소스 모델 (sentence-transformers)
from sentence_transformers import SentenceTransformer
# BGE 모델 - 한국어 지원, 무료
model = SentenceTransformer('BAAI/bge-m3') # 다국어 지원
embeddings = model.encode(texts)
print(f"\n임베딩 차원: {embeddings.shape}") # (4, 1024)
# 5. 배치 처리 + Vector DB 저장 (Chroma 예시)
import chromadb
from chromadb.utils import embedding_functions
chroma_client = chromadb.Client()
openai_ef = embedding_functions.OpenAIEmbeddingFunction(
model_name="text-embedding-3-small"
)
collection = chroma_client.create_collection(
name="documents",
embedding_function=openai_ef
)
# 문서 추가 (임베딩 자동 생성)
collection.add(
documents=texts,
ids=[f"doc_{i}" for i in range(len(texts))]
)
# 유사 문서 검색
results = collection.query(
query_texts=["AI 프로그래밍"],
n_results=2
)
print(f"\n검색된 문서: {results['documents']}")
"The low retrieval quality of the RAG pipeline may be an embedding model issue. Switching from text-embedding-ada to text-embedding-3-large raises performance by about 15% on the MTEB benchmark."
"There are three things I consider when choosing an embedding model. First, the number of dimensions (search speed vs. accuracy trade-off); second, the max token length (whether long documents can be handled); and third, multilingual support (Korean performance)."
"For domain-specific search, consider fine-tuning. With a general embedding model on legal documents, it can't capture technical terms, but contrastive learning on a legal corpus raises recall by more than 30%."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Each model has a completely different vector space. If you change the model, you must regenerate all previously stored embeddings. Otherwise, search results will be a mess.
Most embedding models have a limit of 512 to 8192 tokens. Split long documents into chunks, embed each chunk separately, and combine them at search time.
Some models (E5, BGE) need the prefix "query: " before queries and "passage: " before documents for optimal performance. Always check the model documentation.