module Measurable::Cosine
Public Instance Methods
cosine_distance(u, v) → Float
click to toggle source
Calculate the cosine distance between the orientation of two vectors.
See: en.wikipedia.org/wiki/Cosine_similarity
Arguments:
-
u
-> An array of Numeric objects. -
v
-> An array of Numeric objects.
Returns:
-
The normalized dot product of
u
andv
, that is, the angle between them in the n-dimensional space.
Raises:
-
ArgumentError
-> The sizes ofu
andv
don't match.
# File lib/measurable/cosine.rb, line 46 def cosine_distance(u, v) # TODO: Change this to a more specific, custom-made exception. raise ArgumentError if u.size != v.size 1 - cosine_similarity(u, v) end
cosine_similarity(u, v) → Float
click to toggle source
Calculate the cosine similarity between the orientation of two vectors.
See: en.wikipedia.org/wiki/Cosine_similarity
Arguments:
-
u
-> An array of Numeric objects. -
v
-> An array of Numeric objects.
Returns:
-
The normalized dot product of
u
andv
, that is, the angle between them in the n-dimensional space.
Raises:
-
ArgumentError
-> The sizes ofu
andv
don't match.
# File lib/measurable/cosine.rb, line 22 def cosine_similarity(u, v) # TODO: Change this to a more specific, custom-made exception. raise ArgumentError if u.size != v.size dot_product = u.zip(v).reduce(0.0) { |acc, ary| acc += ary[0] * ary[1] } dot_product / (euclidean(u) * euclidean(v)) end