v9.1.1
Menu

Embedding Cosine Similarity

easyFREEEmbeddings & Positional EncodingLLM 1: Foundations

Compute the cosine similarity between two embedding vectors.

Cosine similarity is defined as: cos_sim(a,b)=a⋅b∥a∥⋅∥b∥\text{cos\_sim}(a, b) = \frac{a \cdot b}{\|a\| \cdot \|b\|}

Input:

  • a: a 1-D NumPy array of floats (vector a)
  • b: a 1-D NumPy array of floats (vector b), same length as a

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

The example below shows each vector as space-separated floats, one per line.

Example

Input
1.0 0.0 0.0
0.0 1.0 0.0
Output
0.0
Reasoning
  • Input: two embedding vectors of the same length. Here a=(1.0,0.0,0.0)a = (1.0, 0.0, 0.0) points purely along the first axis and b=(0.0,1.0,0.0)b = (0.0, 1.0, 0.0) purely along the second.
  • Dot product: multiply matching components and add them: a⋅b=(1.0)(0.0)+(0.0)(1.0)+(0.0)(0.0)=0.0a \cdot b = (1.0)(0.0) + (0.0)(1.0) + (0.0)(0.0) = 0.0. No component is non-zero in both vectors, so nothing survives.
  • Lengths: ∥a∥=1.02+0.02+0.02=1.0\|a\| = \sqrt{1.0^2 + 0.0^2 + 0.0^2} = 1.0 and likewise ∥b∥=1.0\|b\| = 1.0. Both are already unit vectors.
  • Ratio: 0.01.0×1.0=0.0\frac{0.0}{1.0 \times 1.0} = 0.0, rounded to 4 decimal places gives 0.0.
  • Notice: cosine similarity measures only the angle between the vectors, never their size. These two are at 90∘90^\circ, so they are orthogonal: "unrelated" embeddings. Identical directions give 11 (e.g. a=b=(1,2,3)a = b = (1, 2, 3)), and opposite directions give −1-1 (e.g. (1,0)(1, 0) versus (−1,0)(-1, 0)). Scaling either vector by a positive number would not change the result.

Constraints

  • Vectors have the same dimension (1 <= D <= 100)
  • Vectors are not zero vectors
  • Output rounded to 4 decimal places

Learn this in

More from LLM 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.