-
-
Save joshuaob/da7c0b9b8da6bd43b293b9d394f3bc60 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