FastMinKernel.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  1. /**
  2. * @file FastMinKernel.cpp
  3. * @brief Efficient GPs with HIK for classification by regression (Implementation)
  4. * @author Alexander Freytag
  5. * @date 06-12-2011 (dd-mm-yyyy)
  6. */
  7. // STL includes
  8. #include <iostream>
  9. // NICE-core includes
  10. #include <core/basics/vectorio.h>
  11. #include <core/basics/Timer.h>
  12. // gp-hik-core includes
  13. #include "FastMinKernel.h"
  14. using namespace std;
  15. using namespace NICE;
  16. /* protected methods*/
  17. /////////////////////////////////////////////////////
  18. /////////////////////////////////////////////////////
  19. // PUBLIC METHODS
  20. /////////////////////////////////////////////////////
  21. /////////////////////////////////////////////////////
  22. FastMinKernel::FastMinKernel()
  23. {
  24. this->ui_d = 0;
  25. this->ui_n = 0;
  26. this->d_noise = 1.0;
  27. this->approxScheme = MEDIAN;
  28. this->b_verbose = false;
  29. this->setDebug(false);
  30. }
  31. FastMinKernel::FastMinKernel( const std::vector<std::vector<double> > & _X,
  32. const double _noise,
  33. const bool _debug,
  34. const uint & _dim
  35. )
  36. {
  37. this->setDebug(_debug);
  38. this->hik_prepare_kernel_multiplications ( _X, this->X_sorted, _dim);
  39. this->ui_d = this->X_sorted.get_d();
  40. this->ui_n = this->X_sorted.get_n();
  41. this->d_noise = _noise;
  42. this->approxScheme = MEDIAN;
  43. this->b_verbose = false;
  44. }
  45. #ifdef NICE_USELIB_MATIO
  46. FastMinKernel::FastMinKernel ( const sparse_t & _X,
  47. const double _noise,
  48. const std::map<int, int> & _examples,
  49. const bool _debug,
  50. const uint & _dim
  51. ) : this->X_sorted( _X, _examples, _dim )
  52. {
  53. this->ui_d = this->X_sorted.get_d();
  54. this->ui_n = this->X_sorted.get_n();
  55. this->d_noise = _noise;
  56. this->approxScheme = MEDIAN;
  57. this->b_verbose = false;
  58. this->setDebug(_debug);
  59. }
  60. #endif
  61. FastMinKernel::FastMinKernel ( const std::vector< const NICE::SparseVector * > & _X,
  62. const double _noise,
  63. const bool _debug,
  64. const bool & _dimensionsOverExamples,
  65. const uint & _dim)
  66. {
  67. this->setDebug(_debug);
  68. this->hik_prepare_kernel_multiplications ( _X, this->X_sorted, _dimensionsOverExamples, _dim);
  69. this->ui_d = this->X_sorted.get_d();
  70. this->ui_n = this->X_sorted.get_n();
  71. this->d_noise = _noise;
  72. this->approxScheme = MEDIAN;
  73. this->b_verbose = false;
  74. }
  75. FastMinKernel::~FastMinKernel()
  76. {
  77. }
  78. ///////////////////// ///////////////////// /////////////////////
  79. // GET / SET
  80. // INCLUDING ACCESS OPERATORS
  81. ///////////////////// ///////////////////// ////////////////////
  82. uint FastMinKernel::get_n() const
  83. {
  84. return this->ui_n;
  85. }
  86. uint FastMinKernel::get_d() const
  87. {
  88. return this->ui_d;
  89. }
  90. double FastMinKernel::getSparsityRatio() const
  91. {
  92. return this->X_sorted.computeSparsityRatio();
  93. }
  94. void FastMinKernel::setVerbose( const bool & _verbose)
  95. {
  96. this->b_verbose = _verbose;
  97. }
  98. bool FastMinKernel::getVerbose( ) const
  99. {
  100. return this->b_verbose;
  101. }
  102. void FastMinKernel::setDebug( const bool & _debug)
  103. {
  104. this->b_debug = _debug;
  105. this->X_sorted.setDebug( _debug );
  106. }
  107. bool FastMinKernel::getDebug( ) const
  108. {
  109. return this->b_debug;
  110. }
  111. ///////////////////// ///////////////////// /////////////////////
  112. // CLASSIFIER STUFF
  113. ///////////////////// ///////////////////// /////////////////////
  114. void FastMinKernel::applyFunctionToFeatureMatrix ( const NICE::ParameterizedFunction *_pf)
  115. {
  116. this->X_sorted.applyFunctionToFeatureMatrix( _pf );
  117. }
  118. void FastMinKernel::hik_prepare_kernel_multiplications(const std::vector<std::vector<double> > & _X,
  119. NICE::FeatureMatrixT<double> & _X_sorted,
  120. const uint & _dim
  121. )
  122. {
  123. //FIXME why do we hand over the feature matrix here?
  124. _X_sorted.set_features( _X, _dim);
  125. }
  126. void FastMinKernel::hik_prepare_kernel_multiplications(const std::vector< const NICE::SparseVector * > & _X,
  127. NICE::FeatureMatrixT<double> & _X_sorted,
  128. const bool & _dimensionsOverExamples,
  129. const uint & _dim
  130. )
  131. {
  132. //FIXME why do we hand over the feature matrix here?
  133. _X_sorted.set_features( _X, _dimensionsOverExamples, _dim );
  134. }
  135. void FastMinKernel::hik_prepare_alpha_multiplications(const NICE::Vector & _alpha,
  136. NICE::VVector & _A,
  137. NICE::VVector & _B) const
  138. {
  139. // std::cerr << "FastMinKernel::hik_prepare_alpha_multiplications" << std::endl;
  140. // std::cerr << "alpha: " << alpha << std::endl;
  141. _A.resize( this->ui_d );
  142. _B.resize( this->ui_d );
  143. // efficient calculation of k*alpha
  144. // ---------------------------------
  145. //
  146. // sum_i alpha_i k(x^i,x) = sum_i alpha_i sum_k min(x^i_k,x_k)
  147. // = sum_k sum_i alpha_i min(x^i_k, x_k)
  148. //
  149. // now let us define l_k = { i | x^i_k <= x_k }
  150. // and u_k = { i | x^i_k > x_k }, this leads to
  151. //
  152. // = sum_k ( sum_{l \in l_k} alpha_l x^i_k + sum_{u \in u_k} alpha_u x_k
  153. // = sum_k ( sum_{l \in l_k} \alpha_l x^l_k + x_k * sum_{u \in u_k}
  154. // alpha_u
  155. //
  156. // We also define
  157. // l^j_k = { i | x^i_j <= x^j_k } and
  158. // u^j_k = { i | x^i_k > x^j_k }
  159. //
  160. // We now need the partial sums
  161. //
  162. // (Definition 1)
  163. // a_{k,j} = \sum_{l \in l^j_k} \alpha_l x^l_k
  164. //
  165. // and \sum_{u \in u^j_k} \alpha_u
  166. // according to increasing values of x^l_k
  167. //
  168. // With
  169. // (Definition 2)
  170. // b_{k,j} = \sum_{l \in l^j_k} \alpha_l,
  171. //
  172. // we get
  173. // \sum_{u \in u^j_k} \alpha_u = \sum_{u=1}^n alpha_u - \sum_{l \in l^j_k} \alpha_l
  174. // = b_{k,n} - b_{k,j}
  175. // we only need as many entries as we have nonZero entries in our features for the corresponding dimensions
  176. for (int i = 0; i < this->ui_d; i++)
  177. {
  178. uint numNonZero = this->X_sorted.getNumberOfNonZeroElementsPerDimension(i);
  179. //DEBUG
  180. //std::cerr << "number of non-zero elements in dimension " << i << " / " << d << ": " << numNonZero << std::endl;
  181. _A[i].resize( numNonZero );
  182. _B[i].resize( numNonZero );
  183. }
  184. // for more information see hik_prepare_alpha_multiplications
  185. for (uint dim = 0; dim < this->ui_d; dim++)
  186. {
  187. double alpha_sum(0.0);
  188. double alpha_times_x_sum(0.0);
  189. int cntNonzeroFeat(0);
  190. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  191. // loop through all elements in sorted order
  192. for ( SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++ )
  193. {
  194. const SortedVectorSparse<double>::dataelement & de = i->second;
  195. // index of the feature
  196. int index = de.first;
  197. // transformed element of the feature
  198. //
  199. double elem( de.second );
  200. alpha_times_x_sum += _alpha[index] * elem;
  201. _A[dim][cntNonzeroFeat] = alpha_times_x_sum;
  202. alpha_sum += _alpha[index];
  203. _B[dim][cntNonzeroFeat] = alpha_sum;
  204. cntNonzeroFeat++;
  205. }
  206. }
  207. }
  208. double *FastMinKernel::hik_prepare_alpha_multiplications_fast(const NICE::VVector & _A,
  209. const NICE::VVector & _B,
  210. const Quantization & _q,
  211. const ParameterizedFunction *_pf
  212. ) const
  213. {
  214. //NOTE keep in mind: for doing this, we already have precomputed A and B using hik_prepare_alpha_multiplications!
  215. // number of quantization bins
  216. uint hmax = _q.size();
  217. // store (transformed) prototypes
  218. double *prototypes = new double [ hmax ];
  219. for ( uint i = 0 ; i < hmax ; i++ )
  220. if ( _pf != NULL ) {
  221. // FIXME: the transformed prototypes could change from dimension to another dimension
  222. // We skip this flexibility ...but it should be changed in the future
  223. prototypes[i] = _pf->f ( 1, _q.getPrototype(i) );
  224. } else {
  225. prototypes[i] = _q.getPrototype(i);
  226. }
  227. // creating the lookup table as pure C, which might be beneficial
  228. // for fast evaluation
  229. double *Tlookup = new double [ hmax * this->ui_d ];
  230. // std::cerr << "size of LUT: " << hmax * this->ui_d << std::endl;
  231. // sizeOfLUT = hmax * this->d;
  232. // loop through all dimensions
  233. for ( uint dim = 0; dim < this->ui_d; dim++ )
  234. {
  235. uint nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  236. if ( nrZeroIndices == this->ui_n )
  237. continue;
  238. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  239. SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin();
  240. SortedVectorSparse<double>::const_elementpointer iPredecessor = nonzeroElements.begin();
  241. // index of the element, which is always bigger than the current value fval
  242. int index = 0;
  243. // we use the quantization of the original features! the transformed feature were
  244. // already used to calculate A and B, this of course assumes monotonic functions!!!
  245. int qBin = _q.quantize ( i->first );
  246. // the next loop is linear in max(hmax, n)
  247. // REMARK: this could be changed to hmax*log(n), when
  248. // we use binary search
  249. //FIXME cast to int might be dangerous...
  250. for (int j = 0; j < (int)hmax; j++)
  251. {
  252. double fval = prototypes[j];
  253. double t;
  254. if ( (index == 0) && (j < qBin) ) {
  255. // current element is smaller than everything else
  256. // resulting value = fval * sum_l=1^n alpha_l
  257. t = fval*( _B[dim][this->ui_n-1 - nrZeroIndices] );
  258. } else {
  259. // move to next example, if necessary
  260. while ( (j >= qBin) && ( index < (this->ui_n-1-nrZeroIndices)) )
  261. {
  262. index++;
  263. iPredecessor = i;
  264. i++;
  265. if ( i->first != iPredecessor->first )
  266. qBin = _q.quantize ( i->first );
  267. }
  268. // compute current element in the lookup table and keep in mind that
  269. // index is the next element and not the previous one
  270. //NOTE pay attention: this is only valid if we all entries are positiv! - if not, ask wether the current feature is greater than zero. If so, subtract the nrZeroIndices, if not do not
  271. if ( (j >= qBin) && ( index==(this->ui_n-1-nrZeroIndices) ) ) {
  272. // the current element (fval) is equal or bigger to the element indexed by index
  273. // in fact, the term B[dim][this->n-1-nrZeroIndices] - B[dim][index] is equal to zero and vanishes, which is logical, since all elements are smaller than j!
  274. t = _A[dim][index];// + fval*( _B[dim][this->ui_n-1-nrZeroIndices] - _B[dim][index] );
  275. } else {
  276. // standard case
  277. t = _A[dim][index-1] + fval*( _B[dim][this->ui_n-1-nrZeroIndices] - _B[dim][index-1] );
  278. }
  279. }
  280. Tlookup[ dim*hmax + j ] = t;
  281. }
  282. }
  283. delete [] prototypes;
  284. return Tlookup;
  285. }
  286. double *FastMinKernel::hikPrepareLookupTable(const NICE::Vector & _alpha,
  287. const Quantization & _q,
  288. const ParameterizedFunction *_pf
  289. ) const
  290. {
  291. // number of quantization bins
  292. uint hmax = _q.size();
  293. // store (transformed) prototypes
  294. double *prototypes = new double [ hmax ];
  295. for ( uint i = 0 ; i < hmax ; i++ )
  296. if ( _pf != NULL ) {
  297. // FIXME: the transformed prototypes could change from dimension to another dimension
  298. // We skip this flexibility ...but it should be changed in the future
  299. prototypes[i] = _pf->f ( 1, _q.getPrototype(i) );
  300. } else {
  301. prototypes[i] = _q.getPrototype(i);
  302. }
  303. // creating the lookup table as pure C, which might be beneficial
  304. // for fast evaluation
  305. double *Tlookup = new double [ hmax * this->ui_d ];
  306. // sizeOfLUT = hmax * this->d;
  307. // loop through all dimensions
  308. for (uint dim = 0; dim < this->ui_d; dim++)
  309. {
  310. uint nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  311. if ( nrZeroIndices == this->ui_n )
  312. continue;
  313. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  314. double alphaSumTotalInDim(0.0);
  315. double alphaTimesXSumTotalInDim(0.0);
  316. for ( SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++ )
  317. {
  318. alphaSumTotalInDim += _alpha[i->second.first];
  319. alphaTimesXSumTotalInDim += _alpha[i->second.first] * i->second.second;
  320. }
  321. SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin();
  322. SortedVectorSparse<double>::const_elementpointer iPredecessor = nonzeroElements.begin();
  323. // index of the element, which is always bigger than the current value fval
  324. int index = 0;
  325. // we use the quantization of the original features! Nevetheless, the resulting lookupTable is computed using the transformed ones
  326. int qBin = _q.quantize ( i->first );
  327. double alpha_sum(0.0);
  328. double alpha_times_x_sum(0.0);
  329. double alpha_sum_prev(0.0);
  330. double alpha_times_x_sum_prev(0.0);
  331. for (uint j = 0; j < hmax; j++)
  332. {
  333. double fval = prototypes[j];
  334. double t;
  335. if ( (index == 0) && (j < (uint)qBin) ) {
  336. // current element is smaller than everything else
  337. // resulting value = fval * sum_l=1^n alpha_l
  338. //t = fval*( B[dim][this->n-1 - nrZeroIndices] );
  339. t = fval*alphaSumTotalInDim;
  340. } else {
  341. // move to next example, if necessary
  342. while ( (j >= (uint)qBin) && ( index < (this->ui_n-1-nrZeroIndices)) )
  343. {
  344. alpha_times_x_sum_prev = alpha_times_x_sum;
  345. alpha_sum_prev = alpha_sum;
  346. alpha_times_x_sum += _alpha[i->second.first] * i->second.second; //i->dataElement.transformedFeatureValue
  347. alpha_sum += _alpha[i->second.first]; //i->dataElement.OrigIndex
  348. index++;
  349. iPredecessor = i;
  350. i++;
  351. if ( i->first != iPredecessor->first )
  352. qBin = _q.quantize ( i->first );
  353. }
  354. // compute current element in the lookup table and keep in mind that
  355. // index is the next element and not the previous one
  356. //NOTE pay attention: this is only valid if all entries are positiv! - if not, ask wether the current feature is greater than zero. If so, subtract the nrZeroIndices, if not do not
  357. if ( (j >= (uint)qBin) && ( index==(this->ui_n-1-nrZeroIndices) ) ) {
  358. // the current element (fval) is equal or bigger to the element indexed by index
  359. // in fact, the term B[dim][this->n-1-nrZeroIndices] - B[dim][index] is equal to zero and vanishes, which is logical, since all elements are smaller than j!
  360. // double lastTermAlphaTimesXSum;
  361. // double lastTermAlphaSum;
  362. t = alphaTimesXSumTotalInDim;
  363. } else {
  364. // standard case
  365. t = alpha_times_x_sum + fval*( alphaSumTotalInDim - alpha_sum );
  366. }
  367. }
  368. Tlookup[ dim*hmax + j ] = t;
  369. }
  370. }
  371. delete [] prototypes;
  372. return Tlookup;
  373. }
  374. void FastMinKernel::hikUpdateLookupTable(double * _T,
  375. const double & _alphaNew,
  376. const double & _alphaOld,
  377. const int & _idx,
  378. const Quantization & _q,
  379. const ParameterizedFunction *_pf
  380. ) const
  381. {
  382. if (_T == NULL)
  383. {
  384. fthrow(Exception, "FastMinKernel::hikUpdateLookupTable LUT not initialized, run FastMinKernel::hikPrepareLookupTable first!");
  385. return;
  386. }
  387. // number of quantization bins
  388. uint hmax = _q.size();
  389. // store (transformed) prototypes
  390. double *prototypes = new double [ hmax ];
  391. for ( uint i = 0 ; i < hmax ; i++ )
  392. if ( _pf != NULL ) {
  393. // FIXME: the transformed prototypes could change from dimension to another dimension
  394. // We skip this flexibility ...but it should be changed in the future
  395. prototypes[i] = _pf->f ( 1, _q.getPrototype(i) );
  396. } else {
  397. prototypes[i] = _q.getPrototype(i);
  398. }
  399. double diffOfAlpha(_alphaNew - _alphaOld);
  400. // loop through all dimensions
  401. for ( uint dim = 0; dim < this->ui_d; dim++ )
  402. {
  403. double x_i ( (this->X_sorted( dim, _idx)) );
  404. //TODO we could also check wether x_i < tol, if we would store the tol explicitely
  405. if ( x_i == 0.0 ) //nothing to do in this dimension
  406. continue;
  407. //TODO we could speed up this by first doing a binary search for the position where the min changes, and then do two separate for-loops
  408. for (uint j = 0; j < hmax; j++)
  409. {
  410. double fval;
  411. int q_bin = _q.quantize(x_i);
  412. if ( q_bin > (int) j )
  413. fval = prototypes[j];
  414. else
  415. fval = x_i;
  416. _T[ dim*hmax + j ] += diffOfAlpha*fval;
  417. }
  418. }
  419. delete [] prototypes;
  420. }
  421. void FastMinKernel::hik_kernel_multiply(const NICE::VVector & _A,
  422. const NICE::VVector & _B,
  423. const NICE::Vector & _alpha,
  424. NICE::Vector & _beta
  425. ) const
  426. {
  427. _beta.resize( this->ui_n );
  428. _beta.set(0.0);
  429. // runtime is O(n*d), we do no benefit from an additional lookup table here
  430. for (uint dim = 0; dim < this->ui_d; dim++)
  431. {
  432. // -- efficient sparse solution
  433. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  434. uint nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  435. if ( nrZeroIndices == this->ui_n ) {
  436. // all values are zero in this dimension :) and we can simply ignore the feature
  437. continue;
  438. }
  439. int cnt(0);
  440. for ( multimap< double, SortedVectorSparse<double>::dataelement>::const_iterator i = nonzeroElements.begin(); i != nonzeroElements.end(); i++, cnt++)
  441. {
  442. const SortedVectorSparse<double>::dataelement & de = i->second;
  443. uint feat = de.first;
  444. int inversePosition = cnt;
  445. double fval = de.second;
  446. // in which position was the element sorted in? actually we only care about the nonzero elements, so we have to subtract the number of zero elements.
  447. //NOTE pay attention: this is only valid if all entries are positiv! - if not, ask wether the current feature is greater than zero. If so, subtract the nrZeroIndices, if not do not
  448. //we definitly know that this element exists in inversePermutation, so we have not to check wether find returns .end() or not
  449. //int inversePosition(inversePermutation.find(feat)->second - nrZeroIndices);
  450. // sum_{l \in L_k} \alpha_l x^l_k
  451. //
  452. // A is zero for zero feature values (x^l_k is zero for all l \in L_k)
  453. double firstPart( _A[dim][inversePosition] );
  454. // sum_{u \in U_k} alpha_u
  455. // B is not zero for zero feature values, but we do not
  456. // have to care about them, because it is multiplied with
  457. // the feature value
  458. // DEBUG for Björns code
  459. if ( (uint)dim >= _B.size() )
  460. fthrow(Exception, "dim exceeds B.size: " << dim << " " << _B.size() );
  461. if ( _B[dim].size() == 0 )
  462. fthrow(Exception, "B[dim] is empty");
  463. if ( (this->ui_n-1-nrZeroIndices < 0) || ((uint)(this->ui_n-1-nrZeroIndices) >= _B[dim].size() ) )
  464. fthrow(Exception, "n-1-nrZeroIndices is invalid: " << this->ui_n << " " << nrZeroIndices << " " << _B[dim].size() << " d: " << this->ui_d);
  465. if ( inversePosition < 0 || (uint)inversePosition >= _B[dim].size() )
  466. fthrow(Exception, "inverse position is invalid: " << inversePosition << " " << _B[dim].size() );
  467. double secondPart( _B[dim][this->ui_n-1-nrZeroIndices] - _B[dim][inversePosition]);
  468. _beta[feat] += firstPart + fval * secondPart; // i->elementpointer->dataElement->Value
  469. }
  470. }
  471. //FIXME
  472. //do we really want to considere noisy labels?
  473. for (uint feat = 0; feat < this->ui_n; feat++)
  474. {
  475. _beta[feat] += this->d_noise*_alpha[feat];
  476. }
  477. }
  478. void FastMinKernel::hik_kernel_multiply_fast(const double *_Tlookup,
  479. const Quantization & _q,
  480. const NICE::Vector & _alpha,
  481. NICE::Vector & _beta) const
  482. {
  483. _beta.resize( this->ui_n );
  484. _beta.set(0.0);
  485. // runtime is O(n*d), we do no benefit from an additional lookup table here
  486. for (uint dim = 0; dim < this->ui_d; dim++)
  487. {
  488. // -- efficient sparse solution
  489. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  490. int cnt(0);
  491. for ( multimap< double, SortedVectorSparse<double>::dataelement>::const_iterator i = nonzeroElements.begin(); i != nonzeroElements.end(); i++, cnt++)
  492. {
  493. const SortedVectorSparse<double>::dataelement & de = i->second;
  494. uint feat = de.first;
  495. uint qBin = _q.quantize(i->first);
  496. _beta[feat] += _Tlookup[dim*_q.size() + qBin];
  497. }
  498. }
  499. //do we really want to considere noisy labels?
  500. for (uint feat = 0; feat < this->ui_n; feat++)
  501. {
  502. _beta[feat] += this->d_noise*_alpha[feat];
  503. }
  504. }
  505. void FastMinKernel::hik_kernel_sum(const NICE::VVector & _A,
  506. const NICE::VVector & _B,
  507. const NICE::SparseVector & _xstar,
  508. double & _beta,
  509. const ParameterizedFunction *_pf) const
  510. {
  511. // sparse version of hik_kernel_sum, no really significant changes,
  512. // we are just skipping zero elements
  513. _beta = 0.0;
  514. for (SparseVector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++)
  515. {
  516. int dim = i->first;
  517. double fval = i->second;
  518. int nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  519. if ( nrZeroIndices == this->ui_n ) {
  520. // all features are zero and let us ignore it completely
  521. continue;
  522. }
  523. int position;
  524. //where is the example x^z_i located in
  525. //the sorted array? -> perform binary search, runtime O(log(n))
  526. // search using the original value
  527. this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  528. position--;
  529. //NOTE again - pay attention! This is only valid if all entries are NOT negative! - if not, ask wether the current feature is greater than zero. If so, subtract the nrZeroIndices, if not do not
  530. //sum_{l \in L_k} \alpha_l x^l_k
  531. double firstPart(0.0);
  532. //TODO in the "overnext" line there occurs the following error
  533. // Invalid read of size 8
  534. if (position >= 0)
  535. firstPart = (_A[dim][position-nrZeroIndices]);
  536. // sum_{u \in U_k} alpha_u
  537. // sum_{u \in U_k} alpha_u
  538. // => double secondPart( B(dim, n-1) - B(dim, position));
  539. //TODO in the next line there occurs the following error
  540. // Invalid read of size 8
  541. double secondPart( _B[dim][this->ui_n-1-nrZeroIndices]);
  542. //TODO in the "overnext" line there occurs the following error
  543. // Invalid read of size 8
  544. if (position >= 0)
  545. secondPart-= _B[dim][position-nrZeroIndices];
  546. if ( _pf != NULL )
  547. {
  548. fval = _pf->f ( dim, fval );
  549. }
  550. // but apply using the transformed one
  551. _beta += firstPart + secondPart* fval;
  552. }
  553. }
  554. void FastMinKernel::hik_kernel_sum(const NICE::VVector & _A,
  555. const NICE::VVector & _B,
  556. const NICE::Vector & _xstar,
  557. double & _beta,
  558. const ParameterizedFunction *_pf
  559. ) const
  560. {
  561. _beta = 0.0;
  562. int dim ( 0 );
  563. for (NICE::Vector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++, dim++)
  564. {
  565. double fval = *i;
  566. int nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  567. if ( nrZeroIndices == this->ui_n ) {
  568. // all features are zero and let us ignore it completely
  569. continue;
  570. }
  571. int position;
  572. //where is the example x^z_i located in
  573. //the sorted array? -> perform binary search, runtime O(log(n))
  574. // search using the original value
  575. this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  576. position--;
  577. //NOTE again - pay attention! This is only valid if all entries are NOT negative! - if not, ask wether the current feature is greater than zero. If so, subtract the nrZeroIndices, if not do not
  578. //sum_{l \in L_k} \alpha_l x^l_k
  579. double firstPart(0.0);
  580. //TODO in the "overnext" line there occurs the following error
  581. // Invalid read of size 8
  582. if (position >= 0)
  583. firstPart = (_A[dim][position-nrZeroIndices]);
  584. // sum_{u \in U_k} alpha_u
  585. // sum_{u \in U_k} alpha_u
  586. // => double secondPart( B(dim, n-1) - B(dim, position));
  587. //TODO in the next line there occurs the following error
  588. // Invalid read of size 8
  589. double secondPart( _B[dim][this->ui_n-1-nrZeroIndices]);
  590. //TODO in the "overnext" line there occurs the following error
  591. // Invalid read of size 8
  592. if (position >= 0)
  593. secondPart-= _B[dim][position-nrZeroIndices];
  594. if ( _pf != NULL )
  595. {
  596. fval = _pf->f ( dim, fval );
  597. }
  598. // but apply using the transformed one
  599. _beta += firstPart + secondPart* fval;
  600. }
  601. }
  602. void FastMinKernel::hik_kernel_sum_fast(const double *_Tlookup,
  603. const Quantization & _q,
  604. const NICE::Vector & _xstar,
  605. double & _beta
  606. ) const
  607. {
  608. _beta = 0.0;
  609. if ( _xstar.size() != this->ui_d)
  610. {
  611. fthrow(Exception, "FastMinKernel::hik_kernel_sum_fast sizes of xstar and training data does not match!");
  612. return;
  613. }
  614. // runtime is O(d) if the quantizer is O(1)
  615. for ( uint dim = 0; dim < this->ui_d; dim++)
  616. {
  617. double v = _xstar[dim];
  618. uint qBin = _q.quantize(v);
  619. _beta += _Tlookup[dim*_q.size() + qBin];
  620. }
  621. }
  622. void FastMinKernel::hik_kernel_sum_fast(const double *_Tlookup,
  623. const Quantization & _q,
  624. const NICE::SparseVector & _xstar,
  625. double & _beta
  626. ) const
  627. {
  628. _beta = 0.0;
  629. // sparse version of hik_kernel_sum_fast, no really significant changes,
  630. // we are just skipping zero elements
  631. // for additional comments see the non-sparse version of hik_kernel_sum_fast
  632. // runtime is O(d) if the quantizer is O(1)
  633. for (SparseVector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++ )
  634. {
  635. int dim = i->first;
  636. double v = i->second;
  637. uint qBin = _q.quantize(v);
  638. _beta += _Tlookup[dim*_q.size() + qBin];
  639. }
  640. }
  641. double *FastMinKernel::solveLin(const NICE::Vector & _y,
  642. NICE::Vector & _alpha,
  643. const Quantization & _q,
  644. const ParameterizedFunction *_pf,
  645. const bool & _useRandomSubsets,
  646. uint _maxIterations,
  647. const uint & _sizeOfRandomSubset,
  648. double _minDelta,
  649. bool _timeAnalysis
  650. ) const
  651. {
  652. uint sizeOfRandomSubset(_sizeOfRandomSubset);
  653. bool verboseMinimal ( false );
  654. // number of quantization bins
  655. uint hmax = _q.size();
  656. NICE::Vector diagonalElements(_y.size(),0.0);
  657. this->X_sorted.hikDiagonalElements(diagonalElements);
  658. diagonalElements += this->d_noise;
  659. NICE::Vector pseudoResidual (_y.size(),0.0);
  660. NICE::Vector delta_alpha (_y.size(),0.0);
  661. double alpha_old;
  662. double alpha_new;
  663. double x_i;
  664. // initialization
  665. if (_alpha.size() != _y.size())
  666. {
  667. _alpha.resize( _y.size() );
  668. }
  669. _alpha.set(0.0);
  670. double *Tlookup = new double [ hmax * this->ui_d ];
  671. if ( (hmax*this->ui_d) <= 0 )
  672. return Tlookup;
  673. memset(Tlookup, 0, sizeof(Tlookup[0])*hmax*this->ui_d);
  674. uint iter;
  675. Timer t;
  676. if ( _timeAnalysis )
  677. t.start();
  678. if (_useRandomSubsets)
  679. {
  680. std::vector<uint> indices( _y.size() );
  681. for (uint i = 0; i < _y.size(); i++)
  682. indices[i] = i;
  683. if (sizeOfRandomSubset <= 0)
  684. sizeOfRandomSubset = _y.size();
  685. for ( iter = 1; iter <= _maxIterations; iter++ )
  686. {
  687. NICE::Vector perm;
  688. randomPermutation( perm, indices, _sizeOfRandomSubset );
  689. if ( _timeAnalysis )
  690. {
  691. t.stop();
  692. Vector r;
  693. this->hik_kernel_multiply_fast(Tlookup, _q, _alpha, r);
  694. r = r - _y;
  695. double res = r.normL2();
  696. double resMax = r.normInf();
  697. cerr << "SimpleGradientDescent: TIME " << t.getSum() << " " << res << " " << resMax << endl;
  698. t.start();
  699. }
  700. for ( int i = 0; i < sizeOfRandomSubset; i++)
  701. {
  702. pseudoResidual(perm[i]) = -_y(perm[i]) + (this->d_noise * _alpha(perm[i]));
  703. for (uint j = 0; j < this->ui_d; j++)
  704. {
  705. x_i = this->X_sorted(j,perm[i]);
  706. pseudoResidual(perm[i]) += Tlookup[j*hmax + _q.quantize(x_i)];
  707. }
  708. //NOTE: this threshhold could also be a parameter of the function call
  709. if ( fabs(pseudoResidual(perm[i])) > 1e-7 )
  710. {
  711. alpha_old = _alpha(perm[i]);
  712. alpha_new = alpha_old - (pseudoResidual(perm[i])/diagonalElements(perm[i]));
  713. _alpha(perm[i]) = alpha_new;
  714. delta_alpha(perm[i]) = alpha_old-alpha_new;
  715. this->hikUpdateLookupTable(Tlookup, alpha_new, alpha_old, perm[i], _q, _pf ); // works correctly
  716. } else
  717. {
  718. delta_alpha(perm[i]) = 0.0;
  719. }
  720. }
  721. // after this only residual(i) is the valid residual... we should
  722. // really update the whole vector somehow
  723. double delta = delta_alpha.normL2();
  724. if ( this->b_verbose ) {
  725. cerr << "FastMinKernel::solveLin: iteration " << iter << " / " << _maxIterations << endl;
  726. cerr << "FastMinKernel::solveLin: delta = " << delta << endl;
  727. cerr << "FastMinKernel::solveLin: pseudo residual = " << pseudoResidual.scalarProduct(pseudoResidual) << endl;
  728. }
  729. if ( delta < _minDelta )
  730. {
  731. if ( this->b_verbose )
  732. cerr << "FastMinKernel::solveLin: small delta" << endl;
  733. break;
  734. }
  735. }
  736. }
  737. else //don't use random subsets
  738. {
  739. for ( iter = 1; iter <= _maxIterations; iter++ )
  740. {
  741. for ( uint i = 0; i < _y.size(); i++ )
  742. {
  743. pseudoResidual(i) = -_y(i) + (this->d_noise* _alpha(i));
  744. for (uint j = 0; j < this->ui_d; j++)
  745. {
  746. x_i = this->X_sorted(j,i);
  747. pseudoResidual(i) += Tlookup[j*hmax + _q.quantize(x_i)];
  748. }
  749. //NOTE: this threshhold could also be a parameter of the function call
  750. if ( fabs(pseudoResidual(i)) > 1e-7 )
  751. {
  752. alpha_old = _alpha(i);
  753. alpha_new = alpha_old - (pseudoResidual(i)/diagonalElements(i));
  754. _alpha(i) = alpha_new;
  755. delta_alpha(i) = alpha_old-alpha_new;
  756. this->hikUpdateLookupTable(Tlookup, alpha_new, alpha_old, i, _q, _pf ); // works correctly
  757. } else
  758. {
  759. delta_alpha(i) = 0.0;
  760. }
  761. }
  762. double delta = delta_alpha.normL2();
  763. if ( this->b_verbose ) {
  764. cerr << "FastMinKernel::solveLin: iteration " << iter << " / " << _maxIterations << endl;
  765. cerr << "FastMinKernel::solveLin: delta = " << delta << endl;
  766. cerr << "FastMinKernel::solveLin: pseudo residual = " << pseudoResidual.scalarProduct(pseudoResidual) << endl;
  767. }
  768. if ( delta < _minDelta )
  769. {
  770. if ( this->b_verbose )
  771. cerr << "FastMinKernel::solveLin: small delta" << endl;
  772. break;
  773. }
  774. }
  775. }
  776. if (verboseMinimal)
  777. std::cerr << "FastMinKernel::solveLin -- needed " << iter << " iterations" << std::endl;
  778. return Tlookup;
  779. }
  780. void FastMinKernel::randomPermutation(NICE::Vector & _permutation,
  781. const std::vector<uint> & _oldIndices,
  782. const uint & _newSize
  783. ) const
  784. {
  785. std::vector<uint> indices(_oldIndices);
  786. const uint oldSize = _oldIndices.size();
  787. uint resultingSize (std::min( oldSize, _newSize) );
  788. _permutation.resize(resultingSize);
  789. for ( uint i = 0; i < resultingSize; i++)
  790. {
  791. uint newIndex(rand() % indices.size());
  792. _permutation[i] = indices[newIndex ];
  793. indices.erase(indices.begin() + newIndex);
  794. }
  795. }
  796. double FastMinKernel::getFrobNormApprox()
  797. {
  798. double frobNormApprox(0.0);
  799. switch (this->approxScheme)
  800. {
  801. case MEDIAN:
  802. {
  803. //\| K \|_F^1 ~ (n/2)^2 \left( \sum_k \median_k \right)^2
  804. //motivation: estimate half of the values in dim k to zero and half of them to the median (-> lower bound expectation)
  805. for ( uint i = 0; i < this->ui_d; i++ )
  806. {
  807. double median = this->X_sorted.getFeatureValues(i).getMedian();
  808. frobNormApprox += median;
  809. }
  810. frobNormApprox = fabs(frobNormApprox) * this->ui_n/2.0;
  811. break;
  812. }
  813. case EXPECTATION:
  814. {
  815. std::cerr << "EXPECTATION" << std::endl;
  816. //\| K \|_F^1^2 ~ \sum K_{ii}^2 + (n^2 - n) \left( \frac{1}{3} \sum_k \left( 2 a_k + b_k \right) \right)
  817. // with a_k = minimal value in dim k and b_k maximal value
  818. //first term
  819. NICE::Vector diagEl;
  820. X_sorted.hikDiagonalElements(diagEl);
  821. frobNormApprox += diagEl.normL2();
  822. //second term
  823. double secondTerm(0.0);
  824. for ( uint i = 0; i < this->ui_d; i++ )
  825. {
  826. double minInDim;
  827. minInDim = this->X_sorted.getFeatureValues(i).getMin();
  828. double maxInDim;
  829. maxInDim = this->X_sorted.getFeatureValues(i).getMax();
  830. std::cerr << "min: " << minInDim << " max: " << maxInDim << std::endl;
  831. secondTerm += 2.0*minInDim + maxInDim;
  832. }
  833. secondTerm /= 3.0;
  834. secondTerm = pow(secondTerm, 2);
  835. secondTerm *= (this->ui_n * ( this->ui_n - 1 ));
  836. frobNormApprox += secondTerm;
  837. frobNormApprox = sqrt(frobNormApprox);
  838. break;
  839. }
  840. default:
  841. { //do nothing, approximate with zero :)
  842. break;
  843. }
  844. }
  845. return frobNormApprox;
  846. }
  847. void FastMinKernel::setApproximationScheme(const int & _approxScheme)
  848. {
  849. switch(_approxScheme)
  850. {
  851. case 0:
  852. {
  853. this->approxScheme = MEDIAN;
  854. break;
  855. }
  856. case 1:
  857. {
  858. this->approxScheme = EXPECTATION;
  859. break;
  860. }
  861. default:
  862. {
  863. this->approxScheme = MEDIAN;
  864. break;
  865. }
  866. }
  867. }
  868. void FastMinKernel::hikPrepareKVNApproximation(NICE::VVector & _A) const
  869. {
  870. _A.resize( this->ui_d );
  871. // efficient calculation of |k_*|^2 = k_*^T * k_*
  872. // ---------------------------------
  873. //
  874. // \sum_{i=1}^{n} \left( \sum_{d=1}^{D} \min (x_d^*, x_d^i) \right)^2
  875. // <=\sum_{i=1}^{n} \sum_{d=1}^{D} \left( \min (x_d^*, x_d^i) \right)^2
  876. // = \sum_{d=1}^{D} \sum_{i=1}^{n} \left( \min (x_d^*, x_d^i) \right)^2
  877. // = \sum_{d=1}^{D} \left( \sum_{i:x_d^i < x_*^d} (x_d^i)^2 + \sum_{j: x_d^* \leq x_d^j} (x_d^*)^2 \right)
  878. //
  879. // again let us define l_d = { i | x_d^i <= x_d^* }
  880. // and u_d = { i | x_d^i > x_d^* }, this leads to
  881. //
  882. // = \sum_{d=1}^{D} ( \sum_{l \in l_d} (x_d^l)^2 + \sum_{u \in u_d} (x_d^*)^2
  883. // = \sum_{d=1}^{D} ( \sum_{l \in l_d} (x_d^l)^2 + (x_d^*)^2 \sum_{u \in u_d} 1
  884. //
  885. // We also define
  886. // l_d^j = { i | x_d^i <= x_d^j } and
  887. // u_d^j = { i | x_d^i > x_d^j }
  888. //
  889. // We now need the partial sums
  890. //
  891. // (Definition 1)
  892. // a_{d,j} = \sum_{l \in l_d^j} (x_d^l)^2
  893. // according to increasing values of x_d^l
  894. //
  895. // We end at
  896. // |k_*|^2 <= \sum_{d=1}^{D} \left( a_{d,r_d} + (x_d^*)^2 * |u_d^{r_d}| \right)
  897. // with r_d being the index of the last example in the ordered sequence for dimension d, that is not larger than x_d^*
  898. // we only need as many entries as we have nonZero entries in our features for the corresponding dimensions
  899. for ( uint i = 0; i < this->ui_d; i++ )
  900. {
  901. uint numNonZero = this->X_sorted.getNumberOfNonZeroElementsPerDimension(i);
  902. _A[i].resize( numNonZero );
  903. }
  904. // for more information see hik_prepare_alpha_multiplications
  905. for (uint dim = 0; dim < this->ui_d; dim++)
  906. {
  907. double squared_sum(0.0);
  908. int cntNonzeroFeat(0);
  909. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  910. // loop through all elements in sorted order
  911. for ( SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++ )
  912. {
  913. const SortedVectorSparse<double>::dataelement & de = i->second;
  914. // de: first - index, second - transformed feature
  915. double elem( de.second );
  916. squared_sum += pow( elem, 2 );
  917. _A[dim][cntNonzeroFeat] = squared_sum;
  918. cntNonzeroFeat++;
  919. }
  920. }
  921. }
  922. double * FastMinKernel::hikPrepareKVNApproximationFast(NICE::VVector & _A,
  923. const Quantization & _q,
  924. const ParameterizedFunction *_pf ) const
  925. {
  926. //NOTE keep in mind: for doing this, we already have precomputed A using hikPrepareSquaredKernelVector!
  927. // number of quantization bins
  928. uint hmax = _q.size();
  929. // store (transformed) prototypes
  930. double *prototypes = new double [ hmax ];
  931. for ( uint i = 0 ; i < hmax ; i++ )
  932. if ( _pf != NULL ) {
  933. // FIXME: the transformed prototypes could change from dimension to another dimension
  934. // We skip this flexibility ...but it should be changed in the future
  935. prototypes[i] = _pf->f ( 1, _q.getPrototype(i) );
  936. } else {
  937. prototypes[i] = _q.getPrototype(i);
  938. }
  939. // creating the lookup table as pure C, which might be beneficial
  940. // for fast evaluation
  941. double *Tlookup = new double [ hmax * this->ui_d ];
  942. // loop through all dimensions
  943. for (uint dim = 0; dim < this->ui_d; dim++)
  944. {
  945. uint nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  946. if ( nrZeroIndices == this->ui_n )
  947. continue;
  948. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  949. SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin();
  950. SortedVectorSparse<double>::const_elementpointer iPredecessor = nonzeroElements.begin();
  951. // index of the element, which is always bigger than the current value fval
  952. int index = 0;
  953. // we use the quantization of the original features! the transformed feature were
  954. // already used to calculate A and B, this of course assumes monotonic functions!!!
  955. int qBin = _q.quantize ( i->first );
  956. // the next loop is linear in max(hmax, n)
  957. // REMARK: this could be changed to hmax*log(n), when
  958. // we use binary search
  959. for (int j = 0; j < (int)hmax; j++)
  960. {
  961. double fval = prototypes[j];
  962. double t;
  963. if ( (index == 0) && (j < qBin) ) {
  964. // current element is smaller than everything else
  965. // resulting value = fval * sum_l=1^n 1
  966. t = pow( fval, 2 ) * (this->ui_n-nrZeroIndices-index);
  967. } else {
  968. // move to next example, if necessary
  969. while ( (j >= qBin) && ( index < (this->ui_n-nrZeroIndices)) )
  970. {
  971. index++;
  972. iPredecessor = i;
  973. i++;
  974. if ( i->first != iPredecessor->first )
  975. qBin = _q.quantize ( i->first );
  976. }
  977. // compute current element in the lookup table and keep in mind that
  978. // index is the next element and not the previous one
  979. //NOTE pay attention: this is only valid if all entries are positiv! - if not, ask wether the current feature is greater than zero. If so, subtract the nrZeroIndices, if not do not
  980. if ( (j >= (uint)qBin) && ( index==(this->ui_n-1-nrZeroIndices) ) ) {
  981. // the current element (fval) is equal or bigger to the element indexed by index
  982. // the second term vanishes, which is logical, since all elements are smaller than j!
  983. t = _A[dim][index];
  984. } else {
  985. // standard case
  986. t = _A[dim][index-1] + pow( fval, 2 ) * (this->ui_n-nrZeroIndices-(index) );
  987. // A[dim][index-1] + fval * (n-nrZeroIndices-(index) );//fval*fval * (n-nrZeroIndices-(index-1) );
  988. }
  989. }
  990. Tlookup[ dim*hmax + j ] = t;
  991. }
  992. }
  993. delete [] prototypes;
  994. return Tlookup;
  995. }
  996. double* FastMinKernel::hikPrepareLookupTableForKVNApproximation(const Quantization & _q,
  997. const ParameterizedFunction *_pf
  998. ) const
  999. {
  1000. // number of quantization bins
  1001. uint hmax = _q.size();
  1002. // store (transformed) prototypes
  1003. double *prototypes = new double [ hmax ];
  1004. for ( uint i = 0 ; i < hmax ; i++ )
  1005. if ( _pf != NULL ) {
  1006. // FIXME: the transformed prototypes could change from dimension to another dimension
  1007. // We skip this flexibility ...but it should be changed in the future
  1008. prototypes[i] = _pf->f ( 1, _q.getPrototype(i) );
  1009. } else {
  1010. prototypes[i] = _q.getPrototype(i);
  1011. }
  1012. // creating the lookup table as pure C, which might be beneficial
  1013. // for fast evaluation
  1014. double *Tlookup = new double [ hmax * this->ui_d ];
  1015. // loop through all dimensions
  1016. for (int dim = 0; dim < this->ui_d; dim++)
  1017. {
  1018. int nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1019. if ( nrZeroIndices == this->ui_n )
  1020. continue;
  1021. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  1022. SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin();
  1023. SortedVectorSparse<double>::const_elementpointer iPredecessor = nonzeroElements.begin();
  1024. // index of the element, which is always bigger than the current value fval
  1025. int index = 0;
  1026. // we use the quantization of the original features! Nevetheless, the resulting lookupTable is computed using the transformed ones
  1027. int qBin = _q.quantize ( i->first );
  1028. double sum(0.0);
  1029. for (uint j = 0; j < hmax; j++)
  1030. {
  1031. double fval = prototypes[j];
  1032. double t;
  1033. if ( (index == 0) && (j < (uint)qBin) ) {
  1034. // current element is smaller than everything else
  1035. // resulting value = fval * sum_l=1^n 1
  1036. t = pow( fval, 2 ) * (this->ui_n-nrZeroIndices-index);
  1037. } else {
  1038. // move to next example, if necessary
  1039. while ( (j >= (uint)qBin) && ( index < (this->ui_n-nrZeroIndices)) )
  1040. {
  1041. sum += pow( i->second.second, 2 ); //i->dataElement.transformedFeatureValue
  1042. index++;
  1043. iPredecessor = i;
  1044. i++;
  1045. if ( i->first != iPredecessor->first )
  1046. qBin = _q.quantize ( i->first );
  1047. }
  1048. // compute current element in the lookup table and keep in mind that
  1049. // index is the next element and not the previous one
  1050. //NOTE pay attention: this is only valid if we all entries are positiv! - if not, ask wether the current feature is greater than zero. If so, subtract the nrZeroIndices, if not do not
  1051. if ( (j >= (uint)qBin) && ( index==(this->ui_n-1-nrZeroIndices) ) ) {
  1052. // the current element (fval) is equal or bigger to the element indexed by index
  1053. // the second term vanishes, which is logical, since all elements are smaller than j!
  1054. t = sum;
  1055. } else {
  1056. // standard case
  1057. t = sum + pow( fval, 2 ) * (this->ui_n-nrZeroIndices-(index) );
  1058. }
  1059. }
  1060. Tlookup[ dim*hmax + j ] = t;
  1061. }
  1062. }
  1063. delete [] prototypes;
  1064. return Tlookup;
  1065. }
  1066. //////////////////////////////////////////
  1067. // variance computation: sparse inputs
  1068. //////////////////////////////////////////
  1069. void FastMinKernel::hikComputeKVNApproximation(const NICE::VVector & _A,
  1070. const NICE::SparseVector & _xstar,
  1071. double & _norm,
  1072. const ParameterizedFunction *_pf )
  1073. {
  1074. _norm = 0.0;
  1075. for (SparseVector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++)
  1076. {
  1077. int dim = i->first;
  1078. double fval = i->second;
  1079. int nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1080. if ( nrZeroIndices == this->ui_n ) {
  1081. // all features are zero so let us ignore them completely
  1082. continue;
  1083. }
  1084. int position;
  1085. //where is the example x^z_i located in
  1086. //the sorted array? -> perform binary search, runtime O(log(n))
  1087. // search using the original value
  1088. this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  1089. position--;
  1090. //NOTE again - pay attention! This is only valid if all entries are NOT negative! - if not, ask wether the current feature is greater than zero. If so, subtract the nrZeroIndices, if not do not
  1091. double firstPart(0.0);
  1092. //TODO in the "overnext" line there occurs the following error
  1093. // Invalid read of size 8
  1094. if (position >= 0)
  1095. firstPart = (_A[dim][position-nrZeroIndices]);
  1096. else
  1097. firstPart = 0.0;
  1098. double secondPart( 0.0);
  1099. if ( _pf != NULL )
  1100. fval = _pf->f ( dim, fval );
  1101. fval = fval * fval;
  1102. if (position >= 0)
  1103. secondPart = fval * (this->ui_n-nrZeroIndices-(position+1));
  1104. else //if x_d^* is smaller than every non-zero training example
  1105. secondPart = fval * (this->ui_n-nrZeroIndices);
  1106. // but apply using the transformed one
  1107. _norm += firstPart + secondPart;
  1108. }
  1109. }
  1110. void FastMinKernel::hikComputeKVNApproximationFast(const double *_Tlookup,
  1111. const Quantization & _q,
  1112. const NICE::SparseVector & _xstar,
  1113. double & _norm
  1114. ) const
  1115. {
  1116. _norm = 0.0;
  1117. // runtime is O(d) if the quantizer is O(1)
  1118. for (SparseVector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++ )
  1119. {
  1120. int dim = i->first;
  1121. double v = i->second;
  1122. // we do not need a parameterized function here, since the quantizer works on the original feature values.
  1123. // nonetheless, the lookup table was created using the parameterized function
  1124. uint qBin = _q.quantize(v);
  1125. _norm += _Tlookup[dim*_q.size() + qBin];
  1126. }
  1127. }
  1128. void FastMinKernel::hikComputeKernelVector ( const NICE::SparseVector& _xstar,
  1129. NICE::Vector & _kstar
  1130. ) const
  1131. {
  1132. //init
  1133. _kstar.resize( this->ui_n );
  1134. _kstar.set(0.0);
  1135. //let's start :)
  1136. for (SparseVector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++)
  1137. {
  1138. int dim = i->first;
  1139. double fval = i->second;
  1140. int nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1141. if ( nrZeroIndices == this->ui_n ) {
  1142. // all features are zero so let us ignore them completely
  1143. continue;
  1144. }
  1145. int position;
  1146. //where is the example x^z_i located in
  1147. //the sorted array? -> perform binary search, runtime O(log(n))
  1148. // search using the original value
  1149. this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  1150. position--;
  1151. //get the non-zero elements for this dimension
  1152. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  1153. //run over the non-zero elements and add the corresponding entries to our kernel vector
  1154. int count(nrZeroIndices);
  1155. for ( SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++, count++ )
  1156. {
  1157. int origIndex(i->second.first); //orig index (i->second.second would be the transformed feature value)
  1158. if (count <= position)
  1159. _kstar[origIndex] += i->first; //orig feature value
  1160. else
  1161. _kstar[origIndex] += fval;
  1162. }
  1163. }
  1164. }
  1165. //////////////////////////////////////////
  1166. // variance computation: non-sparse inputs
  1167. //////////////////////////////////////////
  1168. void FastMinKernel::hikComputeKVNApproximation(const NICE::VVector & _A,
  1169. const NICE::Vector & _xstar,
  1170. double & _norm,
  1171. const ParameterizedFunction *_pf )
  1172. {
  1173. _norm = 0.0;
  1174. int dim ( 0 );
  1175. for (Vector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++, dim++)
  1176. {
  1177. double fval = *i;
  1178. int nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1179. if ( nrZeroIndices == this->ui_n ) {
  1180. // all features are zero so let us ignore them completely
  1181. continue;
  1182. }
  1183. int position;
  1184. //where is the example x^z_i located in
  1185. //the sorted array? -> perform binary search, runtime O(log(n))
  1186. // search using the original value
  1187. this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  1188. position--;
  1189. //NOTE again - pay attention! This is only valid if all entries are NOT negative! - if not, ask wether the current feature is greater than zero. If so, subtract the nrZeroIndices, if not do not
  1190. double firstPart(0.0);
  1191. //TODO in the "overnext" line there occurs the following error
  1192. // Invalid read of size 8
  1193. if (position >= 0)
  1194. firstPart = (_A[dim][position-nrZeroIndices]);
  1195. else
  1196. firstPart = 0.0;
  1197. double secondPart( 0.0);
  1198. if ( _pf != NULL )
  1199. fval = _pf->f ( dim, fval );
  1200. fval = fval * fval;
  1201. if (position >= 0)
  1202. secondPart = fval * (this->ui_n-nrZeroIndices-(position+1));
  1203. else //if x_d^* is smaller than every non-zero training example
  1204. secondPart = fval * (this->ui_n-nrZeroIndices);
  1205. // but apply using the transformed one
  1206. _norm += firstPart + secondPart;
  1207. }
  1208. }
  1209. void FastMinKernel::hikComputeKVNApproximationFast(const double *_Tlookup,
  1210. const Quantization & _q,
  1211. const NICE::Vector & _xstar,
  1212. double & _norm
  1213. ) const
  1214. {
  1215. _norm = 0.0;
  1216. // runtime is O(d) if the quantizer is O(1)
  1217. int dim ( 0 );
  1218. for (Vector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++, dim++ )
  1219. {
  1220. double v = *i;
  1221. // we do not need a parameterized function here, since the quantizer works on the original feature values.
  1222. // nonetheless, the lookup table was created using the parameterized function
  1223. uint qBin = _q.quantize(v);
  1224. _norm += _Tlookup[dim*_q.size() + qBin];
  1225. }
  1226. }
  1227. void FastMinKernel::hikComputeKernelVector( const NICE::Vector & _xstar,
  1228. NICE::Vector & _kstar) const
  1229. {
  1230. //init
  1231. _kstar.resize(this->ui_n);
  1232. _kstar.set(0.0);
  1233. //let's start :)
  1234. int dim ( 0 );
  1235. for (NICE::Vector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++, dim++)
  1236. {
  1237. double fval = *i;
  1238. int nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1239. if ( nrZeroIndices == this->ui_n ) {
  1240. // all features are zero so let us ignore them completely
  1241. continue;
  1242. }
  1243. int position;
  1244. //where is the example x^z_i located in
  1245. //the sorted array? -> perform binary search, runtime O(log(n))
  1246. // search using the original value
  1247. this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  1248. position--;
  1249. //get the non-zero elements for this dimension
  1250. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  1251. //run over the non-zero elements and add the corresponding entries to our kernel vector
  1252. int count(nrZeroIndices);
  1253. for ( SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++, count++ )
  1254. {
  1255. int origIndex(i->second.first); //orig index (i->second.second would be the transformed feature value)
  1256. if (count <= position)
  1257. _kstar[origIndex] += i->first; //orig feature value
  1258. else
  1259. _kstar[origIndex] += fval;
  1260. }
  1261. }
  1262. }
  1263. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1264. // interface specific methods for store and restore
  1265. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1266. void FastMinKernel::restore ( std::istream & _is,
  1267. int _format )
  1268. {
  1269. bool b_restoreVerbose ( false );
  1270. if ( _is.good() )
  1271. {
  1272. if ( b_restoreVerbose )
  1273. std::cerr << " restore FastMinKernel" << std::endl;
  1274. std::string tmp;
  1275. _is >> tmp; //class name
  1276. if ( ! this->isStartTag( tmp, "FastMinKernel" ) )
  1277. {
  1278. std::cerr << " WARNING - attempt to restore FastMinKernel, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  1279. throw;
  1280. }
  1281. _is.precision (numeric_limits<double>::digits10 + 1);
  1282. bool b_endOfBlock ( false ) ;
  1283. while ( !b_endOfBlock )
  1284. {
  1285. _is >> tmp; // start of block
  1286. if ( this->isEndTag( tmp, "FastMinKernel" ) )
  1287. {
  1288. b_endOfBlock = true;
  1289. continue;
  1290. }
  1291. tmp = this->removeStartTag ( tmp );
  1292. if ( b_restoreVerbose )
  1293. std::cerr << " currently restore section " << tmp << " in FastMinKernel" << std::endl;
  1294. if ( tmp.compare("ui_n") == 0 )
  1295. {
  1296. _is >> this->ui_n;
  1297. _is >> tmp; // end of block
  1298. tmp = this->removeEndTag ( tmp );
  1299. }
  1300. else if ( tmp.compare("ui_d") == 0 )
  1301. {
  1302. _is >> this->ui_d;
  1303. _is >> tmp; // end of block
  1304. tmp = this->removeEndTag ( tmp );
  1305. }
  1306. else if ( tmp.compare("d_noise") == 0 )
  1307. {
  1308. _is >> this->d_noise;
  1309. _is >> tmp; // end of block
  1310. tmp = this->removeEndTag ( tmp );
  1311. }
  1312. else if ( tmp.compare("approxScheme") == 0 )
  1313. {
  1314. int approxSchemeInt;
  1315. _is >> approxSchemeInt;
  1316. setApproximationScheme(approxSchemeInt);
  1317. _is >> tmp; // end of block
  1318. tmp = this->removeEndTag ( tmp );
  1319. }
  1320. else if ( tmp.compare("X_sorted") == 0 )
  1321. {
  1322. this->X_sorted.restore(_is,_format);
  1323. _is >> tmp; // end of block
  1324. tmp = this->removeEndTag ( tmp );
  1325. }
  1326. else
  1327. {
  1328. std::cerr << "WARNING -- unexpected FastMinKernel object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1329. throw;
  1330. }
  1331. }
  1332. }
  1333. else
  1334. {
  1335. std::cerr << "FastMinKernel::restore -- InStream not initialized - restoring not possible!" << std::endl;
  1336. }
  1337. }
  1338. void FastMinKernel::store ( std::ostream & _os,
  1339. int _format
  1340. ) const
  1341. {
  1342. if (_os.good())
  1343. {
  1344. // show starting point
  1345. _os << this->createStartTag( "FastMinKernel" ) << std::endl;
  1346. _os.precision (numeric_limits<double>::digits10 + 1);
  1347. _os << this->createStartTag( "ui_n" ) << std::endl;
  1348. _os << this->ui_n << std::endl;
  1349. _os << this->createEndTag( "ui_n" ) << std::endl;
  1350. _os << this->createStartTag( "ui_d" ) << std::endl;
  1351. _os << this->ui_d << std::endl;
  1352. _os << this->createEndTag( "ui_d" ) << std::endl;
  1353. _os << this->createStartTag( "d_noise" ) << std::endl;
  1354. _os << this->d_noise << std::endl;
  1355. _os << this->createEndTag( "d_noise" ) << std::endl;
  1356. _os << this->createStartTag( "approxScheme" ) << std::endl;
  1357. _os << this->approxScheme << std::endl;
  1358. _os << this->createEndTag( "approxScheme" ) << std::endl;
  1359. _os << this->createStartTag( "X_sorted" ) << std::endl;
  1360. //store the underlying data
  1361. this->X_sorted.store(_os, _format);
  1362. _os << this->createEndTag( "X_sorted" ) << std::endl;
  1363. // done
  1364. _os << this->createEndTag( "FastMinKernel" ) << std::endl;
  1365. }
  1366. else
  1367. {
  1368. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  1369. }
  1370. }
  1371. void FastMinKernel::clear ()
  1372. {
  1373. std::cerr << "FastMinKernel clear-function called" << std::endl;
  1374. }
  1375. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  1376. // interface specific methods for incremental extensions
  1377. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  1378. void FastMinKernel::addExample( const NICE::SparseVector * _example,
  1379. const double & _label,
  1380. const bool & _performOptimizationAfterIncrement
  1381. )
  1382. {
  1383. // no parameterized function was given - use default
  1384. this->addExample ( _example );
  1385. }
  1386. void FastMinKernel::addMultipleExamples( const std::vector< const NICE::SparseVector * > & _newExamples,
  1387. const NICE::Vector & _newLabels,
  1388. const bool & _performOptimizationAfterIncrement
  1389. )
  1390. {
  1391. // no parameterized function was given - use default
  1392. this->addMultipleExamples ( _newExamples );
  1393. }
  1394. void FastMinKernel::addExample( const NICE::SparseVector * _example,
  1395. const NICE::ParameterizedFunction *_pf
  1396. )
  1397. {
  1398. this->X_sorted.add_feature( *_example, _pf );
  1399. this->ui_n++;
  1400. }
  1401. void FastMinKernel::addMultipleExamples( const std::vector< const NICE::SparseVector * > & _newExamples,
  1402. const NICE::ParameterizedFunction *_pf
  1403. )
  1404. {
  1405. for ( std::vector< const NICE::SparseVector * >::const_iterator exIt = _newExamples.begin();
  1406. exIt != _newExamples.end();
  1407. exIt++ )
  1408. {
  1409. this->X_sorted.add_feature( **exIt, _pf );
  1410. this->ui_n++;
  1411. }
  1412. }