kmeans_index.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. /***********************************************************************
  2. * Software License Agreement (BSD License)
  3. *
  4. * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
  5. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
  6. *
  7. * THE BSD LICENSE
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. *
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in the
  17. * documentation and/or other materials provided with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  20. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  21. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  22. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  23. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  24. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  28. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. *************************************************************************/
  30. #ifndef OPENCV_FLANN_KMEANS_INDEX_H_
  31. #define OPENCV_FLANN_KMEANS_INDEX_H_
  32. #include <algorithm>
  33. #include <map>
  34. #include <cassert>
  35. #include <limits>
  36. #include <cmath>
  37. #include "general.h"
  38. #include "nn_index.h"
  39. #include "dist.h"
  40. #include "matrix.h"
  41. #include "result_set.h"
  42. #include "heap.h"
  43. #include "allocator.h"
  44. #include "random.h"
  45. #include "saving.h"
  46. #include "logger.h"
  47. namespace cvflann
  48. {
  49. struct KMeansIndexParams : public IndexParams
  50. {
  51. KMeansIndexParams(int branching = 32, int iterations = 11,
  52. flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 )
  53. {
  54. (*this)["algorithm"] = FLANN_INDEX_KMEANS;
  55. // branching factor
  56. (*this)["branching"] = branching;
  57. // max iterations to perform in one kmeans clustering (kmeans tree)
  58. (*this)["iterations"] = iterations;
  59. // algorithm used for picking the initial cluster centers for kmeans tree
  60. (*this)["centers_init"] = centers_init;
  61. // cluster boundary index. Used when searching the kmeans tree
  62. (*this)["cb_index"] = cb_index;
  63. }
  64. };
  65. /**
  66. * Hierarchical kmeans index
  67. *
  68. * Contains a tree constructed through a hierarchical kmeans clustering
  69. * and other information for indexing a set of points for nearest-neighbour matching.
  70. */
  71. template <typename Distance>
  72. class KMeansIndex : public NNIndex<Distance>
  73. {
  74. public:
  75. typedef typename Distance::ElementType ElementType;
  76. typedef typename Distance::ResultType DistanceType;
  77. typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&);
  78. /**
  79. * The function used for choosing the cluster centers.
  80. */
  81. centersAlgFunction chooseCenters;
  82. /**
  83. * Chooses the initial centers in the k-means clustering in a random manner.
  84. *
  85. * Params:
  86. * k = number of centers
  87. * vecs = the dataset of points
  88. * indices = indices in the dataset
  89. * indices_length = length of indices vector
  90. *
  91. */
  92. void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length)
  93. {
  94. UniqueRandom r(indices_length);
  95. int index;
  96. for (index=0; index<k; ++index) {
  97. bool duplicate = true;
  98. int rnd;
  99. while (duplicate) {
  100. duplicate = false;
  101. rnd = r.next();
  102. if (rnd<0) {
  103. centers_length = index;
  104. return;
  105. }
  106. centers[index] = indices[rnd];
  107. for (int j=0; j<index; ++j) {
  108. DistanceType sq = distance_(dataset_[centers[index]], dataset_[centers[j]], dataset_.cols);
  109. if (sq<1e-16) {
  110. duplicate = true;
  111. }
  112. }
  113. }
  114. }
  115. centers_length = index;
  116. }
  117. /**
  118. * Chooses the initial centers in the k-means using Gonzales' algorithm
  119. * so that the centers are spaced apart from each other.
  120. *
  121. * Params:
  122. * k = number of centers
  123. * vecs = the dataset of points
  124. * indices = indices in the dataset
  125. * Returns:
  126. */
  127. void chooseCentersGonzales(int k, int* indices, int indices_length, int* centers, int& centers_length)
  128. {
  129. int n = indices_length;
  130. int rnd = rand_int(n);
  131. assert(rnd >=0 && rnd < n);
  132. centers[0] = indices[rnd];
  133. int index;
  134. for (index=1; index<k; ++index) {
  135. int best_index = -1;
  136. DistanceType best_val = 0;
  137. for (int j=0; j<n; ++j) {
  138. DistanceType dist = distance_(dataset_[centers[0]],dataset_[indices[j]],dataset_.cols);
  139. for (int i=1; i<index; ++i) {
  140. DistanceType tmp_dist = distance_(dataset_[centers[i]],dataset_[indices[j]],dataset_.cols);
  141. if (tmp_dist<dist) {
  142. dist = tmp_dist;
  143. }
  144. }
  145. if (dist>best_val) {
  146. best_val = dist;
  147. best_index = j;
  148. }
  149. }
  150. if (best_index!=-1) {
  151. centers[index] = indices[best_index];
  152. }
  153. else {
  154. break;
  155. }
  156. }
  157. centers_length = index;
  158. }
  159. /**
  160. * Chooses the initial centers in the k-means using the algorithm
  161. * proposed in the KMeans++ paper:
  162. * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding
  163. *
  164. * Implementation of this function was converted from the one provided in Arthur's code.
  165. *
  166. * Params:
  167. * k = number of centers
  168. * vecs = the dataset of points
  169. * indices = indices in the dataset
  170. * Returns:
  171. */
  172. void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length)
  173. {
  174. int n = indices_length;
  175. double currentPot = 0;
  176. DistanceType* closestDistSq = new DistanceType[n];
  177. // Choose one random center and set the closestDistSq values
  178. int index = rand_int(n);
  179. assert(index >=0 && index < n);
  180. centers[0] = indices[index];
  181. for (int i = 0; i < n; i++) {
  182. closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
  183. closestDistSq[i] = ensureSquareDistance<Distance>( closestDistSq[i] );
  184. currentPot += closestDistSq[i];
  185. }
  186. const int numLocalTries = 1;
  187. // Choose each center
  188. int centerCount;
  189. for (centerCount = 1; centerCount < k; centerCount++) {
  190. // Repeat several trials
  191. double bestNewPot = -1;
  192. int bestNewIndex = -1;
  193. for (int localTrial = 0; localTrial < numLocalTries; localTrial++) {
  194. // Choose our center - have to be slightly careful to return a valid answer even accounting
  195. // for possible rounding errors
  196. double randVal = rand_double(currentPot);
  197. for (index = 0; index < n-1; index++) {
  198. if (randVal <= closestDistSq[index]) break;
  199. else randVal -= closestDistSq[index];
  200. }
  201. // Compute the new potential
  202. double newPot = 0;
  203. for (int i = 0; i < n; i++) {
  204. DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols);
  205. newPot += std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
  206. }
  207. // Store the best result
  208. if ((bestNewPot < 0)||(newPot < bestNewPot)) {
  209. bestNewPot = newPot;
  210. bestNewIndex = index;
  211. }
  212. }
  213. // Add the appropriate center
  214. centers[centerCount] = indices[bestNewIndex];
  215. currentPot = bestNewPot;
  216. for (int i = 0; i < n; i++) {
  217. DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols);
  218. closestDistSq[i] = std::min( ensureSquareDistance<Distance>(dist), closestDistSq[i] );
  219. }
  220. }
  221. centers_length = centerCount;
  222. delete[] closestDistSq;
  223. }
  224. public:
  225. flann_algorithm_t getType() const CV_OVERRIDE
  226. {
  227. return FLANN_INDEX_KMEANS;
  228. }
  229. class KMeansDistanceComputer : public cv::ParallelLoopBody
  230. {
  231. public:
  232. KMeansDistanceComputer(Distance _distance, const Matrix<ElementType>& _dataset,
  233. const int _branching, const int* _indices, const Matrix<double>& _dcenters, const size_t _veclen,
  234. std::vector<int> &_new_centroids, std::vector<DistanceType> &_sq_dists)
  235. : distance(_distance)
  236. , dataset(_dataset)
  237. , branching(_branching)
  238. , indices(_indices)
  239. , dcenters(_dcenters)
  240. , veclen(_veclen)
  241. , new_centroids(_new_centroids)
  242. , sq_dists(_sq_dists)
  243. {
  244. }
  245. void operator()(const cv::Range& range) const CV_OVERRIDE
  246. {
  247. const int begin = range.start;
  248. const int end = range.end;
  249. for( int i = begin; i<end; ++i)
  250. {
  251. DistanceType sq_dist(distance(dataset[indices[i]], dcenters[0], veclen));
  252. int new_centroid(0);
  253. for (int j=1; j<branching; ++j) {
  254. DistanceType new_sq_dist = distance(dataset[indices[i]], dcenters[j], veclen);
  255. if (sq_dist>new_sq_dist) {
  256. new_centroid = j;
  257. sq_dist = new_sq_dist;
  258. }
  259. }
  260. sq_dists[i] = sq_dist;
  261. new_centroids[i] = new_centroid;
  262. }
  263. }
  264. private:
  265. Distance distance;
  266. const Matrix<ElementType>& dataset;
  267. const int branching;
  268. const int* indices;
  269. const Matrix<double>& dcenters;
  270. const size_t veclen;
  271. std::vector<int> &new_centroids;
  272. std::vector<DistanceType> &sq_dists;
  273. KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; }
  274. };
  275. /**
  276. * Index constructor
  277. *
  278. * Params:
  279. * inputData = dataset with the input features
  280. * params = parameters passed to the hierarchical k-means algorithm
  281. */
  282. KMeansIndex(const Matrix<ElementType>& inputData, const IndexParams& params = KMeansIndexParams(),
  283. Distance d = Distance())
  284. : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d)
  285. {
  286. memoryCounter_ = 0;
  287. size_ = dataset_.rows;
  288. veclen_ = dataset_.cols;
  289. branching_ = get_param(params,"branching",32);
  290. iterations_ = get_param(params,"iterations",11);
  291. if (iterations_<0) {
  292. iterations_ = (std::numeric_limits<int>::max)();
  293. }
  294. centers_init_ = get_param(params,"centers_init",FLANN_CENTERS_RANDOM);
  295. if (centers_init_==FLANN_CENTERS_RANDOM) {
  296. chooseCenters = &KMeansIndex::chooseCentersRandom;
  297. }
  298. else if (centers_init_==FLANN_CENTERS_GONZALES) {
  299. chooseCenters = &KMeansIndex::chooseCentersGonzales;
  300. }
  301. else if (centers_init_==FLANN_CENTERS_KMEANSPP) {
  302. chooseCenters = &KMeansIndex::chooseCentersKMeanspp;
  303. }
  304. else {
  305. throw FLANNException("Unknown algorithm for choosing initial centers.");
  306. }
  307. cb_index_ = 0.4f;
  308. }
  309. KMeansIndex(const KMeansIndex&);
  310. KMeansIndex& operator=(const KMeansIndex&);
  311. /**
  312. * Index destructor.
  313. *
  314. * Release the memory used by the index.
  315. */
  316. virtual ~KMeansIndex()
  317. {
  318. if (root_ != NULL) {
  319. free_centers(root_);
  320. }
  321. if (indices_!=NULL) {
  322. delete[] indices_;
  323. }
  324. }
  325. /**
  326. * Returns size of index.
  327. */
  328. size_t size() const CV_OVERRIDE
  329. {
  330. return size_;
  331. }
  332. /**
  333. * Returns the length of an index feature.
  334. */
  335. size_t veclen() const CV_OVERRIDE
  336. {
  337. return veclen_;
  338. }
  339. void set_cb_index( float index)
  340. {
  341. cb_index_ = index;
  342. }
  343. /**
  344. * Computes the inde memory usage
  345. * Returns: memory used by the index
  346. */
  347. int usedMemory() const CV_OVERRIDE
  348. {
  349. return pool_.usedMemory+pool_.wastedMemory+memoryCounter_;
  350. }
  351. /**
  352. * Builds the index
  353. */
  354. void buildIndex() CV_OVERRIDE
  355. {
  356. if (branching_<2) {
  357. throw FLANNException("Branching factor must be at least 2");
  358. }
  359. indices_ = new int[size_];
  360. for (size_t i=0; i<size_; ++i) {
  361. indices_[i] = int(i);
  362. }
  363. root_ = pool_.allocate<KMeansNode>();
  364. std::memset(root_, 0, sizeof(KMeansNode));
  365. computeNodeStatistics(root_, indices_, (int)size_);
  366. computeClustering(root_, indices_, (int)size_, branching_,0);
  367. }
  368. void saveIndex(FILE* stream) CV_OVERRIDE
  369. {
  370. save_value(stream, branching_);
  371. save_value(stream, iterations_);
  372. save_value(stream, memoryCounter_);
  373. save_value(stream, cb_index_);
  374. save_value(stream, *indices_, (int)size_);
  375. save_tree(stream, root_);
  376. }
  377. void loadIndex(FILE* stream) CV_OVERRIDE
  378. {
  379. load_value(stream, branching_);
  380. load_value(stream, iterations_);
  381. load_value(stream, memoryCounter_);
  382. load_value(stream, cb_index_);
  383. if (indices_!=NULL) {
  384. delete[] indices_;
  385. }
  386. indices_ = new int[size_];
  387. load_value(stream, *indices_, size_);
  388. if (root_!=NULL) {
  389. free_centers(root_);
  390. }
  391. load_tree(stream, root_);
  392. index_params_["algorithm"] = getType();
  393. index_params_["branching"] = branching_;
  394. index_params_["iterations"] = iterations_;
  395. index_params_["centers_init"] = centers_init_;
  396. index_params_["cb_index"] = cb_index_;
  397. }
  398. /**
  399. * Find set of nearest neighbors to vec. Their indices are stored inside
  400. * the result object.
  401. *
  402. * Params:
  403. * result = the result object in which the indices of the nearest-neighbors are stored
  404. * vec = the vector for which to search the nearest neighbors
  405. * searchParams = parameters that influence the search algorithm (checks, cb_index)
  406. */
  407. void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE
  408. {
  409. int maxChecks = get_param(searchParams,"checks",32);
  410. if (maxChecks==FLANN_CHECKS_UNLIMITED) {
  411. findExactNN(root_, result, vec);
  412. }
  413. else {
  414. // Priority queue storing intermediate branches in the best-bin-first search
  415. Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
  416. int checks = 0;
  417. findNN(root_, result, vec, checks, maxChecks, heap);
  418. BranchSt branch;
  419. while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
  420. KMeansNodePtr node = branch.node;
  421. findNN(node, result, vec, checks, maxChecks, heap);
  422. }
  423. assert(result.full());
  424. delete heap;
  425. }
  426. }
  427. /**
  428. * Clustering function that takes a cut in the hierarchical k-means
  429. * tree and return the clusters centers of that clustering.
  430. * Params:
  431. * numClusters = number of clusters to have in the clustering computed
  432. * Returns: number of cluster centers
  433. */
  434. int getClusterCenters(Matrix<DistanceType>& centers)
  435. {
  436. int numClusters = centers.rows;
  437. if (numClusters<1) {
  438. throw FLANNException("Number of clusters must be at least 1");
  439. }
  440. DistanceType variance;
  441. KMeansNodePtr* clusters = new KMeansNodePtr[numClusters];
  442. int clusterCount = getMinVarianceClusters(root_, clusters, numClusters, variance);
  443. Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount);
  444. for (int i=0; i<clusterCount; ++i) {
  445. DistanceType* center = clusters[i]->pivot;
  446. for (size_t j=0; j<veclen_; ++j) {
  447. centers[i][j] = center[j];
  448. }
  449. }
  450. delete[] clusters;
  451. return clusterCount;
  452. }
  453. IndexParams getParameters() const CV_OVERRIDE
  454. {
  455. return index_params_;
  456. }
  457. private:
  458. /**
  459. * Struture representing a node in the hierarchical k-means tree.
  460. */
  461. struct KMeansNode
  462. {
  463. /**
  464. * The cluster center.
  465. */
  466. DistanceType* pivot;
  467. /**
  468. * The cluster radius.
  469. */
  470. DistanceType radius;
  471. /**
  472. * The cluster mean radius.
  473. */
  474. DistanceType mean_radius;
  475. /**
  476. * The cluster variance.
  477. */
  478. DistanceType variance;
  479. /**
  480. * The cluster size (number of points in the cluster)
  481. */
  482. int size;
  483. /**
  484. * Child nodes (only for non-terminal nodes)
  485. */
  486. KMeansNode** childs;
  487. /**
  488. * Node points (only for terminal nodes)
  489. */
  490. int* indices;
  491. /**
  492. * Level
  493. */
  494. int level;
  495. };
  496. typedef KMeansNode* KMeansNodePtr;
  497. /**
  498. * Alias definition for a nicer syntax.
  499. */
  500. typedef BranchStruct<KMeansNodePtr, DistanceType> BranchSt;
  501. void save_tree(FILE* stream, KMeansNodePtr node)
  502. {
  503. save_value(stream, *node);
  504. save_value(stream, *(node->pivot), (int)veclen_);
  505. if (node->childs==NULL) {
  506. int indices_offset = (int)(node->indices - indices_);
  507. save_value(stream, indices_offset);
  508. }
  509. else {
  510. for(int i=0; i<branching_; ++i) {
  511. save_tree(stream, node->childs[i]);
  512. }
  513. }
  514. }
  515. void load_tree(FILE* stream, KMeansNodePtr& node)
  516. {
  517. node = pool_.allocate<KMeansNode>();
  518. load_value(stream, *node);
  519. node->pivot = new DistanceType[veclen_];
  520. load_value(stream, *(node->pivot), (int)veclen_);
  521. if (node->childs==NULL) {
  522. int indices_offset;
  523. load_value(stream, indices_offset);
  524. node->indices = indices_ + indices_offset;
  525. }
  526. else {
  527. node->childs = pool_.allocate<KMeansNodePtr>(branching_);
  528. for(int i=0; i<branching_; ++i) {
  529. load_tree(stream, node->childs[i]);
  530. }
  531. }
  532. }
  533. /**
  534. * Helper function
  535. */
  536. void free_centers(KMeansNodePtr node)
  537. {
  538. delete[] node->pivot;
  539. if (node->childs!=NULL) {
  540. for (int k=0; k<branching_; ++k) {
  541. free_centers(node->childs[k]);
  542. }
  543. }
  544. }
  545. /**
  546. * Computes the statistics of a node (mean, radius, variance).
  547. *
  548. * Params:
  549. * node = the node to use
  550. * indices = the indices of the points belonging to the node
  551. */
  552. void computeNodeStatistics(KMeansNodePtr node, int* indices, int indices_length)
  553. {
  554. DistanceType radius = 0;
  555. DistanceType variance = 0;
  556. DistanceType* mean = new DistanceType[veclen_];
  557. memoryCounter_ += int(veclen_*sizeof(DistanceType));
  558. memset(mean,0,veclen_*sizeof(DistanceType));
  559. for (size_t i=0; i<size_; ++i) {
  560. ElementType* vec = dataset_[indices[i]];
  561. for (size_t j=0; j<veclen_; ++j) {
  562. mean[j] += vec[j];
  563. }
  564. variance += distance_(vec, ZeroIterator<ElementType>(), veclen_);
  565. }
  566. for (size_t j=0; j<veclen_; ++j) {
  567. mean[j] /= size_;
  568. }
  569. variance /= size_;
  570. variance -= distance_(mean, ZeroIterator<ElementType>(), veclen_);
  571. DistanceType tmp = 0;
  572. for (int i=0; i<indices_length; ++i) {
  573. tmp = distance_(mean, dataset_[indices[i]], veclen_);
  574. if (tmp>radius) {
  575. radius = tmp;
  576. }
  577. }
  578. node->variance = variance;
  579. node->radius = radius;
  580. node->pivot = mean;
  581. }
  582. /**
  583. * The method responsible with actually doing the recursive hierarchical
  584. * clustering
  585. *
  586. * Params:
  587. * node = the node to cluster
  588. * indices = indices of the points belonging to the current node
  589. * branching = the branching factor to use in the clustering
  590. *
  591. * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point)
  592. */
  593. void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level)
  594. {
  595. node->size = indices_length;
  596. node->level = level;
  597. if (indices_length < branching) {
  598. node->indices = indices;
  599. std::sort(node->indices,node->indices+indices_length);
  600. node->childs = NULL;
  601. return;
  602. }
  603. cv::AutoBuffer<int> centers_idx_buf(branching);
  604. int* centers_idx = centers_idx_buf.data();
  605. int centers_length;
  606. (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);
  607. if (centers_length<branching) {
  608. node->indices = indices;
  609. std::sort(node->indices,node->indices+indices_length);
  610. node->childs = NULL;
  611. return;
  612. }
  613. cv::AutoBuffer<double> dcenters_buf(branching*veclen_);
  614. Matrix<double> dcenters(dcenters_buf.data(), branching, veclen_);
  615. for (int i=0; i<centers_length; ++i) {
  616. ElementType* vec = dataset_[centers_idx[i]];
  617. for (size_t k=0; k<veclen_; ++k) {
  618. dcenters[i][k] = double(vec[k]);
  619. }
  620. }
  621. std::vector<DistanceType> radiuses(branching);
  622. cv::AutoBuffer<int> count_buf(branching);
  623. int* count = count_buf.data();
  624. for (int i=0; i<branching; ++i) {
  625. radiuses[i] = 0;
  626. count[i] = 0;
  627. }
  628. // assign points to clusters
  629. cv::AutoBuffer<int> belongs_to_buf(indices_length);
  630. int* belongs_to = belongs_to_buf.data();
  631. for (int i=0; i<indices_length; ++i) {
  632. DistanceType sq_dist = distance_(dataset_[indices[i]], dcenters[0], veclen_);
  633. belongs_to[i] = 0;
  634. for (int j=1; j<branching; ++j) {
  635. DistanceType new_sq_dist = distance_(dataset_[indices[i]], dcenters[j], veclen_);
  636. if (sq_dist>new_sq_dist) {
  637. belongs_to[i] = j;
  638. sq_dist = new_sq_dist;
  639. }
  640. }
  641. if (sq_dist>radiuses[belongs_to[i]]) {
  642. radiuses[belongs_to[i]] = sq_dist;
  643. }
  644. count[belongs_to[i]]++;
  645. }
  646. bool converged = false;
  647. int iteration = 0;
  648. while (!converged && iteration<iterations_) {
  649. converged = true;
  650. iteration++;
  651. // compute the new cluster centers
  652. for (int i=0; i<branching; ++i) {
  653. memset(dcenters[i],0,sizeof(double)*veclen_);
  654. radiuses[i] = 0;
  655. }
  656. for (int i=0; i<indices_length; ++i) {
  657. ElementType* vec = dataset_[indices[i]];
  658. double* center = dcenters[belongs_to[i]];
  659. for (size_t k=0; k<veclen_; ++k) {
  660. center[k] += vec[k];
  661. }
  662. }
  663. for (int i=0; i<branching; ++i) {
  664. int cnt = count[i];
  665. for (size_t k=0; k<veclen_; ++k) {
  666. dcenters[i][k] /= cnt;
  667. }
  668. }
  669. std::vector<int> new_centroids(indices_length);
  670. std::vector<DistanceType> sq_dists(indices_length);
  671. // reassign points to clusters
  672. KMeansDistanceComputer invoker(distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists);
  673. parallel_for_(cv::Range(0, (int)indices_length), invoker);
  674. for (int i=0; i < (int)indices_length; ++i) {
  675. DistanceType sq_dist(sq_dists[i]);
  676. int new_centroid(new_centroids[i]);
  677. if (sq_dist > radiuses[new_centroid]) {
  678. radiuses[new_centroid] = sq_dist;
  679. }
  680. if (new_centroid != belongs_to[i]) {
  681. count[belongs_to[i]]--;
  682. count[new_centroid]++;
  683. belongs_to[i] = new_centroid;
  684. converged = false;
  685. }
  686. }
  687. for (int i=0; i<branching; ++i) {
  688. // if one cluster converges to an empty cluster,
  689. // move an element into that cluster
  690. if (count[i]==0) {
  691. int j = (i+1)%branching;
  692. while (count[j]<=1) {
  693. j = (j+1)%branching;
  694. }
  695. for (int k=0; k<indices_length; ++k) {
  696. if (belongs_to[k]==j) {
  697. // for cluster j, we move the furthest element from the center to the empty cluster i
  698. if ( distance_(dataset_[indices[k]], dcenters[j], veclen_) == radiuses[j] ) {
  699. belongs_to[k] = i;
  700. count[j]--;
  701. count[i]++;
  702. break;
  703. }
  704. }
  705. }
  706. converged = false;
  707. }
  708. }
  709. }
  710. DistanceType** centers = new DistanceType*[branching];
  711. for (int i=0; i<branching; ++i) {
  712. centers[i] = new DistanceType[veclen_];
  713. memoryCounter_ += (int)(veclen_*sizeof(DistanceType));
  714. for (size_t k=0; k<veclen_; ++k) {
  715. centers[i][k] = (DistanceType)dcenters[i][k];
  716. }
  717. }
  718. // compute kmeans clustering for each of the resulting clusters
  719. node->childs = pool_.allocate<KMeansNodePtr>(branching);
  720. int start = 0;
  721. int end = start;
  722. for (int c=0; c<branching; ++c) {
  723. int s = count[c];
  724. DistanceType variance = 0;
  725. DistanceType mean_radius =0;
  726. for (int i=0; i<indices_length; ++i) {
  727. if (belongs_to[i]==c) {
  728. DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
  729. variance += d;
  730. mean_radius += sqrt(d);
  731. std::swap(indices[i],indices[end]);
  732. std::swap(belongs_to[i],belongs_to[end]);
  733. end++;
  734. }
  735. }
  736. variance /= s;
  737. mean_radius /= s;
  738. variance -= distance_(centers[c], ZeroIterator<ElementType>(), veclen_);
  739. node->childs[c] = pool_.allocate<KMeansNode>();
  740. std::memset(node->childs[c], 0, sizeof(KMeansNode));
  741. node->childs[c]->radius = radiuses[c];
  742. node->childs[c]->pivot = centers[c];
  743. node->childs[c]->variance = variance;
  744. node->childs[c]->mean_radius = mean_radius;
  745. computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
  746. start=end;
  747. }
  748. delete[] centers;
  749. }
  750. /**
  751. * Performs one descent in the hierarchical k-means tree. The branches not
  752. * visited are stored in a priority queue.
  753. *
  754. * Params:
  755. * node = node to explore
  756. * result = container for the k-nearest neighbors found
  757. * vec = query points
  758. * checks = how many points in the dataset have been checked so far
  759. * maxChecks = maximum dataset points to checks
  760. */
  761. void findNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec, int& checks, int maxChecks,
  762. Heap<BranchSt>* heap)
  763. {
  764. // Ignore those clusters that are too far away
  765. {
  766. DistanceType bsq = distance_(vec, node->pivot, veclen_);
  767. DistanceType rsq = node->radius;
  768. DistanceType wsq = result.worstDist();
  769. DistanceType val = bsq-rsq-wsq;
  770. DistanceType val2 = val*val-4*rsq*wsq;
  771. //if (val>0) {
  772. if ((val>0)&&(val2>0)) {
  773. return;
  774. }
  775. }
  776. if (node->childs==NULL) {
  777. if (checks>=maxChecks) {
  778. if (result.full()) return;
  779. }
  780. checks += node->size;
  781. for (int i=0; i<node->size; ++i) {
  782. int index = node->indices[i];
  783. DistanceType dist = distance_(dataset_[index], vec, veclen_);
  784. result.addPoint(dist, index);
  785. }
  786. }
  787. else {
  788. DistanceType* domain_distances = new DistanceType[branching_];
  789. int closest_center = exploreNodeBranches(node, vec, domain_distances, heap);
  790. delete[] domain_distances;
  791. findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap);
  792. }
  793. }
  794. /**
  795. * Helper function that computes the nearest childs of a node to a given query point.
  796. * Params:
  797. * node = the node
  798. * q = the query point
  799. * distances = array with the distances to each child node.
  800. * Returns:
  801. */
  802. int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, Heap<BranchSt>* heap)
  803. {
  804. int best_index = 0;
  805. domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_);
  806. for (int i=1; i<branching_; ++i) {
  807. domain_distances[i] = distance_(q, node->childs[i]->pivot, veclen_);
  808. if (domain_distances[i]<domain_distances[best_index]) {
  809. best_index = i;
  810. }
  811. }
  812. // float* best_center = node->childs[best_index]->pivot;
  813. for (int i=0; i<branching_; ++i) {
  814. if (i != best_index) {
  815. domain_distances[i] -= cb_index_*node->childs[i]->variance;
  816. // float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q);
  817. // if (domain_distances[i]<dist_to_border) {
  818. // domain_distances[i] = dist_to_border;
  819. // }
  820. heap->insert(BranchSt(node->childs[i],domain_distances[i]));
  821. }
  822. }
  823. return best_index;
  824. }
  825. /**
  826. * Function the performs exact nearest neighbor search by traversing the entire tree.
  827. */
  828. void findExactNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec)
  829. {
  830. // Ignore those clusters that are too far away
  831. {
  832. DistanceType bsq = distance_(vec, node->pivot, veclen_);
  833. DistanceType rsq = node->radius;
  834. DistanceType wsq = result.worstDist();
  835. DistanceType val = bsq-rsq-wsq;
  836. DistanceType val2 = val*val-4*rsq*wsq;
  837. // if (val>0) {
  838. if ((val>0)&&(val2>0)) {
  839. return;
  840. }
  841. }
  842. if (node->childs==NULL) {
  843. for (int i=0; i<node->size; ++i) {
  844. int index = node->indices[i];
  845. DistanceType dist = distance_(dataset_[index], vec, veclen_);
  846. result.addPoint(dist, index);
  847. }
  848. }
  849. else {
  850. int* sort_indices = new int[branching_];
  851. getCenterOrdering(node, vec, sort_indices);
  852. for (int i=0; i<branching_; ++i) {
  853. findExactNN(node->childs[sort_indices[i]],result,vec);
  854. }
  855. delete[] sort_indices;
  856. }
  857. }
  858. /**
  859. * Helper function.
  860. *
  861. * I computes the order in which to traverse the child nodes of a particular node.
  862. */
  863. void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices)
  864. {
  865. DistanceType* domain_distances = new DistanceType[branching_];
  866. for (int i=0; i<branching_; ++i) {
  867. DistanceType dist = distance_(q, node->childs[i]->pivot, veclen_);
  868. int j=0;
  869. while (domain_distances[j]<dist && j<i) j++;
  870. for (int k=i; k>j; --k) {
  871. domain_distances[k] = domain_distances[k-1];
  872. sort_indices[k] = sort_indices[k-1];
  873. }
  874. domain_distances[j] = dist;
  875. sort_indices[j] = i;
  876. }
  877. delete[] domain_distances;
  878. }
  879. /**
  880. * Method that computes the squared distance from the query point q
  881. * from inside region with center c to the border between this
  882. * region and the region with center p
  883. */
  884. DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q)
  885. {
  886. DistanceType sum = 0;
  887. DistanceType sum2 = 0;
  888. for (int i=0; i<veclen_; ++i) {
  889. DistanceType t = c[i]-p[i];
  890. sum += t*(q[i]-(c[i]+p[i])/2);
  891. sum2 += t*t;
  892. }
  893. return sum*sum/sum2;
  894. }
  895. /**
  896. * Helper function the descends in the hierarchical k-means tree by splitting those clusters that minimize
  897. * the overall variance of the clustering.
  898. * Params:
  899. * root = root node
  900. * clusters = array with clusters centers (return value)
  901. * varianceValue = variance of the clustering (return value)
  902. * Returns:
  903. */
  904. int getMinVarianceClusters(KMeansNodePtr root, KMeansNodePtr* clusters, int clusters_length, DistanceType& varianceValue)
  905. {
  906. int clusterCount = 1;
  907. clusters[0] = root;
  908. DistanceType meanVariance = root->variance*root->size;
  909. while (clusterCount<clusters_length) {
  910. DistanceType minVariance = (std::numeric_limits<DistanceType>::max)();
  911. int splitIndex = -1;
  912. for (int i=0; i<clusterCount; ++i) {
  913. if (clusters[i]->childs != NULL) {
  914. DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size;
  915. for (int j=0; j<branching_; ++j) {
  916. variance += clusters[i]->childs[j]->variance*clusters[i]->childs[j]->size;
  917. }
  918. if (variance<minVariance) {
  919. minVariance = variance;
  920. splitIndex = i;
  921. }
  922. }
  923. }
  924. if (splitIndex==-1) break;
  925. if ( (branching_+clusterCount-1) > clusters_length) break;
  926. meanVariance = minVariance;
  927. // split node
  928. KMeansNodePtr toSplit = clusters[splitIndex];
  929. clusters[splitIndex] = toSplit->childs[0];
  930. for (int i=1; i<branching_; ++i) {
  931. clusters[clusterCount++] = toSplit->childs[i];
  932. }
  933. }
  934. varianceValue = meanVariance/root->size;
  935. return clusterCount;
  936. }
  937. private:
  938. /** The branching factor used in the hierarchical k-means clustering */
  939. int branching_;
  940. /** Maximum number of iterations to use when performing k-means clustering */
  941. int iterations_;
  942. /** Algorithm for choosing the cluster centers */
  943. flann_centers_init_t centers_init_;
  944. /**
  945. * Cluster border index. This is used in the tree search phase when determining
  946. * the closest cluster to explore next. A zero value takes into account only
  947. * the cluster centres, a value greater then zero also take into account the size
  948. * of the cluster.
  949. */
  950. float cb_index_;
  951. /**
  952. * The dataset used by this index
  953. */
  954. const Matrix<ElementType> dataset_;
  955. /** Index parameters */
  956. IndexParams index_params_;
  957. /**
  958. * Number of features in the dataset.
  959. */
  960. size_t size_;
  961. /**
  962. * Length of each feature.
  963. */
  964. size_t veclen_;
  965. /**
  966. * The root node in the tree.
  967. */
  968. KMeansNodePtr root_;
  969. /**
  970. * Array of indices to vectors in the dataset.
  971. */
  972. int* indices_;
  973. /**
  974. * The distance
  975. */
  976. Distance distance_;
  977. /**
  978. * Pooled memory allocator.
  979. */
  980. PooledAllocator pool_;
  981. /**
  982. * Memory occupied by the index.
  983. */
  984. int memoryCounter_;
  985. };
  986. }
  987. #endif //OPENCV_FLANN_KMEANS_INDEX_H_