How is cosine similarity computed?
- User
How is cosine similarity computed?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How is cosine similarity computed?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Cosine similarity is a measure of similarity between two non-zero vectors in an inner product space. It is defined as the cosine of the angle between the vectors, which means it measures how similar the vectors are in terms of their orientation, regardless of their magnitude.
The cosine similarity between two vectors ( \mathbf{A} ) and ( \mathbf{B} ) is computed as:
[ \text{cosine similarity}(\mathbf{A}, \mathbf{B}) = \frac{\mathbf{A} \cdot \mathbf{B}}{|\mathbf{A}| |\mathbf{B}|} ]
where:
Compute the Dot Product: [ \mathbf{A} \cdot \mathbf{B} = \sum_{i=1}^{n} A_i \cdot B_i ] where ( A_i ) and ( B_i ) are the components of vectors ( \mathbf{A} ) and ( \mathbf{B} ), respectively.
Compute the Magnitudes (Euclidean Norms): [ |\mathbf{A}| = \sqrt{\sum_{i=1}^{n} A_i^2}, \quad |\mathbf{B}| = \sqrt{\sum_{i=1}^{n} B_i^2} ]
Calculate the Cosine Similarity: [ \text{cosine similarity}(\mathbf{A}, \mathbf{B}) = \frac{\mathbf{A} \cdot \mathbf{B}}{|\mathbf{A}| |\mathbf{B}|} ]
Let ( \mathbf{A} = [1, 2, 3] ) and ( \mathbf{B} = [4, 5, 6] ).
Dot product: [ \mathbf{A} \cdot \mathbf{B} = (1 \cdot 4) + (2 \cdot 5) + (3 \cdot 6) = 4 + 10 + 18 = 32 ]
Magnitudes: [ |\mathbf{A}| = \sqrt{1^2 + 2^2 + 3^2} = \sqrt{1 + 4 + 9} = \sqrt{14} ] [ |\mathbf{B}| = \sqrt{4^2 + 5^2 + 6^2} = \sqrt{16 + 25 + 36} = \sqrt{77} ]
Cosine similarity: [ \text{cosine similarity}(\mathbf{A}, \mathbf{B}) = \frac{32}{\sqrt{14} \cdot \sqrt{77}} \approx \frac{32}{32.86} \approx 0.974 ]
This high value indicates that the vectors are very similar in orientation.
Cosine similarity is widely used in: