Skip to content

Instantly share code, notes, and snippets.

@joshuaob
Forked from DDimitris/Cosine.rb
Created May 28, 2023 11:55
Show Gist options
  • Save joshuaob/da7c0b9b8da6bd43b293b9d394f3bc60 to your computer and use it in GitHub Desktop.
Save joshuaob/da7c0b9b8da6bd43b293b9d394f3bc60 to your computer and use it in GitHub Desktop.
Cosine Similarity Ruby
class Cosine
def initialize vecA, vecB
@vecA = vecA
@vecB = vecB
end
def calculate_similarity
return nil unless @vecA.is_a? Array
return nil unless @vecB.is_a? Array
return nil if @vecA.size != @vecB.size
dot_product = 0
@vecA.zip(@vecB).each do |v1i, v2i|
dot_product += v1i * v2i
end
a = @vecA.map { |n| n ** 2 }.reduce(:+)
b = @vecB.map { |n| n ** 2 }.reduce(:+)
return dot_product / (Math.sqrt(a) * Math.sqrt(b))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment