testLinsolvers.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /**
  2. * @file testImageNetBinary.cpp
  3. * @brief perform ImageNet tests with binary classification
  4. * @author Erik Rodner
  5. * @date 01/04/2012
  6. */
  7. #include "core/basics/Config.h"
  8. #include "core/algebra/IterativeLinearSolver.h"
  9. #include "core/algebra/PartialGenericMatrix.h"
  10. #include "core/algebra/GBCDSolver.h"
  11. #include "core/algebra/ILSConjugateGradients.h"
  12. #include <core/matlabAccess/MatFileIO.h>
  13. #include "vislearning/cbaselib/ClassificationResults.h"
  14. #include "vislearning/baselib/ProgressBar.h"
  15. #include <vislearning/matlabAccessHighLevel/ImageNetData.h>
  16. #include <gp-hik-core/kernels/IntersectionKernelFunction.h>
  17. #include <gp-hik-core/tools.h>
  18. #include <gp-hik-core/GMHIKernel.h>
  19. using namespace std;
  20. using namespace NICE;
  21. using namespace OBJREC;
  22. void selectExamples ( const Config *conf, const Vector & y, map<int, int> & examples, Vector & yb )
  23. {
  24. int positiveClass = conf->gI("main", "positive_class");
  25. map< int, set<int> > mysets;
  26. int n = y.size();
  27. set<int> positives;
  28. set<int> negatives;
  29. for ( uint i = 0 ; i < n; i++ )
  30. mysets[ y[i] ].insert ( i );
  31. if ( mysets[ positiveClass ].size() == 0 )
  32. fthrow(Exception, "Class " << positiveClass << " is not available.");
  33. // add our positive examples
  34. for ( set<int>::const_iterator i = mysets[positiveClass].begin(); i != mysets[positiveClass].end(); i++ )
  35. positives.insert ( *i );
  36. int Nneg = conf->gI("main", "nneg", 1 );
  37. for ( map<int, set<int> >::const_iterator k = mysets.begin(); k != mysets.end(); k++ )
  38. {
  39. int classno = k->first;
  40. if ( classno == positiveClass )
  41. continue;
  42. const set<int> & s = k->second;
  43. uint ind = 0;
  44. for ( set<int>::const_iterator i = s.begin(); (i != s.end() && ind < Nneg); i++,ind++ )
  45. negatives.insert ( *i );
  46. }
  47. cerr << "Number of positive examples: " << positives.size() << endl;
  48. cerr << "Number of negative examples: " << negatives.size() << endl;
  49. yb.resize(y.size());
  50. int ind = 0;
  51. for ( uint i = 0 ; i < y.size(); i++ )
  52. {
  53. if (positives.find(i) != positives.end()) {
  54. yb[ examples.size() ] = 1.0;
  55. examples.insert( pair<int, int> ( i, ind ) );
  56. ind++;
  57. } else if ( negatives.find(i) != negatives.end() ) {
  58. yb[ examples.size() ] = -1.0;
  59. examples.insert( pair<int, int> ( i, ind ) );
  60. ind++;
  61. }
  62. }
  63. yb.resize( examples.size() );
  64. cerr << "Examples: " << examples.size() << endl;
  65. }
  66. class BlockHIK : public PartialGenericMatrix
  67. {
  68. protected:
  69. const double *data;
  70. int n;
  71. int d;
  72. double noise;
  73. Vector diag;
  74. public:
  75. BlockHIK ( const double *data, int n, int d, double noise ) {
  76. this->data = data;
  77. this->n = n;
  78. this->d = d;
  79. this->noise = noise;
  80. diag.resize(n);
  81. for ( uint i = 0 ; i < n ; i++ )
  82. {
  83. double sum = 0.0;
  84. for ( uint dim = 0 ; dim < d ; dim++ )
  85. sum += data[i * d + dim];
  86. diag[i] = sum;
  87. }
  88. }
  89. /** multiply a sub-matrix with a given vector: Asub * xsub = ysub */
  90. virtual void multiply ( const SetType & rowSet, const SetType & columnSet, NICE::Vector & y, const NICE::Vector & x) const
  91. {
  92. Matrix K;
  93. if ( rowSet.size() == 0 || columnSet.size() == 0 )
  94. fthrow(Exception, "Sets are zero ...weird" );
  95. K.resize(rowSet.size(), columnSet.size());
  96. K.set(0.0);
  97. //run over every dimension and add the corresponding min-values to the entries in the kernel matrix
  98. int dimension = d;
  99. for (int dim = 0; dim < dimension; dim++)
  100. {
  101. int indi = 0;
  102. for ( SetType::const_iterator i = rowSet.begin(); i != rowSet.end(); i++, indi++ )
  103. {
  104. int indj = 0;
  105. int myi = *i;
  106. double vali = data[ myi * d + dim ];
  107. for ( SetType::const_iterator j = columnSet.begin(); j != columnSet.end(); j++, indj++ )
  108. {
  109. int myj = *j;
  110. double valj = data[ myj * d + dim ];
  111. double val = std::min ( valj, vali );
  112. if ( indi >= K.rows() || indj >= K.cols() )
  113. fthrow(Exception, "... weird indices!!" );
  114. K(indi,indj) += val;
  115. if ( myi == myj )
  116. K(indi, indj) += noise / dimension;
  117. }
  118. }
  119. }//dim-loop
  120. y.resize( rowSet.size() );
  121. y = K*x;
  122. }
  123. /** multiply with a vector: A*x = y */
  124. virtual void multiply (NICE::Vector & y, const NICE::Vector & x) const
  125. {
  126. fthrow(Exception, "You do not really want to compute kernel matrices as big as this one!");
  127. }
  128. virtual double getDiagonalElement ( uint i ) const
  129. {
  130. return diag[i] + noise;
  131. }
  132. virtual uint rows() const
  133. {
  134. return n;
  135. }
  136. virtual uint cols() const
  137. {
  138. return n;
  139. }
  140. };
  141. double *createFlatData ( const FeatureMatrix & f )
  142. {
  143. int n = f.get_n();
  144. int d = f.get_d();
  145. double *data = new double [ n * d ];
  146. memset ( data, 0, n*d*sizeof(double) );
  147. for (int dim = 0; dim < d; dim++)
  148. {
  149. const multimap< double, SortedVectorSparse<double>::dataelement> & nonzeroElements = f.getFeatureValues(dim).nonzeroElements();
  150. int nrZeroIndices = f.getNumberOfZeroElementsPerDimension(dim);
  151. if ( nrZeroIndices == n ) continue;
  152. for ( multimap< double, SortedVectorSparse<double>::dataelement>::const_iterator i = nonzeroElements.begin(); i != nonzeroElements.end(); i++)
  153. {
  154. const SortedVectorSparse<double>::dataelement & de = i->second;
  155. uint feat = de.first;
  156. double fval = de.second;
  157. data[ feat*d + dim ] = fval;
  158. }
  159. }
  160. return data;
  161. }
  162. /**
  163. test the basic functionality of fast-hik hyperparameter optimization
  164. */
  165. int main (int argc, char **argv)
  166. {
  167. std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
  168. Config conf ( argc, argv );
  169. string resultsfile = conf.gS("main", "results", "results.txt" );
  170. int positiveClass = conf.gI("main", "positive_class");
  171. cerr << "Positive class is " << positiveClass << endl;
  172. sparse_t data;
  173. NICE::Vector y;
  174. cerr << "Reading ImageNet data ..." << endl;
  175. bool imageNetLocal = conf.gB("main", "imageNetLocal" , false);
  176. string imageNetPath;
  177. if (imageNetLocal)
  178. imageNetPath = "/users2/rodner/data/imagenet/devkit-1.0/";
  179. else
  180. imageNetPath = "/home/dbv/bilder/imagenet/devkit-1.0/";
  181. ImageNetData imageNet ( imageNetPath + "demo/" );
  182. imageNet.getBatchData ( data, y, "train", "training" );
  183. map<int, int> examples;
  184. Vector yb;
  185. selectExamples ( &conf, y, examples, yb );
  186. double noise = conf.gD("main", "noise", 10);
  187. int dimension = conf.gI("main", "dimension", 1000);
  188. int numBins = conf.gI("main", "num_bins", 100);
  189. Quantization q ( numBins );
  190. FastMinKernel fmk ( data, noise, examples, dimension );
  191. GMHIKernel gmk ( &fmk );
  192. bool verbose = true;
  193. int max_iterations = 500;
  194. vector< IterativeLinearSolver * > methods;
  195. ILSConjugateGradients *m = new ILSConjugateGradients(verbose, max_iterations);
  196. m->setTimeAnalysis ( true );
  197. methods.push_back ( m );
  198. for ( vector< IterativeLinearSolver * >::const_iterator i = methods.begin();
  199. i != methods.end(); i++ )
  200. {
  201. IterativeLinearSolver *method = *i;
  202. Vector sol (gmk.cols(), 0.0);
  203. method->solveLin ( gmk, yb, sol );
  204. }
  205. Vector sol ( gmk.cols(), 0.0 );
  206. double *Tlookup = fmk.solveLin( yb, sol, q, NULL, true /* useRandomSubsets */, 100 /* max iterations */, -1, 0.0, true);
  207. int randomSetSize = conf.gI("main", "random_set_size", 60);
  208. int stepComponents = conf.gI("main", "step_components", 50);
  209. GBCDSolver gbcd ( randomSetSize, stepComponents, true );
  210. gbcd.setTimeAnalysis(true);
  211. Vector sol_gbcd;
  212. double *cdata = createFlatData ( fmk.featureMatrix() );
  213. BlockHIK bhik ( cdata, fmk.get_n(), fmk.get_d(), noise );
  214. gbcd.solveLin ( bhik, yb, sol_gbcd );
  215. delete [] cdata;
  216. return 0;
  217. }