GPHIKRawClassifierMex.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. #ifdef NICE_USELIB_MEX
  2. /**
  3. * @file GPHIKRawClassifierMex.cpp
  4. * @author Alexander Freytag
  5. * @date 21-09-2015 (dd-mm-yyyy)
  6. * @brief Matlab-Interface of our GPHIKRawClassifier, allowing for training and classification without more advanced methods.
  7. */
  8. // STL includes
  9. #include <math.h>
  10. #include <matrix.h>
  11. #include <mex.h>
  12. // NICE-core includes
  13. #include <core/basics/Config.h>
  14. #include <core/basics/Timer.h>
  15. #include <core/vector/MatrixT.h>
  16. #include <core/vector/VectorT.h>
  17. // gp-hik-core includes
  18. #include "gp-hik-core/GPHIKRawClassifier.h"
  19. // Interface for conversion between Matlab and C objects
  20. #include "gp-hik-core/matlab/classHandleMtoC.h"
  21. #include "gp-hik-core/matlab/ConverterMatlabToNICE.h"
  22. #include "gp-hik-core/matlab/ConverterNICEToMatlab.h"
  23. using namespace std; //C basics
  24. using namespace NICE; // nice-core
  25. NICE::Config parseParametersGPHIKRawClassifier(const mxArray *prhs[], int nrhs)
  26. {
  27. NICE::Config conf;
  28. // if first argument is the filename of an existing config file,
  29. // read the config accordingly
  30. int i_start ( 0 );
  31. std::string variable = MatlabConversion::convertMatlabToString(prhs[i_start]);
  32. if(variable == "conf")
  33. {
  34. conf = NICE::Config ( MatlabConversion::convertMatlabToString( prhs[i_start+1] ) );
  35. i_start = i_start+2;
  36. }
  37. // now run over all given parameter specifications
  38. // and add them to the config
  39. for( int i=i_start; i < nrhs; i+=2 )
  40. {
  41. std::string variable = MatlabConversion::convertMatlabToString(prhs[i]);
  42. /////////////////////////////////////////
  43. // READ STANDARD BOOLEAN VARIABLES
  44. /////////////////////////////////////////
  45. if( (variable == "verbose") ||
  46. (variable == "debug") ||
  47. (variable == "use_quantization") ||
  48. (variable == "ils_verbose")
  49. )
  50. {
  51. if ( mxIsChar( prhs[i+1] ) )
  52. {
  53. string value = MatlabConversion::convertMatlabToString( prhs[i+1] );
  54. if ( (value != "true") && (value != "false") )
  55. {
  56. std::string errorMsg = "Unexpected parameter value for \'" + variable + "\'. In string modus, \'true\' or \'false\' expected.";
  57. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  58. }
  59. if( value == "true" )
  60. conf.sB("GPHIKRawClassifier", variable, true);
  61. else
  62. conf.sB("GPHIKRawClassifier", variable, false);
  63. }
  64. else if ( mxIsLogical( prhs[i+1] ) )
  65. {
  66. bool value = MatlabConversion::convertMatlabToBool( prhs[i+1] );
  67. conf.sB("GPHIKRawClassifier", variable, value);
  68. }
  69. else
  70. {
  71. std::string errorMsg = "Unexpected parameter value for \'" + variable + "\'. \'true\', \'false\', or logical expected.";
  72. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  73. }
  74. }
  75. /////////////////////////////////////////
  76. // READ STANDARD INT VARIABLES
  77. /////////////////////////////////////////
  78. /////////////////////////////////////////
  79. // READ STRICT POSITIVE INT VARIABLES
  80. /////////////////////////////////////////
  81. if ( (variable == "num_bins") ||
  82. (variable == "ils_max_iterations" )
  83. )
  84. {
  85. if ( mxIsDouble( prhs[i+1] ) )
  86. {
  87. double value = MatlabConversion::convertMatlabToDouble(prhs[i+1]);
  88. if( value < 1 )
  89. {
  90. std::string errorMsg = "Expected parameter value larger than 0 for \'" + variable + "\'.";
  91. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  92. }
  93. conf.sI("GPHIKRawClassifier", variable, (int) value);
  94. }
  95. else if ( mxIsInt32( prhs[i+1] ) )
  96. {
  97. int value = MatlabConversion::convertMatlabToInt32(prhs[i+1]);
  98. if( value < 1 )
  99. {
  100. std::string errorMsg = "Expected parameter value larger than 0 for \'" + variable + "\'.";
  101. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  102. }
  103. conf.sI("GPHIKRawClassifier", variable, value);
  104. }
  105. else
  106. {
  107. std::string errorMsg = "Unexpected parameter value for \'" + variable + "\'. Int32 or Double expected.";
  108. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  109. }
  110. }
  111. /////////////////////////////////////////
  112. // READ STANDARD DOUBLE VARIABLES
  113. /////////////////////////////////////////
  114. /////////////////////////////////////////
  115. // READ POSITIVE DOUBLE VARIABLES
  116. /////////////////////////////////////////
  117. if ( (variable == "f_tolerance") ||
  118. (variable == "ils_min_delta") ||
  119. (variable == "ils_min_residual") ||
  120. (variable == "noise")
  121. )
  122. {
  123. if ( mxIsDouble( prhs[i+1] ) )
  124. {
  125. double value = MatlabConversion::convertMatlabToDouble(prhs[i+1]);
  126. if( value < 0.0 )
  127. {
  128. std::string errorMsg = "Expected parameter value larger than 0 for \'" + variable + "\'.";
  129. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  130. }
  131. conf.sD("GPHIKRawClassifier", variable, value);
  132. }
  133. else
  134. {
  135. std::string errorMsg = "Unexpected parameter value for \'" + variable + "\'. Double expected.";
  136. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  137. }
  138. }
  139. /////////////////////////////////////////
  140. // READ REMAINING SPECIFIC VARIABLES
  141. /////////////////////////////////////////
  142. if(variable == "ils_method")
  143. {
  144. string value = MatlabConversion::convertMatlabToString(prhs[i+1]);
  145. if(value != "CG" && value != "CGL" && value != "SYMMLQ" && value != "MINRES")
  146. mexErrMsgIdAndTxt("mexnice:error","Unexpected parameter value for \'ils_method\'. \'CG\', \'CGL\', \'SYMMLQ\' or \'MINRES\' expected.");
  147. conf.sS("GPHIKRawClassifier", variable, value);
  148. }
  149. if(variable == "s_quantType")
  150. {
  151. string value = MatlabConversion::convertMatlabToString( prhs[i+1] );
  152. if( value != "1d-aequi-0-1" && value != "1d-aequi-0-max" && value != "nd-aequi-0-max" )
  153. mexErrMsgIdAndTxt("mexnice:error","Unexpected parameter value for \'s_quantType\'. \'1d-aequi-0-1\' , \'1d-aequi-0-max\' or \'nd-aequi-0-max\' expected.");
  154. conf.sS("GPHIKRawClassifier", variable, value);
  155. }
  156. }
  157. return conf;
  158. }
  159. // MAIN MATLAB FUNCTION
  160. void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
  161. {
  162. // get the command string specifying what to do
  163. if (nrhs < 1)
  164. mexErrMsgTxt("No commands and options passed... Aborting!");
  165. if( !mxIsChar( prhs[0] ) )
  166. mexErrMsgTxt("First argument needs to be the command, ie.e, the class method to call... Aborting!");
  167. std::string cmd = MatlabConversion::convertMatlabToString( prhs[0] );
  168. // create object
  169. if ( !strcmp("new", cmd.c_str() ) )
  170. {
  171. // check output variable
  172. if (nlhs != 1)
  173. mexErrMsgTxt("New: One output expected.");
  174. // read config settings
  175. NICE::Config conf = parseParametersGPHIKRawClassifier(prhs+1,nrhs-1);
  176. // create class instance
  177. NICE::GPHIKRawClassifier * classifier = new NICE::GPHIKRawClassifier ( &conf, "GPHIKRawClassifier" /*sectionName in config*/ );
  178. // handle to the C++ instance
  179. plhs[0] = MatlabConversion::convertPtr2Mat<NICE::GPHIKRawClassifier>( classifier );
  180. return;
  181. }
  182. // in all other cases, there should be a second input,
  183. // which the be the class instance handle
  184. if (nrhs < 2)
  185. mexErrMsgTxt("Second input should be a class instance handle.");
  186. // delete object
  187. if ( !strcmp("delete", cmd.c_str() ) )
  188. {
  189. // Destroy the C++ object
  190. MatlabConversion::destroyObject<NICE::GPHIKRawClassifier>(prhs[1]);
  191. return;
  192. }
  193. // get the class instance pointer from the second input
  194. // every following function needs the classifier object
  195. NICE::GPHIKRawClassifier * classifier = MatlabConversion::convertMat2Ptr<NICE::GPHIKRawClassifier>(prhs[1]);
  196. ////////////////////////////////////////
  197. // Check which class method to call //
  198. ////////////////////////////////////////
  199. // standard train - assumes initialized object
  200. if (!strcmp("train", cmd.c_str() ))
  201. {
  202. // Check parameters
  203. if (nlhs < 0 || nrhs < 4)
  204. {
  205. mexErrMsgTxt("Train: Unexpected arguments.");
  206. }
  207. //------------- read the data --------------
  208. std::vector< const NICE::SparseVector *> examplesTrain;
  209. NICE::Vector yMultiTrain;
  210. if ( mxIsSparse( prhs[2] ) )
  211. {
  212. examplesTrain = MatlabConversion::convertSparseMatrixToNice( prhs[2] );
  213. }
  214. else
  215. {
  216. NICE::Matrix dataTrain;
  217. dataTrain = MatlabConversion::convertDoubleMatrixToNice(prhs[2]);
  218. //----------------- convert data to sparse data structures ---------
  219. examplesTrain.resize( dataTrain.rows() );
  220. std::vector< const NICE::SparseVector *>::iterator exTrainIt = examplesTrain.begin();
  221. for (int i = 0; i < (int)dataTrain.rows(); i++, exTrainIt++)
  222. {
  223. *exTrainIt = new NICE::SparseVector( dataTrain.getRow(i) );
  224. }
  225. }
  226. yMultiTrain = MatlabConversion::convertDoubleVectorToNice(prhs[3]);
  227. //----------------- train our classifier -------------
  228. classifier->train ( examplesTrain , yMultiTrain );
  229. //----------------- clean up -------------
  230. for(int i=0;i<examplesTrain.size();i++)
  231. delete examplesTrain[i];
  232. return;
  233. }
  234. // Classify
  235. if ( !strcmp("classify", cmd.c_str() ) )
  236. {
  237. // Check parameters
  238. if ( (nlhs < 0) || (nrhs < 2) )
  239. {
  240. mexErrMsgTxt("Test: Unexpected arguments.");
  241. }
  242. //------------- read the data --------------
  243. uint result;
  244. NICE::SparseVector scores;
  245. if ( mxIsSparse( prhs[2] ) )
  246. {
  247. NICE::SparseVector * example;
  248. example = new NICE::SparseVector ( MatlabConversion::convertSparseVectorToNice( prhs[2] ) );
  249. classifier->classify ( example, result, scores );
  250. //----------------- clean up -------------
  251. delete example;
  252. }
  253. else
  254. {
  255. NICE::Vector * example;
  256. example = new NICE::Vector ( MatlabConversion::convertDoubleVectorToNice(prhs[2]) );
  257. NICE::SparseVector * svec = new NICE::SparseVector( *example );
  258. delete example;
  259. classifier->classify ( svec, result, scores );
  260. //----------------- clean up -------------
  261. delete svec;
  262. }
  263. // output
  264. plhs[0] = mxCreateDoubleScalar( result );
  265. if(nlhs >= 2)
  266. {
  267. plhs[1] = MatlabConversion::convertSparseVectorFromNice( scores, true /*b_adaptIndex*/);
  268. }
  269. return;
  270. }
  271. // Test - evaluate classifier on whole test set
  272. if ( !strcmp("test", cmd.c_str() ) )
  273. {
  274. // Check parameters
  275. if (nlhs < 0 || nrhs < 4)
  276. mexErrMsgTxt("Test: Unexpected arguments.");
  277. //------------- read the data --------------
  278. bool dataIsSparse ( mxIsSparse( prhs[2] ) );
  279. std::vector< const NICE::SparseVector *> dataTest_sparse;
  280. NICE::Matrix dataTest_dense;
  281. if ( dataIsSparse )
  282. {
  283. dataTest_sparse = MatlabConversion::convertSparseMatrixToNice( prhs[2] );
  284. }
  285. else
  286. {
  287. dataTest_dense = MatlabConversion::convertDoubleMatrixToNice(prhs[2]);
  288. }
  289. NICE::Vector yMultiTest;
  290. yMultiTest = MatlabConversion::convertDoubleVectorToNice(prhs[3]);
  291. // ------------------------------------------
  292. // ------------- PREPARATION --------------
  293. // ------------------------------------------
  294. // determine classes known during training and corresponding mapping
  295. // thereby allow for non-continous class labels
  296. std::set< uint > classesKnownTraining = classifier->getKnownClassNumbers();
  297. uint noClassesKnownTraining ( classesKnownTraining.size() );
  298. std::map< uint, uint > mapClNoToIdxTrain;
  299. std::set< uint >::const_iterator clTrIt = classesKnownTraining.begin();
  300. for ( uint i=0; i < noClassesKnownTraining; i++, clTrIt++ )
  301. mapClNoToIdxTrain.insert ( std::pair< uint, uint > ( *clTrIt, i ) );
  302. // determine classes known during testing and corresponding mapping
  303. // thereby allow for non-continous class labels
  304. std::set< uint > classesKnownTest;
  305. classesKnownTest.clear();
  306. // determine which classes we have in our label vector
  307. // -> MATLAB: myClasses = unique(y);
  308. for ( NICE::Vector::const_iterator it = yMultiTest.begin(); it != yMultiTest.end(); it++ )
  309. {
  310. if ( classesKnownTest.find ( *it ) == classesKnownTest.end() )
  311. {
  312. classesKnownTest.insert ( *it );
  313. }
  314. }
  315. int noClassesKnownTest ( classesKnownTest.size() );
  316. std::map< uint, uint> mapClNoToIdxTest;
  317. std::set< uint >::const_iterator clTestIt = classesKnownTest.begin();
  318. for ( uint i=0; i < noClassesKnownTest; i++, clTestIt++ )
  319. mapClNoToIdxTest.insert ( std::pair< uint, uint > ( *clTestIt, i ) );
  320. int i_numTestSamples;
  321. if ( dataIsSparse )
  322. i_numTestSamples = dataTest_sparse.size();
  323. else
  324. i_numTestSamples = (int) dataTest_dense.rows();
  325. NICE::Matrix confusionMatrix( noClassesKnownTraining, noClassesKnownTest, 0.0);
  326. NICE::Matrix scores( i_numTestSamples, noClassesKnownTraining, 0.0);
  327. // ------------------------------------------
  328. // ------------- CLASSIFICATION --------------
  329. // ------------------------------------------
  330. NICE::Timer t;
  331. double testTime (0.0);
  332. for (int i = 0; i < i_numTestSamples; i++)
  333. {
  334. //----------------- convert data to sparse data structures ---------
  335. uint result;
  336. NICE::SparseVector exampleScoresSparse;
  337. if ( dataIsSparse )
  338. {
  339. // and classify
  340. t.start();
  341. classifier->classify( dataTest_sparse[ i ], result, exampleScoresSparse );
  342. t.stop();
  343. testTime += t.getLast();
  344. }
  345. else
  346. {
  347. NICE::Vector example ( dataTest_dense.getRow(i) );
  348. NICE::SparseVector * svec = new NICE::SparseVector ( example );
  349. // and classify
  350. t.start();
  351. classifier->classify( svec, result, exampleScoresSparse );
  352. t.stop();
  353. testTime += t.getLast();
  354. delete svec;
  355. }
  356. confusionMatrix( mapClNoToIdxTrain.find(result)->second, mapClNoToIdxTest.find(yMultiTest[i])->second ) += 1.0;
  357. int scoreCnt ( 0 );
  358. for ( NICE::SparseVector::const_iterator scoreIt = exampleScoresSparse.begin(); scoreIt != exampleScoresSparse.end(); scoreIt++, scoreCnt++ )
  359. {
  360. scores(i,scoreCnt) = scoreIt->second;
  361. }
  362. }
  363. std::cerr << "Time for testing: " << testTime << std::endl;
  364. // clean up
  365. if ( dataIsSparse )
  366. {
  367. for ( std::vector<const NICE::SparseVector *>::iterator it = dataTest_sparse.begin(); it != dataTest_sparse.end(); it++)
  368. delete *it;
  369. }
  370. confusionMatrix.normalizeColumnsL1();
  371. double recRate = confusionMatrix.trace()/confusionMatrix.cols();
  372. plhs[0] = mxCreateDoubleScalar( recRate );
  373. if(nlhs >= 2)
  374. plhs[1] = MatlabConversion::convertMatrixFromNice(confusionMatrix);
  375. if(nlhs >= 3)
  376. plhs[2] = MatlabConversion::convertMatrixFromNice(scores);
  377. return;
  378. }
  379. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  380. // interface specific methods for incremental extensions
  381. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  382. // not supported here
  383. ///////////////////// INTERFACE PERSISTENT /////////////////////
  384. // interface specific methods for store and restore
  385. ///////////////////// INTERFACE PERSISTENT /////////////////////
  386. // not supported here
  387. // Got here, so command not recognized
  388. std::string errorMsg (cmd.c_str() );
  389. errorMsg += " -- command not recognized.";
  390. mexErrMsgTxt( errorMsg.c_str() );
  391. }
  392. #endif