kmeans_index.h 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  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. }
  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 spliting 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_