Home Knowledge Base Cosine Similarity

Cosine Similarity is the standard metric for measuring semantic similarity between text embeddings in NLP — calculating the cosine of the angle between two vectors in high-dimensional space, where a value of 1.0 means the vectors point in exactly the same direction (semantically identical), 0.0 means they are orthogonal (unrelated), and -1.0 means they are opposite, used in every major AI application from semantic search to RAG retrieval to recommendation systems.

What Is Cosine Similarity?

Interpretation

ValueAngleMeaningExample
1.0Identical direction"I love cats" vs "I love cats"
0.8-0.99~15-35°Very similar"I love cats" vs "I adore felines"
0.5-0.8~35-60°Somewhat related"I love cats" vs "Pets are great companions"
0.090°Unrelated"I love cats" vs "The stock market crashed"
-1.0180°OppositeRare in practice with modern embeddings

Why Cosine Similarity Over Euclidean Distance?

PropertyCosine SimilarityEuclidean Distance
Magnitude-invariantYes — long and short documents compare fairlyNo — penalizes different lengths
Range[-1, 1] — bounded and interpretable[0, ∞) — unbounded
Use caseText similarity, embeddings, NLPPhysical distance, spatial data
High dimensionsWorks well in 384-1536D embedding spaceSuffers from "curse of dimensionality"

Python Implementation

import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer('all-MiniLM-L6-v2')
emb_a = model.encode("I love machine learning")
emb_b = model.encode("AI and deep learning fascinate me")

cosine_sim = np.dot(emb_a, emb_b) / (np.linalg.norm(emb_a) * np.linalg.norm(emb_b))
print(f"Similarity: {cosine_sim:.3f}")  # ~0.85

Applications in AI

ApplicationHow Cosine Similarity Is Used
Semantic SearchQuery embedding vs document embeddings → rank by similarity
RAG RetrievalFind most similar chunks to the question
Duplicate DetectionFlag document pairs with similarity > 0.95
Recommendation"This article is similar to articles you've read"
ClusteringGroup items by similarity threshold

Cosine Similarity is the fundamental distance metric powering modern NLP and AI search — providing a magnitude-invariant, bounded measure of semantic relatedness between text embeddings that enables every retrieval, search, and similarity application in production AI systems.

cosine similaritydot productmeasure

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.