FastMinKernel.cpp 50 KB

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