testNullSpaceNovelty.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 "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/KCNullSpaceNovelty.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. using namespace std;
  20. using namespace NICE;
  21. using namespace OBJREC;
  22. // --------------- THE KERNEL FUNCTION ( exponential kernel with euclidian distance ) ----------------------
  23. double measureDistance ( const NICE::SparseVector & a, const NICE::SparseVector & b, const double & sigma = 2.0)
  24. {
  25. double inner_sum(0.0);
  26. double d;
  27. //new version, where we needed on average 0.001707 s for each test sample
  28. NICE::SparseVector::const_iterator aIt = a.begin();
  29. NICE::SparseVector::const_iterator bIt = b.begin();
  30. //compute the euclidian distance between both feature vectores (given as SparseVectors)
  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. //normalization of the exponent
  64. inner_sum /= (2.0*sigma*sigma);
  65. //finally, compute the RBF-kernel score (RBF = radial basis function)
  66. return exp(-inner_sum);
  67. }
  68. // --------------- THE KERNEL FUNCTION ( HIK ) ----------------------
  69. double minimumDistance ( const NICE::SparseVector & a, const NICE::SparseVector & b )
  70. {
  71. double inner_sum(0.0);
  72. NICE::SparseVector::const_iterator aIt = a.begin();
  73. NICE::SparseVector::const_iterator bIt = b.begin();
  74. //compute the minimum distance between both feature vectores (given as SparseVectors)
  75. while ( (aIt != a.end()) && (bIt != b.end()) )
  76. {
  77. if (aIt->first == bIt->first)
  78. {
  79. inner_sum += std::min( aIt->second , bIt->second );
  80. aIt++;
  81. bIt++;
  82. }
  83. else if ( aIt->first < bIt->first)
  84. {
  85. aIt++;
  86. }
  87. else
  88. {
  89. bIt++;
  90. }
  91. }
  92. return inner_sum;
  93. }
  94. /**
  95. test the basic functionality of fast-hik hyperparameter optimization
  96. */
  97. int main (int argc, char **argv)
  98. {
  99. std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
  100. Config conf ( argc, argv );
  101. string resultsfile = conf.gS("main", "results", "results.txt" );
  102. int nrOfExamplesPerClass = conf.gI("main", "nrOfExamplesPerClass", 100);
  103. nrOfExamplesPerClass = std::min(nrOfExamplesPerClass, 100); // we do not have more than 100 examples per class
  104. // -------- read ImageNet data --------------
  105. std::vector<SparseVector> trainingData;
  106. NICE::Vector y;
  107. std::cerr << "Reading ImageNet data ..." << std::endl;
  108. bool imageNetLocal = conf.gB("main", "imageNetLocal" , false);
  109. string imageNetPath;
  110. if (imageNetLocal)
  111. imageNetPath = "/users2/rodner/data/imagenet/devkit-1.0/";
  112. else
  113. imageNetPath = "/home/dbv/bilder/imagenet/devkit-1.0/";
  114. ImageNetData imageNetTrain ( imageNetPath + "demo/" );
  115. imageNetTrain.preloadData( "train", "training" );
  116. trainingData = imageNetTrain.getPreloadedData();
  117. y = imageNetTrain.getPreloadedLabels();
  118. std::cerr << "Reading of training data finished" << std::endl;
  119. std::cerr << "trainingData.size(): " << trainingData.size() << std::endl;
  120. std::cerr << "y.size(): " << y.size() << std::endl;
  121. std::cerr << "Reading ImageNet test data files (takes some seconds)..." << std::endl;
  122. ImageNetData imageNetTest ( imageNetPath + "demo/" );
  123. imageNetTest.preloadData ( "val", "testing" );
  124. imageNetTest.loadExternalLabels ( imageNetPath + "data/ILSVRC2010_validation_ground_truth.txt" );
  125. // -------- select training set -------------
  126. NICE::Vector knownClassLabels(5,0.0);
  127. for (int k=1; k<6; k++)
  128. knownClassLabels(k-1) = k;
  129. std::vector<SparseVector> currentTrainingData;
  130. currentTrainingData.clear();
  131. NICE::Vector currentTrainingLabels(nrOfExamplesPerClass*knownClassLabels.size(),0);
  132. int k(0);
  133. for (size_t i = 0; i < y.size(); i++)
  134. {
  135. for (size_t j=0; j<knownClassLabels.size(); j++)
  136. {
  137. if ( y[i] == knownClassLabels[j] )
  138. {
  139. currentTrainingLabels(k) = knownClassLabels[j];
  140. currentTrainingData.push_back(trainingData[i]);
  141. k++;
  142. break;
  143. }
  144. }
  145. }
  146. Timer tTrain;
  147. tTrain.start();
  148. //compute the kernel matrix
  149. NICE::Matrix kernelMatrix(nrOfExamplesPerClass*knownClassLabels.size(), nrOfExamplesPerClass*knownClassLabels.size(), 0.0);
  150. double kernelScore(0.0);
  151. int cl(0);
  152. for (size_t i = 0; i < kernelMatrix.rows(); i++)
  153. {
  154. for (size_t j = i; j < kernelMatrix.cols(); j++)
  155. {
  156. kernelScore = minimumDistance(currentTrainingData[i],currentTrainingData[j]);
  157. kernelMatrix(i-cl*100,j-cl*100) = kernelScore;
  158. if (i != j)
  159. kernelMatrix(j-cl*100,i-cl*100) = kernelScore;
  160. }
  161. }
  162. KernelData kernelData( &conf, kernelMatrix, "Kernel", false );
  163. KCNullSpaceNovelty knfst( &conf);
  164. knfst.teach(&kernelData, currentTrainingLabels);
  165. tTrain.stop();
  166. std::cerr << "Time used for training " << cl << ": " << tTrain.getLast() << std::endl;
  167. std::cerr << "training set statistic: " << std::endl;
  168. std::map<int,int>::iterator itt;
  169. for (itt = ( (std::map<int,int>) knfst.getTrainingSetStatistic() ).begin(); itt != knfst.getTrainingSetStatistic().end(); itt++)
  170. std::cerr << (*itt).first << " " << (*itt).second << std::endl;
  171. std::cerr << "one-class setting?: " << knfst.isOneClass() << std::endl;
  172. std::cerr << "null space dimension: "<< knfst.getNullSpaceDimension() << std::endl;
  173. std::cerr << "target points: " << std::endl;
  174. for (size_t k=0; k<knfst.getTargetPoints().size(); k++)
  175. std::cerr << knfst.getTargetPoints()[k] << std::endl;
  176. std::cerr << "training done - now perform the evaluation" << std::endl;
  177. // ------------------------------ TESTING ------------------------------
  178. std::cerr << "Classification step ... with " << imageNetTest.getNumPreloadedExamples() << " examples" << std::endl;
  179. ClassificationResults results;
  180. ProgressBar pb;
  181. Timer tTest;
  182. tTest.start();
  183. for ( uint i = 0 ; i < (uint)imageNetTest.getNumPreloadedExamples(); i++ )
  184. {
  185. pb.update ( imageNetTest.getNumPreloadedExamples() );
  186. const SparseVector & svec = imageNetTest.getPreloadedExample ( i );
  187. //compute (self) similarities
  188. double kernelSelf (minimumDistance(svec,svec) );
  189. NICE::Vector kernelVector (nrOfExamplesPerClass, 0.0);
  190. for (int j = 0; j < nrOfExamplesPerClass; j++)
  191. {
  192. kernelVector[j] = minimumDistance(currentTrainingData[j],svec);
  193. }
  194. ClassificationResult r;
  195. r = knfst.classifyKernel( kernelVector, kernelSelf);
  196. // set ground truth label
  197. r.classno_groundtruth = 0;
  198. for (size_t j=0; j<knownClassLabels.size(); j++)
  199. {
  200. if ( ((int)imageNetTest.getPreloadedLabel ( i )) == knownClassLabels[j] )
  201. {
  202. r.classno_groundtruth = 1;
  203. break;
  204. }
  205. }
  206. //remember the results for the evaluation lateron
  207. results.push_back ( r );
  208. }
  209. tTest.stop();
  210. std::cerr << "Time used for evaluation: " << tTest.getLast() << std::endl;
  211. double timeForSingleExample(0.0);
  212. timeForSingleExample = tTest.getLast()/imageNetTest.getNumPreloadedExamples();
  213. std::cerr.precision(10);
  214. std::cerr << "time used for evaluation single elements: " << timeForSingleExample << std::endl;
  215. // run the AUC-evaluation
  216. double perfvalue( 0.0 );
  217. perfvalue = results.getBinaryClassPerformance( ClassificationResults::PERF_AUC );
  218. std::cerr << " novelty detection performance: " << perfvalue << std::endl;
  219. return 0;
  220. }