1. Faiss簡介
Faiss是Facebook開源的一款用于大規(guī)模P維向量最近鄰檢索的工具。
Faiss is a library for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. It also contains supporting code for evaluation and parameter tuning. Faiss is written in C++ with complete wrappers for Python/numpy. Some of the most useful algorithms are implemented on the GPU. It is developed by Facebook AI Research.
他底層采用C ++編寫,并且提供了python的封裝代碼。主要功能是,對(duì)于一個(gè)給定的向量,在所有已知的向量庫中找出與其相似度較高的向量,即該向量的前k個(gè)最近鄰向量。
尤其是隨著萬物皆可Embedding時(shí)代的到來,F(xiàn)aiss越來越受到人們關(guān)注。
2. Faiss安裝
可以pip安裝
pip install faiss-cpu --no-cache
也可以采用conda安裝
#CPU 版本
conda install faiss-cpu -c pytorch
# GPU 版本
conda install faiss-gpu cudatoolkit=8.0 -c pytorch # For CUDA8
conda install faiss-gpu cudatoolkit=9.0 -c pytorch # For CUDA9
conda install faiss-gpu cudatoolkit=10.0 -c pytorch # For CUDA10
3. Faiss Action
faiss的使用方法也比較簡單,歸納為以下三個(gè)步驟:
- 構(gòu)建向量庫,對(duì)已知的數(shù)據(jù)進(jìn)行向量,最終以矩陣的形式表示
- 為矩陣選擇合適的index,將第一步得到的矩陣add到index中
- search得到最終結(jié)果
以IndexFlatL2為例,看一下faiss的用法:
import numpy as np
import faiss
d = 64
nb = 100000
nq = 10000
# 構(gòu)建向量庫
xb = np.random.random((nb, d)).astype('float32')
xb[:, 0] += np.arange(nb) / 1000.
xq = np.random.random((nq, d)).astype('float32')
xq[:, 0] += np.arange(nq) / 1000.
# 關(guān)鍵步驟,build index
index = faiss.IndexFlatL2(d)
index.add(xb)
k = 4
D, I = index.search(xq[:5], k) # 分別返回距離和索引