GPHIKClassifierMex.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. #ifdef NICE_USELIB_MEX
  2. /**
  3. * @file GPHIKClassifierMex.cpp
  4. * @author Alexander Freytag
  5. * @date 07-01-2014 (dd-mm-yyyy)
  6. * @brief Matlab-Interface of our GPHIKClassifier, allowing for training, classification, optimization, variance prediction, incremental learning, and storing/re-storing.
  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/GPHIKClassifier.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 parseParametersGPHIKClassifier(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 == "verboseTime") ||
  46. (variable == "verbose") ||
  47. (variable == "debug") ||
  48. (variable == "optimize_noise") ||
  49. (variable == "uncertaintyPredictionForClassification") ||
  50. (variable == "use_quantization") ||
  51. (variable == "ils_verbose")
  52. )
  53. {
  54. if ( mxIsChar( prhs[i+1] ) )
  55. {
  56. string value = MatlabConversion::convertMatlabToString( prhs[i+1] );
  57. if ( (value != "true") && (value != "false") )
  58. {
  59. std::string errorMsg = "Unexpected parameter value for \'" + variable + "\'. In string modus, \'true\' or \'false\' expected.";
  60. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  61. }
  62. if( value == "true" )
  63. conf.sB("GPHIKClassifier", variable, true);
  64. else
  65. conf.sB("GPHIKClassifier", variable, false);
  66. }
  67. else if ( mxIsLogical( prhs[i+1] ) )
  68. {
  69. bool value = MatlabConversion::convertMatlabToBool( prhs[i+1] );
  70. conf.sB("GPHIKClassifier", variable, value);
  71. }
  72. else
  73. {
  74. std::string errorMsg = "Unexpected parameter value for \'" + variable + "\'. \'true\', \'false\', or logical expected.";
  75. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  76. }
  77. }
  78. /////////////////////////////////////////
  79. // READ STANDARD INT VARIABLES
  80. /////////////////////////////////////////
  81. if ( (variable == "nrOfEigenvaluesToConsiderForVarApprox")
  82. )
  83. {
  84. if ( mxIsDouble( prhs[i+1] ) )
  85. {
  86. double value = MatlabConversion::convertMatlabToDouble(prhs[i+1]);
  87. conf.sI("GPHIKClassifier", variable, (int) value);
  88. }
  89. else if ( mxIsInt32( prhs[i+1] ) )
  90. {
  91. int value = MatlabConversion::convertMatlabToInt32(prhs[i+1]);
  92. conf.sI("GPHIKClassifier", variable, value);
  93. }
  94. else
  95. {
  96. std::string errorMsg = "Unexpected parameter value for \'" + variable + "\'. Int32 or Double expected.";
  97. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  98. }
  99. }
  100. /////////////////////////////////////////
  101. // READ STRICT POSITIVE INT VARIABLES
  102. /////////////////////////////////////////
  103. if ( (variable == "num_bins") ||
  104. (variable == "ils_max_iterations")
  105. )
  106. {
  107. if ( mxIsDouble( prhs[i+1] ) )
  108. {
  109. double value = MatlabConversion::convertMatlabToDouble(prhs[i+1]);
  110. if( value < 1 )
  111. {
  112. std::string errorMsg = "Expected parameter value larger than 0 for \'" + variable + "\'.";
  113. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  114. }
  115. conf.sI("GPHIKClassifier", variable, (int) value);
  116. }
  117. else if ( mxIsInt32( prhs[i+1] ) )
  118. {
  119. int value = MatlabConversion::convertMatlabToInt32(prhs[i+1]);
  120. if( value < 1 )
  121. {
  122. std::string errorMsg = "Expected parameter value larger than 0 for \'" + variable + "\'.";
  123. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  124. }
  125. conf.sI("GPHIKClassifier", variable, value);
  126. }
  127. else
  128. {
  129. std::string errorMsg = "Unexpected parameter value for \'" + variable + "\'. Int32 or Double expected.";
  130. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  131. }
  132. }
  133. /////////////////////////////////////////
  134. // READ STANDARD DOUBLE VARIABLES
  135. /////////////////////////////////////////
  136. if ( (variable == "parameter_upper_bound") ||
  137. (variable == "parameter_lower_bound")
  138. )
  139. {
  140. if ( mxIsDouble( prhs[i+1] ) )
  141. {
  142. double value = MatlabConversion::convertMatlabToDouble(prhs[i+1]);
  143. conf.sD("GPHIKClassifier", variable, value);
  144. }
  145. else
  146. {
  147. std::string errorMsg = "Unexpected parameter value for \'" + variable + "\'. Double expected.";
  148. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  149. }
  150. }
  151. /////////////////////////////////////////
  152. // READ POSITIVE DOUBLE VARIABLES
  153. /////////////////////////////////////////
  154. if ( (variable == "ils_min_delta") ||
  155. (variable == "ils_min_residual") ||
  156. (variable == "noise")
  157. )
  158. {
  159. if ( mxIsDouble( prhs[i+1] ) )
  160. {
  161. double value = MatlabConversion::convertMatlabToDouble(prhs[i+1]);
  162. if( value < 0.0 )
  163. {
  164. std::string errorMsg = "Expected parameter value larger than 0 for \'" + variable + "\'.";
  165. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  166. }
  167. conf.sD("GPHIKClassifier", variable, value);
  168. }
  169. else
  170. {
  171. std::string errorMsg = "Unexpected parameter value for \'" + variable + "\'. Double expected.";
  172. mexErrMsgIdAndTxt( "mexnice:error", errorMsg.c_str() );
  173. }
  174. }
  175. /////////////////////////////////////////
  176. // READ REMAINING SPECIFIC VARIABLES
  177. /////////////////////////////////////////
  178. if(variable == "ils_method")
  179. {
  180. string value = MatlabConversion::convertMatlabToString(prhs[i+1]);
  181. if(value != "CG" && value != "CGL" && value != "SYMMLQ" && value != "MINRES")
  182. mexErrMsgIdAndTxt("mexnice:error","Unexpected parameter value for \'ils_method\'. \'CG\', \'CGL\', \'SYMMLQ\' or \'MINRES\' expected.");
  183. conf.sS("GPHIKClassifier", variable, value);
  184. }
  185. if(variable == "optimization_method")
  186. {
  187. string value = MatlabConversion::convertMatlabToString(prhs[i+1]);
  188. if(value != "greedy" && value != "downhillsimplex" && value != "none")
  189. mexErrMsgIdAndTxt("mexnice:error","Unexpected parameter value for \'optimization_method\'. \'greedy\', \'downhillsimplex\' or \'none\' expected.");
  190. conf.sS("GPHIKClassifier", variable, value);
  191. }
  192. if(variable == "s_quantType")
  193. {
  194. string value = MatlabConversion::convertMatlabToString( prhs[i+1] );
  195. if( value != "1d-aequi-0-1" && value != "1d-aequi-0-max" && value != "nd-aequi-0-max" )
  196. mexErrMsgIdAndTxt("mexnice:error","Unexpected parameter value for \'s_quantType\'. \'1d-aequi-0-1\' , \'1d-aequi-0-max\' or \'nd-aequi-0-max\' expected.");
  197. conf.sS("GPHIKClassifier", variable, value);
  198. }
  199. if(variable == "transform")
  200. {
  201. string value = MatlabConversion::convertMatlabToString( prhs[i+1] );
  202. if( value != "identity" && value != "absexp" && value != "exp" && value != "MKL" && value != "WeightedDim")
  203. mexErrMsgIdAndTxt("mexnice:error","Unexpected parameter value for \'transform\'. \'identity\', \'absexp\', \'exp\' , \'MKL\' or \'WeightedDim\' expected.");
  204. conf.sS("GPHIKClassifier", variable, value);
  205. }
  206. if(variable == "varianceApproximation")
  207. {
  208. string value = MatlabConversion::convertMatlabToString(prhs[i+1]);
  209. if(value != "approximate_fine" && value != "approximate_rough" && value != "exact" && value != "none")
  210. mexErrMsgIdAndTxt("mexnice:error","Unexpected parameter value for \'varianceApproximation\'. \'approximate_fine\', \'approximate_rough\', \'none\' or \'exact\' expected.");
  211. conf.sS("GPHIKClassifier", variable, value);
  212. }
  213. }
  214. return conf;
  215. }
  216. // MAIN MATLAB FUNCTION
  217. void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
  218. {
  219. // get the command string specifying what to do
  220. if (nrhs < 1)
  221. mexErrMsgTxt("No commands and options passed... Aborting!");
  222. if( !mxIsChar( prhs[0] ) )
  223. mexErrMsgTxt("First argument needs to be the command, ie.e, the class method to call... Aborting!");
  224. std::string cmd = MatlabConversion::convertMatlabToString( prhs[0] );
  225. // create object
  226. if ( !strcmp("new", cmd.c_str() ) )
  227. {
  228. // check output variable
  229. if (nlhs != 1)
  230. mexErrMsgTxt("New: One output expected.");
  231. // read config settings
  232. NICE::Config conf = parseParametersGPHIKClassifier(prhs+1,nrhs-1);
  233. // create class instance
  234. NICE::GPHIKClassifier * classifier = new NICE::GPHIKClassifier ( &conf, "GPHIKClassifier" /*sectionName in config*/ );
  235. // handle to the C++ instance
  236. plhs[0] = MatlabConversion::convertPtr2Mat<NICE::GPHIKClassifier>( classifier );
  237. return;
  238. }
  239. // in all other cases, there should be a second input,
  240. // which the be the class instance handle
  241. if (nrhs < 2)
  242. mexErrMsgTxt("Second input should be a class instance handle.");
  243. // delete object
  244. if ( !strcmp("delete", cmd.c_str() ) )
  245. {
  246. // Destroy the C++ object
  247. MatlabConversion::destroyObject<NICE::GPHIKClassifier>(prhs[1]);
  248. return;
  249. }
  250. // get the class instance pointer from the second input
  251. // every following function needs the classifier object
  252. NICE::GPHIKClassifier * classifier = MatlabConversion::convertMat2Ptr<NICE::GPHIKClassifier>(prhs[1]);
  253. ////////////////////////////////////////
  254. // Check which class method to call //
  255. ////////////////////////////////////////
  256. // standard train - assumes initialized object
  257. if (!strcmp("train", cmd.c_str() ))
  258. {
  259. // Check parameters
  260. if (nlhs < 0 || nrhs < 4)
  261. {
  262. mexErrMsgTxt("Train: Unexpected arguments.");
  263. }
  264. //------------- read the data --------------
  265. std::vector< const NICE::SparseVector *> examplesTrain;
  266. NICE::Vector yMultiTrain;
  267. if ( mxIsSparse( prhs[2] ) )
  268. {
  269. examplesTrain = MatlabConversion::convertSparseMatrixToNice( prhs[2] );
  270. }
  271. else
  272. {
  273. NICE::Matrix dataTrain;
  274. dataTrain = MatlabConversion::convertDoubleMatrixToNice(prhs[2]);
  275. //----------------- convert data to sparse data structures ---------
  276. examplesTrain.resize( dataTrain.rows() );
  277. std::vector< const NICE::SparseVector *>::iterator exTrainIt = examplesTrain.begin();
  278. for (int i = 0; i < (int)dataTrain.rows(); i++, exTrainIt++)
  279. {
  280. *exTrainIt = new NICE::SparseVector( dataTrain.getRow(i) );
  281. }
  282. }
  283. yMultiTrain = MatlabConversion::convertDoubleVectorToNice(prhs[3]);
  284. //----------------- train our classifier -------------
  285. classifier->train ( examplesTrain , yMultiTrain );
  286. //----------------- clean up -------------
  287. for(int i=0;i<examplesTrain.size();i++)
  288. delete examplesTrain[i];
  289. return;
  290. }
  291. // Classify
  292. if ( !strcmp("classify", cmd.c_str() ) )
  293. {
  294. // Check parameters
  295. if ( (nlhs < 0) || (nrhs < 2) )
  296. {
  297. mexErrMsgTxt("Test: Unexpected arguments.");
  298. }
  299. //------------- read the data --------------
  300. uint result;
  301. NICE::SparseVector scores;
  302. double uncertainty;
  303. if ( mxIsSparse( prhs[2] ) )
  304. {
  305. NICE::SparseVector * example;
  306. example = new NICE::SparseVector ( MatlabConversion::convertSparseVectorToNice( prhs[2] ) );
  307. classifier->classify ( example, result, scores, uncertainty );
  308. //----------------- clean up -------------
  309. delete example;
  310. }
  311. else
  312. {
  313. NICE::Vector * example;
  314. example = new NICE::Vector ( MatlabConversion::convertDoubleVectorToNice(prhs[2]) );
  315. classifier->classify ( example, result, scores, uncertainty );
  316. //----------------- clean up -------------
  317. delete example;
  318. }
  319. // output
  320. plhs[0] = mxCreateDoubleScalar( result );
  321. if(nlhs >= 2)
  322. {
  323. plhs[1] = MatlabConversion::convertSparseVectorFromNice( scores, true /*b_adaptIndex*/);
  324. }
  325. if(nlhs >= 3)
  326. {
  327. plhs[2] = mxCreateDoubleScalar( uncertainty );
  328. }
  329. return;
  330. }
  331. // Uncertainty prediction
  332. if ( !strcmp("uncertainty", cmd.c_str() ) )
  333. {
  334. // Check parameters
  335. if ( (nlhs < 0) || (nrhs < 2) )
  336. {
  337. mexErrMsgTxt("Test: Unexpected arguments.");
  338. }
  339. double uncertainty;
  340. //------------- read the data --------------
  341. if ( mxIsSparse( prhs[2] ) )
  342. {
  343. NICE::SparseVector * example;
  344. example = new NICE::SparseVector ( MatlabConversion::convertSparseVectorToNice( prhs[2] ) );
  345. classifier->predictUncertainty( example, uncertainty );
  346. //----------------- clean up -------------
  347. delete example;
  348. }
  349. else
  350. {
  351. NICE::Vector * example;
  352. example = new NICE::Vector ( MatlabConversion::convertDoubleVectorToNice(prhs[2]) );
  353. classifier->predictUncertainty( example, uncertainty );
  354. //----------------- clean up -------------
  355. delete example;
  356. }
  357. // output
  358. plhs[0] = mxCreateDoubleScalar( uncertainty );
  359. return;
  360. }
  361. // Test - evaluate classifier on whole test set
  362. if ( !strcmp("test", cmd.c_str() ) )
  363. {
  364. // Check parameters
  365. if (nlhs < 0 || nrhs < 4)
  366. mexErrMsgTxt("Test: Unexpected arguments.");
  367. //------------- read the data --------------
  368. bool dataIsSparse ( mxIsSparse( prhs[2] ) );
  369. std::vector< const NICE::SparseVector *> dataTest_sparse;
  370. NICE::Matrix dataTest_dense;
  371. if ( dataIsSparse )
  372. {
  373. dataTest_sparse = MatlabConversion::convertSparseMatrixToNice( prhs[2] );
  374. }
  375. else
  376. {
  377. dataTest_dense = MatlabConversion::convertDoubleMatrixToNice(prhs[2]);
  378. }
  379. NICE::Vector yMultiTest;
  380. yMultiTest = MatlabConversion::convertDoubleVectorToNice(prhs[3]);
  381. // ------------------------------------------
  382. // ------------- PREPARATION --------------
  383. // ------------------------------------------
  384. // determine classes known during training and corresponding mapping
  385. // thereby allow for non-continous class labels
  386. std::set< uint > classesKnownTraining = classifier->getKnownClassNumbers();
  387. uint noClassesKnownTraining ( classesKnownTraining.size() );
  388. std::map< uint, uint > mapClNoToIdxTrain;
  389. std::set< uint >::const_iterator clTrIt = classesKnownTraining.begin();
  390. for ( uint i=0; i < noClassesKnownTraining; i++, clTrIt++ )
  391. mapClNoToIdxTrain.insert ( std::pair< uint, uint > ( *clTrIt, i ) );
  392. // determine classes known during testing and corresponding mapping
  393. // thereby allow for non-continous class labels
  394. std::set< uint > classesKnownTest;
  395. classesKnownTest.clear();
  396. // determine which classes we have in our label vector
  397. // -> MATLAB: myClasses = unique(y);
  398. for ( NICE::Vector::const_iterator it = yMultiTest.begin(); it != yMultiTest.end(); it++ )
  399. {
  400. if ( classesKnownTest.find ( *it ) == classesKnownTest.end() )
  401. {
  402. classesKnownTest.insert ( *it );
  403. }
  404. }
  405. int noClassesKnownTest ( classesKnownTest.size() );
  406. std::map< uint, uint> mapClNoToIdxTest;
  407. std::set< uint >::const_iterator clTestIt = classesKnownTest.begin();
  408. for ( uint i=0; i < noClassesKnownTest; i++, clTestIt++ )
  409. mapClNoToIdxTest.insert ( std::pair< uint, uint > ( *clTestIt, i ) );
  410. int i_numTestSamples;
  411. if ( dataIsSparse )
  412. i_numTestSamples = dataTest_sparse.size();
  413. else
  414. i_numTestSamples = (int) dataTest_dense.rows();
  415. NICE::Matrix confusionMatrix( noClassesKnownTraining, noClassesKnownTest, 0.0);
  416. NICE::Matrix scores( i_numTestSamples, noClassesKnownTraining, 0.0);
  417. // ------------------------------------------
  418. // ------------- CLASSIFICATION --------------
  419. // ------------------------------------------
  420. NICE::Timer t;
  421. double testTime (0.0);
  422. for (int i = 0; i < i_numTestSamples; i++)
  423. {
  424. //----------------- convert data to sparse data structures ---------
  425. uint result;
  426. NICE::SparseVector exampleScoresSparse;
  427. if ( dataIsSparse )
  428. {
  429. // and classify
  430. t.start();
  431. classifier->classify( dataTest_sparse[ i ], result, exampleScoresSparse );
  432. t.stop();
  433. testTime += t.getLast();
  434. }
  435. else
  436. {
  437. NICE::Vector example ( dataTest_dense.getRow(i) );
  438. // and classify
  439. t.start();
  440. classifier->classify( &example, result, exampleScoresSparse );
  441. t.stop();
  442. testTime += t.getLast();
  443. }
  444. confusionMatrix( mapClNoToIdxTrain.find(result)->second, mapClNoToIdxTest.find(yMultiTest[i])->second ) += 1.0;
  445. int scoreCnt ( 0 );
  446. for ( NICE::SparseVector::const_iterator scoreIt = exampleScoresSparse.begin(); scoreIt != exampleScoresSparse.end(); scoreIt++, scoreCnt++ )
  447. {
  448. scores(i,scoreCnt) = scoreIt->second;
  449. }
  450. }
  451. std::cerr << "Time for testing: " << testTime << std::endl;
  452. // clean up
  453. if ( dataIsSparse )
  454. {
  455. for ( std::vector<const NICE::SparseVector *>::iterator it = dataTest_sparse.begin(); it != dataTest_sparse.end(); it++)
  456. delete *it;
  457. }
  458. confusionMatrix.normalizeColumnsL1();
  459. double recRate = confusionMatrix.trace()/confusionMatrix.cols();
  460. plhs[0] = mxCreateDoubleScalar( recRate );
  461. if(nlhs >= 2)
  462. plhs[1] = MatlabConversion::convertMatrixFromNice(confusionMatrix);
  463. if(nlhs >= 3)
  464. plhs[2] = MatlabConversion::convertMatrixFromNice(scores);
  465. return;
  466. }
  467. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  468. // interface specific methods for incremental extensions
  469. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  470. // addExample
  471. if ( !strcmp("addExample", cmd.c_str() ) )
  472. {
  473. // Check parameters
  474. if ( (nlhs < 0) || (nrhs < 4) )
  475. {
  476. mexErrMsgTxt("Test: Unexpected arguments.");
  477. }
  478. //------------- read the data --------------
  479. NICE::SparseVector * newExample;
  480. double newLabel;
  481. if ( mxIsSparse( prhs[2] ) )
  482. {
  483. newExample = new NICE::SparseVector ( MatlabConversion::convertSparseVectorToNice( prhs[2] ) );
  484. }
  485. else
  486. {
  487. NICE::Vector * example;
  488. example = new NICE::Vector ( MatlabConversion::convertDoubleVectorToNice(prhs[2]) );
  489. newExample = new NICE::SparseVector ( *example );
  490. //----------------- clean up -------------
  491. delete example;
  492. }
  493. newLabel = MatlabConversion::convertMatlabToDouble( prhs[3] );
  494. // setting performOptimizationAfterIncrement is optional
  495. if ( nrhs > 4 )
  496. {
  497. bool performOptimizationAfterIncrement;
  498. performOptimizationAfterIncrement = MatlabConversion::convertMatlabToBool( prhs[4] );
  499. classifier->addExample ( newExample, newLabel, performOptimizationAfterIncrement );
  500. }
  501. else
  502. {
  503. classifier->addExample ( newExample, newLabel );
  504. }
  505. //----------------- clean up -------------
  506. delete newExample;
  507. return;
  508. }
  509. // addMultipleExamples
  510. if ( !strcmp("addMultipleExamples", cmd.c_str() ) )
  511. {
  512. // Check parameters
  513. if ( (nlhs < 0) || (nrhs < 4) )
  514. {
  515. mexErrMsgTxt("Test: Unexpected arguments.");
  516. }
  517. //------------- read the data --------------
  518. std::vector< const NICE::SparseVector *> newExamples;
  519. NICE::Vector newLabels;
  520. if ( mxIsSparse( prhs[2] ) )
  521. {
  522. newExamples = MatlabConversion::convertSparseMatrixToNice( prhs[2] );
  523. }
  524. else
  525. {
  526. NICE::Matrix newData;
  527. newData = MatlabConversion::convertDoubleMatrixToNice(prhs[2]);
  528. //----------------- convert data to sparse data structures ---------
  529. newExamples.resize( newData.rows() );
  530. std::vector< const NICE::SparseVector *>::iterator exTrainIt = newExamples.begin();
  531. for (int i = 0; i < (int)newData.rows(); i++, exTrainIt++)
  532. {
  533. *exTrainIt = new NICE::SparseVector( newData.getRow(i) );
  534. }
  535. }
  536. newLabels = MatlabConversion::convertDoubleVectorToNice(prhs[3]);
  537. // setting performOptimizationAfterIncrement is optional
  538. if ( nrhs > 4 )
  539. {
  540. bool performOptimizationAfterIncrement;
  541. performOptimizationAfterIncrement = MatlabConversion::convertMatlabToBool( prhs[4] );
  542. classifier->addMultipleExamples ( newExamples, newLabels, performOptimizationAfterIncrement );
  543. }
  544. else
  545. {
  546. classifier->addMultipleExamples ( newExamples, newLabels );
  547. }
  548. //----------------- clean up -------------
  549. for ( std::vector< const NICE::SparseVector *>::iterator exIt = newExamples.begin();
  550. exIt != newExamples.end(); exIt++
  551. )
  552. {
  553. delete *exIt;
  554. }
  555. return;
  556. }
  557. ///////////////////// INTERFACE PERSISTENT /////////////////////
  558. // interface specific methods for store and restore
  559. ///////////////////// INTERFACE PERSISTENT /////////////////////
  560. // store the classifier to an external file
  561. if ( !strcmp("store", cmd.c_str() ) || !strcmp("save", cmd.c_str() ) )
  562. {
  563. // Check parameters
  564. if ( nrhs < 3 )
  565. mexErrMsgTxt("store: no destination given.");
  566. std::string s_destination = MatlabConversion::convertMatlabToString( prhs[2] );
  567. std::filebuf fb;
  568. fb.open ( s_destination.c_str(), ios::out );
  569. std::ostream os(&fb);
  570. //
  571. classifier->store( os );
  572. //
  573. fb.close();
  574. return;
  575. }
  576. // load classifier from external file
  577. if ( !strcmp("restore", cmd.c_str() ) || !strcmp("load", cmd.c_str() ) )
  578. {
  579. // Check parameters
  580. if ( nrhs < 3 )
  581. mexErrMsgTxt("restore: no destination given.");
  582. std::string s_destination = MatlabConversion::convertMatlabToString( prhs[2] );
  583. std::cerr << " aim at restoring the classifier from " << s_destination << std::endl;
  584. std::filebuf fbIn;
  585. fbIn.open ( s_destination.c_str(), ios::in );
  586. std::istream is (&fbIn);
  587. //
  588. classifier->restore( is );
  589. //
  590. fbIn.close();
  591. return;
  592. }
  593. // Got here, so command not recognized
  594. std::string errorMsg (cmd.c_str() );
  595. errorMsg += " -- command not recognized.";
  596. mexErrMsgTxt( errorMsg.c_str() );
  597. }
  598. #endif