FastMinKernel.cpp 58 KB

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