Created
June 9, 2017 11:02
-
-
Save DDimitris/694d9da40f8e91326008f8b270afad2a to your computer and use it in GitHub Desktop.
Cosine Similarity Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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