testImageNetBinaryGPBaseline.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /**
  2. * @file testImageNetBinaryGPBaseline.cpp
  3. * @brief perform ImageNet tests with binary tasks for OCC using the baseline GP
  4. * @author Alexander Lütz
  5. * @date 29-05-2012 (dd-mm-yyyy)
  6. */
  7. #include "core/basics/Config.h"
  8. #ifdef NICE_USELIB_MATIO
  9. #include "core/basics/Timer.h"
  10. #include "core/vector/SparseVectorT.h"
  11. #include "core/algebra/CholeskyRobust.h"
  12. #include "core/vector/Algorithms.h"
  13. #include "vislearning/cbaselib/ClassificationResults.h"
  14. #include "vislearning/baselib/ProgressBar.h"
  15. #include "core/matlabAccess/MatFileIO.h"
  16. #include "vislearning/matlabAccessHighLevel/ImageNetData.h"
  17. // #include "fast-hik/tools.h"
  18. using namespace std;
  19. using namespace NICE;
  20. using namespace OBJREC;
  21. double measureDistance ( const NICE::SparseVector & a, const NICE::SparseVector & b, const double & sigma = 2.0)//, const bool & verbose = false)
  22. {
  23. double inner_sum(0.0);
  24. double d;
  25. //new version, where we needed on average 0.001707 s for each test sample
  26. NICE::SparseVector::const_iterator aIt = a.begin();
  27. NICE::SparseVector::const_iterator bIt = b.begin();
  28. while ( (aIt != a.end()) && (bIt != b.end()) )
  29. {
  30. if (aIt->first == bIt->first)
  31. {
  32. d = ( aIt->second - bIt->second );
  33. inner_sum += d * d;
  34. aIt++;
  35. bIt++;
  36. }
  37. else if ( aIt->first < bIt->first)
  38. {
  39. inner_sum += aIt->second * aIt->second;
  40. aIt++;
  41. }
  42. else
  43. {
  44. inner_sum += bIt->second * bIt->second;
  45. bIt++;
  46. }
  47. }
  48. //compute remaining values, if b reached the end but not a
  49. while (aIt != a.end())
  50. {
  51. inner_sum += aIt->second * aIt->second;
  52. aIt++;
  53. }
  54. //compute remaining values, if a reached the end but not b
  55. while (bIt != b.end())
  56. {
  57. inner_sum += bIt->second * bIt->second;
  58. bIt++;
  59. }
  60. inner_sum /= (2.0*sigma*sigma);
  61. return exp(-inner_sum); //expValue;
  62. }
  63. void readParameters(const string & filename, const int & size, NICE::Vector & parameterVector)
  64. {
  65. parameterVector.resize(size);
  66. parameterVector.set(0.0);
  67. ifstream is(filename.c_str());
  68. if ( !is.good() )
  69. fthrow(IOException, "Unable to read parameters.");
  70. //
  71. string tmp;
  72. int cnt(0);
  73. while (! is.eof())
  74. {
  75. is >> tmp;
  76. parameterVector[cnt] = atof(tmp.c_str());
  77. cnt++;
  78. }
  79. //
  80. is.close();
  81. }
  82. /**
  83. test the basic functionality of fast-hik hyperparameter optimization
  84. */
  85. int main (int argc, char **argv)
  86. {
  87. std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
  88. Config conf ( argc, argv );
  89. string resultsfile = conf.gS("main", "results", "results.txt" );
  90. double kernelSigma = conf.gD("main", "kernelSigma", 2.0);
  91. int nrOfExamplesPerClass = conf.gI("main", "nrOfExamplesPerClass", 50);
  92. nrOfExamplesPerClass = std::min(nrOfExamplesPerClass, 100); // we do not have more than 100 examples per class
  93. int nrOfClassesToConcidere = conf.gI("main", "nrOfClassesToConcidere", 1000);
  94. nrOfClassesToConcidere = std::min(nrOfClassesToConcidere, 1000); //we do not have more than 1000 classes
  95. string sigmaFile = conf.gS("main", "sigmaFile", "approxVarSigma.txt");
  96. string noiseFile = conf.gS("main", "noiseFile", "approxVarNoise.txt");
  97. NICE::Vector sigmaParas(nrOfClassesToConcidere,kernelSigma);
  98. NICE::Vector noiseParas(nrOfClassesToConcidere,0.0);
  99. readParameters(sigmaFile,nrOfClassesToConcidere, sigmaParas);
  100. readParameters(noiseFile,nrOfClassesToConcidere, noiseParas);
  101. std::vector<SparseVector> trainingData;
  102. NICE::Vector y;
  103. std::cerr << "Reading ImageNet data ..." << std::endl;
  104. bool imageNetLocal = conf.gB("main", "imageNetLocal" , false);
  105. string imageNetPath;
  106. if (imageNetLocal)
  107. imageNetPath = "/users2/rodner/data/imagenet/devkit-1.0/";
  108. else
  109. imageNetPath = "/home/dbv/bilder/imagenet/devkit-1.0/";
  110. ImageNetData imageNetTrain ( imageNetPath + "demo/" );
  111. imageNetTrain.preloadData( "train", "training" );
  112. trainingData = imageNetTrain.getPreloadedData();
  113. y = imageNetTrain.getPreloadedLabels();
  114. std::cerr << "Reading of training data finished" << std::endl;
  115. std::cerr << "trainingData.size(): " << trainingData.size() << std::endl;
  116. std::cerr << "y.size(): " << y.size() << std::endl;
  117. std::cerr << "Reading ImageNet test data files (takes some seconds)..." << std::endl;
  118. ImageNetData imageNetTest ( imageNetPath + "demo/" );
  119. imageNetTest.preloadData ( "val", "testing" );
  120. imageNetTest.loadExternalLabels ( imageNetPath + "data/ILSVRC2010_validation_ground_truth.txt" );
  121. double OverallPerformance(0.0);
  122. for (int cl = 0; cl < nrOfClassesToConcidere; cl++)
  123. {
  124. std::cerr << "run for class " << cl << std::endl;
  125. int positiveClass = cl+1;
  126. // ------------------------------ TRAINING ------------------------------
  127. kernelSigma = sigmaParas[cl];
  128. std::cerr << "using sigma: " << kernelSigma << " and noise " << noiseParas[cl] << std::endl;
  129. Timer tTrain;
  130. tTrain.start();
  131. NICE::Matrix kernelMatrix (nrOfExamplesPerClass, nrOfExamplesPerClass, 0.0);
  132. //now compute the kernelScores for every element
  133. double kernelScore(0.0);
  134. for (int i = cl*100; i < cl*100+nrOfExamplesPerClass; i++)
  135. {
  136. for (int j = i; j < cl*100+nrOfExamplesPerClass; j++)
  137. {
  138. kernelScore = measureDistance(trainingData[i],trainingData[j], kernelSigma);//optimalParameters[cl]);
  139. kernelMatrix(i-cl*100,j-cl*100) = kernelScore;
  140. if (i != j)
  141. kernelMatrix(j-cl*100,i-cl*100) = kernelScore;
  142. }
  143. }
  144. //adding some noise, if necessary
  145. if (noiseParas[cl] != 0.0)
  146. {
  147. kernelMatrix.addIdentity(noiseParas[cl]);
  148. }
  149. else
  150. {
  151. //zero was already set
  152. }
  153. //compute its inverse
  154. //noise is already added :)
  155. Timer tTrainPrecise;
  156. tTrainPrecise.start();
  157. CholeskyRobust cr ( false /* verbose*/, 0.0 /*noiseStep*/, false /* useCuda*/);
  158. NICE::Matrix choleskyMatrix (nrOfExamplesPerClass, nrOfExamplesPerClass, 0.0);
  159. cr.robustChol ( kernelMatrix, choleskyMatrix );
  160. tTrainPrecise.stop();
  161. std::cerr << "Precise time used for training class " << cl << ": " << tTrainPrecise.getLast() << std::endl;
  162. tTrain.stop();
  163. std::cerr << "Time used for training class " << cl << ": " << tTrain.getLast() << std::endl;
  164. std::cerr << "training done - now perform the evaluation" << std::endl;
  165. // ------------------------------ TESTING ------------------------------
  166. ClassificationResults results;
  167. std::cerr << "Classification step ... with " << imageNetTest.getNumPreloadedExamples() << " examples" << std::endl;
  168. ProgressBar pb;
  169. Timer tTest;
  170. tTest.start();
  171. Timer tTestSingle;
  172. double timeForSingleExamples(0.0);
  173. for ( uint i = 0 ; i < (uint)imageNetTest.getNumPreloadedExamples(); i++ )
  174. {
  175. pb.update ( imageNetTest.getNumPreloadedExamples() );
  176. //get the precomputed features
  177. const SparseVector & svec = imageNetTest.getPreloadedExample ( i );
  178. //compute (self-)similarities
  179. double kernelSelf (measureDistance(svec,svec, kernelSigma) );
  180. NICE::Vector kernelVector (nrOfExamplesPerClass, 0.0);
  181. for (int j = 0; j < nrOfExamplesPerClass; j++)
  182. {
  183. kernelVector[j] = measureDistance(trainingData[j+cl*100],svec, kernelSigma);
  184. }
  185. //compute the resulting score
  186. tTestSingle.start();
  187. NICE::Vector rightPart (nrOfExamplesPerClass);
  188. choleskySolveLargeScale ( choleskyMatrix, kernelVector, rightPart );
  189. double uncertainty = kernelSelf - kernelVector.scalarProduct ( rightPart );
  190. tTestSingle.stop();
  191. timeForSingleExamples += tTestSingle.getLast();
  192. //this is the standard score-object needed for the evaluation
  193. FullVector scores ( 2 );
  194. scores[0] = 0.0;
  195. scores[1] = 1.0 - uncertainty;
  196. ClassificationResult r ( scores[1]<0.5 ? 0 : 1, scores );
  197. // set ground truth label
  198. r.classno_groundtruth = (((int)imageNetTest.getPreloadedLabel ( i )) == positiveClass) ? 1 : 0;
  199. //we could write the resulting score on the command line
  200. // std::cerr << "scores: " << std::endl;
  201. // scores >> std::cerr;
  202. //as well as the ground truth label
  203. // std::cerr << "gt: " << r.classno_groundtruth << " -- " << r.classno << std::endl;
  204. results.push_back ( r );
  205. }
  206. tTest.stop();
  207. std::cerr << "Time used for evaluating class " << cl << ": " << tTest.getLast() << std::endl;
  208. timeForSingleExamples/= imageNetTest.getNumPreloadedExamples();
  209. std::cerr << "Time used for evaluation single elements of class " << cl << " : " << timeForSingleExamples << std::endl;
  210. // we could also write the results to an external file. Note, that this file will be overwritten in every iteration
  211. // so if you want to store all results, you should add a suffix with the class number
  212. // std::cerr << "Writing results to " << resultsfile << std::endl;
  213. // results.writeWEKA ( resultsfile, 1 );
  214. double perfvalue = results.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  215. std::cerr << "Performance: " << perfvalue << std::endl;
  216. OverallPerformance += perfvalue;
  217. }
  218. OverallPerformance /= nrOfClassesToConcidere;
  219. std::cerr << "overall performance: " << OverallPerformance << std::endl;
  220. return 0;
  221. }
  222. #else
  223. int main (int argc, char **argv)
  224. {
  225. }
  226. #endif