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