DTBOblique.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. split_steps = conf->gI(section, "split_steps", 20 );
  19. max_depth = conf->gI(section, "max_depth", 10 );
  20. minimum_information_gain = conf->gD(section, "minimum_information_gain", 10e-7 );
  21. minimum_entropy = conf->gD(section, "minimum_entropy", 10e-5 );
  22. use_shannon_entropy = conf->gB(section, "use_shannon_entropy", false );
  23. min_examples = conf->gI(section, "min_examples", 50);
  24. save_indices = conf->gB(section, "save_indices", false);
  25. lambdaInit = conf->gD(section, "lambda_init", 0.5 );
  26. regularizationType = conf->gI(section, "regularization_type", 1 );
  27. }
  28. DTBOblique::~DTBOblique()
  29. {
  30. }
  31. bool DTBOblique::entropyLeftRight (
  32. const FeatureValuesUnsorted & values,
  33. double threshold,
  34. double* stat_left,
  35. double* stat_right,
  36. double & entropy_left,
  37. double & entropy_right,
  38. double & count_left,
  39. double & count_right,
  40. int maxClassNo )
  41. {
  42. count_left = 0;
  43. count_right = 0;
  44. for ( FeatureValuesUnsorted::const_iterator i = values.begin();
  45. i != values.end();
  46. i++ )
  47. {
  48. int classno = i->second;
  49. double value = i->first;
  50. if ( value < threshold ) {
  51. stat_left[classno] += i->fourth;
  52. count_left+=i->fourth;
  53. }
  54. else
  55. {
  56. stat_right[classno] += i->fourth;
  57. count_right+=i->fourth;
  58. }
  59. }
  60. if ( (count_left == 0) || (count_right == 0) )
  61. return false;
  62. entropy_left = 0.0;
  63. for ( int j = 0 ; j <= maxClassNo ; j++ )
  64. if ( stat_left[j] != 0 )
  65. entropy_left -= stat_left[j] * log(stat_left[j]);
  66. entropy_left /= count_left;
  67. entropy_left += log(count_left);
  68. entropy_right = 0.0;
  69. for ( int j = 0 ; j <= maxClassNo ; j++ )
  70. if ( stat_right[j] != 0 )
  71. entropy_right -= stat_right[j] * log(stat_right[j]);
  72. entropy_right /= count_right;
  73. entropy_right += log (count_right);
  74. return true;
  75. }
  76. /** refresh data matrix X and label vector y */
  77. void DTBOblique::getDataAndLabel(
  78. const FeaturePool &fp,
  79. const Examples &examples,
  80. const std::vector<int> &examples_selection,
  81. NICE::Matrix & matX,
  82. NICE::Vector & vecY )
  83. {
  84. ConvolutionFeature *f = (ConvolutionFeature*)fp.begin()->second;
  85. int amountParams = f->getParameterLength();
  86. int amountExamples = examples_selection.size();
  87. NICE::Matrix X(amountExamples, amountParams, 0.0 );
  88. NICE::Vector y(amountExamples, 0.0);
  89. int matIndex = 0;
  90. for ( vector<int>::const_iterator si = examples_selection.begin();
  91. si != examples_selection.end();
  92. si++ )
  93. {
  94. const pair<int, Example> & p = examples[*si];
  95. const Example & ce = p.second;
  96. NICE::Vector pixelRepr = f->getFeatureVector( &ce );
  97. pixelRepr /= pixelRepr.Max();
  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 << "Examples: " << (int)examples_selection.size()
  185. << " (depth " << (int)depth << ")" << std::endl;
  186. #endif
  187. // initialize new node
  188. DecisionNode *node = new DecisionNode ();
  189. node->distribution = distribution;
  190. // stop criteria: max_depth, min_examples, min_entropy
  191. if ( depth > max_depth
  192. || (int)examples_selection.size() < min_examples
  193. || ( (e <= minimum_entropy) && (e != 0.0) ) ) // FIXME
  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;
  215. NICE::Vector y, beta;
  216. getDataAndLabel( fp, examples, examples_selection, X, y );
  217. // Preparing system of linear equations
  218. //NICE::Matrix XTX = X.transpose()*X;
  219. regularizeDataMatrix( X, XTXr, regularizationType, lambdaCurrent );
  220. // R *= lambdaCurrent;
  221. //choleskyDecomp(XTXr, G);
  222. //choleskyInvert(G, XTXr);
  223. G = NICE::invert(XTXr);
  224. NICE::Matrix temp = G * X.transpose();
  225. for ( int curClass = 0; curClass <= maxClassNo; curClass++ )
  226. {
  227. // One-vs-all: Transforming into {-1,+1} problem
  228. NICE::Vector yCur ( y.size(), -1.0 );
  229. int idx = 0;
  230. bool hasExamples = false;
  231. for ( vector<int>::const_iterator si = examples_selection.begin();
  232. si != examples_selection.end();
  233. si++, idx++ )
  234. {
  235. const pair<int, Example> & p = examples[*si];
  236. if (p.first == curClass)
  237. {
  238. yCur.set( idx, 1.0 );
  239. hasExamples = true;
  240. }
  241. }
  242. // is there a positive example for current class in current set?
  243. if (!hasExamples) continue;
  244. // Solve system of linear equations in a least squares manner
  245. beta.multiply(temp,yCur,false);
  246. // Updating parameter vector in convolutional feature
  247. f->setParameterVector( beta );
  248. // Feature Values
  249. values.clear();
  250. f->calcFeatureValues( examples, examples_selection, values);
  251. double minValue = (min_element ( values.begin(), values.end() ))->first;
  252. double maxValue = (max_element ( values.begin(), values.end() ))->first;
  253. if ( maxValue - minValue < 1e-7 )
  254. std::cerr << "DTBOblique: Difference between min and max of features values to small!" << std::endl;
  255. // get best thresholds by complete search
  256. for ( int i = 0; i < split_steps; i++ )
  257. {
  258. double threshold = (i * (maxValue - minValue ) / (double)split_steps)
  259. + minValue;
  260. // preparations
  261. double el, er;
  262. for ( int k = 0 ; k <= maxClassNo ; k++ )
  263. {
  264. distribution_left[k] = 0.0;
  265. distribution_right[k] = 0.0;
  266. }
  267. /** Test the current split */
  268. // Does another split make sense?
  269. double count_left;
  270. double count_right;
  271. if ( ! entropyLeftRight ( values, threshold,
  272. distribution_left, distribution_right,
  273. el, er, count_left, count_right, maxClassNo ) )
  274. continue;
  275. // information gain and entropy
  276. double pl = (count_left) / (count_left + count_right);
  277. double ig = e - pl*el - (1-pl)*er;
  278. if ( use_shannon_entropy )
  279. {
  280. double esplit = - ( pl*log(pl) + (1-pl)*log(1-pl) );
  281. ig = 2*ig / ( e + esplit );
  282. }
  283. if ( ig > best_ig )
  284. {
  285. best_ig = ig;
  286. best_threshold = threshold;
  287. best_beta = beta;
  288. for ( int k = 0 ; k <= maxClassNo ; k++ )
  289. {
  290. best_distribution_left[k] = distribution_left[k];
  291. best_distribution_right[k] = distribution_right[k];
  292. }
  293. best_entropy_left = el;
  294. best_entropy_right = er;
  295. }
  296. }
  297. }
  298. //cleaning up
  299. delete [] distribution_left;
  300. delete [] distribution_right;
  301. // stop criteria: minimum information gain
  302. if ( best_ig < minimum_information_gain )
  303. {
  304. #ifdef DEBUGTREE
  305. std::cerr << "DTBOblique: Minimum information gain reached!" << std::endl;
  306. #endif
  307. delete [] best_distribution_left;
  308. delete [] best_distribution_right;
  309. node->trainExamplesIndices = examples_selection;
  310. return node;
  311. }
  312. /** Save the best split to current node */
  313. f->setParameterVector( best_beta );
  314. values.clear();
  315. f->calcFeatureValues( examples, examples_selection, values);
  316. node->f = f->clone();
  317. node->threshold = best_threshold;
  318. /** Split examples according to best split function */
  319. vector<int> examples_left;
  320. vector<int> examples_right;
  321. examples_left.reserve ( values.size() / 2 );
  322. examples_right.reserve ( values.size() / 2 );
  323. for ( FeatureValuesUnsorted::const_iterator i = values.begin();
  324. i != values.end(); i++ )
  325. {
  326. double value = i->first;
  327. if ( value < best_threshold )
  328. examples_left.push_back ( i->third );
  329. else
  330. examples_right.push_back ( i->third );
  331. }
  332. #ifdef DEBUGTREE
  333. node->f->store( std::cerr );
  334. std::cerr << std::endl;
  335. std::cerr << "mutual information / shannon entropy " << best_ig << " entropy "
  336. << e << " left entropy " << best_entropy_left << " right entropy "
  337. << best_entropy_right << std::endl;
  338. #endif
  339. FullVector distribution_left_sparse ( distribution.size() );
  340. FullVector distribution_right_sparse ( distribution.size() );
  341. for ( int k = 0 ; k <= maxClassNo ; k++ )
  342. {
  343. double l = best_distribution_left[k];
  344. double r = best_distribution_right[k];
  345. if ( l != 0 )
  346. distribution_left_sparse[k] = l;
  347. if ( r != 0 )
  348. distribution_right_sparse[k] = r;
  349. #ifdef DEBUGTREE
  350. std::cerr << "DTBOblique: split of class " << k << " ("
  351. << l << " <-> " << r << ") " << std::endl;
  352. #endif
  353. }
  354. delete [] best_distribution_left;
  355. delete [] best_distribution_right;
  356. // update lambda by heuristic [Laptev/Buhmann, 2014]
  357. double lambdaLeft = lambdaCurrent *
  358. pow(((double)examples_selection.size()/(double)examples_left.size()),(2./f->getParameterLength()));
  359. double lambdaRight = lambdaCurrent *
  360. pow(((double)examples_selection.size()/(double)examples_right.size()),(2./f->getParameterLength()));
  361. #ifdef DEBUGTREE
  362. std::cerr << "regularization parameter lambda left " << lambdaLeft
  363. << " right " << lambdaRight << std::endl;
  364. #endif
  365. /** Recursion */
  366. // left child
  367. node->left = buildRecursive ( fp, examples, examples_left,
  368. distribution_left_sparse, best_entropy_left,
  369. maxClassNo, depth+1, lambdaLeft );
  370. // right child
  371. node->right = buildRecursive ( fp, examples, examples_right,
  372. distribution_right_sparse, best_entropy_right,
  373. maxClassNo, depth+1, lambdaRight );
  374. return node;
  375. }
  376. /** initial building method */
  377. DecisionNode *DTBOblique::build ( const FeaturePool & fp,
  378. const Examples & examples,
  379. int maxClassNo )
  380. {
  381. int index = 0;
  382. FullVector distribution ( maxClassNo+1 );
  383. vector<int> all;
  384. all.reserve ( examples.size() );
  385. for ( Examples::const_iterator j = examples.begin();
  386. j != examples.end(); j++ )
  387. {
  388. int classno = j->first;
  389. distribution[classno] += j->second.weight;
  390. all.push_back ( index );
  391. index++;
  392. }
  393. double entropy = 0.0;
  394. double sum = 0.0;
  395. for ( int i = 0 ; i < distribution.size(); i++ )
  396. {
  397. double val = distribution[i];
  398. if ( val <= 0.0 ) continue;
  399. entropy -= val*log(val);
  400. sum += val;
  401. }
  402. entropy /= sum;
  403. entropy += log(sum);
  404. return buildRecursive ( fp, examples, all, distribution,
  405. entropy, maxClassNo, 0, lambdaInit );
  406. }