Class: Langchain::Utils::CosineSimilarity
- Inherits:
-
Object
- Object
- Langchain::Utils::CosineSimilarity
- Defined in:
- lib/langchain/utils/cosine_similarity.rb
Instance Attribute Summary collapse
-
#vector_a ⇒ Object
readonly
Returns the value of attribute vector_a.
-
#vector_b ⇒ Object
readonly
Returns the value of attribute vector_b.
Instance Method Summary collapse
-
#calculate_similarity ⇒ Float
Calculate the cosine similarity between two vectors.
-
#initialize(vector_a, vector_b) ⇒ CosineSimilarity
constructor
A new instance of CosineSimilarity.
Constructor Details
#initialize(vector_a, vector_b) ⇒ CosineSimilarity
Returns a new instance of CosineSimilarity.
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_a ⇒ Object (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_b ⇒ Object (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_similarity ⇒ Float
Calculate the cosine similarity between 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 |