FastMinKernel.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797
  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. //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
  1137. double firstPart(0.0);
  1138. //TODO in the "overnext" line there occurs the following error
  1139. // Invalid read of size 8
  1140. if ( !posIsZero && ((position-nrZeroIndices) < this->ui_n) )
  1141. firstPart = (_A[dim][position-nrZeroIndices]);
  1142. if ( _pf != NULL )
  1143. fval = _pf->f ( dim, fval );
  1144. fval = fval * fval;
  1145. double secondPart( 0.0);
  1146. if ( !posIsZero )
  1147. secondPart = fval * (this->ui_n-nrZeroIndices-(position+1));
  1148. else //if x_d^* is smaller than every non-zero training example
  1149. secondPart = fval * (this->ui_n-nrZeroIndices);
  1150. // but apply using the transformed one
  1151. _norm += firstPart + secondPart;
  1152. }
  1153. }
  1154. void FastMinKernel::hikComputeKVNApproximationFast(const double *_Tlookup,
  1155. const Quantization * _q,
  1156. const NICE::SparseVector & _xstar,
  1157. double & _norm
  1158. ) const
  1159. {
  1160. _norm = 0.0;
  1161. // runtime is O(d) if the quantizer is O(1)
  1162. for (SparseVector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++ )
  1163. {
  1164. uint dim = i->first;
  1165. double v = i->second;
  1166. // we do not need a parameterized function here, since the quantizer works on the original feature values.
  1167. // nonetheless, the lookup table was created using the parameterized function
  1168. uint qBin = _q->quantize( v, dim );
  1169. _norm += _Tlookup[dim*_q->getNumberOfBins() + qBin];
  1170. }
  1171. }
  1172. void FastMinKernel::hikComputeKernelVector ( const NICE::SparseVector& _xstar,
  1173. NICE::Vector & _kstar
  1174. ) const
  1175. {
  1176. //init
  1177. _kstar.resize( this->ui_n );
  1178. _kstar.set(0.0);
  1179. if ( this->b_debug )
  1180. {
  1181. std::cerr << " FastMinKernel::hikComputeKernelVector -- input: " << std::endl;
  1182. _xstar.store( std::cerr);
  1183. }
  1184. //let's start :)
  1185. for (SparseVector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++)
  1186. {
  1187. uint dim = i->first;
  1188. double fval = i->second;
  1189. if ( this->b_debug )
  1190. std::cerr << "dim: " << dim << " fval: " << fval << std::endl;
  1191. uint nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1192. if ( nrZeroIndices == this->ui_n ) {
  1193. // all features are zero so let us ignore them completely
  1194. continue;
  1195. }
  1196. uint position;
  1197. //where is the example x^z_i located in
  1198. //the sorted array? -> perform binary search, runtime O(log(n))
  1199. // search using the original value
  1200. this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  1201. //position--;
  1202. if ( this->b_debug )
  1203. std::cerr << " position: " << position << std::endl;
  1204. //get the non-zero elements for this dimension
  1205. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  1206. //run over the non-zero elements and add the corresponding entries to our kernel vector
  1207. uint count(nrZeroIndices);
  1208. for ( SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++, count++ )
  1209. {
  1210. uint origIndex(i->second.first); //orig index (i->second.second would be the transformed feature value)
  1211. if ( this->b_debug )
  1212. std::cerr << "i->1.2: " << i->second.first << " origIndex: " << origIndex << " count: " << count << " position: " << position << std::endl;
  1213. if (count < position)
  1214. _kstar[origIndex] += i->first; //orig feature value
  1215. else
  1216. _kstar[origIndex] += fval;
  1217. }
  1218. }
  1219. }
  1220. //////////////////////////////////////////
  1221. // variance computation: non-sparse inputs
  1222. //////////////////////////////////////////
  1223. void FastMinKernel::hikComputeKVNApproximation(const NICE::VVector & _A,
  1224. const NICE::Vector & _xstar,
  1225. double & _norm,
  1226. const ParameterizedFunction *_pf )
  1227. {
  1228. _norm = 0.0;
  1229. uint dim ( 0 );
  1230. for (Vector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++, dim++)
  1231. {
  1232. double fval = *i;
  1233. uint nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1234. if ( nrZeroIndices == this->ui_n ) {
  1235. // all features are zero so let us ignore them completely
  1236. continue;
  1237. }
  1238. uint position;
  1239. //where is the example x^z_i located in
  1240. //the sorted array? -> perform binary search, runtime O(log(n))
  1241. // search using the original value
  1242. this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  1243. bool posIsZero ( position == 0 );
  1244. if ( !posIsZero )
  1245. {
  1246. position--;
  1247. }
  1248. //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
  1249. double firstPart(0.0);
  1250. //TODO in the "overnext" line there occurs the following error
  1251. // Invalid read of size 8
  1252. if ( !posIsZero && ((position-nrZeroIndices) < this->ui_n) )
  1253. firstPart = (_A[dim][position-nrZeroIndices]);
  1254. double secondPart( 0.0);
  1255. if ( _pf != NULL )
  1256. fval = _pf->f ( dim, fval );
  1257. fval = fval * fval;
  1258. if ( !posIsZero )
  1259. secondPart = fval * (this->ui_n-nrZeroIndices-(position+1));
  1260. else //if x_d^* is smaller than every non-zero training example
  1261. secondPart = fval * (this->ui_n-nrZeroIndices);
  1262. // but apply using the transformed one
  1263. _norm += firstPart + secondPart;
  1264. }
  1265. }
  1266. void FastMinKernel::hikComputeKVNApproximationFast(const double *_Tlookup,
  1267. const Quantization * _q,
  1268. const NICE::Vector & _xstar,
  1269. double & _norm
  1270. ) const
  1271. {
  1272. _norm = 0.0;
  1273. // runtime is O(d) if the quantizer is O(1)
  1274. uint dim ( 0 );
  1275. for ( NICE::Vector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++, dim++ )
  1276. {
  1277. double v = *i;
  1278. // we do not need a parameterized function here, since the quantizer works on the original feature values.
  1279. // nonetheless, the lookup table was created using the parameterized function
  1280. uint qBin = _q->quantize( v, dim );
  1281. _norm += _Tlookup[dim*_q->getNumberOfBins() + qBin];
  1282. }
  1283. }
  1284. void FastMinKernel::hikComputeKernelVector( const NICE::Vector & _xstar,
  1285. NICE::Vector & _kstar) const
  1286. {
  1287. //init
  1288. _kstar.resize(this->ui_n);
  1289. _kstar.set(0.0);
  1290. //let's start :)
  1291. uint dim ( 0 );
  1292. for (NICE::Vector::const_iterator i = _xstar.begin(); i != _xstar.end(); i++, dim++)
  1293. {
  1294. double fval = *i;
  1295. uint nrZeroIndices = this->X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1296. if ( nrZeroIndices == this->ui_n ) {
  1297. // all features are zero so let us ignore them completely
  1298. continue;
  1299. }
  1300. uint position;
  1301. //where is the example x^z_i located in
  1302. //the sorted array? -> perform binary search, runtime O(log(n))
  1303. // search using the original value
  1304. this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  1305. //position--;
  1306. //get the non-zero elements for this dimension
  1307. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = this->X_sorted.getFeatureValues(dim).nonzeroElements();
  1308. //run over the non-zero elements and add the corresponding entries to our kernel vector
  1309. uint count(nrZeroIndices);
  1310. for ( SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++, count++ )
  1311. {
  1312. uint origIndex(i->second.first); //orig index (i->second.second would be the transformed feature value)
  1313. if (count < position)
  1314. _kstar[origIndex] += i->first; //orig feature value
  1315. else
  1316. _kstar[origIndex] += fval;
  1317. }
  1318. }
  1319. }
  1320. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1321. // interface specific methods for store and restore
  1322. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1323. void FastMinKernel::restore ( std::istream & _is,
  1324. int _format )
  1325. {
  1326. bool b_restoreVerbose ( false );
  1327. if ( _is.good() )
  1328. {
  1329. if ( b_restoreVerbose )
  1330. std::cerr << " restore FastMinKernel" << std::endl;
  1331. std::string tmp;
  1332. _is >> tmp; //class name
  1333. if ( ! this->isStartTag( tmp, "FastMinKernel" ) )
  1334. {
  1335. std::cerr << " WARNING - attempt to restore FastMinKernel, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  1336. throw;
  1337. }
  1338. _is.precision (numeric_limits<double>::digits10 + 1);
  1339. bool b_endOfBlock ( false ) ;
  1340. while ( !b_endOfBlock )
  1341. {
  1342. _is >> tmp; // start of block
  1343. if ( this->isEndTag( tmp, "FastMinKernel" ) )
  1344. {
  1345. b_endOfBlock = true;
  1346. continue;
  1347. }
  1348. tmp = this->removeStartTag ( tmp );
  1349. if ( b_restoreVerbose )
  1350. std::cerr << " currently restore section " << tmp << " in FastMinKernel" << std::endl;
  1351. if ( tmp.compare("ui_n") == 0 )
  1352. {
  1353. _is >> this->ui_n;
  1354. _is >> tmp; // end of block
  1355. tmp = this->removeEndTag ( tmp );
  1356. }
  1357. else if ( tmp.compare("ui_d") == 0 )
  1358. {
  1359. _is >> this->ui_d;
  1360. _is >> tmp; // end of block
  1361. tmp = this->removeEndTag ( tmp );
  1362. }
  1363. else if ( tmp.compare("d_noise") == 0 )
  1364. {
  1365. _is >> this->d_noise;
  1366. _is >> tmp; // end of block
  1367. tmp = this->removeEndTag ( tmp );
  1368. }
  1369. else if ( tmp.compare("approxScheme") == 0 )
  1370. {
  1371. int approxSchemeInt;
  1372. _is >> approxSchemeInt;
  1373. setApproximationScheme(approxSchemeInt);
  1374. _is >> tmp; // end of block
  1375. tmp = this->removeEndTag ( tmp );
  1376. }
  1377. else if ( tmp.compare("X_sorted") == 0 )
  1378. {
  1379. this->X_sorted.restore(_is,_format);
  1380. _is >> tmp; // end of block
  1381. tmp = this->removeEndTag ( tmp );
  1382. }
  1383. else
  1384. {
  1385. std::cerr << "WARNING -- unexpected FastMinKernel object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1386. throw;
  1387. }
  1388. }
  1389. }
  1390. else
  1391. {
  1392. std::cerr << "FastMinKernel::restore -- InStream not initialized - restoring not possible!" << std::endl;
  1393. }
  1394. }
  1395. void FastMinKernel::store ( std::ostream & _os,
  1396. int _format
  1397. ) const
  1398. {
  1399. if (_os.good())
  1400. {
  1401. // show starting point
  1402. _os << this->createStartTag( "FastMinKernel" ) << std::endl;
  1403. _os.precision (numeric_limits<double>::digits10 + 1);
  1404. _os << this->createStartTag( "ui_n" ) << std::endl;
  1405. _os << this->ui_n << std::endl;
  1406. _os << this->createEndTag( "ui_n" ) << std::endl;
  1407. _os << this->createStartTag( "ui_d" ) << std::endl;
  1408. _os << this->ui_d << std::endl;
  1409. _os << this->createEndTag( "ui_d" ) << std::endl;
  1410. _os << this->createStartTag( "d_noise" ) << std::endl;
  1411. _os << this->d_noise << std::endl;
  1412. _os << this->createEndTag( "d_noise" ) << std::endl;
  1413. _os << this->createStartTag( "approxScheme" ) << std::endl;
  1414. _os << this->approxScheme << std::endl;
  1415. _os << this->createEndTag( "approxScheme" ) << std::endl;
  1416. _os << this->createStartTag( "X_sorted" ) << std::endl;
  1417. //store the underlying data
  1418. this->X_sorted.store(_os, _format);
  1419. _os << this->createEndTag( "X_sorted" ) << std::endl;
  1420. // done
  1421. _os << this->createEndTag( "FastMinKernel" ) << std::endl;
  1422. }
  1423. else
  1424. {
  1425. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  1426. }
  1427. }
  1428. void FastMinKernel::clear ()
  1429. {
  1430. std::cerr << "FastMinKernel clear-function called" << std::endl;
  1431. }
  1432. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  1433. // interface specific methods for incremental extensions
  1434. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  1435. void FastMinKernel::addExample( const NICE::SparseVector * _example,
  1436. const double & _label,
  1437. const bool & _performOptimizationAfterIncrement
  1438. )
  1439. {
  1440. // no parameterized function was given - use default
  1441. this->addExample ( _example );
  1442. }
  1443. void FastMinKernel::addMultipleExamples( const std::vector< const NICE::SparseVector * > & _newExamples,
  1444. const NICE::Vector & _newLabels,
  1445. const bool & _performOptimizationAfterIncrement
  1446. )
  1447. {
  1448. // no parameterized function was given - use default
  1449. this->addMultipleExamples ( _newExamples );
  1450. }
  1451. void FastMinKernel::addExample( const NICE::SparseVector * _example,
  1452. const NICE::ParameterizedFunction *_pf
  1453. )
  1454. {
  1455. this->X_sorted.add_feature( *_example, _pf );
  1456. this->ui_n++;
  1457. }
  1458. void FastMinKernel::addMultipleExamples( const std::vector< const NICE::SparseVector * > & _newExamples,
  1459. const NICE::ParameterizedFunction *_pf
  1460. )
  1461. {
  1462. for ( std::vector< const NICE::SparseVector * >::const_iterator exIt = _newExamples.begin();
  1463. exIt != _newExamples.end();
  1464. exIt++ )
  1465. {
  1466. this->X_sorted.add_feature( **exIt, _pf );
  1467. this->ui_n++;
  1468. }
  1469. }