DTBObliqueLS.cpp 16 KB

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