Skip to content

Instantly share code, notes, and snippets.

@onlyoneaman
Last active April 4, 2023 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onlyoneaman/4e130830a6b85b2b8161a1f1a6ec7c5e to your computer and use it in GitHub Desktop.
Save onlyoneaman/4e130830a6b85b2b8161a1f1a6ec7c5e to your computer and use it in GitHub Desktop.
Cosine Similarity
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