Cosine Similarity Face Matching
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:
- Obtain face embedding vectors from a face recognition network.
- Calculate the dot product of the two embedding vectors.
- Calculate the magnitudes of the two embedding vectors.
- Compute the cosine similarity using the formula.
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
embeddings = [[1,0,0], [0,1,0], [0.9,0.1,0]] query = [1, 0, 0] threshold = 0.8
[(0, 1.0), (2, 0.99)]
embeddingsholds stored face vectors with features each;queryis the face to identify, andthresholdis the lowest cosine score that still counts as a match.- Magnitudes: the query and rows 0 and 1 all have length ; row 2 has length .
- Row 0 matches the query's direction: dot product , so .
- Row 1: dot product , so the vectors are perpendicular and , so it is rejected.
- Row 2: dot product , so , rounding to , 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