FastMinKernel.cpp 57 KB

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