faiss的python接口使用
生活随笔
收集整理的這篇文章主要介紹了
faiss的python接口使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
faiss的python接口使用
- 1. 簡介
- 2. 安裝
- 3. 示例
1. 簡介
faiss是一種ann(Approximate Nearest Neighbor)庫,可以用于特征的入庫,檢索。
不僅可以在cpu上使用,還可以利用GPU進(jìn)行檢索,提高檢索的速度。
具體可以參考:https://github.com/facebookresearch/faiss
2. 安裝
cpu版本,適用于各個(gè)系統(tǒng)
pip install faiss-cpucpu + gpu版本,目前不適用于windows系統(tǒng)
pip install faiss-gpu3. 示例
新建索引
import faiss# 傳入特征維度 dim = 2048# IndexFlatIP表示利用內(nèi)積來比較特征的相似度 # 這里一般會讓提取的特征進(jìn)行L2歸一化,那么內(nèi)積就等于余弦相似度 index_ip = faiss.IndexFlatIP(dim)# IndexFlatL2表示利用L2距離來比較特征的相似度 index_l2 = faiss.IndexFlatL2(dim)添加特征入庫
import numpy as np# 新建一個(gè)特征,維度為2048,shape為(1, 2048) feature = np.random.random((1, 2048)).astype('float32') index_ip.add(feature)# 當(dāng)然,也可以一次性添加多個(gè)特征 features = np.random.random((10, 2048)).astype('float32') index_ip.add(features)# 打印index_ip包含的特征數(shù)量 print(index_ip.ntotal)自己指定每個(gè)特征的id
在第2步中,添加特征的id是根據(jù)特征入庫的順序?qū)?yīng)的,如果想自己指定id,可以用IndexIDMap包裝一層,代碼如下所示:
index_ids = faiss.IndexFlatIP(2048) index_ids = faiss.IndexIDMap(index_ids)# 添加特征,并指定id,注意添加的id類型為int64 ids = 20 feature_ids = np.random.random((1, 2048)).astype('float32') index_ids.add_with_ids(feature_ids, np.array((ids,)).astype('int64'))這里要注意,包裝的索引必須是空的,即一開始新建索引之后,就進(jìn)行包裝,不能入庫過一些特征后中途再包裝。
檢索
feature_search = np.random.random((1, 2048)).astype('float32')# 檢索最相似的topK個(gè)特征 topK = 5 D, I = index_ip.search(feature_search, topK) # 返回的D表示相似度(或者距離), I表示檢索的topK個(gè)特征id(索引)保存/讀取索引文件
faiss的另一個(gè)優(yōu)點(diǎn)是,可以將保存著特征的索引持久化,保存為文件,類似數(shù)據(jù)庫,這樣就不用每次都提取特征了。
# 保存索引 faiss.write_index(index_ip, 'my.index')# 讀取索引 index = faiss.read_index('my.index')GPU的使用
# 利用單個(gè)gpu res = faiss.StandardGpuResources()gpu_index = faiss.index_cpu_to_gpu(res, 0, index_ip)其他操作可以參考faiss在github上的地址。
結(jié)束。
總結(jié)
以上是生活随笔為你收集整理的faiss的python接口使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下JAVA IDE安装汇总
- 下一篇: websocket python爬虫_p