FastMinKernel.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /**
  2. * @file FastMinKernel.h
  3. * @brief Efficient GPs with HIK for classification by regression (Interface)
  4. * @author Alexander Freytag
  5. * @date 06-12-2011 (dd-mm-yyyy)
  6. */
  7. #ifndef FASTMINKERNELINCLUDE
  8. #define FASTMINKERNELINCLUDE
  9. // STL includes
  10. #include <iostream>
  11. // NICE-core includes
  12. #include <core/basics/Config.h>
  13. #include <core/basics/Exception.h>
  14. #include <core/basics/Persistent.h>
  15. //
  16. //
  17. #include <core/vector/MatrixT.h>
  18. #include <core/vector/SparseVectorT.h>
  19. #include <core/vector/VectorT.h>
  20. #include <core/vector/VVector.h>
  21. // gp-hik-core includes
  22. #include "gp-hik-core/FeatureMatrixT.h"
  23. #include "gp-hik-core/OnlineLearnable.h"
  24. #include "gp-hik-core/Quantization.h"
  25. #include "gp-hik-core/parameterizedFunctions/ParameterizedFunction.h"
  26. namespace NICE {
  27. /**
  28. * @class FastMinKernel
  29. * @brief Efficient GPs with HIK for classification by regression
  30. * @author Alexander Freytag
  31. */
  32. /** interface to FastMinKernel implementation*/
  33. class FastMinKernel : public NICE::Persistent, public OnlineLearnable
  34. {
  35. protected:
  36. /** number of examples */
  37. uint ui_n;
  38. /** dimension of feature vectors */
  39. uint ui_d;
  40. /** noise added to the diagonal of the kernel matrix */
  41. double d_noise;
  42. /** sorted matrix of features (sorted along each dimension) */
  43. NICE::FeatureMatrixT<double> X_sorted;
  44. //! verbose flag for output after calling the restore-function
  45. bool b_verbose;
  46. //! debug flag for output during debugging
  47. bool b_debug;
  48. /**
  49. * @brief Set number of examples
  50. * @author Alexander Freytag
  51. * @date 07-12-2011 (dd-mm-yyyy)
  52. */
  53. void set_n(const uint & _n){this->ui_n = _n;};
  54. /**
  55. * @brief Set number of dimensions
  56. * @author Alexander Freytag
  57. * @date 07-12-2011 (dd-mm-yyyy)
  58. */
  59. void set_d(const uint & _d){this->ui_d = _d;};
  60. void randomPermutation(NICE::Vector & _permutation,
  61. const std::vector<uint> & _oldIndices,
  62. const uint & _newSize
  63. ) const;
  64. enum ApproximationScheme{ MEDIAN = 0, EXPECTATION=1};
  65. ApproximationScheme approxScheme;
  66. public:
  67. //------------------------------------------------------
  68. // several constructors and destructors
  69. //------------------------------------------------------
  70. /**
  71. * @brief default constructor
  72. * @author Alexander Freytag
  73. * @date 20-04-2012 (dd-mm-yyyy)
  74. */
  75. FastMinKernel();
  76. /**
  77. * @brief recommended constructor, initialize with some data
  78. * @author Alexander Freytag
  79. * @date 06-12-2011 (dd-mm-yyyy)
  80. */
  81. FastMinKernel( const std::vector<std::vector<double> > & _X,
  82. const double _noise ,
  83. const bool _debug = false,
  84. const uint & _dim = 0
  85. );
  86. /**
  87. * @brief recommended constructor, just another sparse data structure
  88. *
  89. * @param X vector of sparse vector pointers
  90. * @param noise GP noise
  91. */
  92. FastMinKernel( const std::vector< const NICE::SparseVector * > & _X,
  93. const double _noise,
  94. const bool _debug = false,
  95. const bool & dimensionsOverExamples=false,
  96. const uint & _dim = 0
  97. );
  98. #ifdef NICE_USELIB_MATIO
  99. /**
  100. * @brief recommended constructor, intialize with some data given in a matlab-sparse struct and restricted with an example index
  101. *
  102. * @param X matlab-struct containing the feature vectors
  103. * @param noise additional noise variance of the labels
  104. * @param examples set of indices to include
  105. */
  106. FastMinKernel ( const sparse_t & _X,
  107. const double _noise,
  108. const std::map<uint, uint> & _examples,
  109. const bool _debug = false ,
  110. const uint & _dim = 0);
  111. #endif
  112. /**
  113. * @brief Default destructor
  114. * @author Alexander Freytag
  115. * @date 06-12-2011 (dd-mm-yyyy)
  116. */
  117. ~FastMinKernel();
  118. ///////////////////// ///////////////////// /////////////////////
  119. // GET / SET
  120. // INCLUDING ACCESS OPERATORS
  121. ///////////////////// ///////////////////// /////////////////////
  122. void setApproximationScheme(const ApproximationScheme & _approxScheme = MEDIAN) {approxScheme = _approxScheme;};
  123. virtual void setApproximationScheme(const int & _approxScheme = 0);
  124. /**
  125. * @brief Get number of examples
  126. * @author Alexander Freytag
  127. * @date 07-12-2011 (dd-mm-yyyy)
  128. */
  129. uint get_n() const;
  130. /**
  131. * @brief Get number of dimensions
  132. * @author Alexander Freytag
  133. * @date 07-12-2011 (dd-mm-yyyy)
  134. */
  135. uint get_d() const;
  136. /**
  137. * @brief Computes the ratio of sparsity across the matrix
  138. * @author Alexander Freytag
  139. * @date 11-01-2012 (dd-mm-yyyy)
  140. */
  141. double getSparsityRatio() const;
  142. /** set verbose flag used for restore-functionality*/
  143. void setVerbose( const bool & _verbose);
  144. bool getVerbose( ) const;
  145. /** set debug flag used for debug output*/
  146. void setDebug( const bool & _debug);
  147. bool getDebug( ) const;
  148. //------------------------------------------------------
  149. // high level methods
  150. //------------------------------------------------------
  151. /**
  152. * @brief apply a parameterized function to the feature matrix
  153. * @author Alexander Freytag
  154. * @date 04-05-2012 (dd-mm-yyyy)
  155. *
  156. * @param pf the parameterized function (optional), if not given, nothing will be done
  157. */
  158. void applyFunctionToFeatureMatrix ( const NICE::ParameterizedFunction *_pf = NULL );
  159. /**
  160. * @brief Prepare the efficient HIK-computations part 2: calculate the partial sum for each dimension. Explicitely exploiting sparsity!!! Pay attention: X_sorted is of dimensionality d x n!
  161. * @author Alexander Freytag
  162. * @date 17-01-2012 (dd-mm-yyyy)
  163. */
  164. void hik_prepare_alpha_multiplications(const NICE::Vector & _alpha,
  165. NICE::VVector & _A,
  166. NICE::VVector & _B
  167. ) const;
  168. /**
  169. * @brief Computing K*alpha with the minimum kernel trick, explicitely exploiting sparsity!!!
  170. * @author Alexander Freytag
  171. * @date 17-01-2012 (dd-mm-yyyy)
  172. */
  173. void hik_kernel_multiply(const NICE::VVector & _A,
  174. const NICE::VVector & _B,
  175. const NICE::Vector & _alpha,
  176. NICE::Vector & _beta
  177. ) const;
  178. void hik_kernel_multiply_fast(const double *_Tlookup,
  179. const Quantization & _q,
  180. const NICE::Vector & _alpha,
  181. NICE::Vector & _beta
  182. ) const;
  183. /**
  184. * @brief Computing k_{*}*alpha using the minimum kernel trick and exploiting sparsity of the feature vector given
  185. *
  186. * @author Alexander Freytag
  187. * @date 20-01-2012 (dd-mm-yyyy)
  188. * @param A pre-computation matrix (VVector) (use the prepare method)
  189. * @param B pre-computation matrix (VVector)
  190. * @param xstar new feature vector (SparseVector)
  191. * @param beta result of the scalar product
  192. * @param pf optional feature transformation
  193. */
  194. void hik_kernel_sum(const NICE::VVector & _A,
  195. const NICE::VVector & _B,
  196. const NICE::SparseVector & _xstar,
  197. double & _beta,
  198. const ParameterizedFunction *_pf = NULL
  199. ) const;
  200. /**
  201. * @brief Computing k_{*}*alpha using the minimum kernel trick and exploiting sparsity of the feature vector given
  202. * NOTE: Whenever possible, you should use sparse features to obtain significantly smaller computation times!
  203. *
  204. * @author Alexander Freytag
  205. * @date 18-06-2013 (dd-mm-yyyy)
  206. * @param A pre-computation matrix (VVector) (use the prepare method)
  207. * @param B pre-computation matrix (VVector)
  208. * @param xstar new feature vector (non-sparse Vector)
  209. * @param beta result of the scalar product
  210. * @param pf optional feature transformation
  211. */
  212. void hik_kernel_sum(const NICE::VVector & _A,
  213. const NICE::VVector & _B,
  214. const NICE::Vector & _xstar,
  215. double & _beta,
  216. const ParameterizedFunction *_pf = NULL
  217. ) const;
  218. /**
  219. * @brief compute beta = k_*^T * alpha by using a large lookup table created by hik_prepare_alpha_multiplications_fast
  220. * NOTE: Whenever possible, you should use sparse features to obtain significantly smaller computation times!
  221. * @author Alexander Freytag
  222. * @date 18-06-2013 (dd-mm-yyyy)
  223. *
  224. * @param Tlookup large lookup table calculated by hik_prepare_alpha_multiplications_fast
  225. * @param q Quantization object
  226. * @param xstar feature vector (indirect k_*)
  227. * @param beta result of the calculation
  228. */
  229. void hik_kernel_sum_fast(const double* _Tlookup,
  230. const Quantization & _q,
  231. const NICE::Vector & _xstar,
  232. double & _beta
  233. ) const;
  234. /**
  235. * @brief compute beta = k_*^T * alpha by using a large lookup table created by hik_prepare_alpha_multiplications_fast
  236. * NOTE: Whenever possible, you should use sparse features to obtain significantly smaller computation times!
  237. * @author Alexander Frytag
  238. *
  239. * @param Tlookup large lookup table calculated by hik_prepare_alpha_multiplications_fast
  240. * @param q Quantization object
  241. * @param xstar feature vector (indirect k_*)
  242. * @param beta result of the calculation
  243. */
  244. void hik_kernel_sum_fast(const double *_Tlookup,
  245. const Quantization & _q,
  246. const NICE::SparseVector & _xstar,
  247. double & _beta
  248. ) const;
  249. /**
  250. * @brief compute lookup table for HIK calculation using quantized signals and prepare for K*alpha or k_*^T * alpha computations,
  251. * whenever possible use hikPrepareLookupTable directly.
  252. * @author Erik Rodner, Alexander Freytag
  253. *
  254. * @param alpha coefficient vector
  255. * @param A pre-calculation array computed by hik_prepare_alpha_multiplications
  256. * @param B pre-calculation array computed by hik_prepare_alpha_multiplications
  257. * @param q Quantization
  258. *
  259. * @return C standard vector representing a q.size()*n double matrix and the lookup table T. Elements can be accessed with
  260. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  261. */
  262. double *hik_prepare_alpha_multiplications_fast(const NICE::VVector & _A,
  263. const NICE::VVector & _B,
  264. const Quantization & _q,
  265. const ParameterizedFunction *_pf = NULL
  266. ) const;
  267. /**
  268. * @brief compute lookup table for HIK calculation using quantized signals and prepare for K*alpha or k_*^T * alpha computations
  269. * @author Alexander Freytag
  270. *
  271. * @param alpha coefficient vector
  272. * @param q Quantization
  273. * @param pf ParameterizedFunction to change the original feature values
  274. *
  275. * @return C standard vector representing a q.size()*n double matrix and the lookup table T. Elements can be accessed with
  276. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  277. */
  278. double* hikPrepareLookupTable(const NICE::Vector & _alpha,
  279. const Quantization & _q,
  280. const ParameterizedFunction *_pf = NULL
  281. ) const;
  282. /**
  283. * @brief update the lookup table for HIK calculation using quantized signals and prepare for K*alpha or k_*^T * alpha computations
  284. * @author Alexander Freytag
  285. *
  286. * @param T previously computed LUT, that will be changed
  287. * @param alphaNew new value of alpha at index idx
  288. * @param alphaOld old value of alpha at index idx
  289. * @param idx index in which alpha changed
  290. * @param q Quantization
  291. * @param pf ParameterizedFunction to change the original feature values
  292. */
  293. void hikUpdateLookupTable(double * _T,
  294. const double & _alphaNew,
  295. const double & _alphaOld,
  296. const uint & _idx,
  297. const Quantization & _q,
  298. const ParameterizedFunction *pf
  299. ) const;
  300. /**
  301. * @brief return a reference to the sorted feature matrix
  302. */
  303. FeatureMatrix & featureMatrix(void) { return X_sorted; };
  304. const FeatureMatrix & featureMatrix(void) const { return X_sorted; };
  305. /**
  306. * @brief solve the linear system K*alpha = y with the minimum kernel trick based on the algorithm of Wu (Wu10_AFD)
  307. * @note method converges slowly for large scale problems and even for normal scale :(
  308. * @author Paul Bodesheim
  309. *
  310. * @param y right hand side of linear system
  311. * @param alpha final solution of the linear system
  312. * @param q Quantization
  313. * @param pf ParameterizedFunction to change the original feature values
  314. * @param useRandomSubsets true, if the order of examples in each iteration should be randomly sampled
  315. * @param maxIterations maximum number of iterations
  316. * @param sizeOfRandomSubset nr of Elements that should be randomly considered in each iteration (max: y.size())
  317. * @param minDelta minimum difference between two solutions alpha_t and alpha_{t+1} (convergence criterion)
  318. *
  319. * @return C standard vector representing a q.size()*n double matrix and the lookup table T. Elements can be accessed with
  320. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  321. **/
  322. double *solveLin(const NICE::Vector & _y,
  323. NICE::Vector & _alpha,
  324. const Quantization & _q,
  325. const ParameterizedFunction *_pf = NULL,
  326. const bool & _useRandomSubsets = true,
  327. uint _maxIterations = 10000,
  328. const uint & _sizeOfRandomSubset = 0,
  329. double _minDelta = 1e-7,
  330. bool _timeAnalysis = false
  331. ) const;
  332. //! set the noise parameter
  333. void setNoise ( double _noise ) { this->d_noise = _noise; }
  334. //! get the current noise parameter
  335. double getNoise (void) const { return this->d_noise; }
  336. double getFrobNormApprox();
  337. /**
  338. * @brief Prepare the efficient HIK-computations for the squared kernel vector |k_*|^2 : calculate the partial squared sums for each dimension.
  339. * @author Alexander Freytag
  340. * @date 10-04-2012 (dd-mm-yyyy)
  341. */
  342. void hikPrepareKVNApproximation(NICE::VVector & _A) const;
  343. /**
  344. * @brief Compute lookup table for HIK calculation of |k_*|^2 assuming quantized test samples. You have to run hikPrepareSquaredKernelVector before
  345. * @author Alexander Freytag
  346. * @date 10-04-2012 (dd-mm-yyyy)
  347. *
  348. * @param A pre-calculation array computed by hikPrepareSquaredKernelVector
  349. * @param q Quantization
  350. * @param pf Parameterized Function to efficiently apply a function to the underlying data
  351. *
  352. * @return C standard vector representing a q.size()*d double matrix and the lookup table T. Elements can be accessed with
  353. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  354. */
  355. double * hikPrepareKVNApproximationFast(NICE::VVector & _A, const Quantization & _q, const ParameterizedFunction *_pf = NULL ) const;
  356. /**
  357. * @brief Compute lookup table for HIK calculation of |k_*|^2 assuming quantized test samples ( equals hikPrepareSquaredKernelVector + hikPrepareSquaredKernelVectorFast, but is faster). Approximation does not considere mixed terms between dimensions.
  358. * @author Alexander Freytag
  359. * @date 10-04-2012 (dd-mm-yyyy)
  360. *
  361. * @param q Quantization
  362. * @param pf ParameterizedFunction to change the original feature values
  363. *
  364. * @return C standard vector representing a q.size()*d double matrix and the lookup table T. Elements can be accessed with
  365. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  366. */
  367. double* hikPrepareLookupTableForKVNApproximation(const Quantization & _q, const ParameterizedFunction *_pf = NULL) const;
  368. //////////////////////////////////////////
  369. // variance computation: sparse inputs
  370. //////////////////////////////////////////
  371. /**
  372. * @brief Approximate norm = |k_*|^2 using the minimum kernel trick and exploiting sparsity of the given feature vector. Approximation does not considere mixed terms between dimensions.
  373. * @author Alexander Freytag
  374. * @date 10-04-2012 (dd-mm-yyyy)
  375. *
  376. * @param A pre-computation matrix (VVector) (use the prepare method)
  377. * @param xstar new feature vector (SparseVector)
  378. * @param norm result of the squared norm approximation
  379. * @param pf optional feature transformation
  380. */
  381. void hikComputeKVNApproximation(const NICE::VVector & _A, const NICE::SparseVector & _xstar, double & _norm, const ParameterizedFunction *_pf = NULL ) ;
  382. /**
  383. * @brief Approximate norm = |k_*|^2 using a large lookup table created by hikPrepareSquaredKernelVector and hikPrepareSquaredKernelVectorFast or directly using hikPrepareLookupTableForSquaredKernelVector. Approximation does not considere mixed terms between dimensions.
  384. * @author Alexander Freytag
  385. * @date 10-04-2012 (dd-mm-yyyy)
  386. *
  387. * @param Tlookup large lookup table
  388. * @param q Quantization object
  389. * @param xstar feature vector (indirect k_*)
  390. * @param norm result of the calculation
  391. */
  392. void hikComputeKVNApproximationFast(const double *_Tlookup, const Quantization & _q, const NICE::SparseVector & _xstar, double & _norm ) const;
  393. /**
  394. * @brief Compute the kernel vector k_* between training examples and test example. Runtime. O(n \times D). Exploiting sparsity
  395. * @author Alexander Freytag
  396. * @date 13-04-2012 (dd-mm-yyyy)
  397. *
  398. * @param xstar feature vector
  399. * @param kstar kernel vector
  400. */
  401. void hikComputeKernelVector( const NICE::SparseVector & _xstar, NICE::Vector & _kstar) const;
  402. //////////////////////////////////////////
  403. // variance computation: non-sparse inputs
  404. //////////////////////////////////////////
  405. /**
  406. * @brief Approximate norm = |k_*|^2 using the minimum kernel trick and exploiting sparsity of the given feature vector. Approximation does not considere mixed terms between dimensions.
  407. * @author Alexander Freytag
  408. * @date 19-12-2013 (dd-mm-yyyy)
  409. *
  410. * @param A pre-computation matrix (VVector) (use the prepare method)
  411. * @param xstar new feature vector (Vector)
  412. * @param norm result of the squared norm approximation
  413. * @param pf optional feature transformation
  414. */
  415. void hikComputeKVNApproximation(const NICE::VVector & _A, const NICE::Vector & _xstar, double & _norm, const ParameterizedFunction *_pf = NULL ) ;
  416. /**
  417. * @brief Approximate norm = |k_*|^2 using a large lookup table created by hikPrepareSquaredKernelVector and hikPrepareSquaredKernelVectorFast or directly using hikPrepareLookupTableForSquaredKernelVector. Approximation does not considere mixed terms between dimensions.
  418. * @author Alexander Freytag
  419. * @date 19-12-2013 (dd-mm-yyyy)
  420. *
  421. * @param Tlookup large lookup table
  422. * @param q Quantization object
  423. * @param xstar feature vector (indirect k_*)
  424. * @param norm result of the calculation
  425. */
  426. void hikComputeKVNApproximationFast(const double *_Tlookup, const Quantization & _q, const NICE::Vector & _xstar, double & _norm ) const;
  427. /**
  428. * @brief Compute the kernel vector k_* between training examples and test example. Runtime. O(n \times D). Does not exploit sparsity - deprecated!
  429. * @author Alexander Freytag
  430. * @date 19-12-2013 (dd-mm-yyyy)
  431. *
  432. * @param xstar feature vector
  433. * @param kstar kernel vector
  434. */
  435. void hikComputeKernelVector( const NICE::Vector & _xstar, NICE::Vector & _kstar) const;
  436. /** Persistent interface */
  437. virtual void restore ( std::istream & _is, int _format = 0 );
  438. virtual void store ( std::ostream & _os, int _format = 0 ) const;
  439. virtual void clear ();
  440. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  441. // interface specific methods for incremental extensions
  442. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  443. virtual void addExample( const NICE::SparseVector * _example,
  444. const double & _label,
  445. const bool & _performOptimizationAfterIncrement = true
  446. );
  447. virtual void addMultipleExamples( const std::vector< const NICE::SparseVector * > & _newExamples,
  448. const NICE::Vector & _newLabels,
  449. const bool & _performOptimizationAfterIncrement = true
  450. );
  451. /**
  452. * @brief Add a new example to the feature-storage. You have to update the corresponding variables explicitely after that.
  453. * @author Alexander Freytag
  454. * @date 02-01-2014 (dd-mm-yyyy)
  455. *
  456. * @param example new feature vector
  457. */
  458. void addExample(const NICE::SparseVector * _example, const NICE::ParameterizedFunction *_pf = NULL);
  459. /**
  460. * @brief Add multiple new example to the feature-storage. You have to update the corresponding variables explicitely after that.
  461. * @author Alexander Freytag
  462. * @date 02-01-2014 (dd-mm-yyyy)
  463. *
  464. * @param newExamples new feature vectors
  465. */
  466. void addMultipleExamples(const std::vector<const NICE::SparseVector * > & _newExamples, const NICE::ParameterizedFunction *_pf = NULL);
  467. };
  468. } // namespace
  469. #endif