Skip to content

Commit 7dabe4a

Browse files
author
Joseph Smith
committed
Use proper cosine similarity
1 parent ac5bb48 commit 7dabe4a

1 file changed

Lines changed: 4 additions & 3 deletions

File tree

media-api/app/lib/elasticsearch/ElasticSearch.scala

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -282,12 +282,13 @@ class ElasticSearch(
282282
resolveHit(hit).map { image =>
283283
val semanticScore = image.instance.embedding
284284
.flatMap(_.cohereEmbedV4)
285-
// Save some computation by assuming normalised vectors
286-
// TODO: double check this assumption
285+
// We can't use the dot product shortcut because image vectors
286+
// are truncated 256-dim versions of a normalised 1536-dim vector,
287+
// meaning they will not have magnitude 1.
287288
// Note this is true cosine similarity from -1 to 1,
288289
// *not* the ES-normalised score, but when we max-normalise
289290
// later it will end up in the range 0-1.
290-
.map(e => VectorUtils.dotProduct(e.image, queryEmbedding))
291+
.map(e => VectorUtils.cosineSimilarity(e.image, queryEmbedding))
291292
.getOrElse(-1.0)
292293
HybridResult(hit.id, lexicalScore = hit.score, semanticScore = semanticScore, image = image)
293294
}

0 commit comments

Comments
 (0)