Module: Measurable::Cosine

Included in:
Measurable
Defined in:
lib/measurable/cosine.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object

:nodoc:


53
54
55
56
57
58
# File 'lib/measurable/cosine.rb', line 53

def self.extended(base) # :nodoc:
  base.instance_eval do
    extend Measurable::Euclidean
  end
  super
end

.included(base) ⇒ Object

:nodoc:


60
61
62
63
64
65
# File 'lib/measurable/cosine.rb', line 60

def self.included(base) # :nodoc:
  base.class_eval do
    include Measurable::Euclidean
  end
  super
end

Instance Method Details

#cosine_distance(u, v) ⇒ Object

call-seq:

cosine_distance(u, v) -> Float

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 and v, that is, the angle between them in the n-dimensional space.

Raises:

  • ArgumentError -> The sizes of u and v don't match.

Raises:

  • (ArgumentError)

46
47
48
49
50
51
# 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) ⇒ Object

call-seq:

cosine_similarity(u, v) -> Float

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 and v, that is, the angle between them in the n-dimensional space.

Raises:

  • ArgumentError -> The sizes of u and v don't match.

Raises:

  • (ArgumentError)

22
23
24
25
26
27
28
29
# 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