FastMinKernel.cpp 60 KB

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