FastMinKernel.cpp 60 KB

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