Class CosineSimilarity

java.lang.Object
dev.langchain4j.store.embedding.CosineSimilarity

public class CosineSimilarity extends Object
Utility class for calculating cosine similarity between two vectors.
  • Field Details

    • EPSILON

      public static final float EPSILON
      A small value to avoid division by zero.
      See Also:
  • Method Details

    • between

      public static double between(Embedding embeddingA, Embedding embeddingB)
      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 vector
      embeddingB - 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.