10分鐘入門faiss相似向量檢索
一,faiss簡(jiǎn)介
faiss全稱 Facebook AI Similarity Search,是FaceBook的AI團(tuán)隊(duì)針對(duì)大規(guī)模向量 進(jìn)行 TopK 相似向量 檢索 的一個(gè)工具,使用C++編寫,有python接口,對(duì)10億量級(jí)的索引可以做到毫秒級(jí)檢索的性能。
使用faiss 搭配合適的model和embedding函數(shù),可以幫助我們 構(gòu)建 人臉識(shí)別,相似圖片檢索,LLM知識(shí)庫(kù)問答,推薦系統(tǒng)召回模塊 等應(yīng)用。
faiss的主要原理是構(gòu)建base vectors向量數(shù)據(jù)的index索引,然后利用索引對(duì)search vectors 實(shí)現(xiàn) TopK 相似向量檢索。
faiss支持許多不同的構(gòu)建索引的方式,以下是一些較推薦使用的類型。
1,Flat:暴力精確檢索,全局最優(yōu),適合數(shù)十萬級(jí)。
2,IVF100,Flat:倒排暴力檢索(100聚類后暴力檢索),非全局最優(yōu)但召回高,適合數(shù)百萬級(jí)。
3, HNSW64: 圖網(wǎng)絡(luò)檢索,Hierarchical NSW(Navigable Small World),每個(gè)節(jié)點(diǎn)64條邊,檢索復(fù)雜度log(logn),適合千萬上億規(guī)模以及更大規(guī)模的圖索引,缺點(diǎn)是構(gòu)建索引過程較慢,占用很大的存儲(chǔ)。
公眾號(hào)算法美食屋后臺(tái)回復(fù)關(guān)鍵詞:源碼,獲取本文notebook源代碼。
二,F(xiàn)aiss安裝
pip install faiss-cpu # faiss-gpu (一般來說cpu足夠快了)
三,代碼范例
import faiss
import numpy as np
# 〇,基本參數(shù)設(shè)置
d = 64 # 向量維度
nb = 100000 # index向量庫(kù)的數(shù)據(jù)量
nq = 1000 # 待檢索query的數(shù)目
index_type = 'Flat' # index 類型
metric_type = faiss.METRIC_INNER_PRODUCT # 度量(相似度/距離)類型
# 一,準(zhǔn)備向量庫(kù)向量
print('============================== 1,base vector ==============================')
np.random.seed(1234)
xb = np.random.random((nb, d)).astype('float32')
xb[:, 0] += np.arange(nb) / 1000. # index向量庫(kù)的向量
faiss.normalize_L2(xb)
print('xb.shape = ',xb.shape,'\n')
# 二,準(zhǔn)備查詢向量
print('============================== 2,query vector ==============================')
xq = np.random.random((nq, d)).astype('float32')
xq[:, 0] += np.arange(nq) / 1000. # 待檢索的query向量
faiss.normalize_L2(xq)
print('xq.shape = ',xq.shape,'\n')
# 三,構(gòu)建向量庫(kù)索引
print('============================== 3,create&train ==============================')
index = faiss.index_factory(d,index_type,metric_type) #等價(jià)于 faiss.IndexFlatIP(d)
print('index.is_trained=',index.is_trained) # 輸出為True,代表該類index不需要訓(xùn)練,只需要add向量進(jìn)去即可
index.train(xb)
index.add(xb) # 將向量庫(kù)中的向量加入到index中
print('index.ntotal=',index.ntotal,'\n') # 輸出index中包含的向量總數(shù),為100000
# 四,相似向量查詢
print('============================== 4, search ==============================')
k = 4 # topK的K值
D, I = index.search(xq, k) # xq為待檢索向量,返回的I為每個(gè)待檢索query最相似TopK的索引list,D為其對(duì)應(yīng)的距離
print('nearest vector ids:\n',I[:5],'\n')
print('metric(distances/scores) to query:\n',D[-5:],'\n')
# 五,增刪索引向量
print('============================== 5, add&remove ==============================')
xa = np.random.random((10000, d)).astype('float32')
xa[:, 0] += np.arange(len(xa)) / 1000.
faiss.normalize_L2(xa)
index.add(xa)
print('after add, index.ntotal=',index.ntotal)
index.remove_ids(np.arange(1000,1111))
print('after remove, index.ntotal=',index.ntotal,'\n')
# 六,保存加載索引
print('============================== 6, write&read ==============================')
faiss.write_index(index, "large.index")
index_loaded = faiss.read_index('large.index')
print('index_loaded.ntotal=', index_loaded.ntotal)
輸出如下:
============================== 1,base vector ==============================
xb.shape = (100000, 64)
============================== 2,query vector ==============================
xq.shape = (1000, 64)
============================== 3,create&train ==============================
index.is_trained= True
index.ntotal= 100000
============================== 4, search ==============================
nearest vector ids:
[[ 207 381 1394 1019]
[ 300 911 142 526]
[ 838 1541 527 148]
[ 196 359 184 466]
[ 526 120 917 765]]
metric(distances/scores) to query:
[[0.87687665 0.86128205 0.85667723 0.85451 ]
[0.8702938 0.86668813 0.85934925 0.8523142 ]
[0.862915 0.85807455 0.85384977 0.8499449 ]
[0.8692 0.86600477 0.8647547 0.8634621 ]
[0.8539625 0.84914947 0.84744585 0.8432568 ]]
============================== 5, add&remove ==============================
after add, index.ntotal= 110000
after remove, index.ntotal= 109889
============================== 6, write&read ==============================
index_loaded.ntotal= 109889
參考文章:
1,《Faiss入門以及應(yīng)用經(jīng)驗(yàn)記錄》
https://zhuanlan.zhihu.com/p/357414033
2,《ANN召回算法之HNSW》
https://zhuanlan.zhihu.com/p/379372268
