溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python如何利用Faiss庫實現(xiàn)ANN近鄰搜索

發(fā)布時間:2020-08-03 09:39:29 來源:億速云 閱讀:296 作者:小豬 欄目:開發(fā)技術(shù)

這篇文章主要講解了Python如何利用Faiss庫實現(xiàn)ANN近鄰搜索,內(nèi)容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。

Embedding的近鄰搜索是當前圖推薦系統(tǒng)非常重要的一種召回方式,通過item2vec、矩陣分解、雙塔DNN等方式都能夠產(chǎn)出訓練好的user embedding、item embedding,對于embedding的使用非常的靈活:

  • 輸入user embedding,近鄰搜索item embedding,可以給user推薦感興趣的items
  • 輸入user embedding,近鄰搜搜user embedding,可以給user推薦感興趣的user
  • 輸入item embedding,近鄰搜索item embedding,可以給item推薦相關的items
     

然而有一個工程問題,一旦user embedding、item embedding數(shù)據(jù)量達到一定的程度,對他們的近鄰搜索將會變得非常慢,如果離線階段提前搜索好在高速緩存比如redis存儲好結(jié)果當然沒問題,但是這種方式很不實時,如果能在線階段上線幾十MS的搜索當然效果最好。

Faiss是Facebook AI團隊開源的針對聚類和相似性搜索庫,為稠密向量提供高效相似度搜索和聚類,支持十億級別向量的搜索,是目前最為成熟的近似近鄰搜索庫。

接下來通過jupyter notebook的代碼,給大家演示下使用faiss的簡單流程,內(nèi)容包括:

  • 讀取訓練好的Embedding數(shù)據(jù)
  • 構(gòu)建faiss索引,將待搜索的Embedding添加進去
  • 取得目標Embedding,實現(xiàn)搜索得到ID列表
  • 根據(jù)ID獲取電影標題,返回結(jié)果
     

對于已經(jīng)訓練好的Embedding怎樣實現(xiàn)高速近鄰搜索是一個工程問題,facebook的faiss庫可以構(gòu)建多種embedding索引實現(xiàn)目標embedding的高速近鄰搜索,能夠滿足在線使用的需要

安裝命令:

conda install -c pytorch faiss-cpu 

提前總結(jié)下faiss使用經(jīng)驗:

1. 為了支持自己的ID,可以用faiss.IndexIDMap包裹faiss.IndexFlatL2即可

2. embedding數(shù)據(jù)都需要轉(zhuǎn)換成np.float32,包括索引中的embedding以及待搜索的embedding

3. ids需要轉(zhuǎn)換成int64類型

1. 準備數(shù)據(jù)

import pandas as pd
import numpy as np
df = pd.read_csv("./datas/movielens_sparkals_item_embedding.csv")
df.head()
idfeatures
010[0.25866490602493286, 0.3560594320297241, 0.15…
120[0.12449632585048676, -0.29282501339912415, -0…
230[0.9557555317878723, 0.6764761805534363, 0.114…
340[0.3184879720211029, 0.6365472078323364, 0.596…
450[0.45523127913475037, 0.34402626752853394, -0….

構(gòu)建ids

ids = df["id"].values.astype(np.int64)
type(ids), ids.shape
(numpy.ndarray, (3706,))
ids.dtype
dtype('int64')
ids_size = ids.shape[0]
ids_size
3706

構(gòu)建datas

import json
import numpy as np
datas = []
for x in df["features"]:
 datas.append(json.loads(x))
datas = np.array(datas).astype(np.float32)
datas.dtype
dtype('float32')
datas.shape
(3706, 10)
datas[0]
array([ 0.2586649 , 0.35605943, 0.15589039, -0.7067125 , -0.07414215,
 -0.62500805, -0.0573845 , 0.4533663 , 0.26074877, -0.60799956],
 dtype=float32)
# 維度
dimension = datas.shape[1]
dimension
10

2. 建立索引

import faiss
index = faiss.IndexFlatL2(dimension)
index2 = faiss.IndexIDMap(index)
ids.dtype
dtype('int64')
index2.add_with_ids(datas, ids)
index.ntotal
3706

4. 搜索近鄰ID列表

df_user = pd.read_csv("./datas/movielens_sparkals_user_embedding.csv")
df_user.head()
id features
idfeatures
010[0.5974288582801819, 0.17486965656280518, 0.04…
120[1.3099910020828247, 0.5037978291511536, 0.260…
230[-1.1886241436004639, -0.13511677086353302, 0….
340[1.0809299945831299, 1.0048035383224487, 0.986…
450[0.42388680577278137, 0.5294889807701111, -0.6…
user_embedding = np.array(json.loads(df_user[df_user["id"] == 10]["features"].iloc[0]))
user_embedding = np.expand_dims(user_embedding, axis=0).astype(np.float32)
user_embedding
array([[ 0.59742886, 0.17486966, 0.04345559, -1.3193961 , 0.5313592 ,
 -0.6052168 , -0.19088413, 1.5307966 , 0.09310367, -2.7573566 ]],
 dtype=float32)
user_embedding.shape
(1, 10)
user_embedding.dtype
dtype('float32')
topk = 30
D, I = index.search(user_embedding, topk) # actual search
I.shape
(1, 30)
I
array([[3380, 2900, 1953, 121, 3285, 999, 617, 747, 2351, 601, 2347,
 42, 2383, 538, 1774, 980, 2165, 3049, 2664, 367, 3289, 2866,
 2452, 547, 1072, 2055, 3660, 3343, 3390, 3590]])

5. 根據(jù)電影ID取出電影信息

target_ids = pd.Series(I[0], name="MovieID")
target_ids.head()
0 3380
1 2900
2 1953
3 121
4 3285
Name: MovieID, dtype: int64
df_movie = pd.read_csv("./datas/ml-1m/movies.dat",
  sep="::", header=None, engine="python",
  names = "MovieID::Title::Genres".split("::"))
df_movie.head()
MovieIDTitleGenres
01Toy Story (1995)Animation|Children's|Comedy
12Jumanji (1995)Adventure|Children's|Fantasy
23Grumpier Old Men (1995)Comedy|Romance
34Waiting to Exhale (1995)Comedy|Drama
45Father of the Bride Part II (1995)Comedy
df_result = pd.merge(target_ids, df_movie)
df_result.head()
MovieIDTitleGenres
03380Railroaded! (1947)Film-Noir
12900Monkey Shines (1988)Horror|Sci-Fi
21953French Connection, The (1971)Action|Crime|Drama|Thriller
3121Boys of St. Vincent, The (1993)Drama
43285Beach, The (2000)Adventure|Drama

看完上述內(nèi)容,是不是對Python如何利用Faiss庫實現(xiàn)ANN近鄰搜索有進一步的了解,如果還想學習更多內(nèi)容,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI