testNullSpaceNovelty.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /**
  2. * @file testNullSpaceNovelty.cpp
  3. * @brief test function for class KCNullSpaceNovelty
  4. * @author Paul Bodesheim
  5. * @date 28-11-2012 (dd-mm-yyyy)
  6. */
  7. #include <ctime>
  8. #include <time.h>
  9. #include <iostream>
  10. #ifdef NICE_USELIB_MATIO
  11. #include "core/basics/Config.h"
  12. #include "core/basics/Timer.h"
  13. #include "core/vector/Algorithms.h"
  14. #include "core/vector/SparseVectorT.h"
  15. #include "vislearning/classifier/kernelclassifier/KCNullSpaceNovelty.h"
  16. #include "vislearning/math/kernels/KernelData.h"
  17. #include "vislearning/cbaselib/ClassificationResults.h"
  18. #include "vislearning/baselib/ProgressBar.h"
  19. #include "core/matlabAccess/MatFileIO.h"
  20. #include "vislearning/matlabAccessHighLevel/ImageNetData.h"
  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. // -------- read ImageNet data --------------
  107. std::vector<SparseVector> trainingData;
  108. NICE::Vector y;
  109. std::cerr << "Reading ImageNet data ..." << std::endl;
  110. bool imageNetLocal = conf.gB("main", "imageNetLocal" , false);
  111. string imageNetPath;
  112. if (imageNetLocal)
  113. imageNetPath = "/users2/rodner/data/imagenet/devkit-1.0/";
  114. else
  115. imageNetPath = "/home/dbv/bilder/imagenet/devkit-1.0/";
  116. ImageNetData imageNetTrain ( imageNetPath + "demo/" );
  117. imageNetTrain.preloadData( "train", "training" );
  118. trainingData = imageNetTrain.getPreloadedData();
  119. y = imageNetTrain.getPreloadedLabels();
  120. std::cerr << "Reading of training data finished" << std::endl;
  121. std::cerr << "trainingData.size(): " << trainingData.size() << std::endl;
  122. std::cerr << "y.size(): " << y.size() << std::endl;
  123. std::cerr << "Reading ImageNet test data files (takes some seconds)..." << std::endl;
  124. ImageNetData imageNetTest ( imageNetPath + "demo/" );
  125. imageNetTest.preloadData ( "val", "testing" );
  126. imageNetTest.loadExternalLabels ( imageNetPath + "data/ILSVRC2010_validation_ground_truth.txt" );
  127. // -------- select training set -------------
  128. NICE::Vector knownClassLabels(5,0.0);
  129. for (int k=1; k<6; k++)
  130. knownClassLabels(k-1) = k;
  131. std::vector<SparseVector> currentTrainingData;
  132. currentTrainingData.clear();
  133. NICE::Vector currentTrainingLabels(nrOfExamplesPerClass*knownClassLabels.size(),0);
  134. int k(0);
  135. for (size_t i = 0; i < y.size(); i++)
  136. {
  137. for (size_t j=0; j<knownClassLabels.size(); j++)
  138. {
  139. if ( y[i] == knownClassLabels[j] )
  140. {
  141. currentTrainingLabels(k) = knownClassLabels[j];
  142. currentTrainingData.push_back(trainingData[i]);
  143. k++;
  144. break;
  145. }
  146. }
  147. }
  148. Timer tTrain;
  149. tTrain.start();
  150. //compute the kernel matrix
  151. NICE::Matrix kernelMatrix(nrOfExamplesPerClass*knownClassLabels.size(), nrOfExamplesPerClass*knownClassLabels.size(), 0.0);
  152. double kernelScore(0.0);
  153. int cl(0);
  154. for (size_t i = 0; i < kernelMatrix.rows(); i++)
  155. {
  156. for (size_t j = i; j < kernelMatrix.cols(); j++)
  157. {
  158. kernelScore = minimumDistance(currentTrainingData[i],currentTrainingData[j]);
  159. kernelMatrix(i-cl*100,j-cl*100) = kernelScore;
  160. if (i != j)
  161. kernelMatrix(j-cl*100,i-cl*100) = kernelScore;
  162. }
  163. }
  164. KernelData kernelData( &conf, kernelMatrix, "Kernel", false );
  165. KCNullSpaceNovelty knfst( &conf);
  166. knfst.teach(&kernelData, currentTrainingLabels);
  167. tTrain.stop();
  168. std::cerr << "Time used for training " << cl << ": " << tTrain.getLast() << std::endl;
  169. std::cerr << "training set statistic: " << std::endl;
  170. std::map<int,int>::iterator itt;
  171. for (itt = ( (std::map<int,int>) knfst.getTrainingSetStatistic() ).begin(); itt != knfst.getTrainingSetStatistic().end(); itt++)
  172. std::cerr << (*itt).first << " " << (*itt).second << std::endl;
  173. std::cerr << "one-class setting?: " << knfst.isOneClass() << std::endl;
  174. std::cerr << "null space dimension: "<< knfst.getNullSpaceDimension() << std::endl;
  175. std::cerr << "target points: " << std::endl;
  176. for (size_t k=0; k<knfst.getTargetPoints().size(); k++)
  177. std::cerr << knfst.getTargetPoints()[k] << std::endl;
  178. std::cerr << "training done - now perform the evaluation" << std::endl;
  179. // ------------------------------ TESTING ------------------------------
  180. std::cerr << "Classification step ... with " << imageNetTest.getNumPreloadedExamples() << " examples" << std::endl;
  181. ClassificationResults results;
  182. ProgressBar pb;
  183. Timer tTest;
  184. tTest.start();
  185. for ( uint i = 0 ; i < (uint)imageNetTest.getNumPreloadedExamples(); i++ )
  186. {
  187. pb.update ( imageNetTest.getNumPreloadedExamples() );
  188. const SparseVector & svec = imageNetTest.getPreloadedExample ( i );
  189. //compute (self) similarities
  190. double kernelSelf (minimumDistance(svec,svec) );
  191. NICE::Vector kernelVector (nrOfExamplesPerClass, 0.0);
  192. for (int j = 0; j < nrOfExamplesPerClass; j++)
  193. {
  194. kernelVector[j] = minimumDistance(currentTrainingData[j],svec);
  195. }
  196. ClassificationResult r;
  197. r = knfst.classifyKernel( kernelVector, kernelSelf);
  198. // set ground truth label
  199. r.classno_groundtruth = 0;
  200. for (size_t j=0; j<knownClassLabels.size(); j++)
  201. {
  202. if ( ((int)imageNetTest.getPreloadedLabel ( i )) == knownClassLabels[j] )
  203. {
  204. r.classno_groundtruth = 1;
  205. break;
  206. }
  207. }
  208. //remember the results for the evaluation lateron
  209. results.push_back ( r );
  210. }
  211. tTest.stop();
  212. std::cerr << "Time used for evaluation: " << tTest.getLast() << std::endl;
  213. double timeForSingleExample(0.0);
  214. timeForSingleExample = tTest.getLast()/imageNetTest.getNumPreloadedExamples();
  215. std::cerr.precision(10);
  216. std::cerr << "time used for evaluation single elements: " << timeForSingleExample << std::endl;
  217. // run the AUC-evaluation
  218. double perfvalue( 0.0 );
  219. perfvalue = results.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  220. std::cerr << " novelty detection performance: " << perfvalue << std::endl;
  221. return 0;
  222. }
  223. #else
  224. int main (int argc, char **argv)
  225. {
  226. std::cerr << "MatIO library is missing in your system - this program will have no effect. " << std::endl;
  227. }
  228. #endif