FastMinKernel.cpp 57 KB

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