Package dev.langchain4j.store.embedding
Class CosineSimilarity
java.lang.Object
dev.langchain4j.store.embedding.CosineSimilarity
Utility class for calculating cosine similarity between two vectors.
-
Field Summary
Modifier and TypeFieldDescriptionstatic final float
A small value to avoid division by zero. -
Method Summary
Modifier and TypeMethodDescriptionstatic double
Calculates cosine similarity between two vectors.static double
fromRelevanceScore
(double relevanceScore) Converts relevance score into cosine similarity.
-
Field Details
-
EPSILON
public static final float EPSILONA small value to avoid division by zero.- See Also:
-
-
Method Details
-
between
Calculates cosine similarity between two vectors.Cosine similarity measures the cosine of the angle between two vectors, indicating their directional similarity. It produces a value in the range:
-1 indicates vectors are diametrically opposed (opposite directions).
0 indicates vectors are orthogonal (no directional similarity).
1 indicates vectors are pointing in the same direction (but not necessarily of the same magnitude).
Not to be confused with cosine distance ([0..2]), which quantifies how different two vectors are.
Embeddings of all-zeros vectors are considered orthogonal to all other vectors; including other all-zeros vectors.
- Parameters:
embeddingA
- first embedding vectorembeddingB
- second embedding vector- Returns:
- cosine similarity in the range [-1..1]
-
fromRelevanceScore
public static double fromRelevanceScore(double relevanceScore) Converts relevance score into cosine similarity.- Parameters:
relevanceScore
- Relevance score in the range [0..1] where 0 is not relevant and 1 is relevant.- Returns:
- Cosine similarity in the range [-1..1] where -1 is not relevant and 1 is relevant.
-