kmeans_index.h 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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_