You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2103 lines
71 KiB

8 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /** @file kmeans.c
  2. ** @brief K-means - Declaration
  3. ** @author Andrea Vedaldi, David Novotny
  4. **/
  5. /*
  6. Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
  7. Copyright (C) 2013 Andrea Vedaldi and David Novotny.
  8. All rights reserved.
  9. This file is part of the VLFeat library and is made available under
  10. the terms of the BSD license (see the COPYING file).
  11. */
  12. /**
  13. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  14. @page kmeans K-means clustering
  15. @author Andrea Vedaldi
  16. @author David Novotny
  17. @tableofcontents
  18. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  19. @ref kmeans.h implements a number of algorithm for **K-means
  20. quantization**: Lloyd @cite{lloyd82least}, an accelerated version by
  21. Elkan @cite{elkan03using}, and a large scale algorithm based on
  22. Approximate Nearest Neighbors (ANN). All algorithms support @c float
  23. or @c double data and can use the $l^1$ or the $l^2$ distance for
  24. clustering. Furthermore, all algorithms can take advantage of multiple
  25. CPU cores.
  26. Please see @subpage kmeans-fundamentals for a technical description of
  27. K-means and of the algorithms implemented here.
  28. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  29. @section kmeans-starting Getting started
  30. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  31. The goal of K-means is to partition a dataset into $K$
  32. &ldquo;compact&rdquo; clusters. The following example demonstrates
  33. using @ref kmeans.h in the C programming language to partition @c
  34. numData @c float vectors into compute @c numCenters clusters using
  35. Lloyd's algorithm:
  36. @code
  37. #include <vl/kmeans.h>
  38. double energy ;
  39. double * centers ;
  40. // Use float data and the L2 distance for clustering
  41. KMeans * kmeans = vl_kmeans_new (VLDistanceL2, VL_TYPE_FLOAT) ;
  42. // Use Lloyd algorithm
  43. vl_kmeans_set_algorithm (kmeans, VlKMeansLloyd) ;
  44. // Initialize the cluster centers by randomly sampling the data
  45. vl_kmeans_init_centers_with_rand_data (kmeans, data, dimension, numData, numCenters) ;
  46. // Run at most 100 iterations of cluster refinement using Lloyd algorithm
  47. vl_kmeans_set_max_num_iterations (kmeans, 100) ;
  48. vl_kmeans_refine_centers (kmeans, data, numData) ;
  49. // Obtain the energy of the solution
  50. energy = vl_kmeans_get_energy(kmeans) ;
  51. // Obtain the cluster centers
  52. centers = vl_kmeans_get_centers(kmeans) ;
  53. @endcode
  54. Once the centers have been obtained, new data points can be assigned
  55. to clusters by using the ::vl_kmeans_quantize function:
  56. @code
  57. vl_uint32 * assignments = vl_malloc(sizeof(vl_uint32) * numData) ;
  58. float * distances = vl_malloc(sizeof(float) * numData) ;
  59. vl_kmeans_quantize(kmeans, assignments, distances, data, numData) ;
  60. @endcode
  61. Alternatively, one can directly assign new pointers to the closest
  62. centers, without bothering with a ::VlKMeans object.
  63. There are several considerations that may impact the performance of
  64. KMeans. First, since K-means is usually based local optimization
  65. algorithm, the **initialization method** is important. The following
  66. initialization methods are supported:
  67. Method | Function | Description
  68. ---------------|-----------------------------------------|-----------------------------------------------
  69. Random samples | ::vl_kmeans_init_centers_with_rand_data | Random data points
  70. K-means++ | ::vl_kmeans_init_centers_plus_plus | Random selection biased towards diversity
  71. Custom | ::vl_kmeans_set_centers | Choose centers (useful to run quantization only)
  72. See @ref kmeans-init for further details. The initialization methods
  73. use a randomized selection of the data points; the random number
  74. generator init is controlled by ::vl_rand_init.
  75. The second important choice is the **optimization algorithm**. The
  76. following optimization algorithms are supported:
  77. Algorithm | Symbol | See | Description
  78. ------------|------------------|-------------------|-----------------------------------------------
  79. Lloyd | ::VlKMeansLloyd | @ref kmeans-lloyd | Alternate EM-style optimization
  80. Elkan | ::VlKMeansElkan | @ref kmeans-elkan | A speedup using triangular inequalities
  81. ANN | ::VlKMeansANN | @ref kmeans-ann | A speedup using approximated nearest neighbors
  82. See the relative sections for further details. These algorithm are
  83. iterative, and stop when either a **maximum number of iterations**
  84. (::vl_kmeans_set_max_num_iterations) is reached, or when the energy
  85. changes sufficiently slowly in one iteration (::vl_kmeans_set_min_energy_variation).
  86. All the three algorithms support multithreaded computations. The number
  87. of threads used is usually controlled globally by ::vl_set_num_threads.
  88. **/
  89. /**
  90. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  91. @page kmeans-fundamentals K-means fundamentals
  92. @tableofcontents
  93. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  94. Given $n$ points $\bx_1,\dots,\bx_n \in \real^d$, the goal of K-means
  95. is find $K$ `centers` $\bc_1,\dots,\bc_m \in \real^d$ and
  96. `assignments` $q_1,\dots,q_n \in \{1,\dots,K\}$ of the points to the
  97. centers such that the sum of distances
  98. \[
  99. E(\bc_1,\dots,\bc_k,q_1,\dots,q_n)
  100. = \sum_{i=1}^n \|\bx_i - \bc_{q_i} \|_p^p
  101. \]
  102. is minimized. $K$-means is obtained for the case $p=2$ ($l^2$ norm),
  103. because in this case the optimal centers are the means of the input
  104. vectors assigned to them. Here the generalization $p=1$ ($l^1$ norm)
  105. will also be considered.
  106. Up to normalization, the K-means objective $E$ is also the average
  107. reconstruction error if the original points are approximated with the
  108. cluster centers. Thus K-means is used not only to group the input
  109. points into cluster, but also to `quantize` their values.
  110. K-means is widely used in computer vision, for example in the
  111. construction of vocabularies of visual features (visual words). In
  112. these applications the number $n$ of points to cluster and/or the
  113. number $K$ of clusters is often large. Unfortunately, minimizing the
  114. objective $E$ is in general a difficult combinatorial problem, so
  115. locally optimal or approximated solutions are sought instead.
  116. The basic K-means algorithm alternate between re-estimating the
  117. centers and the assignments (@ref kmeans-lloyd). Combined with a good
  118. initialization strategy (@ref kmeans-init) and, potentially, by
  119. re-running the optimization from a number of randomized starting
  120. states, this algorithm may attain satisfactory solutions in practice.
  121. However, despite its simplicity, Lloyd's algorithm is often too slow.
  122. A good replacement is Elkan's algorithm (@ref kmeans-elkan), which
  123. uses the triangular inequality to cut down significantly the cost of
  124. Lloyd's algorithm. Since this algorithm is otherwise equivalent, it
  125. should often be preferred.
  126. For very large problems (millions of point to clusters and hundreds,
  127. thousands, or more clusters to find), even Elkan's algorithm is not
  128. sufficiently fast. In these cases, one can resort to a variant of
  129. Lloyd's algorithm that uses an approximated nearest neighbors routine
  130. (@ref kmeans-ann).
  131. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  132. @section kmeans-init Initialization methods
  133. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  134. All the $K$-means algorithms considered here find locally optimal
  135. solutions; as such the way they are initialized is important. @ref
  136. kmeans.h supports the following initialization algorithms:
  137. @par Random data samples
  138. The simplest initialization method is to sample $K$ points at random
  139. from the input data and use them as initial values for the cluster
  140. centers.
  141. @par K-means++
  142. @cite{arthur07k-means} proposes a randomized initialization of the
  143. centers which improves upon random selection. The first center $\bc_1$
  144. is selected at random from the data points $\bx_1, \dots, \bx_n $ and
  145. the distance from this center to all points $\|\bx_i - \bc_1\|_p^p$ is
  146. computed. Then the second center $\bc_2$ is selected at random from
  147. the data points with probability proportional to the distance. The
  148. procedure is repeated to obtain the other centers by using the minimum
  149. distance to the centers collected so far.
  150. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  151. @section kmeans-lloyd Lloyd's algorithm
  152. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  153. The most common K-means method is Lloyd's algorithm
  154. @cite{lloyd82least}. This algorithm is based on the observation that,
  155. while jointly optimizing clusters and assignment is difficult,
  156. optimizing one given the other is easy. Lloyd's algorithm alternates
  157. the steps:
  158. 1. **Quantization.** Each point $\bx_i$ is reassigned to the center
  159. $\bc_{q_j}$ closer to it. This requires finding for each point the
  160. closest among $K$ other points, which is potentially slow.
  161. 2. **Center estimation.** Each center $\bc_q$ is updated to minimize
  162. its average distances to the points assigned to it. It is easy to
  163. show that the best center is the mean or median of the points,
  164. respectively if the $l^2$ or $l^1$ norm is considered.
  165. A naive implementation of the assignment step requires $O(dnK)$
  166. operations, where $d$ is the dimensionality of the data, $n$ the
  167. number of data points, and $K$ the number of centers. Updating the
  168. centers is much cheaper: $O(dn)$ operations suffice to compute the $K$
  169. means and a slightly higher cost is required for the medians. Clearly,
  170. the bottleneck is the assignment computation, and this is what the
  171. other K-means algorithm try to improve.
  172. During the iterations, it can happen that a cluster becomes empty. In
  173. this case, K-means automatically **&ldquo;restarts&rdquo; the
  174. cluster** center by selecting a training point at random.
  175. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  176. @section kmeans-elkan Elkan's algorithm
  177. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  178. Elkan's algorithm @cite{elkan03using} is a variation of Lloyd
  179. alternate optimization algorithm (@ref kmeans-lloyd) that uses the
  180. triangular inequality to avoid many distance calculations when
  181. assigning points to clusters. While much faster than Lloyd, Elkan's
  182. method uses storage proportional to the umber of clusters by data
  183. points, which makes it unpractical for a very large number of
  184. clusters.
  185. The idea of this algorithm is that, if a center update does not move
  186. them much, then most of the point-to-center computations can be
  187. avoided when the point-to-center assignments are recomputed. To detect
  188. which distances need evaluation, the triangular inequality is used to
  189. lower and upper bound distances after a center update.
  190. Elkan algorithms uses two key observations. First, one has
  191. \[
  192. \|\bx_i - \bc_{q_i}\|_p \leq \|\bc - \bc_{q_i}\|_p / 2
  193. \quad\Rightarrow\quad
  194. \|\bx_i - \bc_{q_i}\|_p \leq \|\bx_i - \bc\|_p.
  195. \]
  196. Thus if the distance between $\bx_i$ and its current center
  197. $\bc_{q_i}$ is less than half the distance of the center $\bc_{q_i}$
  198. to another center $\bc$, then $\bc$ can be skipped when the new
  199. assignment for $\bx_i$ is searched. Checking this requires keeping
  200. track of all the inter-center distances, but centers are typically a
  201. small fraction of the training data, so overall this can be a
  202. significant saving. In particular, if this condition is satisfied for
  203. all the centers $\bc \not= \bc_{q_i}$, the point $\bx_i$ can be
  204. skipped completely. Furthermore, the condition can be tested also
  205. based on an upper bound $UB_i$ of $\|\bx_i - \bc_{q_i}\|_p$.
  206. Second, if a center $\bc$ is updated to $\hat{\bc}$, then the new
  207. distance from $\bx$ to $\hat{\bc}$ is bounded from below and above by
  208. \[
  209. \|\bx - \bc\|_p - \|bc - \hat\bc\|_p
  210. \leq
  211. \|\bx - \hat{\bc}\|_p
  212. \leq
  213. \|\bx - \hat{\bc}\|_p + \|\bc + \hat{\bc}\|_p.
  214. \]
  215. This allows to maintain an upper bound on the distance of $\bx_i$ to
  216. its current center $\bc_{q_i}$ and a lower bound to any other center
  217. $\bc$:
  218. @f{align*}
  219. UB_i & \leftarrow UB_i + \|\bc_{q_i} - \hat{\bc}_{q_i} \|_p \\
  220. LB_i(\bc) & \leftarrow LB_i(\bc) - \|\bc -\hat \bc\|_p.
  221. @f}
  222. Thus the K-means algorithm becomes:
  223. 1. **Initialization.** Compute $LB_i(\bc) = \|\bx_i -\hat \bc\|_p$ for
  224. all points and centers. Find the current assignments $q_i$ and
  225. bounds $UB_i$ by finding the closest centers to each point: $UB_i =
  226. \min_{\bc} LB_i(\bc)$.
  227. 2. **Center estimation.**
  228. 1. Recompute all the centers based on the new means; call the updated
  229. version $\hat{\bc}$.
  230. 2. Update all the bounds based on the distance $\|\bc - \hat\bc\|_p$
  231. as explained above.
  232. 3. Set $\bc \leftarrow \hat\bc$ for all the centers and go to the next
  233. iteration.
  234. 3. **Quantization.**
  235. 1. Skip any point $\bx_i$ such that $UB_i \leq \frac{1}{2} \|\bc_{q_i} - \bc\|_p$
  236. for all centers $\bc \not= \bc_{q_i}$.
  237. 2. For each remaining point $\bx_i$ and center $\bc \not= \bc_{q_i}$:
  238. 1. Skip $\bc$ if
  239. \[
  240. UB_i \leq \frac{1}{2} \| \bc_{q_i} - \bc \|
  241. \quad\text{or}\quad
  242. UB_i \leq LB_i(\bc).
  243. \]
  244. The first condition reflects the first observation above; the
  245. second uses the bounds to decide if $\bc$ can be closer than the
  246. current center $\bc_{q_i}$ to the point $\bx_i$. If the center
  247. cannot be skipped, continue as follows.
  248. 3. Skip $\bc$ if the condition above is satisfied after making the
  249. upper bound tight:
  250. \[
  251. UB_i = LB_i(\bc_{q_i}) = \| \bx_i - \bc_{q_i} \|_p.
  252. \]
  253. Note that the latter calculation can be done only once for $\bx_i$.
  254. If the center cannot be skipped still, continue as follows.
  255. 4. Tighten the lower bound too:
  256. \[
  257. LB_i(\bc) = \| \bx_i - \bc \|_p.
  258. \]
  259. At this point both $UB_i$ and $LB_i(\bc)$ are tight. If $LB_i <
  260. UB_i$, then the point $\bx_i$ should be reassigned to
  261. $\bc$. Update $q_i$ to the index of center $\bc$ and reset $UB_i
  262. = LB_i(\bc)$.
  263. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  264. @section kmeans-ann ANN algorithm
  265. <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
  266. The *Approximate Nearest Neighbor* (ANN) K-means algorithm
  267. @cite{beis97shape} @cite{silpa-anan08optimised} @cite{muja09fast} is a
  268. variant of Lloyd's algorithm (@ref kmeans-lloyd) uses a best-bin-first
  269. randomized KD-tree algorithm to approximately (and quickly) find the
  270. closest cluster center to each point. The KD-tree implementation is
  271. based on @ref kdtree.
  272. The algorithm can be summarized as follows:
  273. 1. **Quantization.** Each point $\bx_i$ is reassigned to the center
  274. $\bc_{q_j}$ closer to it. This starts by indexing the $K$ centers
  275. by a KD-tree and then using the latter to quickly find the closest
  276. center for every training point. The search is approximated to
  277. further improve speed. This opens up the possibility that a data
  278. point may receive an assignment that is *worse* than the current
  279. one. This is avoided by checking that the new assignment estimated
  280. by using ANN is an improvement; otherwise the old assignment is
  281. kept.
  282. 2. **Center estimation.** Each center $\bc_q$ is updated to minimize
  283. its average distances to the points assigned to it. It is easy to
  284. show that the best center is the mean or median of the points,
  285. respectively if the $l^2$ or $l^1$ norm is considered.
  286. The key is to trade-off carefully the speedup obtained by using the
  287. ANN algorithm and the loss in accuracy when retrieving neighbors. Due
  288. to the curse of dimensionality, KD-trees become less effective for
  289. higher dimensional data, so that the search cost, which in the best
  290. case is logarithmic with this data structure, may become effectively
  291. linear. This is somehow mitigated by the fact that new a new KD-tree
  292. is computed at each iteration, reducing the likelihood that points may
  293. get stuck with sub-optimal assignments.
  294. Experiments with the quantization of 128-dimensional SIFT features
  295. show that the ANN algorithm may use one quarter of the comparisons of
  296. Elkan's while retaining a similar solution accuracy.
  297. */
  298. #include "kmeans.h"
  299. #include "generic.h"
  300. #include "mathop.h"
  301. #include <string.h>
  302. #ifdef _OPENMP
  303. #include <omp.h>
  304. #endif
  305. /* ================================================================ */
  306. #ifndef VL_KMEANS_INSTANTIATING
  307. /** ------------------------------------------------------------------
  308. ** @brief Reset state
  309. **
  310. ** The function reset the state of the KMeans object. It deletes
  311. ** any stored centers, releasing the corresponding memory. This
  312. ** cancels the effect of seeding or setting the centers, but
  313. ** does not change the other configuration parameters.
  314. **/
  315. VL_EXPORT void
  316. vl_kmeans_reset (VlKMeans * self)
  317. {
  318. self->numCenters = 0 ;
  319. self->dimension = 0 ;
  320. if (self->centers) vl_free(self->centers) ;
  321. if (self->centerDistances) vl_free(self->centerDistances) ;
  322. self->centers = NULL ;
  323. self->centerDistances = NULL ;
  324. }
  325. /** ------------------------------------------------------------------
  326. ** @brief Create a new KMeans object
  327. ** @param dataType type of data (::VL_TYPE_FLOAT or ::VL_TYPE_DOUBLE)
  328. ** @param distance distance.
  329. ** @return new KMeans object instance.
  330. **/
  331. VL_EXPORT VlKMeans *
  332. vl_kmeans_new (vl_type dataType,
  333. VlVectorComparisonType distance)
  334. {
  335. VlKMeans * self = (VlKMeans*)vl_calloc(1, sizeof(VlKMeans)) ;
  336. self->algorithm = VlKMeansLloyd ;
  337. self->distance = distance ;
  338. self->dataType = dataType ;
  339. self->verbosity = 0 ;
  340. self->maxNumIterations = 100 ;
  341. self->minEnergyVariation = 1e-4 ;
  342. self->numRepetitions = 1 ;
  343. self->centers = NULL ;
  344. self->centerDistances = NULL ;
  345. self->numTrees = 3;
  346. self->maxNumComparisons = 100;
  347. vl_kmeans_reset (self) ;
  348. return self ;
  349. }
  350. /** ------------------------------------------------------------------
  351. ** @brief Create a new KMeans object by copy
  352. ** @param kmeans KMeans object to copy.
  353. ** @return new copy.
  354. **/
  355. VL_EXPORT VlKMeans *
  356. vl_kmeans_new_copy (VlKMeans const * kmeans)
  357. {
  358. VlKMeans * self = (VlKMeans*)vl_malloc(sizeof(VlKMeans)) ;
  359. self->algorithm = kmeans->algorithm ;
  360. self->distance = kmeans->distance ;
  361. self->dataType = kmeans->dataType ;
  362. self->verbosity = kmeans->verbosity ;
  363. self->maxNumIterations = kmeans->maxNumIterations ;
  364. self->numRepetitions = kmeans->numRepetitions ;
  365. self->dimension = kmeans->dimension ;
  366. self->numCenters = kmeans->numCenters ;
  367. self->centers = NULL ;
  368. self->centerDistances = NULL ;
  369. self->numTrees = kmeans->numTrees;
  370. self->maxNumComparisons = kmeans->maxNumComparisons;
  371. if (kmeans->centers) {
  372. vl_size dataSize = vl_get_type_size(self->dataType) * self->dimension * self->numCenters ;
  373. self->centers = vl_malloc(dataSize) ;
  374. memcpy (self->centers, kmeans->centers, dataSize) ;
  375. }
  376. if (kmeans->centerDistances) {
  377. vl_size dataSize = vl_get_type_size(self->dataType) * self->numCenters * self->numCenters ;
  378. self->centerDistances = vl_malloc(dataSize) ;
  379. memcpy (self->centerDistances, kmeans->centerDistances, dataSize) ;
  380. }
  381. return self ;
  382. }
  383. /** ------------------------------------------------------------------
  384. ** @brief Deletes a KMeans object
  385. ** @param self KMeans object instance.
  386. **
  387. ** The function deletes the KMeans object instance created
  388. ** by ::vl_kmeans_new.
  389. **/
  390. VL_EXPORT void
  391. vl_kmeans_delete (VlKMeans * self)
  392. {
  393. vl_kmeans_reset (self) ;
  394. vl_free (self) ;
  395. }
  396. /* an helper structure */
  397. typedef struct _VlKMeansSortWrapper {
  398. vl_uint32 * permutation ;
  399. void const * data ;
  400. vl_size stride ;
  401. } VlKMeansSortWrapper ;
  402. /* ---------------------------------------------------------------- */
  403. /* Instantiate shuffle algorithm */
  404. #define VL_SHUFFLE_type vl_uindex
  405. #define VL_SHUFFLE_prefix _vl_kmeans
  406. #include "shuffle-def.h"
  407. /* #ifdef VL_KMEANS_INSTANTITATING */
  408. #endif
  409. /* ================================================================ */
  410. #ifdef VL_KMEANS_INSTANTIATING
  411. /* ---------------------------------------------------------------- */
  412. /* Set centers */
  413. /* ---------------------------------------------------------------- */
  414. static void
  415. VL_XCAT(_vl_kmeans_set_centers_, SFX)
  416. (VlKMeans * self,
  417. TYPE const * centers,
  418. vl_size dimension,
  419. vl_size numCenters)
  420. {
  421. self->dimension = dimension ;
  422. self->numCenters = numCenters ;
  423. self->centers = vl_malloc (sizeof(TYPE) * dimension * numCenters) ;
  424. memcpy ((TYPE*)self->centers, centers,
  425. sizeof(TYPE) * dimension * numCenters) ;
  426. }
  427. /* ---------------------------------------------------------------- */
  428. /* Random seeding */
  429. /* ---------------------------------------------------------------- */
  430. static void
  431. VL_XCAT(_vl_kmeans_init_centers_with_rand_data_, SFX)
  432. (VlKMeans * self,
  433. TYPE const * data,
  434. vl_size dimension,
  435. vl_size numData,
  436. vl_size numCenters)
  437. {
  438. vl_uindex i, j, k ;
  439. VlRand * rand = vl_get_rand () ;
  440. self->dimension = dimension ;
  441. self->numCenters = numCenters ;
  442. self->centers = vl_malloc (sizeof(TYPE) * dimension * numCenters) ;
  443. {
  444. vl_uindex * perm = (vl_uindex*)vl_malloc (sizeof(vl_uindex) * numData) ;
  445. #if (FLT == VL_TYPE_FLOAT)
  446. VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ;
  447. #else
  448. VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ;
  449. #endif
  450. TYPE * distances = (TYPE*)vl_malloc (sizeof(TYPE) * numCenters) ;
  451. /* get a random permutation of the data point */
  452. for (i = 0 ; i < numData ; ++i) perm[i] = i ;
  453. _vl_kmeans_shuffle (perm, numData, rand) ;
  454. for (k = 0, i = 0 ; k < numCenters ; ++ i) {
  455. /* compare the next data point to all centers collected so far
  456. to detect duplicates (if there are enough left)
  457. */
  458. if (numCenters - k < numData - i) {
  459. vl_bool duplicateDetected = VL_FALSE ;
  460. VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)(distances,
  461. dimension,
  462. data + dimension * perm[i], 1,
  463. (TYPE*)self->centers, k,
  464. distFn) ;
  465. for (j = 0 ; j < k ; ++j) {
  466. duplicateDetected |= (distances[j] == 0) ;
  467. }
  468. if (duplicateDetected) continue ;
  469. }
  470. /* ok, it is not a duplicate so we can accept it! */
  471. memcpy ((TYPE*)self->centers + dimension * k,
  472. data + dimension * perm[i],
  473. sizeof(TYPE) * dimension) ;
  474. k ++ ;
  475. }
  476. vl_free(distances) ;
  477. vl_free(perm) ;
  478. }
  479. }
  480. /* ---------------------------------------------------------------- */
  481. /* kmeans++ seeding */
  482. /* ---------------------------------------------------------------- */
  483. static void
  484. VL_XCAT(_vl_kmeans_init_centers_plus_plus_, SFX)
  485. (VlKMeans * self,
  486. TYPE const * data,
  487. vl_size dimension,
  488. vl_size numData,
  489. vl_size numCenters)
  490. {
  491. vl_uindex x, c ;
  492. VlRand * rand = vl_get_rand () ;
  493. TYPE * distances = (TYPE*)vl_malloc (sizeof(TYPE) * numData) ;
  494. TYPE * minDistances = (TYPE*)vl_malloc (sizeof(TYPE) * numData) ;
  495. #if (FLT == VL_TYPE_FLOAT)
  496. VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ;
  497. #else
  498. VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ;
  499. #endif
  500. self->dimension = dimension ;
  501. self->numCenters = numCenters ;
  502. self->centers = vl_malloc (sizeof(TYPE) * dimension * numCenters) ;
  503. for (x = 0 ; x < numData ; ++x) {
  504. minDistances[x] = (TYPE) VL_INFINITY_D ;
  505. }
  506. /* select the first point at random */
  507. x = vl_rand_uindex (rand, numData) ;
  508. c = 0 ;
  509. while (1) {
  510. TYPE energy = 0 ;
  511. TYPE acc = 0 ;
  512. TYPE thresh = (TYPE) vl_rand_real1 (rand) ;
  513. memcpy ((TYPE*)self->centers + c * dimension,
  514. data + x * dimension,
  515. sizeof(TYPE) * dimension) ;
  516. c ++ ;
  517. if (c == numCenters) break ;
  518. VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)
  519. (distances,
  520. dimension,
  521. (TYPE*)self->centers + (c - 1) * dimension, 1,
  522. data, numData,
  523. distFn) ;
  524. for (x = 0 ; x < numData ; ++x) {
  525. minDistances[x] = VL_MIN(minDistances[x], distances[x]) ;
  526. energy += minDistances[x] ;
  527. }
  528. for (x = 0 ; x < numData - 1 ; ++x) {
  529. acc += minDistances[x] ;
  530. if (acc >= thresh * energy) break ;
  531. }
  532. }
  533. vl_free(distances) ;
  534. vl_free(minDistances) ;
  535. }
  536. /* ---------------------------------------------------------------- */
  537. /* Quantization */
  538. /* ---------------------------------------------------------------- */
  539. static void
  540. VL_XCAT(_vl_kmeans_quantize_, SFX)
  541. (VlKMeans * self,
  542. vl_uint32 * assignments,
  543. TYPE * distances,
  544. TYPE const * data,
  545. vl_size numData)
  546. {
  547. vl_index i ;
  548. #if (FLT == VL_TYPE_FLOAT)
  549. VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ;
  550. #else
  551. VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ;
  552. #endif
  553. #ifdef _OPENMP
  554. #pragma omp parallel default(none) \
  555. shared(self, distances, assignments, numData, distFn, data) \
  556. num_threads(vl_get_max_threads())
  557. #endif
  558. {
  559. /* vl_malloc cannot be used here if mapped to MATLAB malloc */
  560. TYPE * distanceToCenters = (TYPE*)malloc(sizeof(TYPE) * self->numCenters) ;
  561. #ifdef _OPENMP
  562. #pragma omp for
  563. #endif
  564. for (i = 0 ; i < (signed)numData ; ++i) {
  565. vl_uindex k ;
  566. TYPE bestDistance = (TYPE) VL_INFINITY_D ;
  567. VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)(distanceToCenters,
  568. self->dimension,
  569. data + self->dimension * i, 1,
  570. (TYPE*)self->centers, self->numCenters,
  571. distFn) ;
  572. for (k = 0 ; k < self->numCenters ; ++k) {
  573. if (distanceToCenters[k] < bestDistance) {
  574. bestDistance = distanceToCenters[k] ;
  575. assignments[i] = (vl_uint32)k ;
  576. }
  577. }
  578. if (distances) distances[i] = bestDistance ;
  579. }
  580. free(distanceToCenters) ;
  581. }
  582. }
  583. /* ---------------------------------------------------------------- */
  584. /* ANN quantization */
  585. /* ---------------------------------------------------------------- */
  586. static void
  587. VL_XCAT(_vl_kmeans_quantize_ann_, SFX)
  588. (VlKMeans * self,
  589. vl_uint32 * assignments,
  590. TYPE * distances,
  591. TYPE const * data,
  592. vl_size numData,
  593. vl_bool update)
  594. {
  595. #if (FLT == VL_TYPE_FLOAT)
  596. VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ;
  597. #else
  598. VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ;
  599. #endif
  600. VlKDForest * forest = vl_kdforest_new(self->dataType,self->dimension,self->numTrees, self->distance) ;
  601. vl_kdforest_set_max_num_comparisons(forest,self->maxNumComparisons);
  602. vl_kdforest_set_thresholding_method(forest,VL_KDTREE_MEDIAN);
  603. vl_kdforest_build(forest,self->numCenters,self->centers);
  604. #ifdef _OPENMP
  605. #pragma omp parallel default(none) \
  606. num_threads(vl_get_max_threads()) \
  607. shared(self, forest, update, assignments, distances, data, numData, distFn)
  608. #endif
  609. {
  610. VlKDForestNeighbor neighbor ;
  611. VlKDForestSearcher * searcher ;
  612. vl_index x;
  613. #ifdef _OPENMP
  614. #pragma omp critical
  615. #endif
  616. searcher = vl_kdforest_new_searcher (forest) ;
  617. #ifdef _OPENMP
  618. #pragma omp for
  619. #endif
  620. for(x = 0 ; x < (signed)numData ; ++x) {
  621. vl_kdforestsearcher_query (searcher, &neighbor, 1, (TYPE const *) (data + x*self->dimension));
  622. if (distances) {
  623. if(!update) {
  624. distances[x] = (TYPE) neighbor.distance;
  625. assignments[x] = (vl_uint32) neighbor.index ;
  626. } else {
  627. TYPE prevDist = (TYPE) distFn(self->dimension,
  628. data + self->dimension * x,
  629. (TYPE*)self->centers + self->dimension *assignments[x]);
  630. if (prevDist > (TYPE) neighbor.distance) {
  631. distances[x] = (TYPE) neighbor.distance ;
  632. assignments[x] = (vl_uint32) neighbor.index ;
  633. } else {
  634. distances[x] = prevDist ;
  635. }
  636. }
  637. } else {
  638. assignments[x] = (vl_uint32) neighbor.index ;
  639. }
  640. } /* end for */
  641. } /* end of parallel region */
  642. vl_kdforest_delete(forest);
  643. }
  644. /* ---------------------------------------------------------------- */
  645. /* Helper functions */
  646. /* ---------------------------------------------------------------- */
  647. /* The sorting routine is used to find increasing permutation of each
  648. * data dimension. This is used to quickly find the median for l1
  649. * distance clustering. */
  650. VL_INLINE TYPE
  651. VL_XCAT3(_vl_kmeans_, SFX, _qsort_cmp)
  652. (VlKMeansSortWrapper * array, vl_uindex indexA, vl_uindex indexB)
  653. {
  654. return
  655. ((TYPE*)array->data) [array->permutation[indexA] * array->stride]
  656. -
  657. ((TYPE*)array->data) [array->permutation[indexB] * array->stride] ;
  658. }
  659. VL_INLINE void
  660. VL_XCAT3(_vl_kmeans_, SFX, _qsort_swap)
  661. (VlKMeansSortWrapper * array, vl_uindex indexA, vl_uindex indexB)
  662. {
  663. vl_uint32 tmp = array->permutation[indexA] ;
  664. array->permutation[indexA] = array->permutation[indexB] ;
  665. array->permutation[indexB] = tmp ;
  666. }
  667. #define VL_QSORT_prefix VL_XCAT3(_vl_kmeans_, SFX, _qsort)
  668. #define VL_QSORT_array VlKMeansSortWrapper*
  669. #define VL_QSORT_cmp VL_XCAT3(_vl_kmeans_, SFX, _qsort_cmp)
  670. #define VL_QSORT_swap VL_XCAT3(_vl_kmeans_, SFX, _qsort_swap)
  671. #include "qsort-def.h"
  672. static void
  673. VL_XCAT(_vl_kmeans_sort_data_helper_, SFX)
  674. (VlKMeans * self, vl_uint32 * permutations, TYPE const * data, vl_size numData)
  675. {
  676. vl_uindex d, x ;
  677. for (d = 0 ; d < self->dimension ; ++d) {
  678. VlKMeansSortWrapper array ;
  679. array.permutation = permutations + d * numData ;
  680. array.data = data + d ;
  681. array.stride = self->dimension ;
  682. for (x = 0 ; x < numData ; ++x) {
  683. array.permutation[x] = (vl_uint32)x ;
  684. }
  685. VL_XCAT3(_vl_kmeans_, SFX, _qsort_sort)(&array, numData) ;
  686. }
  687. }
  688. /* ---------------------------------------------------------------- */
  689. /* Lloyd refinement */
  690. /* ---------------------------------------------------------------- */
  691. static double
  692. VL_XCAT(_vl_kmeans_refine_centers_lloyd_, SFX)
  693. (VlKMeans * self,
  694. TYPE const * data,
  695. vl_size numData)
  696. {
  697. vl_size c, d, x, iteration ;
  698. double previousEnergy = VL_INFINITY_D ;
  699. double initialEnergy = VL_INFINITY_D ;
  700. double energy ;
  701. TYPE * distances = (TYPE*)vl_malloc (sizeof(TYPE) * numData) ;
  702. vl_uint32 * assignments = (vl_uint32*)vl_malloc (sizeof(vl_uint32) * numData) ;
  703. vl_size * clusterMasses = (vl_size*)vl_malloc (sizeof(vl_size) * numData) ;
  704. vl_uint32 * permutations = NULL ;
  705. vl_size * numSeenSoFar = NULL ;
  706. VlRand * rand = vl_get_rand () ;
  707. vl_size totNumRestartedCenters = 0 ;
  708. vl_size numRestartedCenters = 0 ;
  709. if (self->distance == VlDistanceL1) {
  710. permutations = (vl_uint32*)vl_malloc(sizeof(vl_uint32) * numData * self->dimension) ;
  711. numSeenSoFar = (vl_size*)vl_malloc(sizeof(vl_size) * self->numCenters) ;
  712. VL_XCAT(_vl_kmeans_sort_data_helper_, SFX)(self, permutations, data, numData) ;
  713. }
  714. for (energy = VL_INFINITY_D,
  715. iteration = 0;
  716. 1 ;
  717. ++ iteration) {
  718. /* assign data to cluters */
  719. VL_XCAT(_vl_kmeans_quantize_, SFX)(self, assignments, distances, data, numData) ;
  720. /* compute energy */
  721. energy = 0 ;
  722. for (x = 0 ; x < numData ; ++x) energy += distances[x] ;
  723. if (self->verbosity) {
  724. VL_PRINTF("kmeans: Lloyd iter %d: energy = %g\n", iteration,
  725. energy) ;
  726. }
  727. /* check termination conditions */
  728. if (iteration >= self->maxNumIterations) {
  729. if (self->verbosity) {
  730. VL_PRINTF("kmeans: Lloyd terminating because maximum number of iterations reached\n") ;
  731. }
  732. break ;
  733. }
  734. if (energy == previousEnergy) {
  735. if (self->verbosity) {
  736. VL_PRINTF("kmeans: Lloyd terminating because the algorithm fully converged\n") ;
  737. }
  738. break ;
  739. }
  740. if (iteration == 0) {
  741. initialEnergy = energy ;
  742. } else {
  743. double eps = (previousEnergy - energy) / (initialEnergy - energy) ;
  744. if (eps < self->minEnergyVariation) {
  745. if (self->verbosity) {
  746. VL_PRINTF("kmeans: ANN terminating because the energy relative variation was less than %f\n", self->minEnergyVariation) ;
  747. }
  748. break ;
  749. }
  750. }
  751. /* begin next iteration */
  752. previousEnergy = energy ;
  753. /* update clusters */
  754. memset(clusterMasses, 0, sizeof(vl_size) * numData) ;
  755. for (x = 0 ; x < numData ; ++x) {
  756. clusterMasses[assignments[x]] ++ ;
  757. }
  758. numRestartedCenters = 0 ;
  759. switch (self->distance) {
  760. case VlDistanceL2:
  761. memset(self->centers, 0, sizeof(TYPE) * self->dimension * self->numCenters) ;
  762. for (x = 0 ; x < numData ; ++x) {
  763. TYPE * cpt = (TYPE*)self->centers + assignments[x] * self->dimension ;
  764. TYPE const * xpt = data + x * self->dimension ;
  765. for (d = 0 ; d < self->dimension ; ++d) {
  766. cpt[d] += xpt[d] ;
  767. }
  768. }
  769. for (c = 0 ; c < self->numCenters ; ++c) {
  770. TYPE * cpt = (TYPE*)self->centers + c * self->dimension ;
  771. if (clusterMasses[c] > 0) {
  772. TYPE mass = clusterMasses[c] ;
  773. for (d = 0 ; d < self->dimension ; ++d) {
  774. cpt[d] /= mass ;
  775. }
  776. } else {
  777. vl_uindex x = vl_rand_uindex(rand, numData) ;
  778. numRestartedCenters ++ ;
  779. for (d = 0 ; d < self->dimension ; ++d) {
  780. cpt[d] = data[x * self->dimension + d] ;
  781. }
  782. }
  783. }
  784. break ;
  785. case VlDistanceL1:
  786. for (d = 0 ; d < self->dimension ; ++d) {
  787. vl_uint32 * perm = permutations + d * numData ;
  788. memset(numSeenSoFar, 0, sizeof(vl_size) * self->numCenters) ;
  789. for (x = 0; x < numData ; ++x) {
  790. c = assignments[perm[x]] ;
  791. if (2 * numSeenSoFar[c] < clusterMasses[c]) {
  792. ((TYPE*)self->centers) [d + c * self->dimension] =
  793. data [d + perm[x] * self->dimension] ;
  794. }
  795. numSeenSoFar[c] ++ ;
  796. }
  797. /* restart the centers as required */
  798. for (c = 0 ; c < self->numCenters ; ++c) {
  799. if (clusterMasses[c] == 0) {
  800. TYPE * cpt = (TYPE*)self->centers + c * self->dimension ;
  801. vl_uindex x = vl_rand_uindex(rand, numData) ;
  802. numRestartedCenters ++ ;
  803. for (d = 0 ; d < self->dimension ; ++d) {
  804. cpt[d] = data[x * self->dimension + d] ;
  805. }
  806. }
  807. }
  808. }
  809. break ;
  810. default:
  811. abort();
  812. } /* done compute centers */
  813. totNumRestartedCenters += numRestartedCenters ;
  814. if (self->verbosity && numRestartedCenters) {
  815. VL_PRINTF("kmeans: Lloyd iter %d: restarted %d centers\n", iteration,
  816. numRestartedCenters) ;
  817. }
  818. } /* next Lloyd iteration */
  819. if (permutations) {
  820. vl_free(permutations) ;
  821. }
  822. if (numSeenSoFar) {
  823. vl_free(numSeenSoFar) ;
  824. }
  825. vl_free(distances) ;
  826. vl_free(assignments) ;
  827. vl_free(clusterMasses) ;
  828. return energy ;
  829. }
  830. static double
  831. VL_XCAT(_vl_kmeans_update_center_distances_, SFX)
  832. (VlKMeans * self)
  833. {
  834. #if (FLT == VL_TYPE_FLOAT)
  835. VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ;
  836. #else
  837. VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ;
  838. #endif
  839. if (! self->centerDistances) {
  840. self->centerDistances = vl_malloc (sizeof(TYPE) *
  841. self->numCenters *
  842. self->numCenters) ;
  843. }
  844. VL_XCAT(vl_eval_vector_comparison_on_all_pairs_, SFX)((TYPE*)self->centerDistances,
  845. self->dimension,
  846. (TYPE*)self->centers, self->numCenters,
  847. NULL, 0,
  848. distFn) ;
  849. return self->numCenters * (self->numCenters - 1) / 2 ;
  850. }
  851. static double
  852. VL_XCAT(_vl_kmeans_refine_centers_ann_, SFX)
  853. (VlKMeans * self,
  854. TYPE const * data,
  855. vl_size numData)
  856. {
  857. vl_size c, d, x, iteration ;
  858. double initialEnergy = VL_INFINITY_D ;
  859. double previousEnergy = VL_INFINITY_D ;
  860. double energy ;
  861. vl_uint32 * permutations = NULL ;
  862. vl_size * numSeenSoFar = NULL ;
  863. VlRand * rand = vl_get_rand () ;
  864. vl_size totNumRestartedCenters = 0 ;
  865. vl_size numRestartedCenters = 0 ;
  866. vl_uint32 * assignments = (vl_uint32*)vl_malloc (sizeof(vl_uint32) * numData) ;
  867. vl_size * clusterMasses = (vl_size*)vl_malloc (sizeof(vl_size) * numData) ;
  868. TYPE * distances = (TYPE*)vl_malloc (sizeof(TYPE) * numData) ;
  869. if (self->distance == VlDistanceL1) {
  870. permutations = (vl_uint32*)vl_malloc(sizeof(vl_uint32) * numData * self->dimension) ;
  871. numSeenSoFar = (vl_size*)vl_malloc(sizeof(vl_size) * self->numCenters) ;
  872. VL_XCAT(_vl_kmeans_sort_data_helper_, SFX)(self, permutations, data, numData) ;
  873. }
  874. for (energy = VL_INFINITY_D,
  875. iteration = 0;
  876. 1 ;
  877. ++ iteration) {
  878. /* assign data to cluters */
  879. VL_XCAT(_vl_kmeans_quantize_ann_, SFX)(self, assignments, distances, data, numData, iteration > 0) ;
  880. /* compute energy */
  881. energy = 0 ;
  882. for (x = 0 ; x < numData ; ++x) energy += distances[x] ;
  883. if (self->verbosity) {
  884. VL_PRINTF("kmeans: ANN iter %d: energy = %g\n", iteration,
  885. energy) ;
  886. }
  887. /* check termination conditions */
  888. if (iteration >= self->maxNumIterations) {
  889. if (self->verbosity) {
  890. VL_PRINTF("kmeans: ANN terminating because the maximum number of iterations has been reached\n") ;
  891. }
  892. break ;
  893. }
  894. if (energy == previousEnergy) {
  895. if (self->verbosity) {
  896. VL_PRINTF("kmeans: ANN terminating because the algorithm fully converged\n") ;
  897. }
  898. break ;
  899. }
  900. if (iteration == 0) {
  901. initialEnergy = energy ;
  902. } else {
  903. double eps = (previousEnergy - energy) / (initialEnergy - energy) ;
  904. if (eps < self->minEnergyVariation) {
  905. if (self->verbosity) {
  906. VL_PRINTF("kmeans: ANN terminating because the energy relative variation was less than %f\n", self->minEnergyVariation) ;
  907. }
  908. break ;
  909. }
  910. }
  911. /* begin next iteration */
  912. previousEnergy = energy ;
  913. /* update clusters */
  914. memset(clusterMasses, 0, sizeof(vl_size) * numData) ;
  915. for (x = 0 ; x < numData ; ++x) {
  916. clusterMasses[assignments[x]] ++ ;
  917. }
  918. numRestartedCenters = 0 ;
  919. switch (self->distance) {
  920. case VlDistanceL2:
  921. memset(self->centers, 0, sizeof(TYPE) * self->dimension * self->numCenters) ;
  922. for (x = 0 ; x < numData ; ++x) {
  923. TYPE * cpt = (TYPE*)self->centers + assignments[x] * self->dimension ;
  924. TYPE const * xpt = data + x * self->dimension ;
  925. for (d = 0 ; d < self->dimension ; ++d) {
  926. cpt[d] += xpt[d] ;
  927. }
  928. }
  929. for (c = 0 ; c < self->numCenters ; ++c) {
  930. TYPE * cpt = (TYPE*)self->centers + c * self->dimension ;
  931. if (clusterMasses[c] > 0) {
  932. TYPE mass = clusterMasses[c] ;
  933. for (d = 0 ; d < self->dimension ; ++d) {
  934. cpt[d] /= mass ;
  935. }
  936. } else {
  937. vl_uindex x = vl_rand_uindex(rand, numData) ;
  938. numRestartedCenters ++ ;
  939. for (d = 0 ; d < self->dimension ; ++d) {
  940. cpt[d] = data[x * self->dimension + d] ;
  941. }
  942. }
  943. }
  944. break ;
  945. case VlDistanceL1:
  946. for (d = 0 ; d < self->dimension ; ++d) {
  947. vl_uint32 * perm = permutations + d * numData ;
  948. memset(numSeenSoFar, 0, sizeof(vl_size) * self->numCenters) ;
  949. for (x = 0; x < numData ; ++x) {
  950. c = assignments[perm[x]] ;
  951. if (2 * numSeenSoFar[c] < clusterMasses[c]) {
  952. ((TYPE*)self->centers) [d + c * self->dimension] =
  953. data [d + perm[x] * self->dimension] ;
  954. }
  955. numSeenSoFar[c] ++ ;
  956. }
  957. /* restart the centers as required */
  958. for (c = 0 ; c < self->numCenters ; ++c) {
  959. if (clusterMasses[c] == 0) {
  960. TYPE * cpt = (TYPE*)self->centers + c * self->dimension ;
  961. vl_uindex x = vl_rand_uindex(rand, numData) ;
  962. numRestartedCenters ++ ;
  963. for (d = 0 ; d < self->dimension ; ++d) {
  964. cpt[d] = data[x * self->dimension + d] ;
  965. }
  966. }
  967. }
  968. }
  969. break ;
  970. default:
  971. VL_PRINT("bad distance set: %d\n",self->distance);
  972. abort();
  973. } /* done compute centers */
  974. totNumRestartedCenters += numRestartedCenters ;
  975. if (self->verbosity && numRestartedCenters) {
  976. VL_PRINTF("kmeans: ANN iter %d: restarted %d centers\n", iteration,
  977. numRestartedCenters) ;
  978. }
  979. }
  980. if (permutations) {
  981. vl_free(permutations) ;
  982. }
  983. if (numSeenSoFar) {
  984. vl_free(numSeenSoFar) ;
  985. }
  986. vl_free(distances) ;
  987. vl_free(assignments) ;
  988. vl_free(clusterMasses) ;
  989. return energy ;
  990. }
  991. /* ---------------------------------------------------------------- */
  992. /* Elkan refinement */
  993. /* ---------------------------------------------------------------- */
  994. static double
  995. VL_XCAT(_vl_kmeans_refine_centers_elkan_, SFX)
  996. (VlKMeans * self,
  997. TYPE const * data,
  998. vl_size numData)
  999. {
  1000. vl_size d, iteration ;
  1001. vl_index x ;
  1002. vl_uint32 c, j ;
  1003. vl_bool allDone ;
  1004. TYPE * distances = (TYPE*)vl_malloc (sizeof(TYPE) * numData) ;
  1005. vl_uint32 * assignments = (vl_uint32*)vl_malloc (sizeof(vl_uint32) * numData) ;
  1006. vl_size * clusterMasses = (vl_size*)vl_malloc (sizeof(vl_size) * numData) ;
  1007. VlRand * rand = vl_get_rand () ;
  1008. #if (FLT == VL_TYPE_FLOAT)
  1009. VlFloatVectorComparisonFunction distFn = vl_get_vector_comparison_function_f(self->distance) ;
  1010. #else
  1011. VlDoubleVectorComparisonFunction distFn = vl_get_vector_comparison_function_d(self->distance) ;
  1012. #endif
  1013. TYPE * nextCenterDistances = (TYPE*)vl_malloc (sizeof(TYPE) * self->numCenters) ;
  1014. TYPE * pointToClosestCenterUB = (TYPE*)vl_malloc (sizeof(TYPE) * numData) ;
  1015. vl_bool * pointToClosestCenterUBIsStrict = (vl_bool*)vl_malloc (sizeof(vl_bool) * numData) ;
  1016. TYPE * pointToCenterLB = (TYPE*)vl_malloc (sizeof(TYPE) * numData * self->numCenters) ;
  1017. TYPE * newCenters = (TYPE*)vl_malloc(sizeof(TYPE) * self->dimension * self->numCenters) ;
  1018. TYPE * centerToNewCenterDistances = (TYPE*)vl_malloc (sizeof(TYPE) * self->numCenters) ;
  1019. vl_uint32 * permutations = NULL ;
  1020. vl_size * numSeenSoFar = NULL ;
  1021. double energy ;
  1022. vl_size totDistanceComputationsToInit = 0 ;
  1023. vl_size totDistanceComputationsToRefreshUB = 0 ;
  1024. vl_size totDistanceComputationsToRefreshLB = 0 ;
  1025. vl_size totDistanceComputationsToRefreshCenterDistances = 0 ;
  1026. vl_size totDistanceComputationsToNewCenters = 0 ;
  1027. vl_size totDistanceComputationsToFinalize = 0 ;
  1028. vl_size totNumRestartedCenters = 0 ;
  1029. if (self->distance == VlDistanceL1) {
  1030. permutations = (vl_uint32*)vl_malloc(sizeof(vl_uint32) * numData * self->dimension) ;
  1031. numSeenSoFar = (vl_size*)vl_malloc(sizeof(vl_size) * self->numCenters) ;
  1032. VL_XCAT(_vl_kmeans_sort_data_helper_, SFX)(self, permutations, data, numData) ;
  1033. }
  1034. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1035. /* Initialization */
  1036. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1037. /* An iteration is: get_new_centers + reassign + get_energy.
  1038. This counts as iteration 0, where get_new_centers is assumed
  1039. to be performed before calling the train function by
  1040. the initialization function */
  1041. /* update distances between centers */
  1042. totDistanceComputationsToInit +=
  1043. VL_XCAT(_vl_kmeans_update_center_distances_, SFX)(self) ;
  1044. /* assigmen points to the initial centers and initialize bounds */
  1045. memset(pointToCenterLB, 0, sizeof(TYPE) * self->numCenters * numData) ;
  1046. for (x = 0 ; x < (signed)numData ; ++x) {
  1047. TYPE distance ;
  1048. /* do the first center */
  1049. assignments[x] = 0 ;
  1050. distance = distFn(self->dimension,
  1051. data + x * self->dimension,
  1052. (TYPE*)self->centers + 0) ;
  1053. pointToClosestCenterUB[x] = distance ;
  1054. pointToClosestCenterUBIsStrict[x] = VL_TRUE ;
  1055. pointToCenterLB[0 + x * self->numCenters] = distance ;
  1056. totDistanceComputationsToInit += 1 ;
  1057. /* do other centers */
  1058. for (c = 1 ; c < self->numCenters ; ++c) {
  1059. /* Can skip if the center assigned so far is twice as close
  1060. as its distance to the center under consideration */
  1061. if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) *
  1062. pointToClosestCenterUB[x] <=
  1063. ((TYPE*)self->centerDistances)
  1064. [c + assignments[x] * self->numCenters]) {
  1065. continue ;
  1066. }
  1067. distance = distFn(self->dimension,
  1068. data + x * self->dimension,
  1069. (TYPE*)self->centers + c * self->dimension) ;
  1070. pointToCenterLB[c + x * self->numCenters] = distance ;
  1071. totDistanceComputationsToInit += 1 ;
  1072. if (distance < pointToClosestCenterUB[x]) {
  1073. pointToClosestCenterUB[x] = distance ;
  1074. assignments[x] = c ;
  1075. }
  1076. }
  1077. }
  1078. /* compute UB on energy */
  1079. energy = 0 ;
  1080. for (x = 0 ; x < (signed)numData ; ++x) {
  1081. energy += pointToClosestCenterUB[x] ;
  1082. }
  1083. if (self->verbosity) {
  1084. VL_PRINTF("kmeans: Elkan iter 0: energy = %g, dist. calc. = %d\n",
  1085. energy, totDistanceComputationsToInit) ;
  1086. }
  1087. /* #define SANITY*/
  1088. #ifdef SANITY
  1089. {
  1090. int xx ;
  1091. int cc ;
  1092. TYPE tol = 1e-5 ;
  1093. VL_PRINTF("inconsistencies after initial assignments:\n");
  1094. for (xx = 0 ; xx < numData ; ++xx) {
  1095. for (cc = 0 ; cc < self->numCenters ; ++cc) {
  1096. TYPE a = pointToCenterLB[cc + xx * self->numCenters] ;
  1097. TYPE b = distFn(self->dimension,
  1098. data + self->dimension * xx,
  1099. (TYPE*)self->centers + self->dimension * cc) ;
  1100. if (cc == assignments[xx]) {
  1101. TYPE z = pointToClosestCenterUB[xx] ;
  1102. if (z+tol<b) VL_PRINTF("UB %d %d = %f < %f\n",
  1103. cc, xx, z, b) ;
  1104. }
  1105. if (a>b+tol) VL_PRINTF("LB %d %d = %f > %f\n",
  1106. cc, xx, a, b) ;
  1107. }
  1108. }
  1109. }
  1110. #endif
  1111. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1112. /* Iterations */
  1113. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1114. for (iteration = 1 ; 1; ++iteration) {
  1115. vl_size numDistanceComputationsToRefreshUB = 0 ;
  1116. vl_size numDistanceComputationsToRefreshLB = 0 ;
  1117. vl_size numDistanceComputationsToRefreshCenterDistances = 0 ;
  1118. vl_size numDistanceComputationsToNewCenters = 0 ;
  1119. vl_size numRestartedCenters = 0 ;
  1120. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1121. /* Compute new centers */
  1122. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1123. memset(clusterMasses, 0, sizeof(vl_size) * numData) ;
  1124. for (x = 0 ; x < (signed)numData ; ++x) {
  1125. clusterMasses[assignments[x]] ++ ;
  1126. }
  1127. switch (self->distance) {
  1128. case VlDistanceL2:
  1129. memset(newCenters, 0, sizeof(TYPE) * self->dimension * self->numCenters) ;
  1130. for (x = 0 ; x < (signed)numData ; ++x) {
  1131. TYPE * cpt = newCenters + assignments[x] * self->dimension ;
  1132. TYPE const * xpt = data + x * self->dimension ;
  1133. for (d = 0 ; d < self->dimension ; ++d) {
  1134. cpt[d] += xpt[d] ;
  1135. }
  1136. }
  1137. for (c = 0 ; c < self->numCenters ; ++c) {
  1138. TYPE * cpt = newCenters + c * self->dimension ;
  1139. if (clusterMasses[c] > 0) {
  1140. TYPE mass = clusterMasses[c] ;
  1141. for (d = 0 ; d < self->dimension ; ++d) {
  1142. cpt[d] /= mass ;
  1143. }
  1144. } else {
  1145. /* restart the center */
  1146. vl_uindex x = vl_rand_uindex(rand, numData) ;
  1147. numRestartedCenters ++ ;
  1148. for (d = 0 ; d < self->dimension ; ++d) {
  1149. cpt[d] = data[x * self->dimension + d] ;
  1150. }
  1151. }
  1152. }
  1153. break ;
  1154. case VlDistanceL1:
  1155. for (d = 0 ; d < self->dimension ; ++d) {
  1156. vl_uint32 * perm = permutations + d * numData ;
  1157. memset(numSeenSoFar, 0, sizeof(vl_size) * self->numCenters) ;
  1158. for (x = 0; x < (signed)numData ; ++x) {
  1159. c = assignments[perm[x]] ;
  1160. if (2 * numSeenSoFar[c] < clusterMasses[c]) {
  1161. newCenters [d + c * self->dimension] =
  1162. data [d + perm[x] * self->dimension] ;
  1163. }
  1164. numSeenSoFar[c] ++ ;
  1165. }
  1166. }
  1167. /* restart the centers as required */
  1168. for (c = 0 ; c < self->numCenters ; ++c) {
  1169. if (clusterMasses[c] == 0) {
  1170. TYPE * cpt = newCenters + c * self->dimension ;
  1171. vl_uindex x = vl_rand_uindex(rand, numData) ;
  1172. numRestartedCenters ++ ;
  1173. for (d = 0 ; d < self->dimension ; ++d) {
  1174. cpt[d] = data[x * self->dimension + d] ;
  1175. }
  1176. }
  1177. }
  1178. break ;
  1179. default:
  1180. abort();
  1181. } /* done compute centers */
  1182. /* compute the distance from the old centers to the new centers */
  1183. for (c = 0 ; c < self->numCenters ; ++c) {
  1184. TYPE distance = distFn(self->dimension,
  1185. newCenters + c * self->dimension,
  1186. (TYPE*)self->centers + c * self->dimension) ;
  1187. centerToNewCenterDistances[c] = distance ;
  1188. numDistanceComputationsToNewCenters += 1 ;
  1189. }
  1190. /* make the new centers current */
  1191. {
  1192. TYPE * tmp = (TYPE*)self->centers ;
  1193. self->centers = newCenters ;
  1194. newCenters = tmp ;
  1195. }
  1196. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1197. /* Reassign points to a centers */
  1198. /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
  1199. /*
  1200. Update distances between centers.
  1201. */
  1202. numDistanceComputationsToRefreshCenterDistances
  1203. += VL_XCAT(_vl_kmeans_update_center_distances_, SFX)(self) ;
  1204. for (c = 0 ; c < self->numCenters ; ++c) {
  1205. nextCenterDistances[c] = (TYPE) VL_INFINITY_D ;
  1206. for (j = 0 ; j < self->numCenters ; ++j) {
  1207. if (j == c) continue ;
  1208. nextCenterDistances[c] = VL_MIN(nextCenterDistances[c],
  1209. ((TYPE*)self->centerDistances)
  1210. [j + c * self->numCenters]) ;
  1211. }
  1212. }
  1213. /*
  1214. Update upper bounds on point-to-closest-center distances
  1215. based on the center variation.
  1216. */
  1217. for (x = 0 ; x < (signed)numData ; ++x) {
  1218. TYPE a = pointToClosestCenterUB[x] ;
  1219. TYPE b = centerToNewCenterDistances[assignments[x]] ;
  1220. if (self->distance == VlDistanceL1) {
  1221. pointToClosestCenterUB[x] = a + b ;
  1222. } else {
  1223. #if (FLT == VL_TYPE_FLOAT)
  1224. TYPE sqrtab = sqrtf (a * b) ;
  1225. #else
  1226. TYPE sqrtab = sqrt (a * b) ;
  1227. #endif
  1228. pointToClosestCenterUB[x] = a + b + 2.0 * sqrtab ;
  1229. }
  1230. pointToClosestCenterUBIsStrict[x] = VL_FALSE ;
  1231. }
  1232. /*
  1233. Update lower bounds on point-to-center distances
  1234. based on the center variation.
  1235. */
  1236. #if defined(_OPENMP)
  1237. #pragma omp parallel for default(shared) private(x,c) num_threads(vl_get_max_threads())
  1238. #endif
  1239. for (x = 0 ; x < (signed)numData ; ++x) {
  1240. for (c = 0 ; c < self->numCenters ; ++c) {
  1241. TYPE a = pointToCenterLB[c + x * self->numCenters] ;
  1242. TYPE b = centerToNewCenterDistances[c] ;
  1243. if (a < b) {
  1244. pointToCenterLB[c + x * self->numCenters] = 0 ;
  1245. } else {
  1246. if (self->distance == VlDistanceL1) {
  1247. pointToCenterLB[c + x * self->numCenters] = a - b ;
  1248. } else {
  1249. #if (FLT == VL_TYPE_FLOAT)
  1250. TYPE sqrtab = sqrtf (a * b) ;
  1251. #else
  1252. TYPE sqrtab = sqrt (a * b) ;
  1253. #endif
  1254. pointToCenterLB[c + x * self->numCenters] = a + b - 2.0 * sqrtab ;
  1255. }
  1256. }
  1257. }
  1258. }
  1259. #ifdef SANITY
  1260. {
  1261. int xx ;
  1262. int cc ;
  1263. TYPE tol = 1e-5 ;
  1264. VL_PRINTF("inconsistencies before assignments:\n");
  1265. for (xx = 0 ; xx < numData ; ++xx) {
  1266. for (cc = 0 ; cc < self->numCenters ; ++cc) {
  1267. TYPE a = pointToCenterLB[cc + xx * self->numCenters] ;
  1268. TYPE b = distFn(self->dimension,
  1269. data + self->dimension * xx,
  1270. (TYPE*)self->centers + self->dimension * cc) ;
  1271. if (cc == assignments[xx]) {
  1272. TYPE z = pointToClosestCenterUB[xx] ;
  1273. if (z+tol<b) VL_PRINTF("UB %d %d = %f < %f\n",
  1274. cc, xx, z, b) ;
  1275. }
  1276. if (a>b+tol) VL_PRINTF("LB %d %d = %f > %f (assign = %d)\n",
  1277. cc, xx, a, b, assignments[xx]) ;
  1278. }
  1279. }
  1280. }
  1281. #endif
  1282. /*
  1283. Scan the data and do the reassignments. Use the bounds to
  1284. skip as many point-to-center distance calculations as possible.
  1285. */
  1286. allDone = VL_TRUE ;
  1287. #if defined(_OPENMP)
  1288. #pragma omp parallel for \
  1289. default(none) \
  1290. shared(self,numData, \
  1291. pointToClosestCenterUB,pointToCenterLB, \
  1292. nextCenterDistances,pointToClosestCenterUBIsStrict, \
  1293. assignments,data,distFn,allDone) \
  1294. private(c,x) \
  1295. reduction(+:numDistanceComputationsToRefreshUB,numDistanceComputationsToRefreshLB) \
  1296. num_threads(vl_get_max_threads())
  1297. #endif
  1298. for (x = 0 ; x < (signed)numData ; ++ x) {
  1299. /*
  1300. A point x sticks with its current center assignmets[x]
  1301. the UB to d(x, c[assigmnets[x]]) is not larger than half
  1302. the distance of c[assigments[x]] to any other center c.
  1303. */
  1304. if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) *
  1305. pointToClosestCenterUB[x] <= nextCenterDistances[assignments[x]]) {
  1306. continue ;
  1307. }
  1308. for (c = 0 ; c < self->numCenters ; ++c) {
  1309. vl_uint32 cx = assignments[x] ;
  1310. TYPE distance ;
  1311. /* The point is not reassigned to a given center c
  1312. if either:
  1313. 0 - c is already the assigned center
  1314. 1 - The UB of d(x, c[assignments[x]]) is smaller than half
  1315. the distance of c[assigments[x]] to c, OR
  1316. 2 - The UB of d(x, c[assignmets[x]]) is smaller than the
  1317. LB of the distance of x to c.
  1318. */
  1319. if (cx == c) {
  1320. continue ;
  1321. }
  1322. if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) *
  1323. pointToClosestCenterUB[x] <= ((TYPE*)self->centerDistances)
  1324. [c + cx * self->numCenters]) {
  1325. continue ;
  1326. }
  1327. if (pointToClosestCenterUB[x] <= pointToCenterLB
  1328. [c + x * self->numCenters]) {
  1329. continue ;
  1330. }
  1331. /* If the UB is loose, try recomputing it and test again */
  1332. if (! pointToClosestCenterUBIsStrict[x]) {
  1333. distance = distFn(self->dimension,
  1334. data + self->dimension * x,
  1335. (TYPE*)self->centers + self->dimension * cx) ;
  1336. pointToClosestCenterUB[x] = distance ;
  1337. pointToClosestCenterUBIsStrict[x] = VL_TRUE ;
  1338. pointToCenterLB[cx + x * self->numCenters] = distance ;
  1339. numDistanceComputationsToRefreshUB += 1 ;
  1340. if (((self->distance == VlDistanceL1) ? 2.0 : 4.0) *
  1341. pointToClosestCenterUB[x] <= ((TYPE*)self->centerDistances)
  1342. [c + cx * self->numCenters]) {
  1343. continue ;
  1344. }
  1345. if (pointToClosestCenterUB[x] <= pointToCenterLB
  1346. [c + x * self->numCenters]) {
  1347. continue ;
  1348. }
  1349. }
  1350. /*
  1351. Now the UB is strict (equal to d(x, assignments[x])), but
  1352. we still could not exclude that x should be reassigned to
  1353. c. We therefore compute the distance, update the LB,
  1354. and check if a reassigmnet must be made
  1355. */
  1356. distance = distFn(self->dimension,
  1357. data + x * self->dimension,
  1358. (TYPE*)self->centers + c * self->dimension) ;
  1359. numDistanceComputationsToRefreshLB += 1 ;
  1360. pointToCenterLB[c + x * self->numCenters] = distance ;
  1361. if (distance < pointToClosestCenterUB[x]) {
  1362. assignments[x] = c ;
  1363. pointToClosestCenterUB[x] = distance ;
  1364. allDone = VL_FALSE ;
  1365. /* the UB strict flag is already set here */
  1366. }
  1367. } /* assign center */
  1368. } /* next data point */
  1369. totDistanceComputationsToRefreshUB
  1370. += numDistanceComputationsToRefreshUB ;
  1371. totDistanceComputationsToRefreshLB
  1372. += numDistanceComputationsToRefreshLB ;
  1373. totDistanceComputationsToRefreshCenterDistances
  1374. += numDistanceComputationsToRefreshCenterDistances ;
  1375. totDistanceComputationsToNewCenters
  1376. += numDistanceComputationsToNewCenters ;
  1377. totNumRestartedCenters
  1378. += numRestartedCenters ;
  1379. #ifdef SANITY
  1380. {
  1381. int xx ;
  1382. int cc ;
  1383. TYPE tol = 1e-5 ;
  1384. VL_PRINTF("inconsistencies after assignments:\n");
  1385. for (xx = 0 ; xx < numData ; ++xx) {
  1386. for (cc = 0 ; cc < self->numCenters ; ++cc) {
  1387. TYPE a = pointToCenterLB[cc + xx * self->numCenters] ;
  1388. TYPE b = distFn(self->dimension,
  1389. data + self->dimension * xx,
  1390. (TYPE*)self->centers + self->dimension * cc) ;
  1391. if (cc == assignments[xx]) {
  1392. TYPE z = pointToClosestCenterUB[xx] ;
  1393. if (z+tol<b) VL_PRINTF("UB %d %d = %f < %f\n",
  1394. cc, xx, z, b) ;
  1395. }
  1396. if (a>b+tol) VL_PRINTF("LB %d %d = %f > %f (assign = %d)\n",
  1397. cc, xx, a, b, assignments[xx]) ;
  1398. }
  1399. }
  1400. }
  1401. #endif
  1402. /* compute UB on energy */
  1403. energy = 0 ;
  1404. for (x = 0 ; x < (signed)numData ; ++x) {
  1405. energy += pointToClosestCenterUB[x] ;
  1406. }
  1407. if (self->verbosity) {
  1408. vl_size numDistanceComputations =
  1409. numDistanceComputationsToRefreshUB +
  1410. numDistanceComputationsToRefreshLB +
  1411. numDistanceComputationsToRefreshCenterDistances +
  1412. numDistanceComputationsToNewCenters ;
  1413. VL_PRINTF("kmeans: Elkan iter %d: energy <= %g, dist. calc. = %d\n",
  1414. iteration,
  1415. energy,
  1416. numDistanceComputations) ;
  1417. if (numRestartedCenters) {
  1418. VL_PRINTF("kmeans: Elkan iter %d: restarted %d centers\n",
  1419. iteration,
  1420. energy,
  1421. numRestartedCenters) ;
  1422. }
  1423. if (self->verbosity > 1) {
  1424. VL_PRINTF("kmeans: Elkan iter %d: total dist. calc. per type: "
  1425. "UB: %.1f%% (%d), LB: %.1f%% (%d), "
  1426. "intra_center: %.1f%% (%d), "
  1427. "new_center: %.1f%% (%d)\n",
  1428. iteration,
  1429. 100.0 * numDistanceComputationsToRefreshUB / numDistanceComputations,
  1430. numDistanceComputationsToRefreshUB,
  1431. 100.0 *numDistanceComputationsToRefreshLB / numDistanceComputations,
  1432. numDistanceComputationsToRefreshLB,
  1433. 100.0 * numDistanceComputationsToRefreshCenterDistances / numDistanceComputations,
  1434. numDistanceComputationsToRefreshCenterDistances,
  1435. 100.0 * numDistanceComputationsToNewCenters / numDistanceComputations,
  1436. numDistanceComputationsToNewCenters) ;
  1437. }
  1438. }
  1439. /* check termination conditions */
  1440. if (iteration >= self->maxNumIterations) {
  1441. if (self->verbosity) {
  1442. VL_PRINTF("kmeans: Elkan terminating because maximum number of iterations reached\n") ;
  1443. }
  1444. break ;
  1445. }
  1446. if (allDone) {
  1447. if (self->verbosity) {
  1448. VL_PRINTF("kmeans: Elkan terminating because the algorithm fully converged\n") ;
  1449. }
  1450. break ;
  1451. }
  1452. } /* next Elkan iteration */
  1453. /* compute true energy */
  1454. energy = 0 ;
  1455. for (x = 0 ; x < (signed)numData ; ++ x) {
  1456. vl_uindex cx = assignments [x] ;
  1457. energy += distFn(self->dimension,
  1458. data + self->dimension * x,
  1459. (TYPE*)self->centers + self->dimension * cx) ;
  1460. totDistanceComputationsToFinalize += 1 ;
  1461. }
  1462. {
  1463. vl_size totDistanceComputations =
  1464. totDistanceComputationsToInit +
  1465. totDistanceComputationsToRefreshUB +
  1466. totDistanceComputationsToRefreshLB +
  1467. totDistanceComputationsToRefreshCenterDistances +
  1468. totDistanceComputationsToNewCenters +
  1469. totDistanceComputationsToFinalize ;
  1470. double saving = (double)totDistanceComputations
  1471. / (iteration * self->numCenters * numData) ;
  1472. if (self->verbosity) {
  1473. VL_PRINTF("kmeans: Elkan: total dist. calc.: %d (%.2f %% of Lloyd)\n",
  1474. totDistanceComputations, saving * 100.0) ;
  1475. if (totNumRestartedCenters) {
  1476. VL_PRINTF("kmeans: Elkan: there have been %d restarts\n",
  1477. totNumRestartedCenters) ;
  1478. }
  1479. }
  1480. if (self->verbosity > 1) {
  1481. VL_PRINTF("kmeans: Elkan: total dist. calc. per type: "
  1482. "init: %.1f%% (%d), UB: %.1f%% (%d), LB: %.1f%% (%d), "
  1483. "intra_center: %.1f%% (%d), "
  1484. "new_center: %.1f%% (%d), "
  1485. "finalize: %.1f%% (%d)\n",
  1486. 100.0 * totDistanceComputationsToInit / totDistanceComputations,
  1487. totDistanceComputationsToInit,
  1488. 100.0 * totDistanceComputationsToRefreshUB / totDistanceComputations,
  1489. totDistanceComputationsToRefreshUB,
  1490. 100.0 *totDistanceComputationsToRefreshLB / totDistanceComputations,
  1491. totDistanceComputationsToRefreshLB,
  1492. 100.0 * totDistanceComputationsToRefreshCenterDistances / totDistanceComputations,
  1493. totDistanceComputationsToRefreshCenterDistances,
  1494. 100.0 * totDistanceComputationsToNewCenters / totDistanceComputations,
  1495. totDistanceComputationsToNewCenters,
  1496. 100.0 * totDistanceComputationsToFinalize / totDistanceComputations,
  1497. totDistanceComputationsToFinalize) ;
  1498. }
  1499. }
  1500. if (permutations) {
  1501. vl_free(permutations) ;
  1502. }
  1503. if (numSeenSoFar) {
  1504. vl_free(numSeenSoFar) ;
  1505. }
  1506. vl_free(distances) ;
  1507. vl_free(assignments) ;
  1508. vl_free(clusterMasses) ;
  1509. vl_free(nextCenterDistances) ;
  1510. vl_free(pointToClosestCenterUB) ;
  1511. vl_free(pointToClosestCenterUBIsStrict) ;
  1512. vl_free(pointToCenterLB) ;
  1513. vl_free(newCenters) ;
  1514. vl_free(centerToNewCenterDistances) ;
  1515. return energy ;
  1516. }
  1517. /* ---------------------------------------------------------------- */
  1518. static double
  1519. VL_XCAT(_vl_kmeans_refine_centers_, SFX)
  1520. (VlKMeans * self,
  1521. TYPE const * data,
  1522. vl_size numData)
  1523. {
  1524. switch (self->algorithm) {
  1525. case VlKMeansLloyd:
  1526. return
  1527. VL_XCAT(_vl_kmeans_refine_centers_lloyd_, SFX)(self, data, numData) ;
  1528. break ;
  1529. case VlKMeansElkan:
  1530. return
  1531. VL_XCAT(_vl_kmeans_refine_centers_elkan_, SFX)(self, data, numData) ;
  1532. break ;
  1533. case VlKMeansANN:
  1534. return
  1535. VL_XCAT(_vl_kmeans_refine_centers_ann_, SFX)(self, data, numData) ;
  1536. break ;
  1537. default:
  1538. abort() ;
  1539. }
  1540. return 0;
  1541. }
  1542. /* VL_KMEANS_INSTANTIATING */
  1543. #else
  1544. #ifndef __DOXYGEN__
  1545. #define FLT VL_TYPE_FLOAT
  1546. #define TYPE float
  1547. #define SFX f
  1548. #define VL_KMEANS_INSTANTIATING
  1549. #include "kmeans.c"
  1550. #define FLT VL_TYPE_DOUBLE
  1551. #define TYPE double
  1552. #define SFX d
  1553. #define VL_KMEANS_INSTANTIATING
  1554. #include "kmeans.c"
  1555. #endif
  1556. /* VL_KMEANS_INSTANTIATING */
  1557. #endif
  1558. /* ================================================================ */
  1559. #ifndef VL_KMEANS_INSTANTIATING
  1560. /** ------------------------------------------------------------------
  1561. ** @brief Set centers
  1562. ** @param self KMeans object.
  1563. ** @param centers centers to copy.
  1564. ** @param dimension data dimension.
  1565. ** @param numCenters number of centers.
  1566. **/
  1567. VL_EXPORT void
  1568. vl_kmeans_set_centers
  1569. (VlKMeans * self,
  1570. void const * centers,
  1571. vl_size dimension,
  1572. vl_size numCenters)
  1573. {
  1574. vl_kmeans_reset (self) ;
  1575. switch (self->dataType) {
  1576. case VL_TYPE_FLOAT :
  1577. _vl_kmeans_set_centers_f
  1578. (self, (float const *)centers, dimension, numCenters) ;
  1579. break ;
  1580. case VL_TYPE_DOUBLE :
  1581. _vl_kmeans_set_centers_d
  1582. (self, (double const *)centers, dimension, numCenters) ;
  1583. break ;
  1584. default:
  1585. abort() ;
  1586. }
  1587. }
  1588. /** ------------------------------------------------------------------
  1589. ** @brief init centers by randomly sampling data
  1590. ** @param self KMeans object.
  1591. ** @param data data to sample from.
  1592. ** @param dimension data dimension.
  1593. ** @param numData nmber of data points.
  1594. ** @param numCenters number of centers.
  1595. **
  1596. ** The function inits the KMeans centers by randomly sampling
  1597. ** the data @a data.
  1598. **/
  1599. VL_EXPORT void
  1600. vl_kmeans_init_centers_with_rand_data
  1601. (VlKMeans * self,
  1602. void const * data,
  1603. vl_size dimension,
  1604. vl_size numData,
  1605. vl_size numCenters)
  1606. {
  1607. vl_kmeans_reset (self) ;
  1608. switch (self->dataType) {
  1609. case VL_TYPE_FLOAT :
  1610. _vl_kmeans_init_centers_with_rand_data_f
  1611. (self, (float const *)data, dimension, numData, numCenters) ;
  1612. break ;
  1613. case VL_TYPE_DOUBLE :
  1614. _vl_kmeans_init_centers_with_rand_data_d
  1615. (self, (double const *)data, dimension, numData, numCenters) ;
  1616. break ;
  1617. default:
  1618. abort() ;
  1619. }
  1620. }
  1621. /** ------------------------------------------------------------------
  1622. ** @brief Seed centers by the KMeans++ algorithm
  1623. ** @param self KMeans object.
  1624. ** @param data data to sample from.
  1625. ** @param dimension data dimension.
  1626. ** @param numData nmber of data points.
  1627. ** @param numCenters number of centers.
  1628. **/
  1629. VL_EXPORT void
  1630. vl_kmeans_init_centers_plus_plus
  1631. (VlKMeans * self,
  1632. void const * data,
  1633. vl_size dimension,
  1634. vl_size numData,
  1635. vl_size numCenters)
  1636. {
  1637. vl_kmeans_reset (self) ;
  1638. switch (self->dataType) {
  1639. case VL_TYPE_FLOAT :
  1640. _vl_kmeans_init_centers_plus_plus_f
  1641. (self, (float const *)data, dimension, numData, numCenters) ;
  1642. break ;
  1643. case VL_TYPE_DOUBLE :
  1644. _vl_kmeans_init_centers_plus_plus_d
  1645. (self, (double const *)data, dimension, numData, numCenters) ;
  1646. break ;
  1647. default:
  1648. abort() ;
  1649. }
  1650. }
  1651. /** ------------------------------------------------------------------
  1652. ** @brief Quantize data
  1653. ** @param self KMeans object.
  1654. ** @param assignments data to closest center assignments (output).
  1655. ** @param distances data to closest center distance (output).
  1656. ** @param data data to quantize.
  1657. ** @param numData number of data points to quantize.
  1658. **/
  1659. VL_EXPORT void
  1660. vl_kmeans_quantize
  1661. (VlKMeans * self,
  1662. vl_uint32 * assignments,
  1663. void * distances,
  1664. void const * data,
  1665. vl_size numData)
  1666. {
  1667. switch (self->dataType) {
  1668. case VL_TYPE_FLOAT :
  1669. _vl_kmeans_quantize_f
  1670. (self, assignments, (float*)distances, (float*)data, numData) ;
  1671. break ;
  1672. case VL_TYPE_DOUBLE :
  1673. _vl_kmeans_quantize_d
  1674. (self, assignments, (double*)distances, (double*)data, numData) ;
  1675. break ;
  1676. default:
  1677. abort() ;
  1678. }
  1679. }
  1680. /** ------------------------------------------------------------------
  1681. ** @brief Quantize data using approximate nearest neighbours (ANN).
  1682. ** @param self KMeans object.
  1683. ** @param assignments data to centers assignments (output).
  1684. ** @param distances data to closes center distance (output)
  1685. ** @param data data to quantize.
  1686. ** @param numData number of data points.
  1687. ** @param update choose wether to update current assignments.
  1688. **
  1689. ** The function uses an ANN procedure to compute the approximate
  1690. ** nearest neighbours of the input data point.
  1691. **
  1692. ** Setting @a update to ::VL_TRUE will cause the algorithm
  1693. ** to *update existing assignments*. This means that each
  1694. ** element of @a assignments and @a distances is updated ony if the
  1695. ** ANN procedure can find a better assignment of the existing one.
  1696. **/
  1697. VL_EXPORT void
  1698. vl_kmeans_quantize_ann
  1699. (VlKMeans * self,
  1700. vl_uint32 * assignments,
  1701. void * distances,
  1702. void const * data,
  1703. vl_size numData,
  1704. vl_bool update)
  1705. {
  1706. switch (self->dataType) {
  1707. case VL_TYPE_FLOAT :
  1708. _vl_kmeans_quantize_ann_f
  1709. (self, assignments, (float*)distances, (float const *)data, numData, update) ;
  1710. break ;
  1711. case VL_TYPE_DOUBLE :
  1712. _vl_kmeans_quantize_ann_d
  1713. (self, assignments, (double*)distances, (double const *)data, numData, update) ;
  1714. break ;
  1715. default:
  1716. abort() ;
  1717. }
  1718. }
  1719. /** ------------------------------------------------------------------
  1720. ** @brief Refine center locations.
  1721. ** @param self KMeans object.
  1722. ** @param data data to quantize.
  1723. ** @param numData number of data points.
  1724. ** @return K-means energy at the end of optimization.
  1725. **
  1726. ** The function calls the underlying K-means quantization algorithm
  1727. ** (@ref VlKMeansAlgorithm) to quantize the specified data @a data.
  1728. ** The function assumes that the cluster centers have already
  1729. ** been assigned by using one of the seeding functions, or by
  1730. ** setting them.
  1731. **/
  1732. VL_EXPORT double
  1733. vl_kmeans_refine_centers
  1734. (VlKMeans * self,
  1735. void const * data,
  1736. vl_size numData)
  1737. {
  1738. assert (self->centers) ;
  1739. switch (self->dataType) {
  1740. case VL_TYPE_FLOAT :
  1741. return
  1742. _vl_kmeans_refine_centers_f
  1743. (self, (float const *)data, numData) ;
  1744. case VL_TYPE_DOUBLE :
  1745. return
  1746. _vl_kmeans_refine_centers_d
  1747. (self, (double const *)data, numData) ;
  1748. default:
  1749. abort() ;
  1750. }
  1751. return 0;
  1752. }
  1753. /** ------------------------------------------------------------------
  1754. ** @brief Cluster data.
  1755. ** @param self KMeans object.
  1756. ** @param data data to quantize.
  1757. ** @param dimension data dimension.
  1758. ** @param numData number of data points.
  1759. ** @param numCenters number of clusters.
  1760. ** @return K-means energy at the end of optimization.
  1761. **
  1762. ** The function initializes the centers by using the initialization
  1763. ** algorithm set by ::vl_kmeans_set_initialization and refines them
  1764. ** by the quantization algorithm set by ::vl_kmeans_set_algorithm.
  1765. ** The process is repeated one or more times (see
  1766. ** ::vl_kmeans_set_num_repetitions) and the resutl with smaller
  1767. ** energy is retained.
  1768. **/
  1769. VL_EXPORT double
  1770. vl_kmeans_cluster (VlKMeans * self,
  1771. void const * data,
  1772. vl_size dimension,
  1773. vl_size numData,
  1774. vl_size numCenters)
  1775. {
  1776. vl_uindex repetition ;
  1777. double bestEnergy = VL_INFINITY_D ;
  1778. void * bestCenters = NULL ;
  1779. for (repetition = 0 ; repetition < self->numRepetitions ; ++ repetition) {
  1780. double energy ;
  1781. double timeRef ;
  1782. if (self->verbosity) {
  1783. VL_PRINTF("kmeans: repetition %d of %d\n", repetition + 1, self->numRepetitions) ;
  1784. }
  1785. timeRef = vl_get_cpu_time() ;
  1786. switch (self->initialization) {
  1787. case VlKMeansRandomSelection :
  1788. vl_kmeans_init_centers_with_rand_data (self,
  1789. data, dimension, numData,
  1790. numCenters) ;
  1791. break ;
  1792. case VlKMeansPlusPlus :
  1793. vl_kmeans_init_centers_plus_plus (self,
  1794. data, dimension, numData,
  1795. numCenters) ;
  1796. break ;
  1797. default:
  1798. abort() ;
  1799. }
  1800. if (self->verbosity) {
  1801. VL_PRINTF("kmeans: K-means initialized in %.2f s\n",
  1802. vl_get_cpu_time() - timeRef) ;
  1803. }
  1804. timeRef = vl_get_cpu_time () ;
  1805. energy = vl_kmeans_refine_centers (self, data, numData) ;
  1806. if (self->verbosity) {
  1807. VL_PRINTF("kmeans: K-means terminated in %.2f s with energy %g\n",
  1808. vl_get_cpu_time() - timeRef, energy) ;
  1809. }
  1810. /* copy centers to output if current solution is optimal */
  1811. /* check repetition == 0 as well in case energy = NaN, which */
  1812. /* can happen if the data contain NaNs */
  1813. if (energy < bestEnergy || repetition == 0) {
  1814. void * temp ;
  1815. bestEnergy = energy ;
  1816. if (bestCenters == NULL) {
  1817. bestCenters = vl_malloc(vl_get_type_size(self->dataType) *
  1818. self->dimension *
  1819. self->numCenters) ;
  1820. }
  1821. /* swap buffers */
  1822. temp = bestCenters ;
  1823. bestCenters = self->centers ;
  1824. self->centers = temp ;
  1825. } /* better energy */
  1826. } /* next repetition */
  1827. vl_free (self->centers) ;
  1828. self->centers = bestCenters ;
  1829. return bestEnergy ;
  1830. }
  1831. /* VL_KMEANS_INSTANTIATING */
  1832. #endif
  1833. #undef SFX
  1834. #undef TYPE
  1835. #undef FLT
  1836. #undef VL_KMEANS_INSTANTIATING