FastMinKernel.cpp 58 KB

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