|
| 1 | +""" |
| 2 | +@file : 001-使用欧式距离和内积的方式检索.py |
| 3 | +@author : xiaolu |
| 4 | +@email : luxiaonlp@163.com |
| 5 | +@time : 2021-08-09 |
| 6 | +""" |
| 7 | +import faiss |
| 8 | +import numpy as np |
| 9 | + |
| 10 | + |
| 11 | +if __name__ == '__main__': |
| 12 | + nb, d = 100, 64 # 100个64维的向量 |
| 13 | + np.random.seed(1234) |
| 14 | + xb = np.random.random((nb, d)).astype('float32') |
| 15 | + # print(xb[:2]) |
| 16 | + |
| 17 | + # 为了使随机产生的向量有较大区别进行人工调整向量 |
| 18 | + xb[:, 0] += np.arange(nb).astype('float32') / 1000 |
| 19 | + # print(xb[:2]) |
| 20 | + |
| 21 | + nq = 10 # 生成十个待查询的向量 |
| 22 | + xq = np.random.random((nq, d)).astype('float32') |
| 23 | + xq[:, 0] += np.arange(nq).astype('float32') / 1000 # 同理 为了有区分度 加点噪声 |
| 24 | + |
| 25 | + # 建立索引 IndexFlatL2使用欧式距离 |
| 26 | + index = faiss.IndexFlatL2(d) # 这里要传入向量的维度信息 |
| 27 | + # print(index.is_trained) # index是否被训练 |
| 28 | + |
| 29 | + index.add(xb) # 添加向量 |
| 30 | + print(index.ntotal) # 看看加入了多少行 |
| 31 | + |
| 32 | + k = 4 |
| 33 | + D, I = index.search(xb[:5], k) |
| 34 | + print(D) |
| 35 | + print('*'*100) |
| 36 | + print(I) |
| 37 | + ''' |
| 38 | + [[0. 7.2511625 7.9736595 8.278999 ] # 第一个向量与最相关的前四个向量的L2距离 |
| 39 | + [0. 7.4973536 7.647169 7.9029927] |
| 40 | + [0. 7.2815123 8.11772 8.547238 ] |
| 41 | + [0. 7.5279865 7.790914 8.373755 ] |
| 42 | + [0. 7.5328097 7.75144 7.786872 ]] |
| 43 | + **************************************************************************************************** |
| 44 | + [[ 0 78 85 41] # 对应的索引 第0个向量肯定与它自己最近 看上面的距离 也可以看出其距离就是0 |
| 45 | + [ 1 77 88 98] |
| 46 | + [ 2 13 43 46] |
| 47 | + [ 3 18 64 74] |
| 48 | + [ 4 18 52 61]] |
| 49 | + ''' |
| 50 | + |
| 51 | + index = faiss.IndexFlatIP(d) # 使用内积的方式 |
| 52 | + index.add(xb) |
| 53 | + k = 4 |
| 54 | + D, I = index.search(xb[:5], k) |
| 55 | + print(D) |
| 56 | + print('*'*100) |
| 57 | + print(I) |
0 commit comments