faiss的安裝使用

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è)步驟:

  1. 構(gòu)建向量庫,對(duì)已知的數(shù)據(jù)進(jìn)行向量,最終以矩陣的形式表示
  2. 為矩陣選擇合適的index,將第一步得到的矩陣add到index中
  3. 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)   # 分別返回距離和索引
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容