GPHIKRawClassifierMex.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. if ( mxIsSparse( prhs[2] ) )
  243. {
  244. if ( MatlabConversion::isSparseDataAMatrix( prhs[2] ) )
  245. {
  246. //----------------- conversion -------------
  247. std::vector< const NICE::SparseVector *> examplesTest;
  248. examplesTest = MatlabConversion::convertSparseMatrixToNice( prhs[2] );
  249. //----------------- classification -------------
  250. NICE::Vector results;
  251. NICE::Matrix scores;
  252. classifier->classify ( examplesTest, results, scores );
  253. //----------------- clean up -------------
  254. for ( std::vector< const NICE::SparseVector *>::iterator exIt = examplesTest.begin();
  255. exIt != examplesTest.end();
  256. exIt++
  257. )
  258. {
  259. delete *exIt;
  260. }
  261. //----------------- output -------------
  262. plhs[0] = MatlabConversion::convertVectorFromNice( results );
  263. if(nlhs >= 2)
  264. {
  265. plhs[1] = MatlabConversion::convertMatrixFromNice( scores );
  266. }
  267. return;
  268. }
  269. else
  270. {
  271. //----------------- conversion -------------
  272. NICE::SparseVector * example;
  273. example = new NICE::SparseVector ( MatlabConversion::convertSparseVectorToNice( prhs[2] ) );
  274. //----------------- classification -------------
  275. uint result;
  276. NICE::SparseVector scores;
  277. classifier->classify ( example, result, scores );
  278. //----------------- clean up -------------
  279. delete example;
  280. //----------------- output -------------
  281. plhs[0] = mxCreateDoubleScalar( result );
  282. if(nlhs >= 2)
  283. {
  284. plhs[1] = MatlabConversion::convertSparseVectorFromNice( scores, true /*b_adaptIndex*/);
  285. }
  286. return;
  287. }
  288. }
  289. else
  290. {
  291. //----------------- conversion -------------
  292. NICE::Vector * example;
  293. example = new NICE::Vector ( MatlabConversion::convertDoubleVectorToNice(prhs[2]) );
  294. NICE::SparseVector * svec = new NICE::SparseVector( *example );
  295. delete example;
  296. //----------------- classification -------------
  297. uint result;
  298. NICE::SparseVector scores;
  299. classifier->classify ( svec, result, scores );
  300. //----------------- clean up -------------
  301. delete svec;
  302. //----------------- output -------------
  303. plhs[0] = mxCreateDoubleScalar( result );
  304. if(nlhs >= 2)
  305. {
  306. plhs[1] = MatlabConversion::convertSparseVectorFromNice( scores, true /*b_adaptIndex*/);
  307. }
  308. return;
  309. }
  310. }
  311. // Test - evaluate classifier on whole test set
  312. if ( !strcmp("test", cmd.c_str() ) )
  313. {
  314. // Check parameters
  315. if (nlhs < 0 || nrhs < 4)
  316. mexErrMsgTxt("Test: Unexpected arguments.");
  317. //------------- read the data --------------
  318. bool dataIsSparse ( mxIsSparse( prhs[2] ) );
  319. std::vector< const NICE::SparseVector *> dataTest_sparse;
  320. NICE::Matrix dataTest_dense;
  321. if ( dataIsSparse )
  322. {
  323. dataTest_sparse = MatlabConversion::convertSparseMatrixToNice( prhs[2] );
  324. }
  325. else
  326. {
  327. dataTest_dense = MatlabConversion::convertDoubleMatrixToNice(prhs[2]);
  328. }
  329. NICE::Vector yMultiTest;
  330. yMultiTest = MatlabConversion::convertDoubleVectorToNice(prhs[3]);
  331. // ------------------------------------------
  332. // ------------- PREPARATION --------------
  333. // ------------------------------------------
  334. // determine classes known during training and corresponding mapping
  335. // thereby allow for non-continous class labels
  336. std::set< uint > classesKnownTraining = classifier->getKnownClassNumbers();
  337. uint noClassesKnownTraining ( classesKnownTraining.size() );
  338. std::map< uint, uint > mapClNoToIdxTrain;
  339. std::set< uint >::const_iterator clTrIt = classesKnownTraining.begin();
  340. for ( uint i=0; i < noClassesKnownTraining; i++, clTrIt++ )
  341. mapClNoToIdxTrain.insert ( std::pair< uint, uint > ( *clTrIt, i ) );
  342. // determine classes known during testing and corresponding mapping
  343. // thereby allow for non-continous class labels
  344. std::set< uint > classesKnownTest;
  345. classesKnownTest.clear();
  346. // determine which classes we have in our label vector
  347. // -> MATLAB: myClasses = unique(y);
  348. for ( NICE::Vector::const_iterator it = yMultiTest.begin(); it != yMultiTest.end(); it++ )
  349. {
  350. if ( classesKnownTest.find ( *it ) == classesKnownTest.end() )
  351. {
  352. classesKnownTest.insert ( *it );
  353. }
  354. }
  355. int noClassesKnownTest ( classesKnownTest.size() );
  356. std::map< uint, uint> mapClNoToIdxTest;
  357. std::set< uint >::const_iterator clTestIt = classesKnownTest.begin();
  358. for ( uint i=0; i < noClassesKnownTest; i++, clTestIt++ )
  359. mapClNoToIdxTest.insert ( std::pair< uint, uint > ( *clTestIt, i ) );
  360. int i_numTestSamples;
  361. if ( dataIsSparse )
  362. i_numTestSamples = dataTest_sparse.size();
  363. else
  364. i_numTestSamples = (int) dataTest_dense.rows();
  365. NICE::Matrix confusionMatrix( noClassesKnownTraining, noClassesKnownTest, 0.0);
  366. NICE::Matrix scores( i_numTestSamples, noClassesKnownTraining, 0.0);
  367. // ------------------------------------------
  368. // ------------- CLASSIFICATION --------------
  369. // ------------------------------------------
  370. NICE::Timer t;
  371. double testTime (0.0);
  372. for (int i = 0; i < i_numTestSamples; i++)
  373. {
  374. //----------------- convert data to sparse data structures ---------
  375. uint result;
  376. NICE::SparseVector exampleScoresSparse;
  377. if ( dataIsSparse )
  378. {
  379. // and classify
  380. t.start();
  381. classifier->classify( dataTest_sparse[ i ], result, exampleScoresSparse );
  382. t.stop();
  383. testTime += t.getLast();
  384. }
  385. else
  386. {
  387. NICE::Vector example ( dataTest_dense.getRow(i) );
  388. NICE::SparseVector * svec = new NICE::SparseVector ( example );
  389. // and classify
  390. t.start();
  391. classifier->classify( svec, result, exampleScoresSparse );
  392. t.stop();
  393. testTime += t.getLast();
  394. delete svec;
  395. }
  396. confusionMatrix( mapClNoToIdxTrain.find(result)->second, mapClNoToIdxTest.find(yMultiTest[i])->second ) += 1.0;
  397. int scoreCnt ( 0 );
  398. for ( NICE::SparseVector::const_iterator scoreIt = exampleScoresSparse.begin(); scoreIt != exampleScoresSparse.end(); scoreIt++, scoreCnt++ )
  399. {
  400. scores(i,scoreCnt) = scoreIt->second;
  401. }
  402. }
  403. std::cerr << "Time for testing: " << testTime << std::endl;
  404. // clean up
  405. if ( dataIsSparse )
  406. {
  407. for ( std::vector<const NICE::SparseVector *>::iterator it = dataTest_sparse.begin(); it != dataTest_sparse.end(); it++)
  408. delete *it;
  409. }
  410. confusionMatrix.normalizeColumnsL1();
  411. double recRate = confusionMatrix.trace()/confusionMatrix.cols();
  412. plhs[0] = mxCreateDoubleScalar( recRate );
  413. if(nlhs >= 2)
  414. plhs[1] = MatlabConversion::convertMatrixFromNice(confusionMatrix);
  415. if(nlhs >= 3)
  416. plhs[2] = MatlabConversion::convertMatrixFromNice(scores);
  417. return;
  418. }
  419. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  420. // interface specific methods for incremental extensions
  421. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  422. // not supported here
  423. ///////////////////// INTERFACE PERSISTENT /////////////////////
  424. // interface specific methods for store and restore
  425. ///////////////////// INTERFACE PERSISTENT /////////////////////
  426. // not supported here
  427. // Got here, so command not recognized
  428. std::string errorMsg (cmd.c_str() );
  429. errorMsg += " -- command not recognized.";
  430. mexErrMsgTxt( errorMsg.c_str() );
  431. }
  432. #endif