FastMinKernel.cpp 62 KB

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