KCGPRegOneVsAll.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /**
  2. * @file KCGPRegOneVsAll.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 <sstream>
  9. #ifdef NICE_USELIB_OPENMP
  10. #include <omp.h>
  11. #endif
  12. #include "core/vector/Algorithms.h"
  13. #include "core/optimization/gradientBased/OptimizationAlgorithmFirst.h"
  14. #include "core/optimization/gradientBased/FirstOrderTrustRegion.h"
  15. #include "core/optimization/gradientBased/FirstOrderRasmussen.h"
  16. #include "vislearning/regression/gpregression/GPRegressionOptimizationProblem.h"
  17. #include "core/algebra/CholeskyRobust.h"
  18. #include "core/algebra/CholeskyRobustAuto.h"
  19. #include "KCGPRegOneVsAll.h"
  20. #include <limits>
  21. #undef DEBUG
  22. using namespace NICE;
  23. using namespace std;
  24. using namespace OBJREC;
  25. KCGPRegOneVsAll::KCGPRegOneVsAll( const Config *conf, Kernel *kernelFunction, const string & section )
  26. : KernelClassifier ( conf, kernelFunction )
  27. {
  28. this->maxClassNo = 0;
  29. this->verbose = conf->gB( section, "verbose", false );
  30. this->optimizeParameters = (kernelFunction == NULL) ? false : conf->gB( section, "optimize_parameters", true );
  31. this->maxIterations = conf->gI( section, "optimization_maxiterations", 500 );
  32. this->numSamplesCalibration = conf->gI( section, "calibrated_probabilities_numsamples", 2000 );
  33. this->calibrateProbabilities = conf->gB( section, "calibrated_probabilities", false );
  34. if ( verbose && this->calibrateProbabilities )
  35. cerr << "KCGPRegOneVsAll: probability calibration is turned on, this can result in massive additional load!" << endl;
  36. // we do joint optimization, therefore single classifiers (cloned from prototype)
  37. // are not allowed to do optimization themselves
  38. Config confNoOptimize ( *conf );
  39. confNoOptimize.sB( section, "optimize_parameters", false );
  40. this->prototype = new RegGaussianProcess ( &confNoOptimize, kernelFunction, section );
  41. // Do not use this option, unless you know what you are doing!
  42. // This function is just necessary for hyperparameter optimization with really large
  43. // kernel matrices of a kronecker structure!
  44. bool approximateTraceTerm = conf->gB(section, "approximate_trace_term", false);
  45. if ( approximateTraceTerm )
  46. traceApproximation = new TraceApproximation ( conf, section );
  47. else
  48. traceApproximation = NULL;
  49. // select final hyperparameters according to leave-one-out
  50. useLooParameters = conf->gB(section, "use_loo_parameters", false );
  51. // select the criterion
  52. modelselcrit = NULL;
  53. if ( useLooParameters ) {
  54. string modelselcrit_s = conf->gS(section, "loo_crit", "loo_pred_prob" );
  55. modelselcrit = GenericGPModelSelection::selectModelSel ( conf, modelselcrit_s );
  56. cerr << "KCGPRegOneVsAll: using additional model selection criterion " << modelselcrit_s << endl;
  57. }
  58. // do we want to compute the uncertainty of the estimate ?
  59. computeUncertainty = conf->gB(section, "compute_uncertainty", false );
  60. }
  61. KCGPRegOneVsAll::KCGPRegOneVsAll( const KCGPRegOneVsAll &vcova ): KernelClassifier(vcova)
  62. {
  63. prototype = vcova.prototype->clone();
  64. optimizeParameters = vcova.optimizeParameters;
  65. verbose = vcova.verbose;
  66. maxIterations = vcova.maxIterations;
  67. useLooParameters = vcova.useLooParameters;
  68. computeUncertainty = vcova.computeUncertainty;
  69. choleskyMatrix = vcova.choleskyMatrix;
  70. calibrateProbabilities = vcova.calibrateProbabilities;
  71. numSamplesCalibration = vcova.numSamplesCalibration;
  72. for (int i = 0; i < (int)vcova.classifiers.size(); i++)
  73. {
  74. classifiers.push_back(pair<int, RegGaussianProcess*>(vcova.classifiers[i].first, vcova.classifiers[i].second->clone()));
  75. }
  76. if ( vcova.traceApproximation == NULL )
  77. traceApproximation = NULL;
  78. else
  79. traceApproximation = new TraceApproximation(*vcova.traceApproximation);
  80. if ( vcova.modelselcrit == NULL )
  81. modelselcrit = NULL;
  82. else
  83. modelselcrit = new GPMSCLooLikelihoodRegression(*vcova.modelselcrit);
  84. }
  85. KCGPRegOneVsAll::~KCGPRegOneVsAll()
  86. {
  87. if ( traceApproximation != NULL )
  88. delete traceApproximation;
  89. if ( modelselcrit != NULL )
  90. delete modelselcrit;
  91. }
  92. void KCGPRegOneVsAll::teach ( KernelData *kernelData, const NICE::Vector & y )
  93. {
  94. maxClassNo = (int)y.Max();
  95. set<int> classesUsed;
  96. for ( uint i = 0 ; i < y.size(); i++ )
  97. classesUsed.insert ( (int)y[i] );
  98. classifiers.clear();
  99. VVector ySet;
  100. VVector ySetZeroMean;
  101. for ( set<int>::const_iterator it = classesUsed.begin();
  102. it != classesUsed.end(); it++)
  103. {
  104. int i = *it;
  105. NICE::Vector ySub ( y.size() );
  106. NICE::Vector ySubZeroMean ( y.size() );
  107. for ( size_t j = 0 ; j < ySub.size() ; j++ )
  108. {
  109. ySub[j] = ((int)y[j] == i) ? 1 : 0;
  110. ySubZeroMean[j] = ((int)y[j] == i) ? 1 : -1;
  111. }
  112. ySet.push_back ( ySub );
  113. ySetZeroMean.push_back ( ySubZeroMean );
  114. }
  115. // Hyperparameter optimization
  116. if ( optimizeParameters )
  117. {
  118. ParameterizedKernel *kernelPara = dynamic_cast< ParameterizedKernel * > ( kernelFunction );
  119. if ( kernelPara == NULL ) {
  120. fthrow(Exception, "KCGPRegOneVsAll: you have to specify a parameterized kernel !");
  121. }
  122. GPRegressionOptimizationProblem gpopt ( kernelData, ySetZeroMean, kernelPara, verbose, modelselcrit, traceApproximation );
  123. // the trust region classifier is better for my large collection of one classification problem :)
  124. // FirstOrderRasmussen optimizer;
  125. FirstOrderTrustRegion optimizer;
  126. optimizer.setMaxIterations ( maxIterations );
  127. optimizer.setEpsilonG ( 0.01 );
  128. cout << "KCGPRegOneVsAll: Hyperparameter optimization ..." << endl;
  129. optimizer.optimizeFirst ( gpopt );
  130. cout << "KCGPRegOneVsAll: Hyperparameter optimization ...done" << endl;
  131. if ( useLooParameters )
  132. {
  133. cerr << "KCGPRegOneVsAll: using best loo parameters" << endl;
  134. gpopt.useLooParameters();
  135. }
  136. gpopt.update();
  137. Vector parameters;
  138. kernelPara->getParameters ( parameters );
  139. cout << "KCGPRegOneVsAll: Optimization finished: " << parameters << endl << endl;
  140. } else {
  141. kernelData->updateCholeskyFactorization();
  142. }
  143. //for binary problems
  144. if (classesUsed.size() == 2 && false)
  145. {
  146. set<int>::const_iterator it = classesUsed.begin();
  147. int classno = *it;
  148. it++;
  149. int classno2 = *it;
  150. const Vector & ySub = ySet[0];
  151. RegGaussianProcess *classifier;
  152. classifier = prototype->clone();
  153. if (verbose)
  154. fprintf (stderr, "KCGPRegOneVsAll: training classifier class %d <-> %d\n", classno, classno2 );
  155. classifier->teach ( kernelData, ySub );
  156. classifiers.push_back ( pair<int, RegGaussianProcess*> (classno, classifier) );
  157. classifiers.push_back ( pair<int, RegGaussianProcess*> (classno2, classifier) );
  158. }
  159. else
  160. {
  161. int i = 0;
  162. for ( set<int>::const_iterator it = classesUsed.begin(); it != classesUsed.end(); it++, i++)
  163. {
  164. int classno = *it;
  165. const Vector & ySubZeroMean = ySetZeroMean[i];
  166. RegGaussianProcess *classifier;
  167. classifier = prototype->clone();
  168. if (verbose)
  169. fprintf (stderr, "KCGPRegOneVsAll: training classifier class %d <-> remainder\n", classno );
  170. classifier->teach ( kernelData, ySubZeroMean );
  171. classifiers.push_back ( pair<int, RegGaussianProcess*> (classno, classifier) );
  172. }
  173. }
  174. if ( computeUncertainty || calibrateProbabilities )
  175. choleskyMatrix = kernelData->getCholeskyMatrix();
  176. }
  177. /**
  178. * @brief Completely the same, only using a different data structure to store the labels
  179. * @author Alexander Lütz
  180. * @date 18/08/2011
  181. */
  182. void KCGPRegOneVsAll::teach ( KernelData *kernelData, const std::vector<double> & y )
  183. {
  184. // FIXME: Do we really need this function? (erik)
  185. Vector y_nice (y);
  186. teach ( kernelData, y_nice );
  187. }
  188. ClassificationResult KCGPRegOneVsAll::classifyKernel ( const NICE::Vector & kernelVector, double kernelSelf ) const
  189. {
  190. if ( classifiers.size() <= 0 )
  191. fthrow(Exception, "The classifier was not trained with training data (use teach(...))");
  192. FullVector scores ( maxClassNo + 1 );
  193. scores.set(0);
  194. //for binary problems
  195. if (classifiers.size() == 2 && false)
  196. {
  197. int classno = classifiers[0].first;
  198. int classno2 = classifiers[1].first;
  199. RegGaussianProcess *classifier = classifiers[0].second;
  200. double yEstimate = classifier->predictKernel(kernelVector, kernelSelf);
  201. scores[classno] = yEstimate;
  202. scores[classno2] = 0;//1-yEstimate;
  203. //cout << "i: " << 0 << ": " << scores[classno] << endl;
  204. //cout << "i: " << 1 << ": " << scores[classno2] << endl;
  205. }
  206. else
  207. {
  208. #pragma omp parallel for
  209. for ( int classifierIndex = 0 ; classifierIndex < (int)classifiers.size(); classifierIndex++ )
  210. {
  211. int classno = classifiers[(uint)classifierIndex].first;
  212. RegGaussianProcess *classifier = classifiers[(uint)classifierIndex].second;
  213. double yEstimate = classifier->predictKernel(kernelVector, kernelSelf);
  214. scores[classno] += yEstimate;
  215. //cout << "i: " << classifierIndex << ": " << scores[classno] << endl;
  216. }
  217. }
  218. double uncertainty = 0.0;
  219. if ( computeUncertainty || calibrateProbabilities )
  220. {
  221. Vector tmp;
  222. choleskySolveLargeScale ( choleskyMatrix, kernelVector, tmp );
  223. // tmp = K^{-1} k*
  224. uncertainty = kernelSelf - kernelVector.scalarProduct ( tmp );
  225. /*if(uncertainty < 0.0)
  226. // uncertainty = 0.0;*/
  227. if ( calibrateProbabilities )
  228. {
  229. /*********************************************************************
  230. * Calibration of probabilities is based on the following
  231. * idea:
  232. *
  233. * The scores \mu_i (or scores[i]) and the uncertainty
  234. * r.uncertainty are the mean and the variance of the predictive
  235. * distribution p(y_i | ...). So actually we do not know the correct value for
  236. * y_i and therefore just taking the maximum score ignores this uncertainty
  237. * completely!
  238. * What we might want to have is the probability for each class k
  239. * p_k = p( k = argmax_i y_i )
  240. *
  241. * Calculating this probability for n>2 is intractable and we
  242. * have to do monte carlo estimation which is performed in the following code
  243. *
  244. * An alternative would be to approximate p_k with
  245. * p( mu_k >= max_{i != k} y_i ) = prod_{i != k} F_i(mu_k)
  246. * with F_i being the cumulative distribution of the normal distribution i
  247. *
  248. * Details: Erik Rodner, "Learning with Few Examples for Visual Recognition Problems", PhD thesis
  249. *
  250. ********************************************************************/
  251. double stddev = sqrt(uncertainty);
  252. FullVector calibratedScores ( maxClassNo + 1 );
  253. calibratedScores.set(0.0);
  254. for ( uint i = 0 ; i < numSamplesCalibration ; i++ )
  255. {
  256. uint cmaxClassno = 0;
  257. double cmax = - std::numeric_limits<double>::max();
  258. for ( int classifierIndex = 0 ; classifierIndex < (int)classifiers.size(); classifierIndex++ )
  259. {
  260. int classno = classifiers[(uint)classifierIndex].first;
  261. double s = randGaussDouble ( stddev ) + scores[classno];
  262. if ( s > cmax )
  263. {
  264. cmax = s;
  265. cmaxClassno = classno;
  266. }
  267. }
  268. calibratedScores[ cmaxClassno ]++;
  269. }
  270. calibratedScores.normalize();
  271. // calibrating probabilities should not affect our hard
  272. // decision for a specific class
  273. if ( verbose ) {
  274. if ( scores.maxElement() != calibratedScores.maxElement() )
  275. cerr << "Calibration of probabilities affected the hard decision, you should increase calibrated_probabilities_numsamples !!" << endl;
  276. }
  277. scores = calibratedScores;
  278. }
  279. }
  280. ClassificationResult r ( scores.maxElement(), scores );
  281. r.uncertainty = uncertainty;
  282. return r;
  283. }
  284. KCGPRegOneVsAll* KCGPRegOneVsAll::clone(void) const
  285. {
  286. KCGPRegOneVsAll *classifier = new KCGPRegOneVsAll( *this );
  287. return classifier;
  288. }
  289. void KCGPRegOneVsAll::clear()
  290. {
  291. //nothing to clear
  292. }
  293. void KCGPRegOneVsAll::restore(std::istream& ifs, int type)
  294. {
  295. ifs.precision (numeric_limits<double>::digits10 + 1);
  296. ifs >> maxClassNo;
  297. ifs >> computeUncertainty;
  298. ifs >> calibrateProbabilities;
  299. if (calibrateProbabilities || computeUncertainty)
  300. {
  301. ifs >> choleskyMatrix;
  302. }
  303. int size;
  304. ifs >> size;
  305. for (int i = 0; i < size; i++)
  306. {
  307. int tmp;
  308. ifs >> tmp;
  309. RegGaussianProcess *classifier;
  310. classifier = prototype->clone();
  311. classifier->restore(ifs);
  312. classifiers.push_back ( pair<int, RegGaussianProcess*> (tmp, classifier) );
  313. }
  314. KernelClassifier::restore(ifs, type);
  315. }
  316. void KCGPRegOneVsAll::store(std::ostream& ofs, int type) const
  317. {
  318. ofs.precision (numeric_limits<double>::digits10 + 1);
  319. ofs << maxClassNo << endl;
  320. ofs << computeUncertainty << endl;
  321. ofs << calibrateProbabilities << endl;
  322. if (calibrateProbabilities || computeUncertainty)
  323. {
  324. ofs << choleskyMatrix << endl;
  325. }
  326. ofs << classifiers.size() << endl;
  327. for (uint i = 0; i < classifiers.size(); i++)
  328. {
  329. ofs << classifiers[i].first << endl;
  330. classifiers[i].second->store(ofs);
  331. ofs << endl;
  332. }
  333. KernelClassifier::store(ofs, type);
  334. }