Faiss的第一个示例 Flat
flyfish
代码分析
将数据的维度变小,代码量变小以便分析
import mkl
mkl.get_max_threads()
import numpy as np
d = 3# # dimension
nb = 10# # database size
nq = 2# # nb of queries
np.random.seed(1234) # make reproducible
xb = np.random.random((nb, d)).astype('float32')
print("xb:",xb)
xb[:, 0] += np.arange(nb) / 1000.
xq = np.random.random((nq, d)).astype('float32')
print("xq:",xq)
xq[:, 0] += np.arange(nq) / 1000.
print("xb:",xb)
print("xq:",xq)
import faiss # make faiss available
index = faiss.IndexFlatL2(d) # build the index
print(index.is_trained)
index.add(xb) # add vectors to the index
print(index.ntotal)
k = 4 # we want to see 4 nearest neighbors
D, I = index.search(xq, k) # actual search
print("I:",I)
print("D:",D)
xb:数据库向量,维度是(nb,d) 这里是(10,3)
xq:查询向量,维度是(nq,d) 这里是(2,3)
np.random.seed(1234)
指定生成“特定”的随机数-与seed 1234 相关,下次生成的数据会与第一次生成的随机数相同
如果seed中参数为空,则生成的随机数“完全”随机
xb[:, 0] += np.arange(nb) / 1000. 的作用
每条数据的第一个元素全都加上了该条数据的index
np.random.random产生的数据是[0.0, 1.0)
如果不加, 则top1是该条数据本身。
#输出
xb: [[0.19151945 0.62210876 0.43772775]
[0.7853586 0.77997583 0.2725926 ]
[0.27646425 0.8018722 0.95813936]
[0.87593263 0.35781726 0.5009951 ]
[0.6834629 0.71270204 0.37025076]
[0.5611962 0.50308317 0.01376845]
[0.7728266 0.8826412 0.364886 ]
[0.6153962 0.07538124 0.368824 ]
[0.9331401 0.65137815 0.39720258]
[0.78873014 0.31683612 0.56809866]]
xq: [[0.8691274 0.4361734 0.8021476 ]
[0.14376682 0.70426095 0.7045813 ]]
xb: [[0.19151945 0.62210876 0.43772775]
[0.7863586 0.77997583 0.2725926 ]
[0.27846426 0.8018722 0.95813936]
[0.87893265 0.35781726 0.5009951 ]
[0.6874629 0.71270204 0.37025076]
[0.5661962 0.50308317 0.01376845]
[0.7788266 0.8826412 0.364886 ]
[0.62239623 0.07538124 0.368824 ]
[0.9411401 0.65137815 0.39720258]
[0.79773015 0.31683612 0.56809866]]
xq: [[0.8691274 0.4361734 0.8021476 ]
[0.14476682 0.70426095 0.7045813 ]]
True
10
I: [[9 3 8 4]
[0 2 4 6]]
D: [[0.07411814 0.09692883 0.21547961 0.296005 ]
[0.08014572 0.09169459 0.40636742 0.54924417]]
is_trianed:索引是否已经被训练过
ntotal:得到当前索引中向量的个数
IndexFlatL2,这是暴力检索L2距离
add方法用于向Index中添加xb向量
search方法用于在add向量后的索引中检索xq的k个近邻
最后的输出
I表示索引,D表示距离
例如以查找对象xq的第一个向量[0.8691274 0.4361734 0.8021476 ]为例
4个近邻的索引[9 3 8 4]
每个向量与xq的第一个向量的距离是 [0.07411814 0.09692883 0.21547961 0.296005 ]