v9.1.1
Menu

Cosine Similarity Face Matching

mediumPROFace RecognitionRecognitionCV: Recognition

Implement face verification using cosine similarity between face embeddings. The goal is to determine if two faces match by comparing their embedding vectors.

Face recognition networks output embedding vectors, which are dense representations of facial features. The similarity between two faces can be measured using the cosine similarity formula, which calculates the dot product of two vectors divided by the product of their magnitudes.

Here are the steps to calculate cosine similarity:

  1. Obtain face embedding vectors from a face recognition network.
  2. Calculate the dot product of the two embedding vectors.
  3. Calculate the magnitudes of the two embedding vectors.
  4. Compute the cosine similarity using the formula.
similarity=e1⋅e2∥e1∥∥e2∥=cos⁡(θ)\text{similarity} = \frac{\mathbf{e}_1 \cdot \mathbf{e}_2}{\|\mathbf{e}_1\| \|\mathbf{e}_2\|} = \cos(\theta)

Output

Return a list of (index, similarity) tuples for every stored embedding whose similarity is greater than or equal to threshold. Round each similarity to 2 decimal places and order the list from highest to lowest similarity.

This technique is widely used in security and surveillance systems.

Example

Input
embeddings = [[1,0,0], [0,1,0], [0.9,0.1,0]]
query = [1, 0, 0]
threshold = 0.8
Output
[(0, 1.0), (2, 0.99)]
Reasoning
  • embeddings holds N=3N = 3 stored face vectors with D=3D = 3 features each; query is the face to identify, and threshold =0.8= 0.8 is the lowest cosine score that still counts as a match.
  • Magnitudes: the query and rows 0 and 1 all have length 11; row 2 has length 0.92+0.12=0.82≈0.9055\sqrt{0.9^2 + 0.1^2} = \sqrt{0.82} \approx 0.9055.
  • Row 0 matches the query's direction: dot product 11, so cos⁡θ=11⋅1=1.0\cos\theta = \frac{1}{1 \cdot 1} = 1.0.
  • Row 1: dot product 0⋅1+1⋅0+0⋅0=00 \cdot 1 + 1 \cdot 0 + 0 \cdot 0 = 0, so the vectors are perpendicular and cos⁡θ=0.0<0.8\cos\theta = 0.0 < 0.8, so it is rejected.
  • Row 2: dot product 0.90.9, so cos⁡θ=0.90.9055⋅1≈0.9939\cos\theta = \frac{0.9}{0.9055 \cdot 1} \approx 0.9939, rounding to 0.99≥0.80.99 \ge 0.8, a match.
  • The output [(0, 1.0), (2, 0.99)] pairs each matching index with its rounded score, best first. Notice row 2 scores high: cosine similarity depends only on the angle, so rescaling an embedding never changes its score.

Constraints

  • embeddings: List of face embedding vectors (N, D)
  • query: Query face embedding (D,)
  • threshold: Similarity threshold for matching
  • Return: List of (index, similarity) for matches above threshold

Learn this in

More from CV: Recognition

PRO

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

Sign in to run your code against the test cases.