DTBObliqueLS.cpp 17 KB

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