KCOneVsAll.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /**
  2. * @file KCOneVsAll.cpp
  3. * @brief One vs. All interface for kernel classifiers
  4. * @author Erik Rodner
  5. * @date 12/10/2009
  6. */
  7. #include <iostream>
  8. #include "KCOneVsAll.h"
  9. #include "core/vector/Algorithms.h"
  10. #include "core/algebra/CholeskyRobust.h"
  11. #include "core/algebra/CholeskyRobustAuto.h"
  12. #include "vislearning/regression/regressionbase/TeachWithInverseKernelMatrix.h"
  13. using namespace std;
  14. using namespace NICE;
  15. using namespace OBJREC;
  16. KCOneVsAll::KCOneVsAll( const Config *conf, const KernelClassifier *prototype, const string & section )
  17. : KernelClassifier ( conf, prototype->getKernelFunction() )
  18. {
  19. this->prototype = prototype;
  20. this->maxClassNo = 0;
  21. this->verbose = conf->gB( section, "verbose", false );
  22. }
  23. KCOneVsAll::~KCOneVsAll()
  24. {
  25. }
  26. void KCOneVsAll::teach ( KernelData *kernelData, const NICE::Vector & y )
  27. {
  28. maxClassNo = (int)y.Max();
  29. classifiers.clear();
  30. for ( int i = 0 ; i <= maxClassNo ; i++ )
  31. {
  32. NICE::Vector ySub ( y );
  33. for ( size_t j = 0 ; j < ySub.size() ; j++ )
  34. ySub[j] = ((int)y[j] == i) ? 1 : 0;
  35. KernelClassifier *classifier;
  36. classifier = prototype->clone();
  37. fprintf (stderr, "KCOneVsAll: training classifier class %d <-> remainder\n", i );
  38. KernelData *kernelDataCopy = kernelData->clone();
  39. classifier->teach ( kernelDataCopy, ySub );
  40. // FIXME: This might be trickier for kernel classifiers which need the kernel data
  41. // explicitly, but otherwise we get a huge! memory leak
  42. delete kernelDataCopy;
  43. classifiers.push_back ( pair<int, KernelClassifier*> (i, classifier) );
  44. }
  45. }
  46. ClassificationResult KCOneVsAll::classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const
  47. {
  48. if ( classifiers.size() <= 0 )
  49. fthrow(Exception, "The classifier was not trained with training data (use teach(...))");
  50. FullVector scores ( maxClassNo+1 );
  51. scores.set(0);
  52. for ( vector< pair<int, KernelClassifier *> >::const_iterator i =
  53. classifiers.begin(); i != classifiers.end(); i++ )
  54. {
  55. int classno = i->first;
  56. KernelClassifier *classifier = i->second;
  57. ClassificationResult r = classifier->classifyKernel(kernelVector, kernelSelf);
  58. scores[classno] += r.scores[1];
  59. }
  60. return ClassificationResult( scores.maxElement(), scores );
  61. }