v9.1.1
Menu

Cosine Similarity

easyFREEText RepresentationNLP 1: Foundations

Calculate the cosine similarity between two vectors.

Cosine similarity measures the angle between two vectors, regardless of their magnitude:

cosine_similarity(A,B)=A⋅B∥A∥×∥B∥\text{cosine\_similarity}(A, B) = \frac{A \cdot B}{\|A\| \times \|B\|}

Where:

  • A⋅B=∑iAi×BiA \cdot B = \sum_i A_i \times B_i (dot product)
  • ∥A∥=∑iAi2\|A\| = \sqrt{\sum_i A_i^2} (Euclidean norm)

This is widely used in NLP to measure document or word similarity.

Input: cosine_similarity(a, b) receives two lists of numbers of the same length (vectors A and B). The example shows each vector as a line of space-separated values.

Output: Return the cosine similarity as a float rounded to 4 decimal places.

Example

Input
1 2 3
4 5 6
Output
0.9746
Reasoning
  • Inputs: a =[1,2,3]= [1, 2, 3] and b =[4,5,6]= [4, 5, 6] are two vectors of the same length (3), e.g. word or document embeddings.
  • Dot product: multiply matching entries and add them: 1⋅4+2⋅5+3⋅6=4+10+18=321 \cdot 4 + 2 \cdot 5 + 3 \cdot 6 = 4 + 10 + 18 = 32.
  • Lengths: ∥A∥=1+4+9=14≈3.7417\|A\| = \sqrt{1 + 4 + 9} = \sqrt{14} \approx 3.7417 and ∥B∥=16+25+36=77≈8.7750\|B\| = \sqrt{16 + 25 + 36} = \sqrt{77} \approx 8.7750. Their product is 1078≈32.8329\sqrt{1078} \approx 32.8329.
  • Divide: 32/32.8329≈0.9746332 / 32.8329 \approx 0.97463, which rounds to 4 decimal places as 0.9746.
  • Output: a single float in [−1,1][-1, 1]. A value this close to 1 means the two vectors point in almost the same direction, even though BB is more than twice as long as AA.
  • Notice that scaling a vector changes nothing: A=[2,4,6]A = [2, 4, 6] gives the same 0.9746, while perpendicular vectors give 0.0.

Constraints

  • Both vectors have the same length
  • Vectors are non-zero
  • Use only math module (no numpy)
  • Round result to 4 decimal places

Learn this in

More from NLP 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.