Skip to content

Commit 632d4a6

Browse files
committed
fix: cosine similarity throws when vectors unequal lengths
1 parent 33dc1a3 commit 632d4a6

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

lib/extensions/vector.dart

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import 'package:ml_linalg/vector.dart';
33

44
extension Similarity on Vector {
55
double cosineSimilarity(Vector vector) {
6+
if (length != vector.length) {
7+
print('Fonnx.Vector.Similarity.cosineSimilarity: Vectors must have the same length. A vector has length $length, while the other has length ${vector.length}. Returning 0 for similarity.');
8+
return 0.0;
9+
}
610
final distance = distanceTo(vector, distance: Distance.cosine);
711
return 1.0 - distance;
812
}

0 commit comments

Comments
 (0)