FastMinKernel.cpp 60 KB

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