FastMinKernel.cpp 52 KB

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