Faiss

- Main Page
- Namespaces
- Classes
- Files

- File List

All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
/data/users/matthijs/github_faiss/faiss/Clustering.cpp
1 /**
2 * Copyright (c) 2015-present, Facebook, Inc.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD+Patents license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9 /* Copyright 2004-present Facebook. All Rights Reserved.
10 kmeans clustering routines
11 */
12
13 #include "Clustering.h"
14
15
16
17 #include <cmath>
18 #include <cstdio>
19 #include <cstring>
20
21 #include "utils.h"
22 #include "FaissAssert.h"
23 #include "IndexFlat.h"
24
25 namespace faiss {
26
27 ClusteringParameters::ClusteringParameters ():
28 niter(25),
29 nredo(1),
30 verbose(false), spherical(false),
31 update_index(false),
32 frozen_centroids(false),
33 min_points_per_centroid(39),
34 max_points_per_centroid(256),
35 seed(1234)
36 {}
37 // 39 corresponds to 10000 / 256 -> to avoid warnings on PQ tests with randu10k
38
39
40 Clustering::Clustering (int d, int k):
41 d(d), k(k) {}
42
43 Clustering::Clustering (int d, int k, const ClusteringParameters &cp):
44 ClusteringParameters (cp), d(d), k(k) {}
45
46
47
48 static double imbalance_factor (int n, int k, long *assign) {
49 std::vector<int> hist(k, 0);
50 for (int i = 0; i < n; i++)
51 hist[assign[i]]++;
52
53 double tot = 0, uf = 0;
54
55 for (int i = 0 ; i < k ; i++) {
56 tot += hist[i];
57 uf += hist[i] * (double) hist[i];
58 }
59 uf = uf * k / (tot * tot);
60
61 return uf;
62 }
63
64
65
66
67 void Clustering::train (idx_t nx, const float *x_in, Index & index) {
68 FAISS_THROW_IF_NOT_FMT (nx >= k,
69 "Number of training points (%ld) should be at least "
70 "as large as number of clusters (%ld)", nx, k);
71
72 double t0 = getmillisecs();
73
74 // yes it is the user's responsibility, but it may spare us some
75 // hard-to-debug reports.
76 for (size_t i = 0; i < nx * d; i++) {
77 FAISS_THROW_IF_NOT_MSG (finite (x_in[i]),
78 "input contains NaN's or Inf's");
79 }
80
81 const float *x = x_in;
82 ScopeDeleter<float> del1;
83
84 if (nx > k * max_points_per_centroid) {
85 if (verbose)
86 printf("Sampling a subset of %ld / %ld for training\n",
87 k * max_points_per_centroid, nx);
88 std::vector<int> perm (nx);
89 rand_perm (perm.data (), nx, seed);
90 nx = k * max_points_per_centroid;
91 float * x_new = new float [nx * d];
92 for (idx_t i = 0; i < nx; i++)
93 memcpy (x_new + i * d, x + perm[i] * d, sizeof(x_new[0]) * d);
94 x = x_new;
95 del1.set (x);
96 } else if (nx < k * min_points_per_centroid) {
97 fprintf (stderr,
98 "WARNING clustering %ld points to %ld centroids: "
99 "please provide at least %ld training points\n",
100 nx, k, idx_t(k) * min_points_per_centroid);
101 }
102
103
104 if (nx == k) {
105 if (verbose) {
106 printf("Number of training points (%ld) same as number of "
107 "clusters, just copying\n", nx);
108 }
109 // this is a corner case, just copy training set to clusters
110 centroids.resize (d * k);
111 memcpy (centroids.data(), x_in, sizeof (*x_in) * d * k);
112 return;
113 }
114
115
116 if (verbose)
117 printf("Clustering %d points in %ldD to %ld clusters, "
118 "redo %d times, %d iterations\n",
119 int(nx), d, k, nredo, niter);
120
121
122
123
124 idx_t * assign = new idx_t[nx];
125 ScopeDeleter<idx_t> del (assign);
126 float * dis = new float[nx];
127 ScopeDeleter<float> del2(dis);
128
129 // for redo
130 float best_err = 1e50;
131 std::vector<float> best_obj;
132 std::vector<float> best_centroids;
133
134 // support input centroids
135
136 FAISS_THROW_IF_NOT_MSG (
137 centroids.size() % d == 0,
138 "size of provided input centroids not a multiple of dimension");
139
140 size_t n_input_centroids = centroids.size() / d;
141
142 if (verbose && n_input_centroids > 0) {
143 printf (" Using %zd centroids provided as input (%sfrozen)\n",
144 n_input_centroids, frozen_centroids ? "" : "not ");
145 }
146
147 double t_search_tot = 0;
148 if (verbose) {
149 printf(" Preprocessing in %.2f s\n",
150 (getmillisecs() - t0)/1000.);
151 }
152 t0 = getmillisecs();
153
154 for (int redo = 0; redo < nredo; redo++) {
155
156 if (verbose && nredo > 1) {
157 printf("Outer iteration %d / %d\n", redo, nredo);
158 }
159
160
161 // initialize remaining centroids with random points from the dataset
162 centroids.resize (d * k);
163 std::vector<int> perm (nx);
164
165 rand_perm (perm.data(), nx, seed + 1 + redo * 15486557L);
166 for (int i = n_input_centroids; i < k ; i++)
167 memcpy (&centroids[i * d], x + perm[i] * d,
168 d * sizeof (float));
169
170 if (spherical)
171 fvec_renorm_L2 (d, k, centroids.data());
172
173 if (!index.is_trained)
174 index.train (k, centroids.data());
175
176 FAISS_THROW_IF_NOT (index.ntotal == 0);
177 index.add (k, centroids.data());
178 float err = 0;
179 for (int i = 0; i < niter; i++) {
180 double t0s = getmillisecs();
181 index.search (nx, x, 1, dis, assign);
182 t_search_tot += getmillisecs() - t0s;
183
184 err = 0;
185 for (int j = 0; j < nx; j++)
186 err += dis[j];
187 obj.push_back (err);
188
189 int nsplit = km_update_centroids (
190 x, centroids.data(),
191 assign, d, k, nx, frozen_centroids ? n_input_centroids : 0);
192
193 if (verbose) {
194 printf (" Iteration %d (%.2f s, search %.2f s): "
195 "objective=%g imbalance=%.3f nsplit=%d \r",
196 i, (getmillisecs() - t0) / 1000.0,
197 t_search_tot / 1000,
198 err, imbalance_factor (nx, k, assign),
199 nsplit);
200 fflush (stdout);
201 }
202
203 if (spherical)
204 fvec_renorm_L2 (d, k, centroids.data());
205
206 index.reset ();
207 if (update_index)
208 index.train (k, centroids.data());
209
210 assert (index.ntotal == 0);
211 index.add (k, centroids.data());
212 }
213 if (verbose) printf("\n");
214 if (nredo > 1) {
215 if (err < best_err) {
216 if (verbose)
217 printf ("Objective improved: keep new clusters\n");
218 best_centroids = centroids;
219 best_obj = obj;
220 best_err = err;
221 }
222 index.reset ();
223 }
224 }
225 if (nredo > 1) {
226 centroids = best_centroids;
227 obj = best_obj;
228 }
229
230 }
231
232 float kmeans_clustering (size_t d, size_t n, size_t k,
233 const float *x,
234 float *centroids)
235 {
236 Clustering clus (d, k);
237 clus.verbose = d * n * k > (1L << 30);
238 // display logs if > 1Gflop per iteration
239 IndexFlatL2 index (d);
240 clus.train (n, x, index);
241 memcpy(centroids, clus.centroids.data(), sizeof(*centroids) * d * k);
242 return clus.obj.back();
243 }
244
245 } // namespace faiss
faiss::km_update_centroids
int km_update_centroids(const float *x, float *centroids, long *assign, size_t d, size_t k, size_t n, size_t k_frozen)
Definition: utils.cpp:1401
faiss::ClusteringParameters::niter
int niter
clustering iterations
Definition: Clustering.h:25
faiss::ClusteringParameters::nredo
int nredo
redo clustering this many times and keep best
Definition: Clustering.h:26
faiss::ClusteringParameters::ClusteringParameters
ClusteringParameters()
sets reasonable defaults
Definition: Clustering.cpp:27
faiss::Index::reset
virtual void reset()=0
removes all elements from the database.
faiss::IndexFlatL2
Definition: IndexFlat.h:79
faiss::Clustering::Clustering
Clustering(int d, int k)
the only mandatory parameters are k and d
Definition: Clustering.cpp:40
faiss::Index::train
virtual void train(idx_t n, const float *x)
Definition: Index.cpp:23
faiss::Clustering::k
size_t k
nb of centroids
Definition: Clustering.h:60
faiss::ScopeDeleter
Definition: FaissException.h:39
faiss::ClusteringParameters::seed
int seed
seed for the random number generator
Definition: Clustering.h:36
faiss::ClusteringParameters::frozen_centroids
bool frozen_centroids
use the centroids provided as input and do not change them during iterations
Definition: Clustering.h:31
faiss::ClusteringParameters::min_points_per_centroid
int min_points_per_centroid
otherwise you get a warning
Definition: Clustering.h:33
faiss::Clustering
Definition: Clustering.h:57
faiss::Index::add
virtual void add(idx_t n, const float *x)=0
faiss::Clustering::obj
std::vector< float > obj
Definition: Clustering.h:67
faiss::kmeans_clustering
float kmeans_clustering(size_t d, size_t n, size_t k, const float *x, float *centroids)
Definition: Clustering.cpp:232
faiss::Index::ntotal
idx_t ntotal
total nb of indexed vectors
Definition: Index.h:65
faiss::getmillisecs
double getmillisecs()
ms elapsed since some arbitrary epoch
Definition: utils.cpp:74
faiss::Clustering::centroids
std::vector< float > centroids
centroids (k * d)
Definition: Clustering.h:63
faiss::Clustering::d
size_t d
dimension of the vectors
Definition: Clustering.h:59
faiss::Index::search
virtual void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const =0
faiss::ClusteringParameters::update_index
bool update_index
update index after each iteration?
Definition: Clustering.h:30
faiss::ClusteringParameters
Definition: Clustering.h:24
faiss::Index
Definition: Index.h:60
faiss::Clustering::train
virtual void train(idx_t n, const float *x, faiss::Index &index)
Index is used during the assignment stage.
Definition: Clustering.cpp:67
faiss::Index::is_trained
bool is_trained
set if the Index does not require training, or if training is done already
Definition: Index.h:69
faiss::ClusteringParameters::spherical
bool spherical
do we want normalized centroids?
Definition: Clustering.h:29
faiss::ClusteringParameters::max_points_per_centroid
int max_points_per_centroid
to limit size of dataset
Definition: Clustering.h:34