GPHIKRawClassifierMex.cpp 16 KB

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