Debian Codegraph @

tutorial/python/1-Flat.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 #
3 # This source code is licensed under the MIT license found in the
4 # LICENSE file in the root directory of this source tree.
5
6 import numpy as np
7
8 d = 64 # dimension
9 nb = 100000 # database size
10 nq = 10000 # nb of queries
11 np.random.seed(1234) # make reproducible
12 xb = np.random.random((nb, d)).astype('float32')
13 xb[:, 0] += np.arange(nb) / 1000.
14 xq = np.random.random((nq, d)).astype('float32')
15 xq[:, 0] += np.arange(nq) / 1000.
16
17 import faiss # make faiss available
18 index = faiss.IndexFlatL2(d) # build the index
19 print(index.is_trained)
20 index.add(xb) # add vectors to the index
21 print(index.ntotal)
22
23 k = 4 # we want to see 4 nearest neighbors
24 D, I = index.search(xb[:5], k) # sanity check
25 print(I)
26 print(D)
27 D, I = index.search(xq, k) # actual search
28 print(I[:5]) # neighbors of the 5 first queries
29 print(I[-5:]) # neighbors of the 5 last queries