DTBOblique.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. bool DTBOblique::adaptDataAndLabelForMultiClass (
  78. const int posClass,
  79. const int negClass,
  80. NICE::Matrix & X,
  81. NICE::Vector & y )
  82. {
  83. bool posHasExamples = false;
  84. bool negHasExamples = false;
  85. // One-vs-one: Transforming into {-1,0,+1} problem
  86. if ( useOneVsOne )
  87. for ( int i = 0; i < y.size(); i++ )
  88. {
  89. if ( y[i] == posClass )
  90. {
  91. y[i] = 1.0;
  92. posHasExamples = true;
  93. }
  94. else if ( y[i] == negClass )
  95. {
  96. y[i] = -1.0;
  97. negHasExamples = true;
  98. }
  99. else
  100. {
  101. y[i] = 0.0;
  102. X.setRow( i, NICE::Vector( X.cols(), 0.0 ) );
  103. }
  104. }
  105. // One-vs-all: Transforming into {-1,+1} problem
  106. else
  107. for ( int i = 0; i < y.size(); i++ )
  108. {
  109. if ( y[i] == posClass )
  110. {
  111. y[i] = 1.0;
  112. posHasExamples = true;
  113. }
  114. else
  115. {
  116. y[i] = -1.0;
  117. negHasExamples = true;
  118. }
  119. }
  120. if ( posHasExamples && negHasExamples )
  121. return true;
  122. else
  123. return false;
  124. }
  125. /** refresh data matrix X and label vector y */
  126. void DTBOblique::getDataAndLabel(
  127. const FeaturePool &fp,
  128. const Examples &examples,
  129. const std::vector<int> &examples_selection,
  130. NICE::Matrix & X,
  131. NICE::Vector & y,
  132. NICE::Vector & w )
  133. {
  134. ConvolutionFeature *f = (ConvolutionFeature*)fp.begin()->second;
  135. int amountParams = f->getParameterLength();
  136. int amountExamples = examples_selection.size();
  137. X = NICE::Matrix(amountExamples, amountParams, 0.0 );
  138. y = NICE::Vector(amountExamples, 0.0);
  139. w = NICE::Vector(amountExamples, 1.0);
  140. int matIndex = 0;
  141. for ( vector<int>::const_iterator si = examples_selection.begin();
  142. si != examples_selection.end();
  143. si++ )
  144. {
  145. const pair<int, Example> & p = examples[*si];
  146. const Example & ex = p.second;
  147. NICE::Vector pixelRepr = f->getFeatureVector( &ex );
  148. double label = p.first;
  149. pixelRepr *= ex.weight;
  150. w.set ( matIndex, ex.weight );
  151. y.set ( matIndex, label );
  152. X.setRow ( matIndex, pixelRepr );
  153. matIndex++;
  154. }
  155. }
  156. void DTBOblique::regularizeDataMatrix(
  157. const NICE::Matrix &X,
  158. NICE::Matrix &XTXreg,
  159. const int regOption,
  160. const double lambda )
  161. {
  162. XTXreg = X.transpose()*X;
  163. NICE::Matrix R;
  164. const int dim = X.cols();
  165. switch (regOption)
  166. {
  167. // identity matrix
  168. case 0:
  169. R.resize(dim,dim);
  170. R.setIdentity();
  171. R *= lambda;
  172. XTXreg += R;
  173. break;
  174. // differences operator, k=1
  175. case 1:
  176. R.resize(dim-1,dim);
  177. R.set( 0.0 );
  178. for ( int r = 0; r < dim-1; r++ )
  179. {
  180. R(r,r) = 1.0;
  181. R(r,r+1) = -1.0;
  182. }
  183. R = R.transpose()*R;
  184. R *= lambda;
  185. XTXreg += R;
  186. break;
  187. // difference operator, k=2
  188. case 2:
  189. R.resize(dim-2,dim);
  190. R.set( 0.0 );
  191. for ( int r = 0; r < dim-2; r++ )
  192. {
  193. R(r,r) = 1.0;
  194. R(r,r+1) = -2.0;
  195. R(r,r+2) = 1.0;
  196. }
  197. R = R.transpose()*R;
  198. R *= lambda;
  199. XTXreg += R;
  200. break;
  201. // as in [Chen et al., 2012]
  202. case 3:
  203. {
  204. NICE::Vector q ( dim, (1.0-lambda) );
  205. q[0] = 1.0;
  206. NICE::Matrix Q;
  207. Q.tensorProduct(q,q);
  208. //R.multiply(XTXreg,Q);
  209. // element-wise multiplication
  210. R.resize(dim,dim);
  211. for ( int r = 0; r < dim; r++ )
  212. {
  213. for ( int c = 0; c < dim; c++ )
  214. R(r,c) = XTXreg(r,c) * Q(r,c);
  215. R(r,r) = q[r] * XTXreg(r,r);
  216. }
  217. XTXreg = R;
  218. break;
  219. }
  220. // no regularization
  221. default:
  222. std::cerr << "DTBOblique::regularizeDataMatrix: No regularization applied!"
  223. << std::endl;
  224. break;
  225. }
  226. }
  227. void DTBOblique::findBestSplitThreshold (
  228. FeatureValuesUnsorted &values,
  229. SplitInfo &bestSplitInfo,
  230. const NICE::Vector &beta,
  231. const double &e,
  232. const int &maxClassNo )
  233. {
  234. double *distribution_left = new double [maxClassNo+1];
  235. double *distribution_right = new double [maxClassNo+1];
  236. double minValue = (min_element ( values.begin(), values.end() ))->first;
  237. double maxValue = (max_element ( values.begin(), values.end() ))->first;
  238. if ( maxValue - minValue < 1e-7 )
  239. std::cerr << "DTBOblique: Difference between min and max of features values to small!"
  240. << " [" << minValue << "," << maxValue << "]" << std::endl;
  241. // get best thresholds using complete search
  242. for ( int i = 0; i < splitSteps; i++ )
  243. {
  244. double threshold = (i * (maxValue - minValue ) / (double)splitSteps)
  245. + minValue;
  246. // preparations
  247. double el, er;
  248. for ( int k = 0 ; k <= maxClassNo ; k++ )
  249. {
  250. distribution_left[k] = 0.0;
  251. distribution_right[k] = 0.0;
  252. }
  253. /** Test the current split */
  254. // Does another split make sense?
  255. double count_left;
  256. double count_right;
  257. if ( ! entropyLeftRight ( values, threshold,
  258. distribution_left, distribution_right,
  259. el, er, count_left, count_right, maxClassNo ) )
  260. continue;
  261. // information gain and entropy
  262. double pl = (count_left) / (count_left + count_right);
  263. double ig = e - pl*el - (1-pl)*er;
  264. if ( useShannonEntropy )
  265. {
  266. double esplit = - ( pl*log(pl) + (1-pl)*log(1-pl) );
  267. ig = 2*ig / ( e + esplit );
  268. }
  269. if ( ig > bestSplitInfo.informationGain )
  270. {
  271. bestSplitInfo.informationGain = ig;
  272. bestSplitInfo.threshold = threshold;
  273. bestSplitInfo.params = beta;
  274. for ( int k = 0 ; k <= maxClassNo ; k++ )
  275. {
  276. bestSplitInfo.distLeft[k] = distribution_left[k];
  277. bestSplitInfo.distRight[k] = distribution_right[k];
  278. }
  279. bestSplitInfo.entropyLeft = el;
  280. bestSplitInfo.entropyRight = er;
  281. }
  282. }
  283. //cleaning up
  284. delete [] distribution_left;
  285. delete [] distribution_right;
  286. }
  287. /** recursive building method */
  288. DecisionNode *DTBOblique::buildRecursive(
  289. const FeaturePool & fp,
  290. const Examples & examples,
  291. std::vector<int> & examples_selection,
  292. FullVector & distribution,
  293. double e,
  294. int maxClassNo,
  295. int depth,
  296. double lambdaCurrent )
  297. {
  298. #ifdef DEBUGTREE
  299. std::cerr << "DTBOblique: Examples: " << (int)examples_selection.size()
  300. << ", Depth: " << (int)depth << ", Entropy: " << e << std::endl;
  301. #endif
  302. // initialize new node
  303. DecisionNode *node = new DecisionNode ();
  304. node->distribution = distribution;
  305. // stop criteria: maxDepth, minExamples, min_entropy
  306. if ( ( e <= minimumEntropy )
  307. || ( (int)examples_selection.size() < minExamples )
  308. || ( depth > maxDepth ) )
  309. {
  310. #ifdef DEBUGTREE
  311. std::cerr << "DTBOblique: Stopping criteria applied!" << std::endl;
  312. #endif
  313. node->trainExamplesIndices = examples_selection;
  314. return node;
  315. }
  316. // variables
  317. FeatureValuesUnsorted values;
  318. SplitInfo bestSplitInfo;
  319. bestSplitInfo.threshold = 0.0;
  320. bestSplitInfo.informationGain = -1.0;
  321. bestSplitInfo.distLeft = new double [maxClassNo+1];
  322. bestSplitInfo.distRight = new double [maxClassNo+1];
  323. bestSplitInfo.entropyLeft = 0.0;
  324. bestSplitInfo.entropyRight = 0.0;
  325. ConvolutionFeature *f = (ConvolutionFeature*)fp.begin()->second;
  326. bestSplitInfo.params = f->getParameterVector();
  327. // Creating data matrix X and label vector y
  328. NICE::Matrix X;
  329. NICE::Vector y, beta, weights;
  330. getDataAndLabel( fp, examples, examples_selection, X, y, weights );
  331. // Transforming into multi-class problem
  332. for ( int posClass = 0; posClass <= maxClassNo; posClass++ )
  333. {
  334. bool gotInnerIteration = false;
  335. for ( int negClass = 0; negClass <= maxClassNo; negClass++ )
  336. {
  337. if ( posClass == negClass ) continue;
  338. NICE::Vector yCur = y;
  339. NICE::Matrix XCur = X;
  340. bool hasExamples = adaptDataAndLabelForMultiClass(
  341. posClass, negClass, XCur, yCur );
  342. yCur *= weights;
  343. // are there examples for positive and negative class?
  344. if ( !hasExamples ) continue;
  345. // one-vs-all setting: only one iteration for inner loop
  346. if ( !useOneVsOne && gotInnerIteration ) continue;
  347. // Preparing system of linear equations
  348. NICE::Matrix XTXr, G, temp;
  349. regularizeDataMatrix( XCur, XTXr, regularizationType, lambdaCurrent );
  350. choleskyDecomp(XTXr, G);
  351. choleskyInvert(G, XTXr);
  352. temp = XTXr * XCur.transpose();
  353. // Solve system of linear equations in a least squares manner
  354. beta.multiply(temp,yCur,false);
  355. // Updating parameter vector in convolutional feature
  356. f->setParameterVector( beta );
  357. // Feature Values
  358. values.clear();
  359. f->calcFeatureValues( examples, examples_selection, values);
  360. // complete search for threshold
  361. findBestSplitThreshold ( values, bestSplitInfo, beta, e, maxClassNo );
  362. gotInnerIteration = true;
  363. }
  364. }
  365. // supress strange behaviour for values near zero (8.88178e-16)
  366. if (bestSplitInfo.entropyLeft < 1.0e-10 ) bestSplitInfo.entropyLeft = 0.0;
  367. if (bestSplitInfo.entropyRight < 1.0e-10 ) bestSplitInfo.entropyRight = 0.0;
  368. // stop criteria: minimum information gain
  369. if ( bestSplitInfo.informationGain < minimumInformationGain )
  370. {
  371. #ifdef DEBUGTREE
  372. std::cerr << "DTBOblique: Minimum information gain reached!" << std::endl;
  373. #endif
  374. delete [] bestSplitInfo.distLeft;
  375. delete [] bestSplitInfo.distRight;
  376. node->trainExamplesIndices = examples_selection;
  377. return node;
  378. }
  379. /** Save the best split to current node */
  380. f->setParameterVector( bestSplitInfo.params );
  381. values.clear();
  382. f->calcFeatureValues( examples, examples_selection, values);
  383. node->f = f->clone();
  384. node->threshold = bestSplitInfo.threshold;
  385. /** Split examples according to best split function */
  386. vector<int> examples_left;
  387. vector<int> examples_right;
  388. examples_left.reserve ( values.size() / 2 );
  389. examples_right.reserve ( values.size() / 2 );
  390. for ( FeatureValuesUnsorted::const_iterator i = values.begin();
  391. i != values.end(); i++ )
  392. {
  393. if ( i->first < bestSplitInfo.threshold )
  394. examples_left.push_back ( i->third );
  395. else
  396. examples_right.push_back ( i->third );
  397. }
  398. #ifdef DEBUGTREE
  399. // node->f->store( std::cerr );
  400. // std::cerr << std::endl;
  401. std::cerr << "DTBOblique: Information Gain: " << bestSplitInfo.informationGain
  402. << ", Left Entropy: " << bestSplitInfo.entropyLeft << ", Right Entropy: "
  403. << bestSplitInfo.entropyRight << std::endl;
  404. #endif
  405. FullVector distribution_left_sparse ( distribution.size() );
  406. FullVector distribution_right_sparse ( distribution.size() );
  407. for ( int k = 0 ; k <= maxClassNo ; k++ )
  408. {
  409. double l = bestSplitInfo.distLeft[k];
  410. double r = bestSplitInfo.distRight[k];
  411. if ( l != 0 )
  412. distribution_left_sparse[k] = l;
  413. if ( r != 0 )
  414. distribution_right_sparse[k] = r;
  415. //#ifdef DEBUGTREE
  416. // std::cerr << "DTBOblique: Split of Class " << k << " ("
  417. // << l << " <-> " << r << ") " << std::endl;
  418. //#endif
  419. }
  420. delete [] bestSplitInfo.distLeft;
  421. delete [] bestSplitInfo.distRight;
  422. // update lambda by heuristic [Laptev/Buhmann, 2014]
  423. double lambdaLeft = lambdaCurrent *
  424. pow(((double)examples_selection.size()/(double)examples_left.size()),(2./f->getParameterLength()));
  425. double lambdaRight = lambdaCurrent *
  426. pow(((double)examples_selection.size()/(double)examples_right.size()),(2./f->getParameterLength()));
  427. //#ifdef DEBUGTREE
  428. // std::cerr << "regularization parameter lambda left " << lambdaLeft
  429. // << " right " << lambdaRight << std::endl;
  430. //#endif
  431. /** Recursion */
  432. // left child
  433. node->left = buildRecursive ( fp, examples, examples_left,
  434. distribution_left_sparse, bestSplitInfo.entropyLeft,
  435. maxClassNo, depth+1, lambdaLeft );
  436. // right child
  437. node->right = buildRecursive ( fp, examples, examples_right,
  438. distribution_right_sparse, bestSplitInfo.entropyRight,
  439. maxClassNo, depth+1, lambdaRight );
  440. return node;
  441. }
  442. /** initial building method */
  443. DecisionNode *DTBOblique::build ( const FeaturePool & fp,
  444. const Examples & examples,
  445. int maxClassNo )
  446. {
  447. int index = 0;
  448. FullVector distribution ( maxClassNo+1 );
  449. vector<int> all;
  450. all.reserve ( examples.size() );
  451. for ( Examples::const_iterator j = examples.begin();
  452. j != examples.end(); j++ )
  453. {
  454. int classno = j->first;
  455. distribution[classno] += j->second.weight;
  456. all.push_back ( index );
  457. index++;
  458. }
  459. double entropy = 0.0;
  460. double sum = 0.0;
  461. for ( int i = 0 ; i < distribution.size(); i++ )
  462. {
  463. double val = distribution[i];
  464. if ( val <= 0.0 ) continue;
  465. entropy -= val*log(val);
  466. sum += val;
  467. }
  468. entropy /= sum;
  469. entropy += log(sum);
  470. return buildRecursive ( fp, examples, all, distribution,
  471. entropy, maxClassNo, 0, lambdaInit );
  472. }