FastMinKernel.cpp 48 KB

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