faiss
faiss是为稠密向量提供高效相似度搜索和聚类的框架。由Facebook AI Research研发。
详见github https://github.com/facebookresearch/faiss
faiss常用的两个相似度搜索是L2欧氏距离搜索和余弦距离搜索(注意不是余弦相似度)
简单的使用流程:
import faiss
index = faiss.IndexFlatL2(d) # 建立L2索引,d是向量维度
index = faiss.IndexFlatIP(d) # 建立Inner product索引
index.add(train) # 添加矩阵
D,I = index.search(test, k) # (D.shape = test.shape[0] * k, I同理)
上述代码实现了对于test向量(也可以是矩阵)索引train中L2距离最近的k个向量,返回其具体distance和索引index
IndexFlatIP()函数实现的是余弦距离的计算也就是xytxy^txyt,显然,当向量范数不为一的情况下不能等同于余弦相似度xyt∣∣x∣∣∣∣y∣∣\frac{xy^t}{||x||||y||}∣∣x∣∣∣∣