Class: Langchain::Utils::CosineSimilarity

Inherits:
Object
  • Object
show all
Defined in:
lib/langchain/utils/cosine_similarity.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vector_a, vector_b) ⇒ CosineSimilarity

Returns a new instance of CosineSimilarity.

Parameters:

  • vector_a (Array<Float>)

    First vector

  • vector_b (Array<Float>)

    Second vector



10
11
12
13
# File 'lib/langchain/utils/cosine_similarity.rb', line 10

def initialize(vector_a, vector_b)
  @vector_a = vector_a
  @vector_b = vector_b
end

Instance Attribute Details

#vector_aObject (readonly)

Returns the value of attribute vector_a.



6
7
8
# File 'lib/langchain/utils/cosine_similarity.rb', line 6

def vector_a
  @vector_a
end

#vector_bObject (readonly)

Returns the value of attribute vector_b.



6
7
8
# File 'lib/langchain/utils/cosine_similarity.rb', line 6

def vector_b
  @vector_b
end

Instance Method Details

#calculate_similarityFloat

Calculate the cosine similarity between two vectors

Returns:

  • (Float)

    The cosine similarity between the two vectors



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/langchain/utils/cosine_similarity.rb', line 17

def calculate_similarity
  return nil unless vector_a.is_a? Array
  return nil unless vector_b.is_a? Array
  return nil if vector_a.size != vector_b.size

  dot_product = 0
  vector_a.zip(vector_b).each do |v1i, v2i|
    dot_product += v1i * v2i
  end

  a = vector_a.map { |n| n**2 }.reduce(:+)
  b = vector_b.map { |n| n**2 }.reduce(:+)

  dot_product / (Math.sqrt(a) * Math.sqrt(b))
end