module Ollama::Utils::Math
def convert_to_vector(vector)
- Example: Convert an array to a Numo NArray -
Returns:
-
(Numo::NArray)
- The converted NArray, or the original if it's already a Numo NArray.
Parameters:
-
vector
(Array
) -- The input array to be converted.
def convert_to_vector(vector) vector.is_a?(Numo::NArray) and return vector Numo::NArray[*vector] end
def cosine_similarity(a:, b:, a_norm: norm(a), b_norm: norm(b))
- See: #norm -
See: #convert_to_vector -
Other tags:
- Example: Calculate the cosine similarity between two vectors -
Returns:
-
(Float)
- The cosine similarity between the two vectors
Options Hash:
(**b_norm)
-
b
(Float
) -- The Euclidean norm of vector b (default: calculated from b) -
a
(Float
) -- The Euclidean norm of vector a (default: calculated from a)
Parameters:
-
b
(Vector
) -- The second vector -
a
(Vector
) -- The first vector
def cosine_similarity(a:, b:, a_norm: norm(a), b_norm: norm(b)) a, b = convert_to_vector(a), convert_to_vector(b) a.dot(b) / (a_norm * b_norm) end
def norm(vector)
-
(Float)
- The magnitude of the vector.
Parameters:
-
vector
(Array
) -- The input vector.
def norm(vector) s = 0.0 vector.each { s += _1.abs2 } Math.sqrt(s) end