Skip to content

Instantly share code, notes, and snippets.

@DDimitris
Created June 9, 2017 11:02
Show Gist options
  • Save DDimitris/694d9da40f8e91326008f8b270afad2a to your computer and use it in GitHub Desktop.
Save DDimitris/694d9da40f8e91326008f8b270afad2a 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