Faiss

- Main Page
- Namespaces
- Classes
- Files

- File List

All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
1-Flat.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
13 #include <faiss/IndexFlat.h>
14
15
16 int main() {
17 int d = 64; // dimension
18 int nb = 100000; // database size
19 int nq = 10000; // nb of queries
20
21 float *xb = new float[d * nb];
22 float *xq = new float[d * nq];
23
24 for(int i = 0; i < nb; i++) {
25 for(int j = 0; j < d; j++)
26 xb[d * i + j] = drand48();
27 xb[d * i] += i / 1000.;
28 }
29
30 for(int i = 0; i < nq; i++) {
31 for(int j = 0; j < d; j++)
32 xq[d * i + j] = drand48();
33 xq[d * i] += i / 1000.;
34 }
35
36 faiss::IndexFlatL2 index(d); // call constructor
37 printf("is_trained = %s\n", index.is_trained ? "true" : "false");
38 index.add(nb, xb); // add vectors to the index
39 printf("ntotal = %ld\n", index.ntotal);
40
41 int k = 4;
42
43 { // sanity check: search 5 first vectors of xb
44 long *I = new long[k * 5];
45 float *D = new float[k * 5];
46
47 index.search(5, xb, k, D, I);
48
49 // print results
50 printf("I=\n");
51 for(int i = 0; i < 5; i++) {
52 for(int j = 0; j < k; j++)
53 printf("%5ld ", I[i * k + j]);
54 printf("\n");
55 }
56
57 printf("D=\n");
58 for(int i = 0; i < 5; i++) {
59 for(int j = 0; j < k; j++)
60 printf("%7g ", D[i * k + j]);
61 printf("\n");
62 }
63
64 delete [] I;
65 delete [] D;
66 }
67
68
69 { // search xq
70 long *I = new long[k * nq];
71 float *D = new float[k * nq];
72
73 index.search(nq, xq, k, D, I);
74
75 // print results
76 printf("I (5 first results)=\n");
77 for(int i = 0; i < 5; i++) {
78 for(int j = 0; j < k; j++)
79 printf("%5ld ", I[i * k + j]);
80 printf("\n");
81 }
82
83 printf("I (5 last results)=\n");
84 for(int i = nq - 5; i < nq; i++) {
85 for(int j = 0; j < k; j++)
86 printf("%5ld ", I[i * k + j]);
87 printf("\n");
88 }
89
90 delete [] I;
91 delete [] D;
92 }
93
94
95
96 delete [] xb;
97 delete [] xq;
98
99 return 0;
100 }
faiss::IndexFlatL2
Definition: IndexFlat.h:81