testImageNetBinaryBruteForce.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. /**
  2. * @file testImageNetBinaryBruteForce.cpp
  3. * @brief perform ImageNet tests with binary tasks for OCC using GP mean and variance, sophisticated approximations of both, Parzen Density Estimation and SVDD
  4. * @author Alexander Lütz
  5. * @date 23-05-2012 (dd-mm-yyyy)
  6. */
  7. #include <ctime>
  8. #include <time.h>
  9. #include "core/basics/Config.h"
  10. #include "core/basics/Timer.h"
  11. #include "core/algebra/CholeskyRobust.h"
  12. #include "core/vector/Algorithms.h"
  13. #include "core/vector/SparseVectorT.h"
  14. #include "vislearning/cbaselib/ClassificationResults.h"
  15. #include "vislearning/baselib/ProgressBar.h"
  16. #include "vislearning/classifier/kernelclassifier/KCMinimumEnclosingBall.h"
  17. #include "fast-hik/tools.h"
  18. #include "fast-hik/MatFileIO.h"
  19. #include "fast-hik/ImageNetData.h"
  20. using namespace std;
  21. using namespace NICE;
  22. using namespace OBJREC;
  23. // --------------- THE KERNEL FUNCTION ( exponential kernel with euclidian distance ) ----------------------
  24. double measureDistance ( const NICE::SparseVector & a, const NICE::SparseVector & b, const double & sigma = 2.0)//, const bool & verbose = false)
  25. {
  26. double inner_sum(0.0);
  27. double d;
  28. //new version, where we needed on average 0.001707 s for each test sample
  29. NICE::SparseVector::const_iterator aIt = a.begin();
  30. NICE::SparseVector::const_iterator bIt = b.begin();
  31. while ( (aIt != a.end()) && (bIt != b.end()) )
  32. {
  33. if (aIt->first == bIt->first)
  34. {
  35. d = ( aIt->second - bIt->second );
  36. inner_sum += d * d;
  37. aIt++;
  38. bIt++;
  39. }
  40. else if ( aIt->first < bIt->first)
  41. {
  42. inner_sum += aIt->second * aIt->second;
  43. aIt++;
  44. }
  45. else
  46. {
  47. inner_sum += bIt->second * bIt->second;
  48. bIt++;
  49. }
  50. }
  51. //compute remaining values, if b reached the end but not a
  52. while (aIt != a.end())
  53. {
  54. inner_sum += aIt->second * aIt->second;
  55. aIt++;
  56. }
  57. //compute remaining values, if a reached the end but not b
  58. while (bIt != b.end())
  59. {
  60. inner_sum += bIt->second * bIt->second;
  61. bIt++;
  62. }
  63. inner_sum /= (2.0*sigma*sigma);
  64. return exp(-inner_sum);
  65. }
  66. void readParameters(string & filename, const int & size, NICE::Vector & parameterVector)
  67. {
  68. parameterVector.resize(size);
  69. parameterVector.set(0.0);
  70. ifstream is(filename.c_str());
  71. if ( !is.good() )
  72. fthrow(IOException, "Unable to read parameters.");
  73. //
  74. string tmp;
  75. int cnt(0);
  76. while (! is.eof())
  77. {
  78. is >> tmp;
  79. parameterVector[cnt] = atof(tmp.c_str());
  80. cnt++;
  81. }
  82. //
  83. is.close();
  84. }
  85. //------------------- TRAINING METHODS --------------------
  86. void inline trainGPVarApprox(NICE::Vector & matrixDInv, const double & noise, const NICE::Matrix & kernelMatrix, const int & nrOfExamplesPerClass, const int & classNumber, const int & runsPerClassToAverageTraining )
  87. {
  88. std::cerr << "nrOfExamplesPerClass : " << nrOfExamplesPerClass << std::endl;
  89. Timer tTrainPreciseTimer;
  90. tTrainPreciseTimer.start();
  91. for (int run = 0; run < runsPerClassToAverageTraining; run++)
  92. {
  93. matrixDInv.resize(nrOfExamplesPerClass);
  94. matrixDInv.set(0.0);
  95. //compute D
  96. //start with adding some noise, if necessary
  97. if (noise != 0.0)
  98. matrixDInv.set(noise);
  99. else
  100. matrixDInv.set(0.0);
  101. for (int i = 0; i < nrOfExamplesPerClass; i++)
  102. {
  103. for (int j = i; j < nrOfExamplesPerClass; j++)
  104. {
  105. matrixDInv[i] += kernelMatrix(i,j);
  106. if (i != j)
  107. matrixDInv[j] += kernelMatrix(i,j);
  108. }
  109. }
  110. //compute its inverse
  111. for (int i = 0; i < nrOfExamplesPerClass; i++)
  112. {
  113. matrixDInv[i] = 1.0 / matrixDInv[i];
  114. }
  115. }
  116. tTrainPreciseTimer.stop();
  117. std::cerr << "Precise time used for GPVarApprox training class " << classNumber << ": " << tTrainPreciseTimer.getLast()/(double)runsPerClassToAverageTraining << std::endl;
  118. }
  119. void inline trainGPVar(NICE::Matrix & choleskyMatrix, const double & noise, const NICE::Matrix & kernelMatrix, const int & nrOfExamplesPerClass, const int & classNumber, const int & runsPerClassToAverageTraining )
  120. {
  121. Timer tTrainPrecise;
  122. tTrainPrecise.start();
  123. for (int run = 0; run < runsPerClassToAverageTraining; run++)
  124. {
  125. CholeskyRobust cr ( false /* verbose*/, 0.0 /*noiseStep*/, false /* useCuda*/);
  126. choleskyMatrix.resize(nrOfExamplesPerClass, nrOfExamplesPerClass);
  127. choleskyMatrix.set(0.0);
  128. cr.robustChol ( kernelMatrix, choleskyMatrix );
  129. }
  130. tTrainPrecise.stop();
  131. std::cerr << "Precise time used for GPVar training class " << classNumber << ": " << tTrainPrecise.getLast()/(double)runsPerClassToAverageTraining << std::endl;
  132. }
  133. void inline trainGPMeanApprox(NICE::Vector & GPMeanApproxRightPart, const double & noise, const NICE::Matrix & kernelMatrix, const int & nrOfExamplesPerClass, const int & classNumber, const int & runsPerClassToAverageTraining )
  134. {
  135. Timer tTrainPrecise;
  136. tTrainPrecise.start();
  137. for (int run = 0; run < runsPerClassToAverageTraining; run++)
  138. {
  139. NICE::Vector matrixDInv(nrOfExamplesPerClass,0.0);
  140. //compute D
  141. //start with adding some noise, if necessary
  142. if (noise != 0.0)
  143. matrixDInv.set(noise);
  144. else
  145. matrixDInv.set(0.0);
  146. for (int i = 0; i < nrOfExamplesPerClass; i++)
  147. {
  148. for (int j = i; j < nrOfExamplesPerClass; j++)
  149. {
  150. matrixDInv[i] += kernelMatrix(i,j);
  151. if (i != j)
  152. matrixDInv[j] += kernelMatrix(i,j);
  153. }
  154. }
  155. //compute its inverse (and multiply every element with the label vector, which contains only one-entries...)
  156. GPMeanApproxRightPart.resize(nrOfExamplesPerClass);
  157. for (int i = 0; i < nrOfExamplesPerClass; i++)
  158. {
  159. GPMeanApproxRightPart[i] = 1.0 / matrixDInv[i];
  160. }
  161. }
  162. tTrainPrecise.stop();
  163. std::cerr << "Precise time used for GPMeanApprox training class " << classNumber << ": " << tTrainPrecise.getLast()/(double)runsPerClassToAverageTraining << std::endl;
  164. }
  165. void inline trainGPMean(NICE::Vector & GPMeanRightPart, const double & noise, const NICE::Matrix & kernelMatrix, const int & nrOfExamplesPerClass, const int & classNumber, const int & runsPerClassToAverageTraining )
  166. {
  167. Timer tTrainPrecise;
  168. tTrainPrecise.start();
  169. for (int run = 0; run < runsPerClassToAverageTraining; run++)
  170. {
  171. CholeskyRobust cr ( false /* verbose*/, 0.0 /*noiseStep*/, false /* useCuda*/);
  172. NICE::Matrix choleskyMatrix (nrOfExamplesPerClass, nrOfExamplesPerClass, 0.0);
  173. cr.robustChol ( kernelMatrix, choleskyMatrix );
  174. GPMeanRightPart.resize(nrOfExamplesPerClass);
  175. GPMeanRightPart.set(0.0);
  176. NICE::Vector y(nrOfExamplesPerClass,1.0); //OCC setting :)
  177. choleskySolveLargeScale ( choleskyMatrix, y, GPMeanRightPart );
  178. }
  179. tTrainPrecise.stop();
  180. std::cerr << "Precise time used for GPMean training class " << classNumber << ": " << tTrainPrecise.getLast()/(double)runsPerClassToAverageTraining << std::endl;
  181. }
  182. KCMinimumEnclosingBall *trainSVDD( const double & noise, const NICE::Matrix kernelMatrix, const int & nrOfExamplesPerClass, const int & classNumber, const int & runsPerClassToAverageTraining )
  183. {
  184. Config conf;
  185. // set the outlier ratio (Paul optimized this paramter FIXME)
  186. conf.sD( "SVDD", "outlier_fraction", 0.1 );
  187. KCMinimumEnclosingBall *svdd = new KCMinimumEnclosingBall ( &conf, NULL /* no kernel function */, "SVDD" /* config section */ );
  188. KernelData kernelData ( &conf, kernelMatrix, "Kernel" );
  189. Timer tTrainPrecise;
  190. tTrainPrecise.start();
  191. for (int run = 0; run < runsPerClassToAverageTraining; run++)
  192. {
  193. NICE::Vector y(nrOfExamplesPerClass,1.0); //OCC setting :)
  194. // KCMinimumEnclosingBall does not store the kernel data object, therefore, we are save with passing a local copy
  195. svdd->teach ( &kernelData, y );
  196. }
  197. tTrainPrecise.stop();
  198. std::cerr << "Precise time used for SVDD training class " << classNumber << ": " << tTrainPrecise.getLast()/(double)runsPerClassToAverageTraining << std::endl;
  199. return svdd;
  200. }
  201. // ------------- EVALUATION METHODS ---------------------
  202. void inline evaluateGPVarApprox(const NICE::Vector & kernelVector, const double & kernelSelf, const NICE::Vector & matrixDInv, ClassificationResult & r, double & timeForSingleExamples, const int & runsPerClassToAverageTesting)
  203. {
  204. double uncertainty;
  205. Timer tTestSingle;
  206. tTestSingle.start();
  207. for (int run = 0; run < runsPerClassToAverageTesting; run++)
  208. {
  209. NICE::Vector rightPart (kernelVector.size());
  210. for (int j = 0; j < kernelVector.size(); j++)
  211. {
  212. rightPart[j] = kernelVector[j] * matrixDInv[j];
  213. }
  214. uncertainty = kernelSelf - kernelVector.scalarProduct ( rightPart );
  215. }
  216. tTestSingle.stop();
  217. timeForSingleExamples += tTestSingle.getLast()/(double)runsPerClassToAverageTesting;
  218. FullVector scores ( 2 );
  219. scores[0] = 0.0;
  220. scores[1] = 1.0 - uncertainty;
  221. r = ClassificationResult ( scores[1]<0.5 ? 0 : 1, scores );
  222. }
  223. void inline evaluateGPVar(const NICE::Vector & kernelVector, const double & kernelSelf, const NICE::Matrix & choleskyMatrix, ClassificationResult & r, double & timeForSingleExamples, const int & runsPerClassToAverageTesting)
  224. {
  225. double uncertainty;
  226. Timer tTestSingle;
  227. tTestSingle.start();
  228. for (int run = 0; run < runsPerClassToAverageTesting; run++)
  229. {
  230. NICE::Vector rightPart (kernelVector.size(),0.0);
  231. choleskySolveLargeScale ( choleskyMatrix, kernelVector, rightPart );
  232. uncertainty = kernelSelf - kernelVector.scalarProduct ( rightPart );
  233. }
  234. tTestSingle.stop();
  235. timeForSingleExamples += tTestSingle.getLast()/(double)runsPerClassToAverageTesting;
  236. FullVector scores ( 2 );
  237. scores[0] = 0.0;
  238. scores[1] = 1.0 - uncertainty;
  239. r = ClassificationResult ( scores[1]<0.5 ? 0 : 1, scores );
  240. }
  241. void inline evaluateGPMeanApprox(const NICE::Vector & kernelVector, const NICE::Vector & rightPart, ClassificationResult & r, double & timeForSingleExamples, const int & runsPerClassToAverageTesting)
  242. {
  243. double mean;
  244. Timer tTestSingle;
  245. tTestSingle.start();
  246. for (int run = 0; run < runsPerClassToAverageTesting; run++)
  247. {
  248. mean = kernelVector.scalarProduct ( rightPart );
  249. }
  250. tTestSingle.stop();
  251. timeForSingleExamples += tTestSingle.getLast()/(double)runsPerClassToAverageTesting;
  252. FullVector scores ( 2 );
  253. scores[0] = 0.0;
  254. scores[1] = mean;
  255. r = ClassificationResult ( scores[1]<0.5 ? 0 : 1, scores );
  256. }
  257. void inline evaluateGPMean(const NICE::Vector & kernelVector, const NICE::Vector & GPMeanRightPart, ClassificationResult & r, double & timeForSingleExamples, const int & runsPerClassToAverageTesting)
  258. {
  259. double mean;
  260. Timer tTestSingle;
  261. tTestSingle.start();
  262. for (int run = 0; run < runsPerClassToAverageTesting; run++)
  263. {
  264. mean = kernelVector.scalarProduct ( GPMeanRightPart );
  265. }
  266. tTestSingle.stop();
  267. timeForSingleExamples += tTestSingle.getLast()/(double)runsPerClassToAverageTesting;
  268. FullVector scores ( 2 );
  269. scores[0] = 0.0;
  270. scores[1] = mean;
  271. r = ClassificationResult ( scores[1]<0.5 ? 0 : 1, scores );
  272. }
  273. void inline evaluateParzen(const NICE::Vector & kernelVector, ClassificationResult & r, double & timeForSingleExamples, const int & runsPerClassToAverageTesting)
  274. {
  275. double score;
  276. Timer tTestSingle;
  277. tTestSingle.start();
  278. for (int run = 0; run < runsPerClassToAverageTesting; run++)
  279. {
  280. double score( kernelVector.Sum() / (double) kernelVector.size() ); //maybe we could directly call kernelVector.Mean()
  281. }
  282. tTestSingle.stop();
  283. timeForSingleExamples += tTestSingle.getLast()/(double)runsPerClassToAverageTesting;
  284. FullVector scores ( 2 );
  285. scores[0] = 0.0;
  286. scores[1] = score;
  287. r = ClassificationResult ( scores[1]<0.5 ? 0 : 1, scores );
  288. }
  289. void inline evaluateSVDD( KCMinimumEnclosingBall *svdd, const NICE::Vector & kernelVector, ClassificationResult & r, double & timeForSingleExamples, const int & runsPerClassToAverageTesting)
  290. {
  291. Timer tTestSingle;
  292. tTestSingle.start();
  293. for (int run = 0; run < runsPerClassToAverageTesting; run++)
  294. {
  295. // In the following, we assume that we are using a Gaussian kernel
  296. r = svdd->classifyKernel ( kernelVector, 1.0 /* kernel self */ );
  297. }
  298. tTestSingle.stop();
  299. timeForSingleExamples += tTestSingle.getLast()/(double)runsPerClassToAverageTesting;
  300. }
  301. /**
  302. test the basic functionality of fast-hik hyperparameter optimization
  303. */
  304. int main (int argc, char **argv)
  305. {
  306. std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
  307. Config conf ( argc, argv );
  308. string resultsfile = conf.gS("main", "results", "results.txt" );
  309. int nrOfExamplesPerClass = conf.gI("main", "nrOfExamplesPerClass", 50);
  310. nrOfExamplesPerClass = std::min(nrOfExamplesPerClass, 100); // we do not have more than 100 examples per class
  311. int indexOfFirstClass = conf.gI("main", "indexOfFirstClass", 0);
  312. indexOfFirstClass = std::max(indexOfFirstClass, 0); //we do not have less than 0 classes
  313. int indexOfLastClass = conf.gI("main", "indexOfLastClass", 999);
  314. indexOfLastClass = std::min(indexOfLastClass, 999); //we do not have more than 1000 classes
  315. int nrOfClassesToConcidere = (indexOfLastClass - indexOfLastClass)+1;
  316. int runsPerClassToAverageTraining = conf.gI( "main", "runsPerClassToAverageTraining", 1 );
  317. int runsPerClassToAverageTesting = conf.gI( "main", "runsPerClassToAverageTesting", 1 );
  318. bool shareParameters = conf.gB("main" , "shareParameters", true);
  319. // GP variance approximation
  320. NICE::Vector sigmaGPVarApproxParas(nrOfClassesToConcidere,0.0);
  321. NICE::Vector noiseGPVarApproxParas(nrOfClassesToConcidere,0.0);
  322. // GP variance
  323. NICE::Vector sigmaGPVarParas(nrOfClassesToConcidere,0.0);
  324. NICE::Vector noiseGPVarParas(nrOfClassesToConcidere,0.0);
  325. //GP mean approximation
  326. NICE::Vector sigmaGPMeanApproxParas(nrOfClassesToConcidere,0.0);
  327. NICE::Vector noiseGPMeanApproxParas(nrOfClassesToConcidere,0.0);
  328. //GP mean
  329. NICE::Vector sigmaGPMeanParas(nrOfClassesToConcidere,0.0);
  330. NICE::Vector noiseGPMeanParas(nrOfClassesToConcidere,0.0);
  331. //Parzen
  332. NICE::Vector sigmaParzenParas(nrOfClassesToConcidere,0.0);
  333. NICE::Vector noiseParzenParas(nrOfClassesToConcidere,0.0);
  334. //SVDD
  335. NICE::Vector sigmaSVDDParas(nrOfClassesToConcidere,0.0);
  336. NICE::Vector noiseSVDDParas(nrOfClassesToConcidere,0.0);
  337. if (!shareParameters)
  338. {
  339. //read the optimal parameters for the different methods
  340. // GP variance approximation
  341. string sigmaGPVarApproxFile = conf.gS("main", "sigmaGPVarApproxFile", "approxVarSigma.txt");
  342. string noiseGPVarApproxFile = conf.gS("main", "noiseGPVarApproxFile", "approxVarNoise.txt");
  343. // GP variance
  344. string sigmaGPVarFile = conf.gS("main", "sigmaGPVarFile", "approxVarSigma.txt");
  345. string noiseGPVarFile = conf.gS("main", "noiseGPVarFile", "approxVarNoise.txt");
  346. //GP mean approximation
  347. string sigmaGPMeanApproxFile = conf.gS("main", "sigmaGPMeanApproxFile", "approxVarSigma.txt");
  348. string noiseGPMeanApproxFile = conf.gS("main", "noiseGPMeanApproxFile", "approxVarNoise.txt");
  349. //GP mean
  350. string sigmaGPMeanFile = conf.gS("main", "sigmaGPMeanFile", "approxVarSigma.txt");
  351. string noiseGPMeanFile = conf.gS("main", "noiseGPMeanFile", "approxVarNoise.txt");
  352. //Parzen
  353. string sigmaParzenFile = conf.gS("main", "sigmaParzenFile", "approxVarSigma.txt");
  354. string noiseParzenFile = conf.gS("main", "noiseParzenFile", "approxVarNoise.txt");
  355. //SVDD
  356. string sigmaSVDDFile = conf.gS("main", "sigmaSVDDFile", "approxVarSigma.txt");
  357. string noiseSVDDFile = conf.gS("main", "noiseSVDDFile", "approxVarNoise.txt");
  358. // GP variance approximation
  359. readParameters(sigmaGPVarApproxFile,nrOfClassesToConcidere, sigmaGPVarApproxParas);
  360. readParameters(noiseGPVarApproxFile,nrOfClassesToConcidere, noiseGPVarApproxParas);
  361. // GP variance
  362. readParameters(sigmaGPVarApproxFile,nrOfClassesToConcidere, sigmaGPVarParas);
  363. readParameters(noiseGPVarApproxFile,nrOfClassesToConcidere, noiseGPVarParas);
  364. //GP mean approximation
  365. readParameters(sigmaGPVarApproxFile,nrOfClassesToConcidere, sigmaGPMeanApproxParas);
  366. readParameters(noiseGPVarApproxFile,nrOfClassesToConcidere, noiseGPMeanApproxParas);
  367. //GP mean
  368. readParameters(sigmaGPVarApproxFile,nrOfClassesToConcidere, sigmaGPMeanParas);
  369. readParameters(noiseGPVarApproxFile,nrOfClassesToConcidere, noiseGPMeanParas);
  370. //Parzen
  371. readParameters(sigmaGPVarApproxFile,nrOfClassesToConcidere, sigmaParzenParas);
  372. readParameters(noiseGPVarApproxFile,nrOfClassesToConcidere, noiseParzenParas);
  373. //SVDD
  374. readParameters(sigmaGPVarApproxFile,nrOfClassesToConcidere, sigmaSVDDParas);
  375. readParameters(noiseGPVarApproxFile,nrOfClassesToConcidere, noiseSVDDParas);
  376. }
  377. else
  378. {
  379. double noise = conf.gD( "main", "noise", 0.01 );
  380. double sigma = conf.gD( "main", "sigma", 1.0 );
  381. sigmaGPVarApproxParas.set(sigma);
  382. noiseGPVarApproxParas.set(noise);
  383. // GP variance
  384. sigmaGPVarParas.set(sigma);
  385. noiseGPVarParas.set(noise);
  386. //GP mean approximation
  387. sigmaGPMeanApproxParas.set(sigma);
  388. noiseGPMeanApproxParas.set(noise);
  389. //GP mean
  390. sigmaGPMeanParas.set(sigma);
  391. noiseGPMeanParas.set(noise);
  392. //Parzen
  393. sigmaParzenParas.set(sigma);
  394. noiseParzenParas.set(noise);
  395. //SVDD
  396. sigmaSVDDParas.set(sigma);
  397. noiseSVDDParas.set(noise);
  398. }
  399. // -------- optimal parameters read --------------
  400. std::vector<SparseVector> trainingData;
  401. NICE::Vector y;
  402. std::cerr << "Reading ImageNet data ..." << std::endl;
  403. bool imageNetLocal = conf.gB("main", "imageNetLocal" , false);
  404. string imageNetPath;
  405. if (imageNetLocal)
  406. imageNetPath = "/users2/rodner/data/imagenet/devkit-1.0/";
  407. else
  408. imageNetPath = "/home/dbv/bilder/imagenet/devkit-1.0/";
  409. ImageNetData imageNetTrain ( imageNetPath + "demo/" );
  410. imageNetTrain.preloadData( "train", "training" );
  411. trainingData = imageNetTrain.getPreloadedData();
  412. y = imageNetTrain.getPreloadedLabels();
  413. std::cerr << "Reading of training data finished" << std::endl;
  414. std::cerr << "trainingData.size(): " << trainingData.size() << std::endl;
  415. std::cerr << "y.size(): " << y.size() << std::endl;
  416. std::cerr << "Reading ImageNet test data files (takes some seconds)..." << std::endl;
  417. ImageNetData imageNetTest ( imageNetPath + "demo/" );
  418. imageNetTest.preloadData ( "val", "testing" );
  419. imageNetTest.loadExternalLabels ( imageNetPath + "data/ILSVRC2010_validation_ground_truth.txt" );
  420. double OverallPerformanceGPVarApprox(0.0);
  421. double OverallPerformanceGPVar(0.0);
  422. double OverallPerformanceGPMeanApprox(0.0);
  423. double OverallPerformanceGPMean(0.0);
  424. double OverallPerformanceParzen(0.0);
  425. double OverallPerformanceSVDD(0.0);
  426. double kernelSigmaGPVarApprox;
  427. double kernelSigmaGPVar;
  428. double kernelSigmaGPMeanApprox;
  429. double kernelSigmaGPMean;
  430. double kernelSigmaParzen;
  431. double kernelSigmaSVDD;
  432. for (int cl = indexOfFirstClass; cl <= indexOfLastClass; cl++)
  433. {
  434. std::cerr << "run for class " << cl << std::endl;
  435. int positiveClass = cl+1; //labels are from 1 to 1000, but our indices from 0 to 999
  436. // ------------------------------ TRAINING ------------------------------
  437. kernelSigmaGPVarApprox = sigmaGPVarApproxParas[cl];
  438. kernelSigmaGPVar = sigmaGPVarParas[cl];
  439. kernelSigmaGPMeanApprox = sigmaGPMeanApproxParas[cl];
  440. kernelSigmaGPMean = sigmaGPMeanParas[cl];
  441. kernelSigmaParzen = sigmaParzenParas[cl];
  442. kernelSigmaSVDD = sigmaSVDDParas[cl];
  443. Timer tTrain;
  444. tTrain.start();
  445. NICE::Matrix kernelMatrix(nrOfExamplesPerClass, nrOfExamplesPerClass, 0.0);
  446. //TODO in theory we have to compute a single kernel Matrix for every method, since every method may have its own optimal parameter
  447. // I'm sure, we can speed it up a bit and compute it only for every different parameter
  448. //nonetheless, it's not as nice as we originally thought (same matrix for every method)
  449. //NOTE since we're only interested in runtimes, we can ignore this (and still do some further code optimization...) //TODO
  450. /* //adding some noise, if necessary
  451. if (noiseParas[cl] != 0.0)
  452. {
  453. kernelMatrix.addIdentity(noiseParas[cl]);
  454. }
  455. else
  456. {
  457. //zero was already set
  458. } */
  459. //now sum up all entries of each row in the original kernel matrix
  460. double kernelScore(0.0);
  461. for (int i = cl*100; i < cl*100+nrOfExamplesPerClass; i++)
  462. {
  463. for (int j = i; j < cl*100+nrOfExamplesPerClass; j++)
  464. {
  465. kernelScore = measureDistance(trainingData[i],trainingData[j], kernelSigmaGPVarApprox);
  466. kernelMatrix(i-cl*100,j-cl*100) = kernelScore;
  467. if (i != j)
  468. kernelMatrix(j-cl*100,i-cl*100) = kernelScore;
  469. }
  470. }
  471. //train GP Var Approx
  472. NICE::Vector matrixDInv;
  473. for (int i = 0; i < runsPerClassToAverageTraining; i++)
  474. trainGPVarApprox(matrixDInv, noiseGPVarApproxParas[cl], kernelMatrix, nrOfExamplesPerClass, cl, runsPerClassToAverageTraining );
  475. //train GP Var
  476. NICE::Matrix GPVarCholesky;
  477. trainGPVar(GPVarCholesky, noiseGPVarParas[cl], kernelMatrix, nrOfExamplesPerClass, cl, runsPerClassToAverageTraining );
  478. //train GP Mean Approx
  479. NICE::Vector GPMeanApproxRightPart;
  480. trainGPMeanApprox(GPMeanApproxRightPart, noiseGPMeanApproxParas[cl], kernelMatrix, nrOfExamplesPerClass, cl, runsPerClassToAverageTraining );
  481. //train GP Mean
  482. NICE::Vector GPMeanRightPart;
  483. trainGPMean(GPMeanRightPart, noiseGPMeanParas[cl], kernelMatrix, nrOfExamplesPerClass, cl, runsPerClassToAverageTraining );
  484. //train Parzen
  485. //nothing to do :)
  486. //train SVDD
  487. //TODO what do we need here?
  488. KCMinimumEnclosingBall *svdd = trainSVDD(noiseSVDDParas[cl], kernelMatrix, nrOfExamplesPerClass, cl, runsPerClassToAverageTraining );
  489. tTrain.stop();
  490. std::cerr << "Time used for training class " << cl << ": " << tTrain.getLast() << std::endl;
  491. std::cerr << "training done - now perform the evaluation" << std::endl;
  492. // ------------------------------ TESTING ------------------------------
  493. std::cerr << "Classification step ... with " << imageNetTest.getNumPreloadedExamples() << " examples" << std::endl;
  494. ClassificationResults resultsGPVarApprox;
  495. ClassificationResults resultsGPVar;
  496. ClassificationResults resultsGPMeanApprox;
  497. ClassificationResults resultsGPMean;
  498. ClassificationResults resultsParzen;
  499. ClassificationResults resultsSVDD;
  500. ProgressBar pb;
  501. Timer tTest;
  502. tTest.start();
  503. Timer tTestSingle;
  504. double timeForSingleExamplesGPVarApprox(0.0);
  505. double timeForSingleExamplesGPVar(0.0);
  506. double timeForSingleExamplesGPMeanApprox(0.0);
  507. double timeForSingleExamplesGPMean(0.0);
  508. double timeForSingleExamplesParzen(0.0);
  509. double timeForSingleExamplesSVDD(0.0);
  510. for ( uint i = 0 ; i < (uint)imageNetTest.getNumPreloadedExamples(); i++ )
  511. {
  512. pb.update ( imageNetTest.getNumPreloadedExamples() );
  513. const SparseVector & svec = imageNetTest.getPreloadedExample ( i );
  514. //TODO: again we should use method-specific optimal parameters. If we're only interested in the runtimes, this doesn't matter
  515. double kernelSelf (measureDistance(svec,svec, kernelSigmaGPVarApprox) );
  516. NICE::Vector kernelVector (nrOfExamplesPerClass, 0.0);
  517. for (int j = 0; j < nrOfExamplesPerClass; j++)
  518. {
  519. kernelVector[j] = measureDistance(trainingData[j+cl*100],svec, kernelSigmaGPVarApprox);
  520. }
  521. //evaluate GP Var Approx
  522. ClassificationResult rGPVarApprox;
  523. evaluateGPVarApprox( kernelVector, kernelSelf, matrixDInv, rGPVarApprox, timeForSingleExamplesGPVarApprox, runsPerClassToAverageTesting );
  524. //evaluate GP Var
  525. ClassificationResult rGPVar;
  526. evaluateGPVar( kernelVector, kernelSelf, GPVarCholesky, rGPVar, timeForSingleExamplesGPVar, runsPerClassToAverageTesting );
  527. //evaluate GP Mean Approx
  528. ClassificationResult rGPMeanApprox;
  529. evaluateGPMeanApprox( kernelVector, matrixDInv, rGPMeanApprox, timeForSingleExamplesGPMeanApprox, runsPerClassToAverageTesting );
  530. //evaluate GP Mean
  531. ClassificationResult rGPMean;
  532. evaluateGPMean( kernelVector, GPMeanRightPart, rGPMean, timeForSingleExamplesGPMean, runsPerClassToAverageTesting );
  533. //evaluate Parzen
  534. ClassificationResult rParzen;
  535. evaluateParzen( kernelVector, rParzen, timeForSingleExamplesParzen, runsPerClassToAverageTesting );
  536. //evaluate SVDD
  537. ClassificationResult rSVDD;
  538. evaluateSVDD( svdd, kernelVector, rSVDD, timeForSingleExamplesSVDD, runsPerClassToAverageTesting );
  539. // set ground truth label
  540. rGPVarApprox.classno_groundtruth = (((int)imageNetTest.getPreloadedLabel ( i )) == positiveClass) ? 1 : 0;
  541. rGPVar.classno_groundtruth = (((int)imageNetTest.getPreloadedLabel ( i )) == positiveClass) ? 1 : 0;
  542. rGPMeanApprox.classno_groundtruth = (((int)imageNetTest.getPreloadedLabel ( i )) == positiveClass) ? 1 : 0;
  543. rGPMean.classno_groundtruth = (((int)imageNetTest.getPreloadedLabel ( i )) == positiveClass) ? 1 : 0;
  544. rParzen.classno_groundtruth = (((int)imageNetTest.getPreloadedLabel ( i )) == positiveClass) ? 1 : 0;
  545. rSVDD.classno_groundtruth = (((int)imageNetTest.getPreloadedLabel ( i )) == positiveClass) ? 1 : 0;
  546. // std::cerr << "scores: " << std::endl;
  547. // scores >> std::cerr;
  548. // std::cerr << "gt: " << r.classno_groundtruth << " -- " << r.classno << std::endl;
  549. resultsGPVarApprox.push_back ( rGPVarApprox );
  550. resultsGPVar.push_back ( rGPVar );
  551. resultsGPMeanApprox.push_back ( rGPMeanApprox );
  552. resultsGPMean.push_back ( rGPMean );
  553. resultsParzen.push_back ( rParzen );
  554. resultsSVDD.push_back ( rSVDD );
  555. }
  556. tTest.stop();
  557. std::cerr << "Time used for evaluating class " << cl << ": " << tTest.getLast() << std::endl;
  558. timeForSingleExamplesGPVarApprox/= imageNetTest.getNumPreloadedExamples();
  559. timeForSingleExamplesGPVar/= imageNetTest.getNumPreloadedExamples();
  560. timeForSingleExamplesGPMeanApprox/= imageNetTest.getNumPreloadedExamples();
  561. timeForSingleExamplesGPMean/= imageNetTest.getNumPreloadedExamples();
  562. timeForSingleExamplesParzen/= imageNetTest.getNumPreloadedExamples();
  563. timeForSingleExamplesSVDD/= imageNetTest.getNumPreloadedExamples();
  564. std::cerr << "GPVarApprox -- time used for evaluation single elements of class " << cl << " : " << timeForSingleExamplesGPVarApprox << std::endl;
  565. std::cerr << "GPVar -- time used for evaluation single elements of class " << cl << " : " << timeForSingleExamplesGPVar << std::endl;
  566. std::cerr << "GPMeanApprox -- time used for evaluation single elements of class " << cl << " : " << timeForSingleExamplesGPMeanApprox << std::endl;
  567. std::cerr << "GPMean -- time used for evaluation single elements of class " << cl << " : " << timeForSingleExamplesGPMean << std::endl;
  568. std::cerr << "Parzen -- time used for evaluation single elements of class " << cl << " : " << timeForSingleExamplesParzen << std::endl;
  569. std::cerr << "SVDD -- time used for evaluation single elements of class " << cl << " : " << timeForSingleExamplesSVDD << std::endl;
  570. // std::cerr << "Writing results to " << resultsfile << std::endl;
  571. // results.writeWEKA ( resultsfile, 1 );
  572. double perfvalueGPVarApprox = resultsGPVarApprox.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  573. double perfvalueGPVar = resultsGPVar.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  574. double perfvalueGPMeanApprox = resultsGPMeanApprox.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  575. double perfvalueGPMean = resultsGPMean.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  576. double perfvalueParzen = resultsParzen.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  577. double perfvalueSVDD = resultsSVDD.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  578. std::cerr << "Performance GPVarApprox: " << perfvalueGPVarApprox << std::endl;
  579. std::cerr << "Performance GPVar: " << perfvalueGPVar << std::endl;
  580. std::cerr << "Performance GPMeanApprox: " << perfvalueGPMeanApprox << std::endl;
  581. std::cerr << "Performance GPMean: " << perfvalueGPMean << std::endl;
  582. std::cerr << "Performance Parzen: " << perfvalueParzen << std::endl;
  583. std::cerr << "Performance SVDD: " << perfvalueSVDD << std::endl;
  584. OverallPerformanceGPVarApprox += perfvalueGPVar;
  585. OverallPerformanceGPVar += perfvalueGPVarApprox;
  586. OverallPerformanceGPMeanApprox += perfvalueGPMeanApprox;
  587. OverallPerformanceGPMean += perfvalueGPMean;
  588. OverallPerformanceParzen += perfvalueParzen;
  589. OverallPerformanceSVDD += perfvalueSVDD;
  590. // clean up memory used by SVDD
  591. delete svdd;
  592. }
  593. OverallPerformanceGPVarApprox /= nrOfClassesToConcidere;
  594. OverallPerformanceGPVar /= nrOfClassesToConcidere;
  595. OverallPerformanceGPMeanApprox /= nrOfClassesToConcidere;
  596. OverallPerformanceGPMean /= nrOfClassesToConcidere;
  597. OverallPerformanceParzen /= nrOfClassesToConcidere;
  598. OverallPerformanceSVDD /= nrOfClassesToConcidere;
  599. std::cerr << "overall performance GPVarApprox: " << OverallPerformanceGPVarApprox << std::endl;
  600. std::cerr << "overall performance GPVar: " << OverallPerformanceGPVar << std::endl;
  601. std::cerr << "overall performance GPMeanApprox: " << OverallPerformanceGPMeanApprox << std::endl;
  602. std::cerr << "overall performance GPMean: " << OverallPerformanceGPMean << std::endl;
  603. std::cerr << "overall performance Parzen: " << OverallPerformanceParzen << std::endl;
  604. std::cerr << "overall performance SVDD: " << OverallPerformanceSVDD << std::endl;
  605. return 0;
  606. }