PIXELBANKv9.1.0
Menu

Cosine Similarity for Face Verification

You are given two face embeddings and need to calculate their cosine similarity.

Cosine similarity measures the angle between two vectors, ignoring their magnitudes:

cos⁡(θ)=a⋅b∥a∥∥b∥=∑iaibi∑iai2⋅∑ibi2\cos(\theta) = \frac{a \cdot b}{\|a\| \|b\|} = \frac{\sum_i a_i b_i}{\sqrt{\sum_i a_i^2} \cdot \sqrt{\sum_i b_i^2}}

Values range from:

  • 1: vectors point in the same direction (very similar)
  • 0: vectors are perpendicular (unrelated)
  • -1: vectors point in opposite directions

For normalized embeddings (common in face recognition), cosine similarity and Euclidean distance are directly related.

Example:

Input:
a = [1, 0, 0]
b = [1, 0, 0]
Output:
1.0
Reasoning:

Computing dot product and magnitudes:

  • Dot product: 1×1 + 0×0 + 0×0 = 1
  • ||a|| = √(1² + 0² + 0²) = 1
  • ||b|| = √(1² + 0² + 0²) = 1

Cosine similarity = 1 / (1 × 1) = 1.0

Identical vectors have similarity 1.

Constraints:

  • a and b are lists of floats (embeddings) of the same length
  • Return similarity rounded to 4 decimal places
  • If either vector has zero magnitude, return 0.0
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Cosine Similarity for Face Verification - Easy | PixelBank