FastMinKernel.cpp 52 KB

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