kmeans_index.h 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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
  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. int* _count, int* _belongs_to, std::vector<DistanceType>& _radiuses, bool& _converged, cv::Mutex& _mtx)
  235. : distance(_distance)
  236. , dataset(_dataset)
  237. , branching(_branching)
  238. , indices(_indices)
  239. , dcenters(_dcenters)
  240. , veclen(_veclen)
  241. , count(_count)
  242. , belongs_to(_belongs_to)
  243. , radiuses(_radiuses)
  244. , converged(_converged)
  245. , mtx(_mtx)
  246. {
  247. }
  248. void operator()(const cv::Range& range) const
  249. {
  250. const int begin = range.start;
  251. const int end = range.end;
  252. for( int i = begin; i<end; ++i)
  253. {
  254. DistanceType sq_dist = distance(dataset[indices[i]], dcenters[0], veclen);
  255. int new_centroid = 0;
  256. for (int j=1; j<branching; ++j) {
  257. DistanceType new_sq_dist = distance(dataset[indices[i]], dcenters[j], veclen);
  258. if (sq_dist>new_sq_dist) {
  259. new_centroid = j;
  260. sq_dist = new_sq_dist;
  261. }
  262. }
  263. if (sq_dist > radiuses[new_centroid]) {
  264. radiuses[new_centroid] = sq_dist;
  265. }
  266. if (new_centroid != belongs_to[i]) {
  267. count[belongs_to[i]]--;
  268. count[new_centroid]++;
  269. belongs_to[i] = new_centroid;
  270. mtx.lock();
  271. converged = false;
  272. mtx.unlock();
  273. }
  274. }
  275. }
  276. private:
  277. Distance distance;
  278. const Matrix<ElementType>& dataset;
  279. const int branching;
  280. const int* indices;
  281. const Matrix<double>& dcenters;
  282. const size_t veclen;
  283. int* count;
  284. int* belongs_to;
  285. std::vector<DistanceType>& radiuses;
  286. bool& converged;
  287. cv::Mutex& mtx;
  288. KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; }
  289. };
  290. /**
  291. * Index constructor
  292. *
  293. * Params:
  294. * inputData = dataset with the input features
  295. * params = parameters passed to the hierarchical k-means algorithm
  296. */
  297. KMeansIndex(const Matrix<ElementType>& inputData, const IndexParams& params = KMeansIndexParams(),
  298. Distance d = Distance())
  299. : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d)
  300. {
  301. memoryCounter_ = 0;
  302. size_ = dataset_.rows;
  303. veclen_ = dataset_.cols;
  304. branching_ = get_param(params,"branching",32);
  305. iterations_ = get_param(params,"iterations",11);
  306. if (iterations_<0) {
  307. iterations_ = (std::numeric_limits<int>::max)();
  308. }
  309. centers_init_ = get_param(params,"centers_init",FLANN_CENTERS_RANDOM);
  310. if (centers_init_==FLANN_CENTERS_RANDOM) {
  311. chooseCenters = &KMeansIndex::chooseCentersRandom;
  312. }
  313. else if (centers_init_==FLANN_CENTERS_GONZALES) {
  314. chooseCenters = &KMeansIndex::chooseCentersGonzales;
  315. }
  316. else if (centers_init_==FLANN_CENTERS_KMEANSPP) {
  317. chooseCenters = &KMeansIndex::chooseCentersKMeanspp;
  318. }
  319. else {
  320. throw FLANNException("Unknown algorithm for choosing initial centers.");
  321. }
  322. cb_index_ = 0.4f;
  323. }
  324. KMeansIndex(const KMeansIndex&);
  325. KMeansIndex& operator=(const KMeansIndex&);
  326. /**
  327. * Index destructor.
  328. *
  329. * Release the memory used by the index.
  330. */
  331. virtual ~KMeansIndex()
  332. {
  333. if (root_ != NULL) {
  334. free_centers(root_);
  335. }
  336. if (indices_!=NULL) {
  337. delete[] indices_;
  338. }
  339. }
  340. /**
  341. * Returns size of index.
  342. */
  343. size_t size() const
  344. {
  345. return size_;
  346. }
  347. /**
  348. * Returns the length of an index feature.
  349. */
  350. size_t veclen() const
  351. {
  352. return veclen_;
  353. }
  354. void set_cb_index( float index)
  355. {
  356. cb_index_ = index;
  357. }
  358. /**
  359. * Computes the inde memory usage
  360. * Returns: memory used by the index
  361. */
  362. int usedMemory() const
  363. {
  364. return pool_.usedMemory+pool_.wastedMemory+memoryCounter_;
  365. }
  366. /**
  367. * Builds the index
  368. */
  369. void buildIndex()
  370. {
  371. if (branching_<2) {
  372. throw FLANNException("Branching factor must be at least 2");
  373. }
  374. indices_ = new int[size_];
  375. for (size_t i=0; i<size_; ++i) {
  376. indices_[i] = int(i);
  377. }
  378. root_ = pool_.allocate<KMeansNode>();
  379. std::memset(root_, 0, sizeof(KMeansNode));
  380. computeNodeStatistics(root_, indices_, (int)size_);
  381. computeClustering(root_, indices_, (int)size_, branching_,0);
  382. }
  383. void saveIndex(FILE* stream)
  384. {
  385. save_value(stream, branching_);
  386. save_value(stream, iterations_);
  387. save_value(stream, memoryCounter_);
  388. save_value(stream, cb_index_);
  389. save_value(stream, *indices_, (int)size_);
  390. save_tree(stream, root_);
  391. }
  392. void loadIndex(FILE* stream)
  393. {
  394. load_value(stream, branching_);
  395. load_value(stream, iterations_);
  396. load_value(stream, memoryCounter_);
  397. load_value(stream, cb_index_);
  398. if (indices_!=NULL) {
  399. delete[] indices_;
  400. }
  401. indices_ = new int[size_];
  402. load_value(stream, *indices_, size_);
  403. if (root_!=NULL) {
  404. free_centers(root_);
  405. }
  406. load_tree(stream, root_);
  407. index_params_["algorithm"] = getType();
  408. index_params_["branching"] = branching_;
  409. index_params_["iterations"] = iterations_;
  410. index_params_["centers_init"] = centers_init_;
  411. index_params_["cb_index"] = cb_index_;
  412. }
  413. /**
  414. * Find set of nearest neighbors to vec. Their indices are stored inside
  415. * the result object.
  416. *
  417. * Params:
  418. * result = the result object in which the indices of the nearest-neighbors are stored
  419. * vec = the vector for which to search the nearest neighbors
  420. * searchParams = parameters that influence the search algorithm (checks, cb_index)
  421. */
  422. void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams)
  423. {
  424. int maxChecks = get_param(searchParams,"checks",32);
  425. if (maxChecks==FLANN_CHECKS_UNLIMITED) {
  426. findExactNN(root_, result, vec);
  427. }
  428. else {
  429. // Priority queue storing intermediate branches in the best-bin-first search
  430. Heap<BranchSt>* heap = new Heap<BranchSt>((int)size_);
  431. int checks = 0;
  432. findNN(root_, result, vec, checks, maxChecks, heap);
  433. BranchSt branch;
  434. while (heap->popMin(branch) && (checks<maxChecks || !result.full())) {
  435. KMeansNodePtr node = branch.node;
  436. findNN(node, result, vec, checks, maxChecks, heap);
  437. }
  438. assert(result.full());
  439. delete heap;
  440. }
  441. }
  442. /**
  443. * Clustering function that takes a cut in the hierarchical k-means
  444. * tree and return the clusters centers of that clustering.
  445. * Params:
  446. * numClusters = number of clusters to have in the clustering computed
  447. * Returns: number of cluster centers
  448. */
  449. int getClusterCenters(Matrix<DistanceType>& centers)
  450. {
  451. int numClusters = centers.rows;
  452. if (numClusters<1) {
  453. throw FLANNException("Number of clusters must be at least 1");
  454. }
  455. DistanceType variance;
  456. KMeansNodePtr* clusters = new KMeansNodePtr[numClusters];
  457. int clusterCount = getMinVarianceClusters(root_, clusters, numClusters, variance);
  458. Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount);
  459. for (int i=0; i<clusterCount; ++i) {
  460. DistanceType* center = clusters[i]->pivot;
  461. for (size_t j=0; j<veclen_; ++j) {
  462. centers[i][j] = center[j];
  463. }
  464. }
  465. delete[] clusters;
  466. return clusterCount;
  467. }
  468. IndexParams getParameters() const
  469. {
  470. return index_params_;
  471. }
  472. private:
  473. /**
  474. * Struture representing a node in the hierarchical k-means tree.
  475. */
  476. struct KMeansNode
  477. {
  478. /**
  479. * The cluster center.
  480. */
  481. DistanceType* pivot;
  482. /**
  483. * The cluster radius.
  484. */
  485. DistanceType radius;
  486. /**
  487. * The cluster mean radius.
  488. */
  489. DistanceType mean_radius;
  490. /**
  491. * The cluster variance.
  492. */
  493. DistanceType variance;
  494. /**
  495. * The cluster size (number of points in the cluster)
  496. */
  497. int size;
  498. /**
  499. * Child nodes (only for non-terminal nodes)
  500. */
  501. KMeansNode** childs;
  502. /**
  503. * Node points (only for terminal nodes)
  504. */
  505. int* indices;
  506. /**
  507. * Level
  508. */
  509. int level;
  510. };
  511. typedef KMeansNode* KMeansNodePtr;
  512. /**
  513. * Alias definition for a nicer syntax.
  514. */
  515. typedef BranchStruct<KMeansNodePtr, DistanceType> BranchSt;
  516. void save_tree(FILE* stream, KMeansNodePtr node)
  517. {
  518. save_value(stream, *node);
  519. save_value(stream, *(node->pivot), (int)veclen_);
  520. if (node->childs==NULL) {
  521. int indices_offset = (int)(node->indices - indices_);
  522. save_value(stream, indices_offset);
  523. }
  524. else {
  525. for(int i=0; i<branching_; ++i) {
  526. save_tree(stream, node->childs[i]);
  527. }
  528. }
  529. }
  530. void load_tree(FILE* stream, KMeansNodePtr& node)
  531. {
  532. node = pool_.allocate<KMeansNode>();
  533. load_value(stream, *node);
  534. node->pivot = new DistanceType[veclen_];
  535. load_value(stream, *(node->pivot), (int)veclen_);
  536. if (node->childs==NULL) {
  537. int indices_offset;
  538. load_value(stream, indices_offset);
  539. node->indices = indices_ + indices_offset;
  540. }
  541. else {
  542. node->childs = pool_.allocate<KMeansNodePtr>(branching_);
  543. for(int i=0; i<branching_; ++i) {
  544. load_tree(stream, node->childs[i]);
  545. }
  546. }
  547. }
  548. /**
  549. * Helper function
  550. */
  551. void free_centers(KMeansNodePtr node)
  552. {
  553. delete[] node->pivot;
  554. if (node->childs!=NULL) {
  555. for (int k=0; k<branching_; ++k) {
  556. free_centers(node->childs[k]);
  557. }
  558. }
  559. }
  560. /**
  561. * Computes the statistics of a node (mean, radius, variance).
  562. *
  563. * Params:
  564. * node = the node to use
  565. * indices = the indices of the points belonging to the node
  566. */
  567. void computeNodeStatistics(KMeansNodePtr node, int* indices, int indices_length)
  568. {
  569. DistanceType radius = 0;
  570. DistanceType variance = 0;
  571. DistanceType* mean = new DistanceType[veclen_];
  572. memoryCounter_ += int(veclen_*sizeof(DistanceType));
  573. memset(mean,0,veclen_*sizeof(DistanceType));
  574. for (size_t i=0; i<size_; ++i) {
  575. ElementType* vec = dataset_[indices[i]];
  576. for (size_t j=0; j<veclen_; ++j) {
  577. mean[j] += vec[j];
  578. }
  579. variance += distance_(vec, ZeroIterator<ElementType>(), veclen_);
  580. }
  581. for (size_t j=0; j<veclen_; ++j) {
  582. mean[j] /= size_;
  583. }
  584. variance /= size_;
  585. variance -= distance_(mean, ZeroIterator<ElementType>(), veclen_);
  586. DistanceType tmp = 0;
  587. for (int i=0; i<indices_length; ++i) {
  588. tmp = distance_(mean, dataset_[indices[i]], veclen_);
  589. if (tmp>radius) {
  590. radius = tmp;
  591. }
  592. }
  593. node->variance = variance;
  594. node->radius = radius;
  595. node->pivot = mean;
  596. }
  597. /**
  598. * The method responsible with actually doing the recursive hierarchical
  599. * clustering
  600. *
  601. * Params:
  602. * node = the node to cluster
  603. * indices = indices of the points belonging to the current node
  604. * branching = the branching factor to use in the clustering
  605. *
  606. * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point)
  607. */
  608. void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level)
  609. {
  610. node->size = indices_length;
  611. node->level = level;
  612. if (indices_length < branching) {
  613. node->indices = indices;
  614. std::sort(node->indices,node->indices+indices_length);
  615. node->childs = NULL;
  616. return;
  617. }
  618. cv::AutoBuffer<int> centers_idx_buf(branching);
  619. int* centers_idx = (int*)centers_idx_buf;
  620. int centers_length;
  621. (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length);
  622. if (centers_length<branching) {
  623. node->indices = indices;
  624. std::sort(node->indices,node->indices+indices_length);
  625. node->childs = NULL;
  626. return;
  627. }
  628. cv::AutoBuffer<double> dcenters_buf(branching*veclen_);
  629. Matrix<double> dcenters((double*)dcenters_buf,branching,veclen_);
  630. for (int i=0; i<centers_length; ++i) {
  631. ElementType* vec = dataset_[centers_idx[i]];
  632. for (size_t k=0; k<veclen_; ++k) {
  633. dcenters[i][k] = double(vec[k]);
  634. }
  635. }
  636. std::vector<DistanceType> radiuses(branching);
  637. cv::AutoBuffer<int> count_buf(branching);
  638. int* count = (int*)count_buf;
  639. for (int i=0; i<branching; ++i) {
  640. radiuses[i] = 0;
  641. count[i] = 0;
  642. }
  643. // assign points to clusters
  644. cv::AutoBuffer<int> belongs_to_buf(indices_length);
  645. int* belongs_to = (int*)belongs_to_buf;
  646. for (int i=0; i<indices_length; ++i) {
  647. DistanceType sq_dist = distance_(dataset_[indices[i]], dcenters[0], veclen_);
  648. belongs_to[i] = 0;
  649. for (int j=1; j<branching; ++j) {
  650. DistanceType new_sq_dist = distance_(dataset_[indices[i]], dcenters[j], veclen_);
  651. if (sq_dist>new_sq_dist) {
  652. belongs_to[i] = j;
  653. sq_dist = new_sq_dist;
  654. }
  655. }
  656. if (sq_dist>radiuses[belongs_to[i]]) {
  657. radiuses[belongs_to[i]] = sq_dist;
  658. }
  659. count[belongs_to[i]]++;
  660. }
  661. bool converged = false;
  662. int iteration = 0;
  663. while (!converged && iteration<iterations_) {
  664. converged = true;
  665. iteration++;
  666. // compute the new cluster centers
  667. for (int i=0; i<branching; ++i) {
  668. memset(dcenters[i],0,sizeof(double)*veclen_);
  669. radiuses[i] = 0;
  670. }
  671. for (int i=0; i<indices_length; ++i) {
  672. ElementType* vec = dataset_[indices[i]];
  673. double* center = dcenters[belongs_to[i]];
  674. for (size_t k=0; k<veclen_; ++k) {
  675. center[k] += vec[k];
  676. }
  677. }
  678. for (int i=0; i<branching; ++i) {
  679. int cnt = count[i];
  680. for (size_t k=0; k<veclen_; ++k) {
  681. dcenters[i][k] /= cnt;
  682. }
  683. }
  684. // reassign points to clusters
  685. cv::Mutex mtx;
  686. KMeansDistanceComputer invoker(distance_, dataset_, branching, indices, dcenters, veclen_, count, belongs_to, radiuses, converged, mtx);
  687. parallel_for_(cv::Range(0, (int)indices_length), invoker);
  688. for (int i=0; i<branching; ++i) {
  689. // if one cluster converges to an empty cluster,
  690. // move an element into that cluster
  691. if (count[i]==0) {
  692. int j = (i+1)%branching;
  693. while (count[j]<=1) {
  694. j = (j+1)%branching;
  695. }
  696. for (int k=0; k<indices_length; ++k) {
  697. if (belongs_to[k]==j) {
  698. // for cluster j, we move the furthest element from the center to the empty cluster i
  699. if ( distance_(dataset_[indices[k]], dcenters[j], veclen_) == radiuses[j] ) {
  700. belongs_to[k] = i;
  701. count[j]--;
  702. count[i]++;
  703. break;
  704. }
  705. }
  706. }
  707. converged = false;
  708. }
  709. }
  710. }
  711. DistanceType** centers = new DistanceType*[branching];
  712. for (int i=0; i<branching; ++i) {
  713. centers[i] = new DistanceType[veclen_];
  714. memoryCounter_ += (int)(veclen_*sizeof(DistanceType));
  715. for (size_t k=0; k<veclen_; ++k) {
  716. centers[i][k] = (DistanceType)dcenters[i][k];
  717. }
  718. }
  719. // compute kmeans clustering for each of the resulting clusters
  720. node->childs = pool_.allocate<KMeansNodePtr>(branching);
  721. int start = 0;
  722. int end = start;
  723. for (int c=0; c<branching; ++c) {
  724. int s = count[c];
  725. DistanceType variance = 0;
  726. DistanceType mean_radius =0;
  727. for (int i=0; i<indices_length; ++i) {
  728. if (belongs_to[i]==c) {
  729. DistanceType d = distance_(dataset_[indices[i]], ZeroIterator<ElementType>(), veclen_);
  730. variance += d;
  731. mean_radius += sqrt(d);
  732. std::swap(indices[i],indices[end]);
  733. std::swap(belongs_to[i],belongs_to[end]);
  734. end++;
  735. }
  736. }
  737. variance /= s;
  738. mean_radius /= s;
  739. variance -= distance_(centers[c], ZeroIterator<ElementType>(), veclen_);
  740. node->childs[c] = pool_.allocate<KMeansNode>();
  741. std::memset(node->childs[c], 0, sizeof(KMeansNode));
  742. node->childs[c]->radius = radiuses[c];
  743. node->childs[c]->pivot = centers[c];
  744. node->childs[c]->variance = variance;
  745. node->childs[c]->mean_radius = mean_radius;
  746. computeClustering(node->childs[c],indices+start, end-start, branching, level+1);
  747. start=end;
  748. }
  749. delete[] centers;
  750. }
  751. /**
  752. * Performs one descent in the hierarchical k-means tree. The branches not
  753. * visited are stored in a priority queue.
  754. *
  755. * Params:
  756. * node = node to explore
  757. * result = container for the k-nearest neighbors found
  758. * vec = query points
  759. * checks = how many points in the dataset have been checked so far
  760. * maxChecks = maximum dataset points to checks
  761. */
  762. void findNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec, int& checks, int maxChecks,
  763. Heap<BranchSt>* heap)
  764. {
  765. // Ignore those clusters that are too far away
  766. {
  767. DistanceType bsq = distance_(vec, node->pivot, veclen_);
  768. DistanceType rsq = node->radius;
  769. DistanceType wsq = result.worstDist();
  770. DistanceType val = bsq-rsq-wsq;
  771. DistanceType val2 = val*val-4*rsq*wsq;
  772. //if (val>0) {
  773. if ((val>0)&&(val2>0)) {
  774. return;
  775. }
  776. }
  777. if (node->childs==NULL) {
  778. if (checks>=maxChecks) {
  779. if (result.full()) return;
  780. }
  781. checks += node->size;
  782. for (int i=0; i<node->size; ++i) {
  783. int index = node->indices[i];
  784. DistanceType dist = distance_(dataset_[index], vec, veclen_);
  785. result.addPoint(dist, index);
  786. }
  787. }
  788. else {
  789. DistanceType* domain_distances = new DistanceType[branching_];
  790. int closest_center = exploreNodeBranches(node, vec, domain_distances, heap);
  791. delete[] domain_distances;
  792. findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap);
  793. }
  794. }
  795. /**
  796. * Helper function that computes the nearest childs of a node to a given query point.
  797. * Params:
  798. * node = the node
  799. * q = the query point
  800. * distances = array with the distances to each child node.
  801. * Returns:
  802. */
  803. int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, Heap<BranchSt>* heap)
  804. {
  805. int best_index = 0;
  806. domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_);
  807. for (int i=1; i<branching_; ++i) {
  808. domain_distances[i] = distance_(q, node->childs[i]->pivot, veclen_);
  809. if (domain_distances[i]<domain_distances[best_index]) {
  810. best_index = i;
  811. }
  812. }
  813. // float* best_center = node->childs[best_index]->pivot;
  814. for (int i=0; i<branching_; ++i) {
  815. if (i != best_index) {
  816. domain_distances[i] -= cb_index_*node->childs[i]->variance;
  817. // float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q);
  818. // if (domain_distances[i]<dist_to_border) {
  819. // domain_distances[i] = dist_to_border;
  820. // }
  821. heap->insert(BranchSt(node->childs[i],domain_distances[i]));
  822. }
  823. }
  824. return best_index;
  825. }
  826. /**
  827. * Function the performs exact nearest neighbor search by traversing the entire tree.
  828. */
  829. void findExactNN(KMeansNodePtr node, ResultSet<DistanceType>& result, const ElementType* vec)
  830. {
  831. // Ignore those clusters that are too far away
  832. {
  833. DistanceType bsq = distance_(vec, node->pivot, veclen_);
  834. DistanceType rsq = node->radius;
  835. DistanceType wsq = result.worstDist();
  836. DistanceType val = bsq-rsq-wsq;
  837. DistanceType val2 = val*val-4*rsq*wsq;
  838. // if (val>0) {
  839. if ((val>0)&&(val2>0)) {
  840. return;
  841. }
  842. }
  843. if (node->childs==NULL) {
  844. for (int i=0; i<node->size; ++i) {
  845. int index = node->indices[i];
  846. DistanceType dist = distance_(dataset_[index], vec, veclen_);
  847. result.addPoint(dist, index);
  848. }
  849. }
  850. else {
  851. int* sort_indices = new int[branching_];
  852. getCenterOrdering(node, vec, sort_indices);
  853. for (int i=0; i<branching_; ++i) {
  854. findExactNN(node->childs[sort_indices[i]],result,vec);
  855. }
  856. delete[] sort_indices;
  857. }
  858. }
  859. /**
  860. * Helper function.
  861. *
  862. * I computes the order in which to traverse the child nodes of a particular node.
  863. */
  864. void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices)
  865. {
  866. DistanceType* domain_distances = new DistanceType[branching_];
  867. for (int i=0; i<branching_; ++i) {
  868. DistanceType dist = distance_(q, node->childs[i]->pivot, veclen_);
  869. int j=0;
  870. while (domain_distances[j]<dist && j<i) j++;
  871. for (int k=i; k>j; --k) {
  872. domain_distances[k] = domain_distances[k-1];
  873. sort_indices[k] = sort_indices[k-1];
  874. }
  875. domain_distances[j] = dist;
  876. sort_indices[j] = i;
  877. }
  878. delete[] domain_distances;
  879. }
  880. /**
  881. * Method that computes the squared distance from the query point q
  882. * from inside region with center c to the border between this
  883. * region and the region with center p
  884. */
  885. DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q)
  886. {
  887. DistanceType sum = 0;
  888. DistanceType sum2 = 0;
  889. for (int i=0; i<veclen_; ++i) {
  890. DistanceType t = c[i]-p[i];
  891. sum += t*(q[i]-(c[i]+p[i])/2);
  892. sum2 += t*t;
  893. }
  894. return sum*sum/sum2;
  895. }
  896. /**
  897. * Helper function the descends in the hierarchical k-means tree by spliting those clusters that minimize
  898. * the overall variance of the clustering.
  899. * Params:
  900. * root = root node
  901. * clusters = array with clusters centers (return value)
  902. * varianceValue = variance of the clustering (return value)
  903. * Returns:
  904. */
  905. int getMinVarianceClusters(KMeansNodePtr root, KMeansNodePtr* clusters, int clusters_length, DistanceType& varianceValue)
  906. {
  907. int clusterCount = 1;
  908. clusters[0] = root;
  909. DistanceType meanVariance = root->variance*root->size;
  910. while (clusterCount<clusters_length) {
  911. DistanceType minVariance = (std::numeric_limits<DistanceType>::max)();
  912. int splitIndex = -1;
  913. for (int i=0; i<clusterCount; ++i) {
  914. if (clusters[i]->childs != NULL) {
  915. DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size;
  916. for (int j=0; j<branching_; ++j) {
  917. variance += clusters[i]->childs[j]->variance*clusters[i]->childs[j]->size;
  918. }
  919. if (variance<minVariance) {
  920. minVariance = variance;
  921. splitIndex = i;
  922. }
  923. }
  924. }
  925. if (splitIndex==-1) break;
  926. if ( (branching_+clusterCount-1) > clusters_length) break;
  927. meanVariance = minVariance;
  928. // split node
  929. KMeansNodePtr toSplit = clusters[splitIndex];
  930. clusters[splitIndex] = toSplit->childs[0];
  931. for (int i=1; i<branching_; ++i) {
  932. clusters[clusterCount++] = toSplit->childs[i];
  933. }
  934. }
  935. varianceValue = meanVariance/root->size;
  936. return clusterCount;
  937. }
  938. private:
  939. /** The branching factor used in the hierarchical k-means clustering */
  940. int branching_;
  941. /** Maximum number of iterations to use when performing k-means clustering */
  942. int iterations_;
  943. /** Algorithm for choosing the cluster centers */
  944. flann_centers_init_t centers_init_;
  945. /**
  946. * Cluster border index. This is used in the tree search phase when determining
  947. * the closest cluster to explore next. A zero value takes into account only
  948. * the cluster centres, a value greater then zero also take into account the size
  949. * of the cluster.
  950. */
  951. float cb_index_;
  952. /**
  953. * The dataset used by this index
  954. */
  955. const Matrix<ElementType> dataset_;
  956. /** Index parameters */
  957. IndexParams index_params_;
  958. /**
  959. * Number of features in the dataset.
  960. */
  961. size_t size_;
  962. /**
  963. * Length of each feature.
  964. */
  965. size_t veclen_;
  966. /**
  967. * The root node in the tree.
  968. */
  969. KMeansNodePtr root_;
  970. /**
  971. * Array of indices to vectors in the dataset.
  972. */
  973. int* indices_;
  974. /**
  975. * The distance
  976. */
  977. Distance distance_;
  978. /**
  979. * Pooled memory allocator.
  980. */
  981. PooledAllocator pool_;
  982. /**
  983. * Memory occupied by the index.
  984. */
  985. int memoryCounter_;
  986. };
  987. }
  988. #endif //OPENCV_FLANN_KMEANS_INDEX_H_