FastMinKernel.cpp 49 KB

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