Skip to content

Commit

Permalink
fix: cosine similarity throws when vectors unequal lengths
Browse files Browse the repository at this point in the history
  • Loading branch information
jpohhhh committed Jan 12, 2025
1 parent 33dc1a3 commit 632d4a6
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/extensions/vector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import 'package:ml_linalg/vector.dart';

extension Similarity on Vector {
double cosineSimilarity(Vector vector) {
if (length != vector.length) {
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.');
return 0.0;
}
final distance = distanceTo(vector, distance: Distance.cosine);
return 1.0 - distance;
}
Expand Down

0 comments on commit 632d4a6

Please sign in to comment.