Last active
April 4, 2023 07:54
-
-
Save onlyoneaman/4e130830a6b85b2b8161a1f1a6ec7c5e to your computer and use it in GitHub Desktop.
Cosine Similarity
This file contains 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) && @vecB.is_a?(Array) && @vecA.size == @vecB.size | |
dot_product = @vecA.each_with_object(0).with_index { |(v1i, sum), i| sum += v1i * @vecB[i] } | |
a = @vecA.zip(@vecA).map { |v1i, v2i| v1i**2 }.sum | |
b = @vecB.zip(@vecB).map { |v1i, v2i| v1i**2 }.sum | |
square_root = Math.sqrt(a) * Math.sqrt(b) | |
square_root == 0 ? 0 : dot_product / square_root | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment