DTBOblique.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. /**
  2. * @file DTBOblique.cpp
  3. * @brief random oblique decision tree
  4. * @author Sven Sickert
  5. * @date 10/15/2014
  6. */
  7. #include <iostream>
  8. #include <time.h>
  9. #include "DTBOblique.h"
  10. #include "vislearning/features/fpfeatures/ConvolutionFeature.h"
  11. #include "core/vector/Algorithms.h"
  12. using namespace OBJREC;
  13. #define DEBUGTREE
  14. using namespace std;
  15. using namespace NICE;
  16. DTBOblique::DTBOblique ( const Config *conf, string section )
  17. {
  18. saveIndices = conf->gB( section, "save_indices", false);
  19. useShannonEntropy = conf->gB( section, "use_shannon_entropy", false );
  20. useOneVsOne = conf->gB( section, "use_one_vs_one", false );
  21. splitSteps = conf->gI( section, "split_steps", 20 );
  22. maxDepth = conf->gI( section, "max_depth", 10 );
  23. minExamples = conf->gI( section, "min_examples", 50);
  24. regularizationType = conf->gI( section, "regularization_type", 1 );
  25. minimumEntropy = conf->gD( section, "minimum_entropy", 10e-5 );
  26. minimumInformationGain = conf->gD( section, "minimum_information_gain", 10e-7 );
  27. lambdaInit = conf->gD( section, "lambda_init", 0.5 );
  28. }
  29. DTBOblique::~DTBOblique()
  30. {
  31. }
  32. bool DTBOblique::entropyLeftRight (
  33. const FeatureValuesUnsorted & values,
  34. double threshold,
  35. double* stat_left,
  36. double* stat_right,
  37. double & entropy_left,
  38. double & entropy_right,
  39. double & count_left,
  40. double & count_right,
  41. int maxClassNo )
  42. {
  43. count_left = 0;
  44. count_right = 0;
  45. for ( FeatureValuesUnsorted::const_iterator i = values.begin();
  46. i != values.end();
  47. i++ )
  48. {
  49. int classno = i->second;
  50. double value = i->first;
  51. if ( value < threshold ) {
  52. stat_left[classno] += i->fourth;
  53. count_left+=i->fourth;
  54. }
  55. else
  56. {
  57. stat_right[classno] += i->fourth;
  58. count_right+=i->fourth;
  59. }
  60. }
  61. if ( (count_left == 0) || (count_right == 0) )
  62. return false;
  63. entropy_left = 0.0;
  64. for ( int j = 0 ; j <= maxClassNo ; j++ )
  65. if ( stat_left[j] != 0 )
  66. entropy_left -= stat_left[j] * log(stat_left[j]);
  67. entropy_left /= count_left;
  68. entropy_left += log(count_left);
  69. entropy_right = 0.0;
  70. for ( int j = 0 ; j <= maxClassNo ; j++ )
  71. if ( stat_right[j] != 0 )
  72. entropy_right -= stat_right[j] * log(stat_right[j]);
  73. entropy_right /= count_right;
  74. entropy_right += log (count_right);
  75. return true;
  76. }
  77. /** refresh data matrix X and label vector y */
  78. void DTBOblique::getDataAndLabel(
  79. const FeaturePool &fp,
  80. const Examples &examples,
  81. const std::vector<int> &examples_selection,
  82. NICE::Matrix & matX,
  83. NICE::Vector & vecY )
  84. {
  85. ConvolutionFeature *f = (ConvolutionFeature*)fp.begin()->second;
  86. int amountParams = f->getParameterLength();
  87. int amountExamples = examples_selection.size();
  88. NICE::Matrix X(amountExamples, amountParams, 0.0 );
  89. NICE::Vector y(amountExamples, 0.0);
  90. int matIndex = 0;
  91. for ( vector<int>::const_iterator si = examples_selection.begin();
  92. si != examples_selection.end();
  93. si++ )
  94. {
  95. const pair<int, Example> & p = examples[*si];
  96. const Example & ce = p.second;
  97. NICE::Vector pixelRepr = f->getFeatureVector( &ce );
  98. double label = p.first * ce.weight;
  99. pixelRepr *= ce.weight;
  100. y.set( matIndex, label );
  101. X.setRow(matIndex,pixelRepr);
  102. matIndex++;
  103. }
  104. matX = X;
  105. vecY = y;
  106. }
  107. void DTBOblique::regularizeDataMatrix(
  108. const NICE::Matrix &X,
  109. NICE::Matrix &XTXreg,
  110. const int regOption,
  111. const double lambda )
  112. {
  113. XTXreg = X.transpose()*X;
  114. NICE::Matrix R;
  115. const int dim = X.cols();
  116. switch (regOption)
  117. {
  118. // identity matrix
  119. case 0:
  120. R.resize(dim,dim);
  121. R.setIdentity();
  122. R *= lambda;
  123. XTXreg += R;
  124. break;
  125. // differences operator, k=1
  126. case 1:
  127. R.resize(dim-1,dim);
  128. R.set( 0.0 );
  129. for ( int r = 0; r < dim-1; r++ )
  130. {
  131. R(r,r) = 1.0;
  132. R(r,r+1) = -1.0;
  133. }
  134. R = R.transpose()*R;
  135. R *= lambda;
  136. XTXreg += R;
  137. break;
  138. // difference operator, k=2
  139. case 2:
  140. R.resize(dim-2,dim);
  141. R.set( 0.0 );
  142. for ( int r = 0; r < dim-2; r++ )
  143. {
  144. R(r,r) = 1.0;
  145. R(r,r+1) = -2.0;
  146. R(r,r+2) = 1.0;
  147. }
  148. R = R.transpose()*R;
  149. R *= lambda;
  150. XTXreg += R;
  151. break;
  152. // as in [Chen et al., 2012]
  153. case 3:
  154. {
  155. NICE::Vector q ( dim, (1.0-lambda) );
  156. q[0] = 1;
  157. NICE::Matrix Q;
  158. Q.tensorProduct(q,q);
  159. R.multiply(XTXreg,Q);
  160. for ( int r = 0; r < dim; r++ )
  161. R(r,r) = q[r] * XTXreg(r,r);
  162. XTXreg = R;
  163. break;
  164. }
  165. // no regularization
  166. default:
  167. std::cerr << "DTBOblique::regularizeDataMatrix: No regularization applied!"
  168. << std::endl;
  169. break;
  170. }
  171. }
  172. /** recursive building method */
  173. DecisionNode *DTBOblique::buildRecursive(
  174. const FeaturePool & fp,
  175. const Examples & examples,
  176. std::vector<int> & examples_selection,
  177. FullVector & distribution,
  178. double e,
  179. int maxClassNo,
  180. int depth,
  181. double lambdaCurrent )
  182. {
  183. #ifdef DEBUGTREE
  184. std::cerr << "DTBOblique: Examples: " << (int)examples_selection.size()
  185. << ", Depth: " << (int)depth << ", Entropy: " << e << std::endl;
  186. #endif
  187. // initialize new node
  188. DecisionNode *node = new DecisionNode ();
  189. node->distribution = distribution;
  190. // stop criteria: maxDepth, minExamples, min_entropy
  191. if ( ( e <= minimumEntropy )
  192. || ( (int)examples_selection.size() < minExamples )
  193. || ( depth > maxDepth ) )
  194. {
  195. #ifdef DEBUGTREE
  196. std::cerr << "DTBOblique: Stopping criteria applied!" << std::endl;
  197. #endif
  198. node->trainExamplesIndices = examples_selection;
  199. return node;
  200. }
  201. // variables
  202. double best_threshold = 0.0;
  203. double best_ig = -1.0;
  204. FeatureValuesUnsorted values;
  205. double *best_distribution_left = new double [maxClassNo+1];
  206. double *best_distribution_right = new double [maxClassNo+1];
  207. double *distribution_left = new double [maxClassNo+1];
  208. double *distribution_right = new double [maxClassNo+1];
  209. double best_entropy_left = 0.0;
  210. double best_entropy_right = 0.0;
  211. ConvolutionFeature *f = (ConvolutionFeature*)fp.begin()->second;
  212. NICE::Vector best_beta = f->getParameterVector();
  213. // Creating data matrix X and label vector y
  214. NICE::Matrix X, XTXr, G, temp;
  215. NICE::Vector y, beta;
  216. getDataAndLabel( fp, examples, examples_selection, X, y );
  217. // Preparing system of linear equations
  218. regularizeDataMatrix( X, XTXr, regularizationType, lambdaCurrent );
  219. if (regularizationType == 3)
  220. {
  221. G = NICE::invert(XTXr);
  222. temp = G * X.transpose();
  223. }
  224. else
  225. {
  226. choleskyDecomp(XTXr, G);
  227. choleskyInvert(G, XTXr);
  228. temp = XTXr * X.transpose();
  229. }
  230. for ( int curClass = 0; curClass <= maxClassNo; curClass++ )
  231. {
  232. // One-vs-all: Transforming into {-1,+1} problem
  233. NICE::Vector yCur ( y.size(), -1.0 );
  234. int idx = 0;
  235. bool hasExamples = false;
  236. for ( vector<int>::const_iterator si = examples_selection.begin();
  237. si != examples_selection.end();
  238. si++, idx++ )
  239. {
  240. const pair<int, Example> & p = examples[*si];
  241. if (p.first == curClass)
  242. {
  243. yCur.set( idx, 1.0 );
  244. hasExamples = true;
  245. }
  246. }
  247. // TODO: One-vs-one: Transforming into {-1,0,+1} problem
  248. // is there a positive example for current class in current set?
  249. if (!hasExamples) continue;
  250. // Solve system of linear equations in a least squares manner
  251. beta.multiply(temp,yCur,false);
  252. // Updating parameter vector in convolutional feature
  253. f->setParameterVector( beta );
  254. // Feature Values
  255. values.clear();
  256. f->calcFeatureValues( examples, examples_selection, values);
  257. double minValue = (min_element ( values.begin(), values.end() ))->first;
  258. double maxValue = (max_element ( values.begin(), values.end() ))->first;
  259. if ( maxValue - minValue < 1e-7 )
  260. std::cerr << "DTBOblique: Difference between min and max of features values to small!" << std::endl;
  261. // get best thresholds using complete search
  262. for ( int i = 0; i < splitSteps; i++ )
  263. {
  264. double threshold = (i * (maxValue - minValue ) / (double)splitSteps)
  265. + minValue;
  266. // preparations
  267. double el, er;
  268. for ( int k = 0 ; k <= maxClassNo ; k++ )
  269. {
  270. distribution_left[k] = 0.0;
  271. distribution_right[k] = 0.0;
  272. }
  273. /** Test the current split */
  274. // Does another split make sense?
  275. double count_left;
  276. double count_right;
  277. if ( ! entropyLeftRight ( values, threshold,
  278. distribution_left, distribution_right,
  279. el, er, count_left, count_right, maxClassNo ) )
  280. continue;
  281. // information gain and entropy
  282. double pl = (count_left) / (count_left + count_right);
  283. double ig = e - pl*el - (1-pl)*er;
  284. if ( useShannonEntropy )
  285. {
  286. double esplit = - ( pl*log(pl) + (1-pl)*log(1-pl) );
  287. ig = 2*ig / ( e + esplit );
  288. }
  289. if ( ig > best_ig )
  290. {
  291. best_ig = ig;
  292. best_threshold = threshold;
  293. best_beta = beta;
  294. for ( int k = 0 ; k <= maxClassNo ; k++ )
  295. {
  296. best_distribution_left[k] = distribution_left[k];
  297. best_distribution_right[k] = distribution_right[k];
  298. }
  299. best_entropy_left = el;
  300. best_entropy_right = er;
  301. }
  302. }
  303. }
  304. // supress strange behaviour for values near zero (8.88178e-16)
  305. if (best_entropy_left < 1.0e-10 ) best_entropy_left = 0.0;
  306. if (best_entropy_right < 1.0e-10 ) best_entropy_right = 0.0;
  307. //cleaning up
  308. delete [] distribution_left;
  309. delete [] distribution_right;
  310. // stop criteria: minimum information gain
  311. if ( best_ig < minimumInformationGain )
  312. {
  313. #ifdef DEBUGTREE
  314. std::cerr << "DTBOblique: Minimum information gain reached!" << std::endl;
  315. #endif
  316. delete [] best_distribution_left;
  317. delete [] best_distribution_right;
  318. node->trainExamplesIndices = examples_selection;
  319. return node;
  320. }
  321. /** Save the best split to current node */
  322. f->setParameterVector( best_beta );
  323. values.clear();
  324. f->calcFeatureValues( examples, examples_selection, values);
  325. node->f = f->clone();
  326. node->threshold = best_threshold;
  327. /** Split examples according to best split function */
  328. vector<int> examples_left;
  329. vector<int> examples_right;
  330. examples_left.reserve ( values.size() / 2 );
  331. examples_right.reserve ( values.size() / 2 );
  332. for ( FeatureValuesUnsorted::const_iterator i = values.begin();
  333. i != values.end(); i++ )
  334. {
  335. double value = i->first;
  336. if ( value < best_threshold )
  337. examples_left.push_back ( i->third );
  338. else
  339. examples_right.push_back ( i->third );
  340. }
  341. #ifdef DEBUGTREE
  342. node->f->store( std::cerr );
  343. std::cerr << std::endl;
  344. std::cerr << "DTBOblique: Information Gain: " << best_ig
  345. << ", Left Entropy: " << best_entropy_left << ", Right Entropy: "
  346. << best_entropy_right << std::endl;
  347. #endif
  348. FullVector distribution_left_sparse ( distribution.size() );
  349. FullVector distribution_right_sparse ( distribution.size() );
  350. for ( int k = 0 ; k <= maxClassNo ; k++ )
  351. {
  352. double l = best_distribution_left[k];
  353. double r = best_distribution_right[k];
  354. if ( l != 0 )
  355. distribution_left_sparse[k] = l;
  356. if ( r != 0 )
  357. distribution_right_sparse[k] = r;
  358. #ifdef DEBUGTREE
  359. std::cerr << "DTBOblique: Split of Class " << k << " ("
  360. << l << " <-> " << r << ") " << std::endl;
  361. #endif
  362. }
  363. delete [] best_distribution_left;
  364. delete [] best_distribution_right;
  365. // update lambda by heuristic [Laptev/Buhmann, 2014]
  366. double lambdaLeft = lambdaCurrent *
  367. pow(((double)examples_selection.size()/(double)examples_left.size()),(2./f->getParameterLength()));
  368. double lambdaRight = lambdaCurrent *
  369. pow(((double)examples_selection.size()/(double)examples_right.size()),(2./f->getParameterLength()));
  370. //#ifdef DEBUGTREE
  371. // std::cerr << "regularization parameter lambda left " << lambdaLeft
  372. // << " right " << lambdaRight << std::endl;
  373. //#endif
  374. /** Recursion */
  375. // left child
  376. node->left = buildRecursive ( fp, examples, examples_left,
  377. distribution_left_sparse, best_entropy_left,
  378. maxClassNo, depth+1, lambdaLeft );
  379. // right child
  380. node->right = buildRecursive ( fp, examples, examples_right,
  381. distribution_right_sparse, best_entropy_right,
  382. maxClassNo, depth+1, lambdaRight );
  383. return node;
  384. }
  385. /** initial building method */
  386. DecisionNode *DTBOblique::build ( const FeaturePool & fp,
  387. const Examples & examples,
  388. int maxClassNo )
  389. {
  390. int index = 0;
  391. FullVector distribution ( maxClassNo+1 );
  392. vector<int> all;
  393. all.reserve ( examples.size() );
  394. for ( Examples::const_iterator j = examples.begin();
  395. j != examples.end(); j++ )
  396. {
  397. int classno = j->first;
  398. distribution[classno] += j->second.weight;
  399. all.push_back ( index );
  400. index++;
  401. }
  402. double entropy = 0.0;
  403. double sum = 0.0;
  404. for ( int i = 0 ; i < distribution.size(); i++ )
  405. {
  406. double val = distribution[i];
  407. if ( val <= 0.0 ) continue;
  408. entropy -= val*log(val);
  409. sum += val;
  410. }
  411. entropy /= sum;
  412. entropy += log(sum);
  413. return buildRecursive ( fp, examples, all, distribution,
  414. entropy, maxClassNo, 0, lambdaInit );
  415. }