testNullSpace.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /**
  2. * @file testNullSpace.cpp
  3. * @brief test function for class KCNullSpace
  4. * @author Paul Bodesheim
  5. * @date 28-11-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/vector/Algorithms.h"
  12. #include "core/vector/SparseVectorT.h"
  13. #include "vislearning/classifier/kernelclassifier/KCNullSpace.h"
  14. #include "vislearning/math/kernels/KernelData.h"
  15. #include "vislearning/cbaselib/ClassificationResults.h"
  16. #include "vislearning/baselib/ProgressBar.h"
  17. #include "core/matlabAccess/MatFileIO.h"
  18. #include "vislearning/matlabAccessHighLevel/ImageNetData.h"
  19. // #include <iostream>
  20. // #include <fstream>
  21. using namespace std;
  22. using namespace NICE;
  23. using namespace OBJREC;
  24. // --------------- THE KERNEL FUNCTION ( exponential kernel with euclidian distance ) ----------------------
  25. double measureDistance ( const NICE::SparseVector & a, const NICE::SparseVector & b, const double & sigma = 2.0)
  26. {
  27. double inner_sum(0.0);
  28. double d;
  29. //new version, where we needed on average 0.001707 s for each test sample
  30. NICE::SparseVector::const_iterator aIt = a.begin();
  31. NICE::SparseVector::const_iterator bIt = b.begin();
  32. //compute the euclidian distance between both feature vectores (given as SparseVectors)
  33. while ( (aIt != a.end()) && (bIt != b.end()) )
  34. {
  35. if (aIt->first == bIt->first)
  36. {
  37. d = ( aIt->second - bIt->second );
  38. inner_sum += d * d;
  39. aIt++;
  40. bIt++;
  41. }
  42. else if ( aIt->first < bIt->first)
  43. {
  44. inner_sum += aIt->second * aIt->second;
  45. aIt++;
  46. }
  47. else
  48. {
  49. inner_sum += bIt->second * bIt->second;
  50. bIt++;
  51. }
  52. }
  53. //compute remaining values, if b reached the end but not a
  54. while (aIt != a.end())
  55. {
  56. inner_sum += aIt->second * aIt->second;
  57. aIt++;
  58. }
  59. //compute remaining values, if a reached the end but not b
  60. while (bIt != b.end())
  61. {
  62. inner_sum += bIt->second * bIt->second;
  63. bIt++;
  64. }
  65. //normalization of the exponent
  66. inner_sum /= (2.0*sigma*sigma);
  67. //finally, compute the RBF-kernel score (RBF = radial basis function)
  68. return exp(-inner_sum);
  69. }
  70. // --------------- THE KERNEL FUNCTION ( HIK ) ----------------------
  71. double minimumDistance ( const NICE::SparseVector & a, const NICE::SparseVector & b )
  72. {
  73. double inner_sum(0.0);
  74. NICE::SparseVector::const_iterator aIt = a.begin();
  75. NICE::SparseVector::const_iterator bIt = b.begin();
  76. //compute the minimum distance between both feature vectores (given as SparseVectors)
  77. while ( (aIt != a.end()) && (bIt != b.end()) )
  78. {
  79. if (aIt->first == bIt->first)
  80. {
  81. inner_sum += std::min( aIt->second , bIt->second );
  82. aIt++;
  83. bIt++;
  84. }
  85. else if ( aIt->first < bIt->first)
  86. {
  87. aIt++;
  88. }
  89. else
  90. {
  91. bIt++;
  92. }
  93. }
  94. return inner_sum;
  95. }
  96. /**
  97. test the basic functionality of fast-hik hyperparameter optimization
  98. */
  99. int main (int argc, char **argv)
  100. {
  101. std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
  102. Config conf ( argc, argv );
  103. string resultsfile = conf.gS("main", "results", "results.txt" );
  104. int nrOfExamplesPerClass = conf.gI("main", "nrOfExamplesPerClass", 100);
  105. nrOfExamplesPerClass = std::min(nrOfExamplesPerClass, 100); // we do not have more than 100 examples per class
  106. int maxKnownClass = conf.gI("KCNullSpace", "maxKnownClass", 5);
  107. int OCCsingleClassLabel = conf.gI("KCNullSpace", "OCCsingleClassLabel", 1);
  108. bool testVerbose = conf.gB("KCNullSpace", "verbose", false);
  109. std::cerr << "conf verbose: " << testVerbose << std::endl;
  110. // -------- read ImageNet data --------------
  111. std::vector<SparseVector> trainingData;
  112. NICE::Vector y;
  113. NICE::Vector yTest;
  114. std::cerr << "Reading ImageNet data ..." << std::endl;
  115. bool imageNetLocal = conf.gB("main", "imageNetLocal" , false);
  116. string imageNetPath;
  117. if (imageNetLocal)
  118. imageNetPath = "/users2/rodner/data/imagenet/devkit-1.0/";
  119. else
  120. imageNetPath = "/home/dbv/bilder/imagenet/devkit-1.0/";
  121. ImageNetData imageNetTrain ( imageNetPath + "demo/" );
  122. imageNetTrain.preloadData( "train", "training" );
  123. imageNetTrain.normalizeData("L1");
  124. trainingData = imageNetTrain.getPreloadedData();
  125. y = imageNetTrain.getPreloadedLabels();
  126. std::cerr << "Reading of training data finished" << std::endl;
  127. std::cerr << "trainingData.size(): " << trainingData.size() << std::endl;
  128. std::cerr << "y.size(): " << y.size() << std::endl;
  129. std::cerr << "Reading ImageNet test data files (takes some seconds)..." << std::endl;
  130. ImageNetData imageNetTest ( imageNetPath + "demo/" );
  131. imageNetTest.preloadData ( "val", "testing" );
  132. imageNetTest.normalizeData("L1");
  133. imageNetTest.loadExternalLabels ( imageNetPath + "data/ILSVRC2010_validation_ground_truth.txt" );
  134. yTest = imageNetTest.getPreloadedLabels();
  135. // ---------- SELECT TRAINING SET FOR MULTICLASS NOVELTY DETECTION AND COMPUTE KERNEL MATRIX ------------------------
  136. NICE::Vector knownClassLabels(maxKnownClass,0.0);
  137. for (int k=1; k<=maxKnownClass; k++)
  138. knownClassLabels(k-1) = k;
  139. std::vector<SparseVector> currentTrainingData;
  140. currentTrainingData.clear();
  141. NICE::Vector currentTrainingLabels(nrOfExamplesPerClass*knownClassLabels.size(),0);
  142. int kk(0);
  143. for (size_t i = 0; i < y.size(); i++)
  144. {
  145. for (size_t j=0; j<knownClassLabels.size(); j++)
  146. {
  147. if ( y[i] == knownClassLabels[j] )
  148. {
  149. currentTrainingLabels(kk) = knownClassLabels[j];
  150. currentTrainingData.push_back(trainingData[i]);
  151. kk++;
  152. break;
  153. }
  154. }
  155. }
  156. Timer tTrain;
  157. tTrain.start();
  158. //compute the kernel matrix
  159. NICE::Matrix kernelMatrix(nrOfExamplesPerClass*knownClassLabels.size(), nrOfExamplesPerClass*knownClassLabels.size(), 0.0);
  160. double kernelScore(0.0);
  161. for (size_t i = 0; i < kernelMatrix.rows(); i++)
  162. {
  163. for (size_t j = i; j < kernelMatrix.cols(); j++)
  164. {
  165. kernelScore = minimumDistance(currentTrainingData[i],currentTrainingData[j]);
  166. kernelMatrix(i,j) = kernelScore;
  167. if (i != j)
  168. kernelMatrix(j,i) = kernelScore;
  169. }
  170. }
  171. KernelData kernelData( &conf, kernelMatrix, "Kernel", false );
  172. KCNullSpace knfst( &conf);
  173. // train the model
  174. knfst.teach(&kernelData, currentTrainingLabels);
  175. tTrain.stop();
  176. std::cerr << "Time used for training " << ": " << tTrain.getLast() << std::endl;
  177. // some outputs of training
  178. std::cerr << "training set statistic: " << std::endl;
  179. for (std::map<int,int>::iterator it = knfst.getTrainingSetStatistic()->begin(); it != knfst.getTrainingSetStatistic()->end(); it++)
  180. {
  181. std::cerr << "class label: " << (*it).first << " number of class samples: " << (*it).second << std::endl;
  182. }
  183. std::cerr << "one-class setting?: " << knfst.isOneClass() << std::endl;
  184. std::cerr << "null space dimension: "<< knfst.getNullSpaceDimension() << std::endl;
  185. std::cerr << "target points: " << std::endl;
  186. for (std::map<int,NICE::Vector>::iterator it = knfst.getTargetPoints()->begin(); it != knfst.getTargetPoints()->end(); it++)
  187. std::cerr << (*it).second << std::endl;
  188. std::cerr << "training done - now perform the evaluation" << std::endl;
  189. // --------- TESTING MULTICLASS NOVELTY DETECTION ------------------------------
  190. std::cerr << "Multi-class novelty detection... with " << imageNetTest.getNumPreloadedExamples() << " examples" << std::endl;
  191. ClassificationResults results;
  192. ProgressBar pb;
  193. Timer tTest;
  194. tTest.start();
  195. for ( uint i = 0 ; i < (uint)imageNetTest.getNumPreloadedExamples(); i++ )
  196. {
  197. if ( (i % 100)==0)
  198. pb.update ( imageNetTest.getNumPreloadedExamples()/100 );
  199. const SparseVector & svec = imageNetTest.getPreloadedExample ( i );
  200. // compute (self) similarities
  201. double kernelSelf (minimumDistance(svec,svec) );
  202. NICE::Vector kernelVector (nrOfExamplesPerClass*knownClassLabels.size(), 0.0);
  203. for (uint j = 0; j < nrOfExamplesPerClass*knownClassLabels.size(); j++)
  204. {
  205. kernelVector[j] = minimumDistance(currentTrainingData[j],svec);
  206. }
  207. ClassificationResult r;
  208. r = knfst.noveltyDetection( kernelVector, kernelSelf);
  209. // set ground truth label
  210. r.classno_groundtruth = 0;
  211. for (size_t j=0; j<knownClassLabels.size(); j++)
  212. {
  213. if ( yTest[i] == knownClassLabels[j] )
  214. {
  215. r.classno_groundtruth = 1;
  216. break;
  217. }
  218. }
  219. // remember the results for the evaluation lateron
  220. results.push_back ( r );
  221. }
  222. tTest.stop();
  223. std::cerr << "Time used for evaluation: " << tTest.getLast() << std::endl;
  224. double timeForSingleExample(0.0);
  225. timeForSingleExample = tTest.getLast()/imageNetTest.getNumPreloadedExamples();
  226. std::cerr.precision(10);
  227. std::cerr << "time used for evaluation of single elements: " << timeForSingleExample << std::endl;
  228. // run the AUC-evaluation
  229. double perfvalue( 0.0 );
  230. perfvalue = results.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  231. std::cerr << " novelty detection performance: " << perfvalue << std::endl;
  232. // --------- TESTING MULTICLASS CLASSIFICATION ------------------------------
  233. results.clear();
  234. tTest.start();
  235. for ( uint i = 0 ; i < (uint)imageNetTest.getNumPreloadedExamples(); i++ )
  236. {
  237. // only use samples of known classes
  238. if ( yTest[i] > maxKnownClass)
  239. {
  240. continue;
  241. }
  242. const SparseVector & svec = imageNetTest.getPreloadedExample ( i );
  243. // compute (self) similarities
  244. double kernelSelf (minimumDistance(svec,svec) );
  245. NICE::Vector kernelVector (nrOfExamplesPerClass*knownClassLabels.size(), 0.0);
  246. for (uint j = 0; j < nrOfExamplesPerClass*knownClassLabels.size(); j++)
  247. {
  248. kernelVector[j] = minimumDistance(currentTrainingData[j],svec);
  249. }
  250. ClassificationResult r;
  251. r = knfst.classifyKernel( kernelVector, kernelSelf);
  252. // set ground truth label
  253. for (uint j=0; j < knownClassLabels.size(); j++)
  254. {
  255. if (yTest[i] == knownClassLabels[j])
  256. {
  257. r.classno_groundtruth = j;
  258. break;
  259. }
  260. }
  261. // remember the results for the evaluation lateron
  262. results.push_back ( r );
  263. }
  264. tTest.stop();
  265. std::cerr << "Time used for evaluation: " << tTest.getLast() << std::endl;
  266. timeForSingleExample = tTest.getLast()/imageNetTest.getNumPreloadedExamples();
  267. std::cerr.precision(10);
  268. std::cerr << "time used for evaluation of single elements: " << timeForSingleExample << std::endl;
  269. // run the AUC-evaluation
  270. perfvalue = results.getAverageRecognitionRate();
  271. std::cerr << " classification performance: " << perfvalue << std::endl;
  272. // ---------- SELECT TRAINING SET FOR ONECLASS CLASSIFICATION AND COMPUTE KERNEL MATRIX ------------------------
  273. currentTrainingData.clear();
  274. currentTrainingLabels.clear();
  275. for (size_t i = 0; i < y.size(); i++)
  276. {
  277. if ( y[i] == OCCsingleClassLabel )
  278. {
  279. currentTrainingLabels.append(OCCsingleClassLabel);
  280. currentTrainingData.push_back(trainingData[i]);
  281. }
  282. }
  283. tTrain.start();
  284. //compute the kernel matrix
  285. NICE::Matrix kernelMatrixOCC(currentTrainingData.size(), currentTrainingData.size(), 0.0);
  286. std::cerr << "OCC Kernel Matrix: " << kernelMatrixOCC.rows() << " x " << kernelMatrixOCC.cols() << std::endl;
  287. for (size_t i = 0; i < kernelMatrixOCC.rows(); i++)
  288. {
  289. for (size_t j = i; j < kernelMatrixOCC.cols(); j++)
  290. {
  291. kernelScore = minimumDistance(currentTrainingData[i],currentTrainingData[j]);
  292. kernelMatrixOCC(i,j) = kernelScore;
  293. if (i != j)
  294. kernelMatrixOCC(j,i) = kernelScore;
  295. }
  296. }
  297. filebuf fb;
  298. fb.open("/home/bodesheim/experiments/kernelMatrixOCC.txt",ios::out);
  299. ostream os (&fb);
  300. os << kernelMatrixOCC;
  301. fb.close();
  302. KernelData kernelDataOCC( &conf, kernelMatrixOCC, "Kernel", false );
  303. // train the model
  304. std::cerr << "Train OCC model... " << std::endl;
  305. knfst.teach(&kernelDataOCC, currentTrainingLabels);
  306. tTrain.stop();
  307. std::cerr << "Time used for training " << ": " << tTrain.getLast() << std::endl;
  308. // some outputs of training
  309. std::cerr << "training set statistic: " << std::endl;
  310. for (std::map<int,int>::iterator itt = knfst.getTrainingSetStatistic()->begin(); itt != knfst.getTrainingSetStatistic()->end(); itt++)
  311. {
  312. std::cerr << "class label: " << (*itt).first << " number of class samples: " << (*itt).second << std::endl;
  313. }
  314. std::cerr << "one-class setting?: " << knfst.isOneClass() << std::endl;
  315. std::cerr << "null space dimension: "<< knfst.getNullSpaceDimension() << std::endl;
  316. std::cerr << "target points: " << std::endl;
  317. for (std::map<int,NICE::Vector>::const_iterator it = knfst.getTargetPoints()->begin(); it != knfst.getTargetPoints()->end(); it++)
  318. std::cerr << (*it).second << std::endl;
  319. std::cerr << "training done - now perform the evaluation" << std::endl;
  320. // --------- TESTING OCC ------------------------------
  321. std::cerr << "OCC... with " << imageNetTest.getNumPreloadedExamples() << " examples" << std::endl;
  322. results.clear();
  323. tTest.start();
  324. ProgressBar pb3;
  325. std::cerr << "start for loop" << std::endl;
  326. for ( uint i = 0 ; i < (uint)imageNetTest.getNumPreloadedExamples(); i++ )
  327. {
  328. if ( (i % 100)==0)
  329. pb3.update ( imageNetTest.getNumPreloadedExamples()/100 );
  330. const SparseVector & svec = imageNetTest.getPreloadedExample ( i );
  331. //compute (self) similarities
  332. double kernelSelf (minimumDistance(svec,svec) );
  333. NICE::Vector kernelVector (currentTrainingData.size(), 0.0);
  334. for (uint j = 0; j < currentTrainingData.size(); j++)
  335. {
  336. kernelVector[j] = minimumDistance(currentTrainingData[j],svec);
  337. }
  338. ClassificationResult r;
  339. r = knfst.noveltyDetection( kernelVector, kernelSelf);
  340. // set ground truth label
  341. r.classno_groundtruth = 0;
  342. if ( yTest[i] == OCCsingleClassLabel )
  343. {
  344. r.classno_groundtruth = 1;
  345. }
  346. else
  347. {
  348. r.classno_groundtruth = 0;
  349. }
  350. //remember the results for the evaluation lateron
  351. results.push_back ( r );
  352. }
  353. tTest.stop();
  354. std::cerr << "Time used for evaluation: " << tTest.getLast() << std::endl;
  355. double timeForSingleExampleOCC = tTest.getLast()/imageNetTest.getNumPreloadedExamples();
  356. std::cerr.precision(10);
  357. std::cerr << "time used for evaluation of single elements: " << timeForSingleExampleOCC << std::endl;
  358. // run the AUC-evaluation
  359. double perfvalueOCC = results.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  360. std::cerr << " occ performance: " << perfvalueOCC << std::endl;
  361. return 0;
  362. }