FastMinKernel.cpp 58 KB

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