Faiss
 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 
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_MSG (nx >= k,
69  "need at least as many training points as clusters");
70 
71  double t0 = getmillisecs();
72 
73  // yes it is the user's responsibility, but it may spare us some
74  // hard-to-debug reports.
75  for (size_t i = 0; i < nx * d; i++) {
76  FAISS_THROW_IF_NOT_MSG (finite (x_in[i]),
77  "input contains NaN's or Inf's");
78  }
79 
80  const float *x = x_in;
82 
83  if (nx > k * max_points_per_centroid) {
84  if (verbose)
85  printf("Sampling a subset of %ld / %ld for training\n",
86  k * max_points_per_centroid, nx);
87  std::vector<int> perm (nx);
88  rand_perm (perm.data (), nx, seed);
89  nx = k * max_points_per_centroid;
90  float * x_new = new float [nx * d];
91  for (idx_t i = 0; i < nx; i++)
92  memcpy (x_new + i * d, x + perm[i] * d, sizeof(x_new[0]) * d);
93  x = x_new;
94  del1.set (x);
95  } else if (nx < k * min_points_per_centroid) {
96  fprintf (stderr,
97  "WARNING clustering %ld points to %ld centroids: "
98  "please provide at least %ld training points\n",
99  nx, k, idx_t(k) * min_points_per_centroid);
100  }
101 
102 
103  if (verbose)
104  printf("Clustering %d points in %ldD to %ld clusters, "
105  "redo %d times, %d iterations\n",
106  int(nx), d, k, nredo, niter);
107 
108 
109  idx_t * assign = new idx_t[nx];
110  ScopeDeleter<idx_t> del (assign);
111  float * dis = new float[nx];
112  ScopeDeleter<float> del2(dis);
113 
114  // for redo
115  float best_err = 1e50;
116  std::vector<float> best_obj;
117  std::vector<float> best_centroids;
118 
119  // support input centroids
120 
121  FAISS_THROW_IF_NOT_MSG (
122  centroids.size() % d == 0,
123  "size of provided input centroids not a multiple of dimension");
124 
125  size_t n_input_centroids = centroids.size() / d;
126 
127  if (verbose && n_input_centroids > 0) {
128  printf (" Using %zd centroids provided as input (%sfrozen)\n",
129  n_input_centroids, frozen_centroids ? "" : "not ");
130  }
131 
132  double t_search_tot = 0;
133  if (verbose) {
134  printf(" Preprocessing in %.2f s\n",
135  (getmillisecs() - t0)/1000.);
136  }
137  t0 = getmillisecs();
138 
139  for (int redo = 0; redo < nredo; redo++) {
140 
141  if (verbose && nredo > 1) {
142  printf("Outer iteration %d / %d\n", redo, nredo);
143  }
144 
145 
146  // initialize remaining centroids with random points from the dataset
147  centroids.resize (d * k);
148  std::vector<int> perm (nx);
149 
150  rand_perm (perm.data(), nx, seed + 1 + redo * 15486557L);
151  for (int i = n_input_centroids; i < k ; i++)
152  memcpy (&centroids[i * d], x + perm[i] * d,
153  d * sizeof (float));
154 
155  if (spherical)
156  fvec_renorm_L2 (d, k, centroids.data());
157 
158  if (!index.is_trained)
159  index.train (k, centroids.data());
160 
161  FAISS_THROW_IF_NOT (index.ntotal == 0);
162  index.add (k, centroids.data());
163  float err = 0;
164  for (int i = 0; i < niter; i++) {
165  double t0s = getmillisecs();
166  index.search (nx, x, 1, dis, assign);
167  t_search_tot += getmillisecs() - t0s;
168 
169  err = 0;
170  for (int j = 0; j < nx; j++)
171  err += dis[j];
172  obj.push_back (err);
173 
174  int nsplit = km_update_centroids (
175  x, centroids.data(),
176  assign, d, k, nx, frozen_centroids ? n_input_centroids : 0);
177 
178  if (verbose) {
179  printf (" Iteration %d (%.2f s, search %.2f s): "
180  "objective=%g imbalance=%.3f nsplit=%d \r",
181  i, (getmillisecs() - t0) / 1000.0,
182  t_search_tot / 1000,
183  err, imbalance_factor (nx, k, assign),
184  nsplit);
185  fflush (stdout);
186  }
187 
188  if (spherical)
189  fvec_renorm_L2 (d, k, centroids.data());
190 
191  index.reset ();
192  if (update_index)
193  index.train (k, centroids.data());
194 
195  assert (index.ntotal == 0);
196  index.add (k, centroids.data());
197  }
198  if (verbose) printf("\n");
199  if (nredo > 1) {
200  if (err < best_err) {
201  if (verbose)
202  printf ("Objective improved: keep new clusters\n");
203  best_centroids = centroids;
204  best_obj = obj;
205  best_err = err;
206  }
207  index.reset ();
208  }
209  }
210  if (nredo > 1) {
211  centroids = best_centroids;
212  obj = best_obj;
213  }
214 
215 }
216 
217 float kmeans_clustering (size_t d, size_t n, size_t k,
218  const float *x,
219  float *centroids)
220 {
221  Clustering clus (d, k);
222  clus.verbose = d * n * k > (1L << 30);
223  // display logs if > 1Gflop per iteration
224  IndexFlatL2 index (d);
225  clus.train (n, x, index);
226  memcpy(centroids, clus.centroids.data(), sizeof(*centroids) * d * k);
227  return clus.obj.back();
228 }
229 
230 } // namespace faiss
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:1399
int niter
clustering iterations
Definition: Clustering.h:25
int nredo
redo clustering this many times and keep best
Definition: Clustering.h:26
ClusteringParameters()
sets reasonable defaults
Definition: Clustering.cpp:27
virtual void reset()=0
removes all elements from the database.
virtual void train(idx_t, const float *)
Definition: Index.h:89
Clustering(int d, int k)
the only mandatory parameters are k and d
Definition: Clustering.cpp:40
size_t k
nb of centroids
Definition: Clustering.h:60
int seed
seed for the random number generator
Definition: Clustering.h:36
bool frozen_centroids
use the centroids provided as input and do not change them during iterations
Definition: Clustering.h:31
int min_points_per_centroid
otherwise you get a warning
Definition: Clustering.h:33
virtual void add(idx_t n, const float *x)=0
std::vector< float > obj
Definition: Clustering.h:67
float kmeans_clustering(size_t d, size_t n, size_t k, const float *x, float *centroids)
Definition: Clustering.cpp:217
idx_t ntotal
total nb of indexed vectors
Definition: Index.h:65
double getmillisecs()
ms elapsed since some arbitrary epoch
Definition: utils.cpp:74
std::vector< float > centroids
centroids (k * d)
Definition: Clustering.h:63
size_t d
dimension of the vectors
Definition: Clustering.h:59
virtual void search(idx_t n, const float *x, idx_t k, float *distances, idx_t *labels) const =0
bool update_index
update index after each iteration?
Definition: Clustering.h:30
virtual void train(idx_t n, const float *x, faiss::Index &index)
Index is used during the assignment stage.
Definition: Clustering.cpp:67
bool is_trained
set if the Index does not require training, or if training is done already
Definition: Index.h:69
bool spherical
do we want normalized centroids?
Definition: Clustering.h:29
int max_points_per_centroid
to limit size of dataset
Definition: Clustering.h:34