testImageNetBinaryGPBaseline.cpp 9.1 KB

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