From 3c24345b68be89ebd2befbefd53d5ab0c7550505 Mon Sep 17 00:00:00 2001 From: laurenspriem Date: Mon, 6 May 2024 16:38:19 +0530 Subject: [PATCH] [mob][photos] Add method for safe cosine distance --- .../face_ml/face_clustering/cosine_distance.dart | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/mobile/lib/services/machine_learning/face_ml/face_clustering/cosine_distance.dart b/mobile/lib/services/machine_learning/face_ml/face_clustering/cosine_distance.dart index 7ba4c582b..0611a1d83 100644 --- a/mobile/lib/services/machine_learning/face_ml/face_clustering/cosine_distance.dart +++ b/mobile/lib/services/machine_learning/face_ml/face_clustering/cosine_distance.dart @@ -1,9 +1,9 @@ import 'dart:math' show sqrt; -import "package:ml_linalg/vector.dart"; +import "package:ml_linalg/linalg.dart"; /// Calculates the cosine distance between two embeddings/vectors using SIMD from ml_linalg -/// +/// /// WARNING: This assumes both vectors are already normalized! double cosineDistanceSIMD(Vector vector1, Vector vector2) { if (vector1.length != vector2.length) { @@ -13,6 +13,17 @@ double cosineDistanceSIMD(Vector vector1, Vector vector2) { return 1 - vector1.dot(vector2); } +/// Calculates the cosine distance between two embeddings/vectors using SIMD from ml_linalg +/// +/// WARNING: Only use when you're not sure if vectors are normalized. If you're sure they are, use [cosineDistanceSIMD] instead for better performance. +double cosineDistanceSIMDSafe(Vector vector1, Vector vector2) { + if (vector1.length != vector2.length) { + throw ArgumentError('Vectors must be the same length'); + } + + return vector1.distanceTo(vector2, distance: Distance.cosine); +} + /// Calculates the cosine distance between two embeddings/vectors. /// /// Throws an ArgumentError if the vectors are of different lengths or