cosineSimilarity static method

double cosineSimilarity(
  1. Float32List a,
  2. Float32List b
)

Computes the cosine similarity between two embedding vectors.

Cosine similarity measures the angle between two vectors, ranging from -1 (opposite) to 1 (identical). For face embeddings:

  • Values > 0.6 strongly suggest the same person
  • Values > 0.5 suggest the same person
  • Values < 0.3 suggest different people

Both a and b should be L2-normalized embeddings (as returned by call). If not normalized, this method will still work but may give different thresholds.

Example:

final similarity = FaceEmbedding.cosineSimilarity(embedding1, embedding2);
if (similarity > 0.6) {
  print('Very likely the same person');
}

Implementation

static double cosineSimilarity(Float32List a, Float32List b) {
  if (a.length != b.length) {
    throw ArgumentError(
      'Embedding dimensions must match: ${a.length} vs ${b.length}',
    );
  }

  double dot = 0.0;
  double normA = 0.0;
  double normB = 0.0;

  for (int i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }

  final double denom = math.sqrt(normA) * math.sqrt(normB);
  return denom > 0 ? dot / denom : 0.0;
}