Currently, I see faiss support L2 distance and inner product distance. My question is whether faiss distance function support cosine distance.
Thanks.
Gary
OS:
Faiss version:
Faiss compilation options:
Running on:
Interface:
This seems like a duplicate of #95. The cosine distance is obtained with the inner product after normalizing all vectors to unit norm.
Thanks Eduardo!
Does that mean if I want to use cosine similarity, I need to convert both the query vectors and the centroids vectors to unit vector beforehand?
Does that mean if I want to use cosine similarity, I need to convert both the query vectors and the centroids vectors to unit vector beforehand?
That is correct.
Thanks for your quick reply. And I will try to add cosine distance option to faiss, since sometimes the input vectors are not unit vectors and converting them beforehand on CPU cost more time.
@Qiaogx please don't spend effort on that. Anything you can do will be more expensive than normalizing the vectors.
Hi Matthijs,
When using cosine similarity, except normalizing the query and centroid vectors, are there any other factors I need to pay attention to? I normalized the vectors and set l2Distance_ to False in faiss/gpu/impl/FlatIndex.cu, but It did not work.
Thanks.
Hi Matthijs,
When using cosine similarity, except normalizing the query and centroid vectors, are there any other factors I need to pay attention to? I normalized the vectors and set l2Distance_ to False in faiss/gpu/impl/FlatIndex.cu, but It did not work.
Thanks.
this works.
quantizer = faiss.IndexFlatIP(d)
index = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_INNER_PRODUCT)
Thank you@liqima. However, it seems IndexIVFPQ does not fully support inner product.
Inner product con IndexIVFPQ is fully supported on CPU, otherwise it is a bug.
Another note: for normalized vectors, L2 and inner product search are equivalent so you can use L2 search.
No activity. Closing.
Hi,@Qiaogx,can you tell me how do you achieve the cosine distance? normalized vector or other ways?
Note that there is now a FAQ entry for this question:
https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances#how-can-i-index-vectors-for-cosine-similarity
Note that there is now a FAQ entry for this question:
https://github.com/facebookresearch/faiss/wiki/FAQ#how-can-i-index-vectors-for-cosine-distance
This is the updated link:
https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances#how-can-i-index-vectors-for-cosine-similarity
Thanks! updated the link above to avoid confusion.
Most helpful comment
This seems like a duplicate of #95. The cosine distance is obtained with the inner product after normalizing all vectors to unit norm.