FastMinKernel.cpp 52 KB

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