Faiss
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
2-IVFFlat.cpp
1 
2 /**
3  * Copyright (c) 2015-present, Facebook, Inc.
4  * All rights reserved.
5  *
6  * This source code is licensed under the CC-by-NC license found in the
7  * LICENSE file in the root directory of this source tree.
8  */
9 
10 #include <cstdio>
11 #include <cstdlib>
12 #include <cassert>
13 
14 #include <faiss/IndexFlat.h>
15 #include <faiss/IndexIVF.h>
16 
17 
18 int main() {
19  int d = 64; // dimension
20  int nb = 100000; // database size
21  int nq = 10000; // nb of queries
22 
23  float *xb = new float[d * nb];
24  float *xq = new float[d * nq];
25 
26  for(int i = 0; i < nb; i++) {
27  for(int j = 0; j < d; j++)
28  xb[d * i + j] = drand48();
29  xb[d * i] += i / 1000.;
30  }
31 
32  for(int i = 0; i < nq; i++) {
33  for(int j = 0; j < d; j++)
34  xq[d * i + j] = drand48();
35  xq[d * i] += i / 1000.;
36  }
37 
38 
39  int nlist = 100;
40  int k = 4;
41 
42  faiss::IndexFlatL2 quantizer(d); // the other index
43  faiss::IndexIVFFlat index(&quantizer, d, nlist, faiss::METRIC_L2);
44  // here we specify METRIC_L2, by default it performs inner-product search
45  assert(!index.is_trained);
46  index.train(nb, xb);
47  assert(index.is_trained);
48  index.add(nb, xb);
49 
50  { // search xq
51  long *I = new long[k * nq];
52  float *D = new float[k * nq];
53 
54  index.search(nq, xq, k, D, I);
55 
56  printf("I=\n");
57  for(int i = nq - 5; i < nq; i++) {
58  for(int j = 0; j < k; j++)
59  printf("%5ld ", I[i * k + j]);
60  printf("\n");
61  }
62 
63  index.nprobe = 10;
64  index.search(nq, xq, k, D, I);
65 
66  printf("I=\n");
67  for(int i = nq - 5; i < nq; i++) {
68  for(int j = 0; j < k; j++)
69  printf("%5ld ", I[i * k + j]);
70  printf("\n");
71  }
72 
73  delete [] I;
74  delete [] D;
75  }
76 
77 
78 
79  delete [] xb;
80  delete [] xq;
81 
82  return 0;
83 }