FastMinKernel.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  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 > 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. beta = 0.0;
  425. for (SparseVector::const_iterator i = xstar.begin(); i != xstar.end(); i++)
  426. {
  427. int dim = i->first;
  428. double fval = i->second;
  429. int nrZeroIndices = X_sorted.getNumberOfZeroElementsPerDimension(dim);
  430. if ( nrZeroIndices == n ) {
  431. // all features are zero and let us ignore it completely
  432. continue;
  433. }
  434. int position;
  435. //where is the example x^z_i located in
  436. //the sorted array? -> perform binary search, runtime O(log(n))
  437. // search using the original value
  438. X_sorted.findFirstLargerInDimension(dim, fval, position);
  439. position--;
  440. //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
  441. //sum_{l \in L_k} \alpha_l x^l_k
  442. double firstPart(0.0);
  443. //TODO in the "overnext" line there occurs the following error
  444. // Invalid read of size 8
  445. if (position >= 0)
  446. firstPart = (A[dim][position-nrZeroIndices]);
  447. // sum_{u \in U_k} alpha_u
  448. // sum_{u \in U_k} alpha_u
  449. // => double secondPart( B(dim, n-1) - B(dim, position));
  450. //TODO in the next line there occurs the following error
  451. // Invalid read of size 8
  452. double secondPart( B[dim][n-1-nrZeroIndices]);
  453. //TODO in the "overnext" line there occurs the following error
  454. // Invalid read of size 8
  455. if (position >= 0)
  456. secondPart-= B[dim][position-nrZeroIndices];
  457. if ( pf != NULL )
  458. {
  459. fval = pf->f ( dim, fval );
  460. }
  461. // but apply using the transformed one
  462. beta += firstPart + secondPart* fval;
  463. }
  464. }
  465. void FastMinKernel::hik_kernel_sum(const NICE::VVector & A, const NICE::VVector & B, const NICE::Vector & xstar, double & beta, const ParameterizedFunction *pf) const
  466. {
  467. beta = 0.0;
  468. int dim ( 0 );
  469. for (NICE::Vector::const_iterator i = xstar.begin(); i != xstar.end(); i++, dim++)
  470. {
  471. double fval = *i;
  472. int nrZeroIndices = X_sorted.getNumberOfZeroElementsPerDimension(dim);
  473. if ( nrZeroIndices == n ) {
  474. // all features are zero and let us ignore it completely
  475. continue;
  476. }
  477. int position;
  478. //where is the example x^z_i located in
  479. //the sorted array? -> perform binary search, runtime O(log(n))
  480. // search using the original value
  481. X_sorted.findFirstLargerInDimension(dim, fval, position);
  482. position--;
  483. //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
  484. //sum_{l \in L_k} \alpha_l x^l_k
  485. double firstPart(0.0);
  486. //TODO in the "overnext" line there occurs the following error
  487. // Invalid read of size 8
  488. if (position >= 0)
  489. firstPart = (A[dim][position-nrZeroIndices]);
  490. // sum_{u \in U_k} alpha_u
  491. // sum_{u \in U_k} alpha_u
  492. // => double secondPart( B(dim, n-1) - B(dim, position));
  493. //TODO in the next line there occurs the following error
  494. // Invalid read of size 8
  495. double secondPart( B[dim][n-1-nrZeroIndices]);
  496. //TODO in the "overnext" line there occurs the following error
  497. // Invalid read of size 8
  498. if (position >= 0)
  499. secondPart-= B[dim][position-nrZeroIndices];
  500. if ( pf != NULL )
  501. {
  502. fval = pf->f ( dim, fval );
  503. }
  504. // but apply using the transformed one
  505. beta += firstPart + secondPart* fval;
  506. }
  507. }
  508. void FastMinKernel::hik_kernel_sum_fast(const double *Tlookup, const Quantization & q, const NICE::Vector & xstar, double & beta) const
  509. {
  510. beta = 0.0;
  511. if ((int) xstar.size() != d)
  512. {
  513. fthrow(Exception, "FastMinKernel::hik_kernel_sum_fast sizes of xstar and training data does not match!");
  514. return;
  515. }
  516. // runtime is O(d) if the quantizer is O(1)
  517. for (int dim = 0; dim < d; dim++)
  518. {
  519. double v = xstar[dim];
  520. uint qBin = q.quantize(v);
  521. beta += Tlookup[dim*q.size() + qBin];
  522. }
  523. }
  524. void FastMinKernel::hik_kernel_sum_fast(const double *Tlookup, const Quantization & q, const NICE::SparseVector & xstar, double & beta) const
  525. {
  526. beta = 0.0;
  527. // sparse version of hik_kernel_sum_fast, no really significant changes,
  528. // we are just skipping zero elements
  529. // for additional comments see the non-sparse version of hik_kernel_sum_fast
  530. // runtime is O(d) if the quantizer is O(1)
  531. for (SparseVector::const_iterator i = xstar.begin(); i != xstar.end(); i++ )
  532. {
  533. int dim = i->first;
  534. double v = i->second;
  535. uint qBin = q.quantize(v);
  536. beta += Tlookup[dim*q.size() + qBin];
  537. }
  538. }
  539. 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
  540. {
  541. int sizeOfRandomSubset(_sizeOfRandomSubset);
  542. bool verbose ( false );
  543. bool verboseMinimal ( false );
  544. // number of quantization bins
  545. uint hmax = q.size();
  546. NICE::Vector diagonalElements(y.size(),0.0);
  547. X_sorted.hikDiagonalElements(diagonalElements);
  548. diagonalElements += this->noise;
  549. NICE::Vector pseudoResidual (y.size(),0.0);
  550. NICE::Vector delta_alpha (y.size(),0.0);
  551. double alpha_old;
  552. double alpha_new;
  553. double x_i;
  554. // initialization
  555. if (alpha.size() != y.size())
  556. alpha.resize(y.size());
  557. alpha.set(0.0);
  558. double *Tlookup = new double [ hmax * this->d ];
  559. if ( (hmax*this->d) <= 0 ) return Tlookup;
  560. memset(Tlookup, 0, sizeof(Tlookup[0])*hmax*this->d);
  561. uint iter;
  562. Timer t;
  563. if ( timeAnalysis )
  564. t.start();
  565. if (useRandomSubsets)
  566. {
  567. std::vector<int> indices(y.size());
  568. for (uint i = 0; i < y.size(); i++)
  569. indices[i] = i;
  570. if (sizeOfRandomSubset <= 0)
  571. sizeOfRandomSubset = y.size();
  572. for ( iter = 1; iter <= maxIterations; iter++ )
  573. {
  574. NICE::Vector perm;
  575. randomPermutation(perm,indices,sizeOfRandomSubset);
  576. if ( timeAnalysis )
  577. {
  578. t.stop();
  579. Vector r;
  580. this->hik_kernel_multiply_fast(Tlookup, q, alpha, r);
  581. r = r - y;
  582. double res = r.normL2();
  583. double resMax = r.normInf();
  584. cerr << "SimpleGradientDescent: TIME " << t.getSum() << " " << res << " " << resMax << endl;
  585. t.start();
  586. }
  587. for ( int i = 0; i < sizeOfRandomSubset; i++)
  588. {
  589. pseudoResidual(perm[i]) = -y(perm[i]) + (this->noise*alpha(perm[i]));
  590. for (uint j = 0; j < (uint)this->d; j++)
  591. {
  592. x_i = X_sorted(j,perm[i]);
  593. pseudoResidual(perm[i]) += Tlookup[j*hmax + q.quantize(x_i)];
  594. }
  595. //NOTE: this threshhold could also be a parameter of the function call
  596. if ( fabs(pseudoResidual(perm[i])) > 1e-7 )
  597. {
  598. alpha_old = alpha(perm[i]);
  599. alpha_new = alpha_old - (pseudoResidual(perm[i])/diagonalElements(perm[i]));
  600. alpha(perm[i]) = alpha_new;
  601. delta_alpha(perm[i]) = alpha_old-alpha_new;
  602. this->hikUpdateLookupTable(Tlookup, alpha_new, alpha_old, perm[i], q, pf ); // works correctly
  603. } else
  604. {
  605. delta_alpha(perm[i]) = 0.0;
  606. }
  607. }
  608. // after this only residual(i) is the valid residual... we should
  609. // really update the whole vector somehow
  610. double delta = delta_alpha.normL2();
  611. if ( verbose ) {
  612. cerr << "FastMinKernel::solveLin: iteration " << iter << " / " << maxIterations << endl;
  613. cerr << "FastMinKernel::solveLin: delta = " << delta << endl;
  614. cerr << "FastMinKernel::solveLin: pseudo residual = " << pseudoResidual.scalarProduct(pseudoResidual) << endl;
  615. }
  616. if ( delta < minDelta )
  617. {
  618. if ( verbose )
  619. cerr << "FastMinKernel::solveLin: small delta" << endl;
  620. break;
  621. }
  622. }
  623. }
  624. else //don't use random subsets
  625. {
  626. for ( iter = 1; iter <= maxIterations; iter++ )
  627. {
  628. for ( uint i = 0; i < y.size(); i++ )
  629. {
  630. pseudoResidual(i) = -y(i) + (this->noise*alpha(i));
  631. for (uint j = 0; j < (uint) this->d; j++)
  632. {
  633. x_i = X_sorted(j,i);
  634. pseudoResidual(i) += Tlookup[j*hmax + q.quantize(x_i)];
  635. }
  636. //NOTE: this threshhold could also be a parameter of the function call
  637. if ( fabs(pseudoResidual(i)) > 1e-7 )
  638. {
  639. alpha_old = alpha(i);
  640. alpha_new = alpha_old - (pseudoResidual(i)/diagonalElements(i));
  641. alpha(i) = alpha_new;
  642. delta_alpha(i) = alpha_old-alpha_new;
  643. this->hikUpdateLookupTable(Tlookup, alpha_new, alpha_old, i, q, pf ); // works correctly
  644. } else
  645. {
  646. delta_alpha(i) = 0.0;
  647. }
  648. }
  649. double delta = delta_alpha.normL2();
  650. if ( verbose ) {
  651. cerr << "FastMinKernel::solveLin: iteration " << iter << " / " << maxIterations << endl;
  652. cerr << "FastMinKernel::solveLin: delta = " << delta << endl;
  653. cerr << "FastMinKernel::solveLin: pseudo residual = " << pseudoResidual.scalarProduct(pseudoResidual) << endl;
  654. }
  655. if ( delta < minDelta )
  656. {
  657. if ( verbose )
  658. cerr << "FastMinKernel::solveLin: small delta" << endl;
  659. break;
  660. }
  661. }
  662. }
  663. if (verboseMinimal)
  664. std::cerr << "FastMinKernel::solveLin -- needed " << iter << " iterations" << std::endl;
  665. return Tlookup;
  666. }
  667. void FastMinKernel::randomPermutation(NICE::Vector & permutation, const std::vector<int> & oldIndices, const int & newSize) const
  668. {
  669. std::vector<int> indices(oldIndices);
  670. int resultingSize (std::min((int) (oldIndices.size()),newSize) );
  671. permutation.resize(resultingSize);
  672. for (int i = 0; i < resultingSize; i++)
  673. {
  674. int newIndex(rand() % indices.size());
  675. permutation[i] = indices[newIndex ];
  676. indices.erase(indices.begin() + newIndex);
  677. }
  678. }
  679. double FastMinKernel::getFrobNormApprox()
  680. {
  681. double frobNormApprox(0.0);
  682. switch (approxScheme)
  683. {
  684. case MEDIAN:
  685. {
  686. //\| K \|_F^1 ~ (n/2)^2 \left( \sum_k \median_k \right)^2
  687. //motivation: estimate half of the values in dim k to zero and half of them to the median (-> lower bound expectation)
  688. for (int i = 0; i < d; i++)
  689. {
  690. double median = this->X_sorted.getFeatureValues(i).getMedian();
  691. frobNormApprox += median;
  692. }
  693. frobNormApprox = fabs(frobNormApprox) * n/2.0;
  694. break;
  695. }
  696. case EXPECTATION:
  697. {
  698. std::cerr << "EXPECTATION" << std::endl;
  699. //\| 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)
  700. // with a_k = minimal value in dim k and b_k maximal value
  701. //first term
  702. NICE::Vector diagEl;
  703. X_sorted.hikDiagonalElements(diagEl);
  704. frobNormApprox += diagEl.normL2();
  705. //second term
  706. double secondTerm(0.0);
  707. for (int i = 0; i < d; i++)
  708. {
  709. double minInDim;
  710. minInDim = this->X_sorted.getFeatureValues(i).getMin();
  711. double maxInDim;
  712. maxInDim = this->X_sorted.getFeatureValues(i).getMax();
  713. std::cerr << "min: " << minInDim << " max: " << maxInDim << std::endl;
  714. secondTerm += 2.0*minInDim + maxInDim;
  715. }
  716. secondTerm /= 3.0;
  717. secondTerm = pow(secondTerm, 2);
  718. secondTerm *= (pow(this->n,2) - this->n);
  719. frobNormApprox += secondTerm;
  720. frobNormApprox = sqrt(frobNormApprox);
  721. break;
  722. }
  723. default:
  724. { //do nothing, approximate with zero :)
  725. break;
  726. }
  727. }
  728. return frobNormApprox;
  729. }
  730. void FastMinKernel::setApproximationScheme(const int & _approxScheme)
  731. {
  732. switch(_approxScheme)
  733. {
  734. case 0:
  735. {
  736. approxScheme = MEDIAN;
  737. break;
  738. }
  739. case 1:
  740. {
  741. approxScheme = EXPECTATION;
  742. break;
  743. }
  744. default:
  745. {
  746. approxScheme = MEDIAN;
  747. break;
  748. }
  749. }
  750. }
  751. void FastMinKernel::hikPrepareKVNApproximation(NICE::VVector & A) const
  752. {
  753. A.resize(d);
  754. // efficient calculation of |k_*|^2 = k_*^T * k_*
  755. // ---------------------------------
  756. //
  757. // \sum_{i=1}^{n} \left( \sum_{d=1}^{D} \min (x_d^*, x_d^i) \right)^2
  758. // <=\sum_{i=1}^{n} \sum_{d=1}^{D} \left( \min (x_d^*, x_d^i) \right)^2
  759. // = \sum_{d=1}^{D} \sum_{i=1}^{n} \left( \min (x_d^*, x_d^i) \right)^2
  760. // = \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)
  761. //
  762. // again let us define l_d = { i | x_d^i <= x_d^* }
  763. // and u_d = { i | x_d^i > x_d^* }, this leads to
  764. //
  765. // = \sum_{d=1}^{D} ( \sum_{l \in l_d} (x_d^l)^2 + \sum_{u \in u_d} (x_d^*)^2
  766. // = \sum_{d=1}^{D} ( \sum_{l \in l_d} (x_d^l)^2 + (x_d^*)^2 \sum_{u \in u_d} 1
  767. //
  768. // We also define
  769. // l_d^j = { i | x_d^i <= x_d^j } and
  770. // u_d^j = { i | x_d^i > x_d^j }
  771. //
  772. // We now need the partial sums
  773. //
  774. // (Definition 1)
  775. // a_{d,j} = \sum_{l \in l_d^j} (x_d^l)^2
  776. // according to increasing values of x_d^l
  777. //
  778. // We end at
  779. // |k_*|^2 <= \sum_{d=1}^{D} \left( a_{d,r_d} + (x_d^*)^2 * |u_d^{r_d}| \right)
  780. // with r_d being the index of the last example in the ordered sequence for dimension d, that is not larger than x_d^*
  781. // we only need as many entries as we have nonZero entries in our features for the corresponding dimensions
  782. for (int i = 0; i < d; i++)
  783. {
  784. uint numNonZero = X_sorted.getNumberOfNonZeroElementsPerDimension(i);
  785. A[i].resize( numNonZero );
  786. }
  787. // for more information see hik_prepare_alpha_multiplications
  788. for (int dim = 0; dim < d; dim++)
  789. {
  790. double squared_sum(0.0);
  791. int cntNonzeroFeat(0);
  792. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = X_sorted.getFeatureValues(dim).nonzeroElements();
  793. // loop through all elements in sorted order
  794. for ( SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++ )
  795. {
  796. const SortedVectorSparse<double>::dataelement & de = i->second;
  797. // de: first - index, second - transformed feature
  798. double elem( de.second );
  799. squared_sum += pow( elem, 2 );
  800. A[dim][cntNonzeroFeat] = squared_sum;
  801. cntNonzeroFeat++;
  802. }
  803. }
  804. }
  805. double * FastMinKernel::hikPrepareKVNApproximationFast(NICE::VVector & A, const Quantization & q, const ParameterizedFunction *pf ) const
  806. {
  807. //NOTE keep in mind: for doing this, we already have precomputed A using hikPrepareSquaredKernelVector!
  808. // number of quantization bins
  809. uint hmax = q.size();
  810. // store (transformed) prototypes
  811. double *prototypes = new double [ hmax ];
  812. for ( uint i = 0 ; i < hmax ; i++ )
  813. if ( pf != NULL ) {
  814. // FIXME: the transformed prototypes could change from dimension to another dimension
  815. // We skip this flexibility ...but it should be changed in the future
  816. prototypes[i] = pf->f ( 1, q.getPrototype(i) );
  817. } else {
  818. prototypes[i] = q.getPrototype(i);
  819. }
  820. // creating the lookup table as pure C, which might be beneficial
  821. // for fast evaluation
  822. double *Tlookup = new double [ hmax * this->d ];
  823. // loop through all dimensions
  824. for (int dim = 0; dim < this->d; dim++)
  825. {
  826. int nrZeroIndices = X_sorted.getNumberOfZeroElementsPerDimension(dim);
  827. if ( nrZeroIndices == n )
  828. continue;
  829. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = X_sorted.getFeatureValues(dim).nonzeroElements();
  830. SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin();
  831. SortedVectorSparse<double>::const_elementpointer iPredecessor = nonzeroElements.begin();
  832. // index of the element, which is always bigger than the current value fval
  833. int index = 0;
  834. // we use the quantization of the original features! the transformed feature were
  835. // already used to calculate A and B, this of course assumes monotonic functions!!!
  836. int qBin = q.quantize ( i->first );
  837. // the next loop is linear in max(hmax, n)
  838. // REMARK: this could be changed to hmax*log(n), when
  839. // we use binary search
  840. for (int j = 0; j < (int)hmax; j++)
  841. {
  842. double fval = prototypes[j];
  843. double t;
  844. if ( (index == 0) && (j < qBin) ) {
  845. // current element is smaller than everything else
  846. // resulting value = fval * sum_l=1^n 1
  847. t = pow( fval, 2 ) * (n-nrZeroIndices-index);
  848. } else {
  849. // move to next example, if necessary
  850. while ( (j >= qBin) && ( index < (this->n-nrZeroIndices)) )
  851. {
  852. index++;
  853. iPredecessor = i;
  854. i++;
  855. if ( i->first != iPredecessor->first )
  856. qBin = q.quantize ( i->first );
  857. }
  858. // compute current element in the lookup table and keep in mind that
  859. // index is the next element and not the previous one
  860. //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
  861. if ( (j >= (uint)qBin) && ( index==(this->n-1-nrZeroIndices) ) ) {
  862. // the current element (fval) is equal or bigger to the element indexed by index
  863. // the second term vanishes, which is logical, since all elements are smaller than j!
  864. t = A[dim][index];
  865. } else {
  866. // standard case
  867. t = A[dim][index-1] + pow( fval, 2 ) * (n-nrZeroIndices-(index) );
  868. // A[dim][index-1] + fval * (n-nrZeroIndices-(index) );//fval*fval * (n-nrZeroIndices-(index-1) );
  869. }
  870. }
  871. Tlookup[ dim*hmax + j ] = t;
  872. }
  873. }
  874. delete [] prototypes;
  875. return Tlookup;
  876. }
  877. double* FastMinKernel::hikPrepareLookupTableForKVNApproximation(const Quantization & q, const ParameterizedFunction *pf ) const
  878. {
  879. // number of quantization bins
  880. uint hmax = q.size();
  881. // store (transformed) prototypes
  882. double *prototypes = new double [ hmax ];
  883. for ( uint i = 0 ; i < hmax ; i++ )
  884. if ( pf != NULL ) {
  885. // FIXME: the transformed prototypes could change from dimension to another dimension
  886. // We skip this flexibility ...but it should be changed in the future
  887. prototypes[i] = pf->f ( 1, q.getPrototype(i) );
  888. } else {
  889. prototypes[i] = q.getPrototype(i);
  890. }
  891. // creating the lookup table as pure C, which might be beneficial
  892. // for fast evaluation
  893. double *Tlookup = new double [ hmax * this->d ];
  894. // loop through all dimensions
  895. for (int dim = 0; dim < this->d; dim++)
  896. {
  897. int nrZeroIndices = X_sorted.getNumberOfZeroElementsPerDimension(dim);
  898. if ( nrZeroIndices == n )
  899. continue;
  900. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = X_sorted.getFeatureValues(dim).nonzeroElements();
  901. SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin();
  902. SortedVectorSparse<double>::const_elementpointer iPredecessor = nonzeroElements.begin();
  903. // index of the element, which is always bigger than the current value fval
  904. int index = 0;
  905. // we use the quantization of the original features! Nevetheless, the resulting lookupTable is computed using the transformed ones
  906. int qBin = q.quantize ( i->first );
  907. double sum(0.0);
  908. for (uint j = 0; j < hmax; j++)
  909. {
  910. double fval = prototypes[j];
  911. double t;
  912. if ( (index == 0) && (j < (uint)qBin) ) {
  913. // current element is smaller than everything else
  914. // resulting value = fval * sum_l=1^n 1
  915. t = pow( fval, 2 ) * (n-nrZeroIndices-index);
  916. } else {
  917. // move to next example, if necessary
  918. while ( (j >= (uint)qBin) && ( index < (this->n-nrZeroIndices)) )
  919. {
  920. sum += pow( i->second.second, 2 ); //i->dataElement.transformedFeatureValue
  921. index++;
  922. iPredecessor = i;
  923. i++;
  924. if ( i->first != iPredecessor->first )
  925. qBin = q.quantize ( i->first );
  926. }
  927. // compute current element in the lookup table and keep in mind that
  928. // index is the next element and not the previous one
  929. //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
  930. if ( (j >= (uint)qBin) && ( index==(this->n-1-nrZeroIndices) ) ) {
  931. // the current element (fval) is equal or bigger to the element indexed by index
  932. // the second term vanishes, which is logical, since all elements are smaller than j!
  933. t = sum;
  934. } else {
  935. // standard case
  936. t = sum + pow( fval, 2 ) * (n-nrZeroIndices-(index) );
  937. }
  938. }
  939. Tlookup[ dim*hmax + j ] = t;
  940. }
  941. }
  942. delete [] prototypes;
  943. return Tlookup;
  944. }
  945. void FastMinKernel::hikComputeKVNApproximation(const NICE::VVector & A, const NICE::SparseVector & xstar, double & norm, const ParameterizedFunction *pf )
  946. {
  947. norm = 0.0;
  948. for (SparseVector::const_iterator i = xstar.begin(); i != xstar.end(); i++)
  949. {
  950. int dim = i->first;
  951. double fval = i->second;
  952. int nrZeroIndices = X_sorted.getNumberOfZeroElementsPerDimension(dim);
  953. if ( nrZeroIndices == n ) {
  954. // all features are zero so let us ignore them completely
  955. continue;
  956. }
  957. int position;
  958. //where is the example x^z_i located in
  959. //the sorted array? -> perform binary search, runtime O(log(n))
  960. // search using the original value
  961. X_sorted.findFirstLargerInDimension(dim, fval, position);
  962. position--;
  963. //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
  964. double firstPart(0.0);
  965. //TODO in the "overnext" line there occurs the following error
  966. // Invalid read of size 8
  967. if (position >= 0)
  968. firstPart = (A[dim][position-nrZeroIndices]);
  969. else
  970. firstPart = 0.0;
  971. double secondPart( 0.0);
  972. if ( pf != NULL )
  973. fval = pf->f ( dim, fval );
  974. fval = fval * fval;
  975. if (position >= 0)
  976. secondPart = fval * (n-nrZeroIndices-(position+1));
  977. else //if x_d^* is smaller than every non-zero training example
  978. secondPart = fval * (n-nrZeroIndices);
  979. // but apply using the transformed one
  980. norm += firstPart + secondPart;
  981. }
  982. }
  983. void FastMinKernel::hikComputeKVNApproximationFast(const double *Tlookup, const Quantization & q, const NICE::SparseVector & xstar, double & norm) const
  984. {
  985. norm = 0.0;
  986. // runtime is O(d) if the quantizer is O(1)
  987. for (SparseVector::const_iterator i = xstar.begin(); i != xstar.end(); i++ )
  988. {
  989. int dim = i->first;
  990. double v = i->second;
  991. // we do not need a parameterized function here, since the quantizer works on the original feature values.
  992. // nonetheless, the lookup table was created using the parameterized function
  993. uint qBin = q.quantize(v);
  994. norm += Tlookup[dim*q.size() + qBin];
  995. }
  996. }
  997. void FastMinKernel::hikComputeKernelVector ( const NICE::SparseVector& xstar, NICE::Vector & kstar ) const
  998. {
  999. //init
  1000. kstar.resize(this->n);
  1001. kstar.set(0.0);
  1002. //let's start :)
  1003. for (SparseVector::const_iterator i = xstar.begin(); i != xstar.end(); i++)
  1004. {
  1005. int dim = i->first;
  1006. double fval = i->second;
  1007. int nrZeroIndices = X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1008. if ( nrZeroIndices == n ) {
  1009. // all features are zero so let us ignore them completely
  1010. continue;
  1011. }
  1012. int position;
  1013. //where is the example x^z_i located in
  1014. //the sorted array? -> perform binary search, runtime O(log(n))
  1015. // search using the original value
  1016. X_sorted.findFirstLargerInDimension(dim, fval, position);
  1017. position--;
  1018. //get the non-zero elements for this dimension
  1019. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = X_sorted.getFeatureValues(dim).nonzeroElements();
  1020. //run over the non-zero elements and add the corresponding entries to our kernel vector
  1021. int count(nrZeroIndices);
  1022. for ( SortedVectorSparse<double>::const_elementpointer i = nonzeroElements.begin(); i != nonzeroElements.end(); i++, count++ )
  1023. {
  1024. int origIndex(i->second.first); //orig index (i->second.second would be the transformed feature value)
  1025. if (count <= position)
  1026. kstar[origIndex] += i->first; //orig feature value
  1027. else
  1028. kstar[origIndex] += fval;
  1029. }
  1030. }
  1031. }
  1032. // ---------------------- STORE AND RESTORE FUNCTIONS ----------------------
  1033. void FastMinKernel::restore ( std::istream & is, int format )
  1034. {
  1035. if (is.good())
  1036. {
  1037. is.precision (numeric_limits<double>::digits10 + 1);
  1038. string tmp;
  1039. is >> tmp; //class name
  1040. is >> tmp;
  1041. is >> n;
  1042. is >> tmp;
  1043. is >> d;
  1044. is >> tmp;
  1045. is >> noise;
  1046. is >> tmp;
  1047. int approxSchemeInt;
  1048. is >> approxSchemeInt;
  1049. setApproximationScheme(approxSchemeInt);
  1050. X_sorted.restore(is,format);
  1051. }
  1052. else
  1053. {
  1054. std::cerr << "FastMinKernel::restore -- InStream not initialized - restoring not possible!" << std::endl;
  1055. }
  1056. }
  1057. void FastMinKernel::store ( std::ostream & os, int format ) const
  1058. {
  1059. if (os.good())
  1060. {
  1061. os.precision (numeric_limits<double>::digits10 + 1);
  1062. os << "FastMinKernel" << std::endl;
  1063. os << "n: " << n << std::endl;
  1064. os << "d: " << d << std::endl;
  1065. os << "noise: " << noise << std::endl;
  1066. os << "approxScheme: " << approxScheme << std::endl;
  1067. X_sorted.store(os,format);
  1068. }
  1069. else
  1070. {
  1071. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  1072. }
  1073. }
  1074. void FastMinKernel::clear ()
  1075. {
  1076. std::cerr << "FastMinKernel clear-function called" << std::endl;
  1077. }
  1078. void FastMinKernel::setVerbose( const bool & _verbose)
  1079. {
  1080. verbose = _verbose;
  1081. }
  1082. bool FastMinKernel::getVerbose( ) const
  1083. {
  1084. return verbose;
  1085. }
  1086. void FastMinKernel::setDebug( const bool & _debug)
  1087. {
  1088. debug = _debug;
  1089. X_sorted.setDebug( _debug );
  1090. }
  1091. bool FastMinKernel::getDebug( ) const
  1092. {
  1093. return debug;
  1094. }
  1095. // ----------------- INCREMENTAL LEARNING METHODS -----------------------
  1096. void FastMinKernel::addExample(const NICE::SparseVector & _v, const ParameterizedFunction *pf )
  1097. {
  1098. X_sorted.add_feature(_v, pf );
  1099. n++;
  1100. }
  1101. void FastMinKernel::addExample(const std::vector<double> & _v, const ParameterizedFunction *pf )
  1102. {
  1103. X_sorted.add_feature(_v, pf );
  1104. n++;
  1105. }
  1106. void FastMinKernel::updatePreparationForAlphaMultiplications(const NICE::SparseVector & _v, const double & alpha, NICE::VVector & A, NICE::VVector & B, const ParameterizedFunction *pf) const
  1107. {
  1108. NICE::SparseVector::const_iterator it = _v.begin();
  1109. for (int dim = 0; dim < this->d; dim++)
  1110. {
  1111. if (it->first == dim)
  1112. {
  1113. //increase both datastructures by one
  1114. A[dim].append(0.0);
  1115. B[dim].append(0.0);
  1116. //this is the index of the new example in this dimension, which was already added
  1117. int idx;
  1118. X_sorted.findLastInDimension(dim, it->second, idx);
  1119. //actually we do not want to have the next position, but the current one
  1120. idx--;
  1121. // and we do not care about zero elements since we store matrices A and B only for non-zero elements in the training data
  1122. idx -= X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1123. // we start using the last old element, which is located at size-2
  1124. for( int i = A[dim].size()-2; i >= (idx-1); i--)
  1125. {
  1126. if (pf != NULL)
  1127. A[dim][i+1] = A[dim][i] + alpha * pf->f ( 1, it->second );
  1128. else
  1129. {
  1130. A[dim][i+1] = A[dim][i] + alpha * it->second;
  1131. }
  1132. }
  1133. // remember: in contrast to the explanations in our ECCV-paper, we store the alpha-values of the INCREASINGLY ordered features
  1134. // in the matrix B, not in decreasing order
  1135. for (int i = B[dim].size()-1; i >= std::max(1,idx); i--)
  1136. {
  1137. B[dim][i] = B[dim][i-1] + alpha;
  1138. }
  1139. //special case
  1140. if (idx == 0)
  1141. {
  1142. if (pf != NULL)
  1143. A[dim][0] = alpha * pf->f ( 1, it->second );
  1144. else
  1145. A[dim][0] = alpha * it->second;
  1146. B[dim][0] = alpha;
  1147. }
  1148. it++;
  1149. }
  1150. else //_v is zero for that dimension
  1151. {
  1152. //nothing to do, since we do not store any information about zero elements
  1153. }
  1154. }
  1155. }
  1156. void FastMinKernel::updateLookupTableForAlphaMultiplications(const NICE::SparseVector & _v, const double & alpha, double * T, const Quantization & q, const ParameterizedFunction *pf) const
  1157. {
  1158. //be aware, index n-1 is only valid, if we do not explicitely changed the indices while inserting elements
  1159. //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
  1160. // this->hikUpdateLookupTable(T, alpha, 0.0, n-1, q, pf );
  1161. if (T == NULL)
  1162. {
  1163. fthrow(Exception, "FastMinKernel::updateLookupTableForAlphaMultiplications LUT not initialized, run FastMinKernel::hikPrepareLookupTable first!");
  1164. return;
  1165. }
  1166. // number of quantization bins
  1167. uint hmax = q.size();
  1168. // store (transformed) prototypes
  1169. double *prototypes = new double [ hmax ];
  1170. for ( uint i = 0 ; i < hmax ; i++ )
  1171. if ( pf != NULL ) {
  1172. // FIXME: the transformed prototypes could change from dimension to another dimension
  1173. // We skip this flexibility ...but it should be changed in the future
  1174. prototypes[i] = pf->f ( 1, q.getPrototype(i) );
  1175. } else {
  1176. prototypes[i] = q.getPrototype(i);
  1177. }
  1178. // loop through all dimensions
  1179. for (NICE::SparseVector::const_iterator it = _v.begin(); it != _v.end(); it++)
  1180. {
  1181. int dim(it->first);
  1182. double x_i = it->second;
  1183. //as usually, we quantize the original features, but use the quantized transformed features lateron
  1184. int q_bin = q.quantize(x_i);
  1185. //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
  1186. for (uint j = 0; j < hmax; j++)
  1187. {
  1188. double fval;
  1189. if (q_bin > j)
  1190. fval = prototypes[j]; //the prototypes are already transformed
  1191. else
  1192. {
  1193. if (pf != NULL)
  1194. fval = pf->f( 1, x_i );
  1195. else
  1196. fval = x_i;
  1197. }
  1198. // pay attention: we use either the quantized prototypes or the REAL feature values, not the quantized ones!
  1199. T[ dim*hmax + j ] += alpha*fval;
  1200. }
  1201. }
  1202. delete [] prototypes;
  1203. }
  1204. void FastMinKernel::updatePreparationForKVNApproximation(const NICE::SparseVector & _v, NICE::VVector & A, const ParameterizedFunction *pf) const
  1205. {
  1206. for (NICE::SparseVector::const_iterator it = _v.begin(); it != _v.end(); it++)
  1207. {
  1208. int dim(it->first);
  1209. int idx;
  1210. // we use the original feature value for this search, not the transformed one (see FeatureMatrixT)
  1211. // we assume that the nex example was already inserted to the FeatureMatrix
  1212. X_sorted.findLastInDimension(dim, it->second, idx);
  1213. //we do not want to considere zero elements, since we store it in a sparse way
  1214. idx -= X_sorted.getNumberOfZeroElementsPerDimension(dim);
  1215. // not the next one, but the current (position vs index)
  1216. idx--;
  1217. // perform a resize operations, since we have a new element
  1218. A[dim].resize(A[dim].size()+1);
  1219. // update :)
  1220. for( int i = A[dim].size()-1; i >= idx; i--)
  1221. {
  1222. if (pf != NULL)
  1223. A[dim][i] = A[dim][i-1] + pow(pf->f ( 1, it->second ), 2);
  1224. else
  1225. A[dim][i] = A[dim][i-1] + pow(it->second, 2);
  1226. }
  1227. }
  1228. }
  1229. void FastMinKernel::updateLookupTableForKVNApproximation(const NICE::SparseVector & _v, double * T, const Quantization & q, const ParameterizedFunction *pf) const
  1230. {
  1231. if (T == NULL)
  1232. {
  1233. fthrow(Exception, "FastMinKernel::updateLookupTableForKernelVectorNorm LUT not initialized, run FastMinKernel::hikPrepareLookupTableForKernelVectorNorm first!");
  1234. return;
  1235. }
  1236. // number of quantization bins
  1237. uint hmax = q.size();
  1238. // store (transformed) prototypes
  1239. double *prototypes = new double [ hmax ];
  1240. for ( uint i = 0 ; i < hmax ; i++ )
  1241. if ( pf != NULL ) {
  1242. // FIXME: the transformed prototypes could change from dimension to another dimension
  1243. // We skip this flexibility ...but it should be changed in the future
  1244. prototypes[i] = pf->f ( 1, q.getPrototype(i) );
  1245. } else {
  1246. prototypes[i] = q.getPrototype(i);
  1247. }
  1248. // loop through all dimensions
  1249. for (NICE::SparseVector::const_iterator it = _v.begin(); it != _v.end(); it++)
  1250. {
  1251. int dim(it->first);
  1252. double x_i = it->second;
  1253. //as usually, we quantize the original features, but use the quantized transformed features lateron
  1254. int q_bin = q.quantize(x_i);
  1255. //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
  1256. for (uint j = 0; j < hmax; j++)
  1257. {
  1258. double fval;
  1259. if (q_bin > j)
  1260. fval = prototypes[j]; //the prototypes are already transformed
  1261. else
  1262. {
  1263. if (pf != NULL)
  1264. fval = pf->f( 1, x_i );
  1265. else
  1266. fval = x_i;
  1267. }
  1268. // pay attention: we use either the quantized prototypes or the REAL feature values, not the quantized ones!
  1269. T[ dim*hmax + j ] += pow( fval, 2 );
  1270. }
  1271. }
  1272. delete [] prototypes;
  1273. }