🤖 AI/ML

Cosine Similarity

Cosine Similarity

Similarity based on the cosine of the angle between two vectors. Standard for comparing embeddings.

📖 Detailed Explanation

Cosine Similarity is a method of calculating similarity by measuring the angle between two vectors. It takes the value 1 if the two vectors point in the same direction, 0 if they are perpendicular, and -1 if they point in opposite directions. Because it considers only direction rather than the vector's magnitude, it is well suited to measuring text similarity without being affected by document length.

The mathematical definition of cosine similarity is the dot product of two vectors A and B divided by the product of their magnitudes. As a formula, it is expressed as cos(theta) = (A dot B) / (||A|| * ||B||). The concept was first used in the field of information retrieval in the 1960s, and it has now become a core tool in natural language processing and recommendation systems.

In modern AI, cosine similarity is the standard for comparing embedding vectors. After converting words, sentences, and documents into high-dimensional vectors, semantic similarity is measured with cosine similarity. OpenAI's text-embedding-3 model produces 3072-dimensional vectors, and when the cosine similarity between these vectors is 0.8 or higher, they are judged to be semantically similar.

In practice, it is essential for semantic search, duplicate document detection, recommendation systems, and retrieving relevant documents for RAG. Vector databases such as Pinecone and Weaviate adopt cosine similarity as the default similarity metric and find similar items among millions of vectors in milliseconds.

💻 Code Example

import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

# 두 벡터의 코사인 유사도 계산 (직접 구현)
def cosine_sim(a, b):
    dot_product = np.dot(a, b)
    norm_a = np.linalg.norm(a)
    norm_b = np.linalg.norm(b)
    return dot_product / (norm_a * norm_b)

# 예제: 문장 임베딩 비교
vec1 = np.array([0.2, 0.5, 0.8, 0.1])  # "고양이가 잠을 잔다"
vec2 = np.array([0.3, 0.4, 0.7, 0.2])  # "강아지가 쉬고 있다"
vec3 = np.array([0.9, 0.1, 0.1, 0.9])  # "주식 시장이 폭락했다"

print(f"유사한 문장 간: {cosine_sim(vec1, vec2):.4f}")  # 0.9833
print(f"다른 주제 문장 간: {cosine_sim(vec1, vec3):.4f}")  # 0.4588

# sklearn 활용 (여러 벡터 동시 비교)
vectors = np.array([vec1, vec2, vec3])
similarity_matrix = cosine_similarity(vectors)
print(f"\n유사도 행렬:\n{similarity_matrix.round(4)}")

# OpenAI 임베딩과 함께 사용
from openai import OpenAI
client = OpenAI()

def get_embedding(text):
    response = client.embeddings.create(
        input=text,
        model="text-embedding-3-small"
    )
    return np.array(response.data[0].embedding)

# 실제 문장 비교
emb1 = get_embedding("인공지능이 세상을 바꾸고 있다")
emb2 = get_embedding("AI 기술이 혁신을 이끌고 있다")
print(f"\n의미적 유사도: {cosine_sim(emb1, emb2):.4f}")  # ~0.89

🗣️ Say It Like This in Practice

In a search system design meeting

"How about switching FAQ search from keyword matching to semantic search based on cosine similarity? Even if a user types 'I forgot my password,' it can find the 'How to reset your password' document. We can start with a threshold of 0.75 and tune it."

In a technical interview

"To explain the difference between cosine similarity and Euclidean distance: cosine compares only the direction of vectors, while Euclidean compares absolute positions. Cosine is advantageous for comparing texts of varying length, and for normalized embeddings the two are mathematically equivalent."

In a code review

"You implemented cosine similarity by hand here, but for large-scale batch operations, using sklearn's cosine_similarity or PyTorch's F.cosine_similarity is more than 10x faster, because they use vectorized operations and GPU acceleration."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1.
Missing zero-vector handling

If a vector's magnitude is 0, the denominator becomes 0 and a calculation error occurs. In practice, zero vectors can arise from embedding failures or empty-string input, so always add exception handling.

2.
Fixed threshold

Fixing a similarity of 0.8 or higher as "similar" is risky. The appropriate threshold differs by domain, embedding model, and language. Always decide after a precision-recall test on real data.

3.
Unsuitable for sparse vectors

With sparse vectors such as TF-IDF, most dimensions are 0, so cosine similarity often returns extreme values (0 or 1). For sparse vectors, consider Jaccard similarity or BM25.

🔗 Related Terms

📚 Learn More