progCodebookRandomForest.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /**
  2. * @brief Extremely randomized clustering forest program for Matlab input data.
  3. *
  4. * @author Johannes Ruehle
  5. * @date 10/05/2014
  6. */
  7. #include <string>
  8. #include <exception>
  9. #include <iostream>
  10. #include <fstream>
  11. //----------
  12. #include "vislearning/features/simplefeatures/CodebookRandomForest.h"
  13. #include "vislearning/features/fpfeatures/VectorFeature.h"
  14. #include "vislearning/cbaselib/FeaturePool.h"
  15. #include <core/matlabAccess/MatFileIO.h>
  16. const bool verbose = false;
  17. const bool verboseStartEnd = true;
  18. using namespace OBJREC;
  19. using namespace NICE;
  20. using namespace std;
  21. #undef DEBUG_VERBOSE
  22. struct structCommands
  23. {
  24. QString sFunction;
  25. QString sFileTrainData;
  26. QString sFileTrainDataLabels;
  27. QString sConfigFile;
  28. QString sFileStoreClassifier; // txt file storing the config of the trained codebook rdf
  29. QString sFileStoreResult; // matlab mat file storing the generated histogram
  30. };
  31. bool loadMatlabMatrix(const std::string &sFilename, const std::string &matrix_name, NICE::Matrix &p_Matrix)
  32. {
  33. NICE::MatFileIO matlab_file(sFilename, MAT_ACC_RDONLY);
  34. #ifdef DEBUG_VERBOSE
  35. // Show the number of variables in the file
  36. int vars_in_file = matlab_file.getNumberOfVariables();
  37. std::cout << vars_in_file << " Variables in " << sFilename << "\n";
  38. // Load the matrix
  39. std::cout << "Loading matrix \"" << matrix_name << "\"...\n";
  40. #endif
  41. // Check if the variable is a matrix
  42. matvar_t* matrix_variable = matlab_file.getVariableViaName(matrix_name);
  43. if(matrix_variable == NULL)
  44. {
  45. std::cout << "variable is not found in mat file.\n";
  46. return false;
  47. }
  48. if(matrix_variable->rank != 2) {
  49. std::cout << "Variable is not a matrix. Rank: " << matrix_variable->rank << ".\n";
  50. return false;
  51. }
  52. // Read the dimensions
  53. int cols = matrix_variable->dims[1];
  54. int rows = matrix_variable->dims[0];
  55. std::cout << "Dimensions: " << cols << " x " << rows << "\n";
  56. // Read the matrix into a vector of vectors
  57. std::vector< std::vector<double> > matrix_vecvec(rows, std::vector<double>(cols));
  58. matlab_file.getFeatureMatrixViaName(matrix_vecvec, matrix_name);
  59. // Now, we want a NICE matrix
  60. //NICE::MatrixT<double> matrix(rows, cols);
  61. p_Matrix.resize(rows, cols);
  62. for(int i = 0; i < rows; i++) {
  63. for(int j = 0; j < cols; j++) {
  64. p_Matrix(i,j) = matrix_vecvec[i][j];
  65. }
  66. }
  67. return true;
  68. }
  69. NICE::Matrix* loadMatlabVec(const std::string &sFilename, const std::string &matrix_name)
  70. {
  71. NICE::Matrix *pMatrix = NULL;
  72. NICE::MatFileIO *matFile = new NICE::MatFileIO(sFilename, MAT_ACC_RDONLY );
  73. matvar_t *t = matFile->getVariableViaName(matrix_name);
  74. if ( t->class_type == MAT_C_DOUBLE)
  75. {
  76. double *pD = (double*)( t->data );
  77. pMatrix = new NICE::Matrix(pD , (int)t->dims[0], (int)t->dims[1], Matrix::copy );
  78. }
  79. else
  80. {
  81. std::cerr << "raw format of matlab matrix not supported" << std::endl;
  82. }
  83. Mat_VarFree(t);
  84. delete matFile;
  85. return pMatrix;
  86. }
  87. bool saveMatlabVector(const std::string &sFilename, const NICE::Vector &p_Vector, int p_iFodID)
  88. {
  89. std::ofstream ofs;
  90. ofs.open (sFilename.c_str(), std::ofstream::out);
  91. if (!ofs.is_open())
  92. return false;
  93. ofs << p_iFodID << " #fodID" << std::endl;
  94. ofs << p_Vector.size() << std::endl;
  95. for(int i=0; i<p_Vector.size(); i++)
  96. ofs << p_Vector[i] << std::endl;
  97. ofs.close();
  98. return true;
  99. }
  100. bool storeClassifier(const structCommands &p_Command, const OBJREC::CodebookRandomForest *p_pCodebookRandomForest)
  101. {
  102. if( p_Command.sFileStoreClassifier.isEmpty() )
  103. return false;
  104. std::string t_sDestinationSave = p_Command.sFileStoreClassifier.toStdString();
  105. std::ofstream ofs;
  106. ofs.open (t_sDestinationSave.c_str(), std::ofstream::out);
  107. p_pCodebookRandomForest->store( ofs );
  108. ofs.close();
  109. return true;
  110. }
  111. bool restoreClassifier(const structCommands &p_Command, OBJREC::CodebookRandomForest *p_pCodebookRandomForest)
  112. {
  113. if( p_Command.sFileStoreClassifier.isEmpty() )
  114. return false;
  115. if (p_pCodebookRandomForest == NULL )
  116. return false;
  117. std::string t_sDestinationSave = p_Command.sFileStoreClassifier.toStdString();
  118. std::ifstream ifs2;
  119. ifs2.open (t_sDestinationSave.c_str() );
  120. p_pCodebookRandomForest->restore( ifs2 );
  121. ifs2.close();
  122. return true;
  123. }
  124. bool createAndTrain( const structCommands &p_Command)
  125. {
  126. if( p_Command.sConfigFile.isEmpty() )
  127. {
  128. std::cout << "no config file provided. Exiting" << std::endl;
  129. return false;
  130. }
  131. NICE::Config t_conf = NICE::Config( p_Command.sConfigFile.toStdString() );
  132. Matrix *t_pMatDataTrain = loadMatlabVec( p_Command.sFileTrainData.toStdString(), "matFeatures");
  133. if( t_pMatDataTrain == NULL )
  134. {
  135. std::cout << "Training data Matrix couldn't be loaded" << std::endl;
  136. return 0;
  137. }
  138. #ifdef DEBUG_VERBOSE
  139. for(int i = 0; i<10; i++)
  140. {
  141. std::cerr << (*t_pMatDataTrain)(i,0) << " ## " << (*t_pMatDataTrain)(0,i) << std::endl;
  142. }
  143. #endif
  144. Matrix *t_pMatDataTrainLabels = loadMatlabVec( p_Command.sFileTrainDataLabels.toStdString(), "matLabels");
  145. if( t_pMatDataTrainLabels == NULL )
  146. {
  147. std::cout << "Training data label Matrix couldn't be loaded" << std::endl;
  148. return 0;
  149. }
  150. int iNumFeatureDimension = t_pMatDataTrain->rows();
  151. NICE::Vector t_vecLabelsTrain(t_pMatDataTrainLabels->getDataPointer(), t_pMatDataTrainLabels->rows(), Vector::external);
  152. OBJREC::Examples examplesTrain;
  153. bool bRet = OBJREC::Examples::wrapExamplesAroundFeatureMatrix( *t_pMatDataTrain, t_vecLabelsTrain, examplesTrain );
  154. if( !bRet )
  155. {
  156. std::cout << "createAndTrain: Error creating Examples from raw feature matrix and labels." << std::endl;
  157. return 0;
  158. }
  159. //----------------- create raw feature mapping -------------
  160. OBJREC::FeaturePool fp;
  161. OBJREC::VectorFeature *pVecFeature = new OBJREC::VectorFeature(iNumFeatureDimension);
  162. pVecFeature->explode(fp);
  163. #ifdef DEBUG_VERBOSE
  164. //----------------- debug features -------------
  165. OBJREC::Example t_Exp = examplesTrain[0].second;
  166. NICE::Vector t_FeatVector;
  167. fp.calcFeatureVector(t_Exp, t_FeatVector);
  168. std::cerr << "first full Feature Vec: " <<t_FeatVector << std::endl;
  169. #endif
  170. //----------------- train our random Forest -------------
  171. OBJREC::FPCRandomForests *pRandForest = new OBJREC::FPCRandomForests(&t_conf,"RandomForest");
  172. pRandForest->train(fp, examplesTrain);
  173. //----------------- create codebook ERC clusterer -------------
  174. int nMaxDepth = t_conf.gI("CodebookRandomForest", "maxDepthTree",10);
  175. int nMaxCodebookSize = t_conf.gI("CodebookRandomForest", "maxCodebookSize",100);
  176. #ifdef DEBUG_VERBOSE
  177. std::cerr << "maxDepthTree " << nMaxDepth << std::endl;
  178. std::cerr << "nMaxCodebookSize " << nMaxCodebookSize << std::endl;
  179. #endif
  180. OBJREC::CodebookRandomForest *pCodebookRandomForest = new OBJREC::CodebookRandomForest(pRandForest, nMaxDepth,nMaxCodebookSize);
  181. //----------------- store classifier in file ---------------------
  182. bool bSuccess = storeClassifier(p_Command, pCodebookRandomForest);
  183. //----------------- clean up -------------
  184. delete pCodebookRandomForest;
  185. delete pVecFeature;
  186. pVecFeature = NULL;
  187. // delete all "exploded" features, they are internally cloned in the random trees anyway
  188. fp.destroy();
  189. //
  190. examplesTrain.clean();
  191. delete t_pMatDataTrain;
  192. delete t_pMatDataTrainLabels;
  193. return true;
  194. }
  195. bool generateHistogram( const structCommands &p_Command)
  196. {
  197. Matrix *t_pMatFodID = loadMatlabVec( p_Command.sFileTrainData.toStdString(), "fodID");
  198. if( t_pMatFodID == NULL )
  199. {
  200. std::cout << "Data Matrix didn't include a fodID, so couldn't be loaded" << std::endl;
  201. return 0;
  202. }
  203. int iFodID = (*t_pMatFodID)(0,0);
  204. Matrix *t_pMatDataTrain = loadMatlabVec( p_Command.sFileTrainData.toStdString(), "matFeatures");
  205. if( t_pMatDataTrain == NULL )
  206. {
  207. std::cout << "Data Matrix couldn't be loaded" << std::endl;
  208. return 0;
  209. }
  210. //----------------- restore trained codebook forest -------------
  211. OBJREC::CodebookRandomForest *pCodebookRandomForest = new OBJREC::CodebookRandomForest(-1,-1);
  212. if( !restoreClassifier(p_Command, pCodebookRandomForest ) )
  213. {
  214. std::cout << "Error restoring codebook random forest" << std::endl;
  215. return false;
  216. }
  217. size_t numTrainSamples = t_pMatDataTrain->cols();
  218. size_t iNumFeatureDimension = t_pMatDataTrain->rows();
  219. size_t iNumCodewords = pCodebookRandomForest->getCodebookSize();
  220. #ifdef DEBUG_VERBOSE
  221. std::cerr << "numTrainSamples " << numTrainSamples << std::endl;
  222. std::cerr << "iNumFeatureDimension " << iNumFeatureDimension << std::endl;
  223. std::cerr << "iNumCodewords " << iNumCodewords << std::endl;
  224. #endif
  225. //----------------- parse config options -------------
  226. bool bVerboseOutput = false;
  227. // if( nrhs > 3)
  228. // {
  229. // NICE::Config conf = parseParametersERC(prhs+3, nrhs-3 );
  230. // bVerboseOutput = conf.gB("CodebookRandomForest", "verbose", false);
  231. // }
  232. //----------------- quantize samples into histogram -------------
  233. NICE::Vector histogram(iNumCodewords, 0.0f);
  234. const double *pDataPtr = t_pMatDataTrain->getDataPointer();
  235. int t_iCodebookEntry; double t_fWeight; double t_fDistance;
  236. for (size_t i = 0; i < numTrainSamples; i++, pDataPtr+= iNumFeatureDimension )
  237. {
  238. const NICE::Vector t_VecTrainData( pDataPtr , iNumFeatureDimension);
  239. pCodebookRandomForest->voteVQ(t_VecTrainData, histogram, t_iCodebookEntry, t_fWeight, t_fDistance );
  240. if(bVerboseOutput)
  241. std::cerr << i << ": " << "CBEntry " << t_iCodebookEntry << " Weight: " << t_fWeight << " Distance: " << t_fDistance << std::endl;
  242. }
  243. // store histogram
  244. bool bSuccess = saveMatlabVector(p_Command.sFileStoreResult.toStdString(), histogram , iFodID);
  245. //----------------- clean up -------------
  246. delete pCodebookRandomForest;
  247. delete t_pMatDataTrain;
  248. return bSuccess;
  249. }
  250. int main(int argc, char **argv)
  251. {
  252. std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
  253. structCommands sCommand;
  254. QString sCmdArg;
  255. int iCurrArgIdx = 1;
  256. while(iCurrArgIdx < argc)
  257. {
  258. sCmdArg = QString(argv[iCurrArgIdx]);
  259. if ( sCmdArg == "--function" )
  260. {
  261. iCurrArgIdx++;
  262. sCommand.sFunction = QString(argv[iCurrArgIdx]);
  263. }
  264. else if( sCmdArg == "--config" )
  265. {
  266. iCurrArgIdx++;
  267. sCommand.sConfigFile = QString(argv[iCurrArgIdx]);
  268. }
  269. else if( sCmdArg == "--traindata" )
  270. {
  271. iCurrArgIdx++;
  272. sCommand.sFileTrainData = QString(argv[iCurrArgIdx]);
  273. }
  274. else if( sCmdArg == "--traindatalabels" )
  275. {
  276. iCurrArgIdx++;
  277. sCommand.sFileTrainDataLabels = QString(argv[iCurrArgIdx]);
  278. }
  279. else if( sCmdArg == "--results" )
  280. {
  281. iCurrArgIdx++;
  282. sCommand.sFileStoreResult = QString(argv[iCurrArgIdx]);
  283. }
  284. else if( sCmdArg == "--classifier" )
  285. {
  286. iCurrArgIdx++;
  287. sCommand.sFileStoreClassifier = QString(argv[iCurrArgIdx]);
  288. }
  289. else if( sCmdArg == "--help" )
  290. {
  291. // print_usage();
  292. return 0;
  293. }
  294. else
  295. {
  296. std::cout << "unknown command arg: " << sCmdArg.toStdString() << std::endl;
  297. }
  298. iCurrArgIdx++;
  299. }
  300. ///////////////////////////////////////////////////
  301. try
  302. {
  303. if( sCommand.sFunction.compare("createAndTrain") == 0)
  304. {
  305. bool bSuccess = createAndTrain(sCommand);
  306. }
  307. else if( sCommand.sFunction.compare("generateHistogram") == 0)
  308. {
  309. bool bSuccess = generateHistogram(sCommand);
  310. }
  311. }
  312. catch(std::exception &e)
  313. {
  314. std::cerr << "exception occured: " << e.what() << std::endl;
  315. }
  316. return 0;
  317. }