Loading the problem
Before you start
Cosine similarity measures the angle between two vectors and ignores their length. It is the default way to compare embeddings, because for text the direction carries the meaning and the magnitude mostly carries frequency.
cos(a, b) = (a . b) / (||a|| * ||b||)
The result is in [-1, 1]: 1 for vectors pointing the same way, 0 for
perpendicular, -1 for opposite.
If either vector has zero length the angle is undefined, so return 0.0.
def cosine_similarity(a, b):
Input
cosine_similarity(np.array([1.0, 0.0]), np.array([1.0, 1.0]))
Output
0.7071067811865475
Reasoning
The dot product is 1, and the norms are 1 and sqrt(2). So the cosine is 1 / sqrt(2), about 0.7071, which is a 45 degree angle.
0.0 when either vector has zero length.[-1, 1].Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell