MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / cosine_similarity

Function cosine_similarity

machine_learning/similarity_search.py:143–156  ·  view source on GitHub ↗

Calculates cosine similarity between two data. :param input_a: ndarray of first vector. :param input_b: ndarray of second vector. :return: Cosine similarity of input_a and input_b. By using math.sqrt(), result will be float. >>> cosine_similarity(np.array([1]), np.

(input_a: np.ndarray, input_b: np.ndarray)

Source from the content-addressed store, hash-verified

141
142
143def cosine_similarity(input_a: np.ndarray, input_b: np.ndarray) -> float:
144 """
145 Calculates cosine similarity between two data.
146 :param input_a: ndarray of first vector.
147 :param input_b: ndarray of second vector.
148 :return: Cosine similarity of input_a and input_b. By using math.sqrt(),
149 result will be float.
150
151 >>> cosine_similarity(np.array([1]), np.array([1]))
152 1.0
153 >>> cosine_similarity(np.array([1, 2]), np.array([6, 32]))
154 0.9615239476408232
155 """
156 return float(np.dot(input_a, input_b) / (norm(input_a) * norm(input_b)))
157
158
159if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected