GPHIKClassifierMex.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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 == "transform")
  193. {
  194. string value = MatlabConversion::convertMatlabToString( prhs[i+1] );
  195. if( value != "identity" && value != "absexp" && value != "exp" && value != "MKL" && value != "WeightedDim")
  196. mexErrMsgIdAndTxt("mexnice:error","Unexpected parameter value for \'transform\'. \'identity\', \'absexp\', \'exp\' , \'MKL\' or \'WeightedDim\' expected.");
  197. conf.sS("GPHIKClassifier", variable, value);
  198. }
  199. if(variable == "varianceApproximation")
  200. {
  201. string value = MatlabConversion::convertMatlabToString(prhs[i+1]);
  202. if(value != "approximate_fine" && value != "approximate_rough" && value != "exact" && value != "none")
  203. mexErrMsgIdAndTxt("mexnice:error","Unexpected parameter value for \'varianceApproximation\'. \'approximate_fine\', \'approximate_rough\', \'none\' or \'exact\' expected.");
  204. conf.sS("GPHIKClassifier", variable, value);
  205. }
  206. }
  207. return conf;
  208. }
  209. // MAIN MATLAB FUNCTION
  210. void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
  211. {
  212. // get the command string specifying what to do
  213. if (nrhs < 1)
  214. mexErrMsgTxt("No commands and options passed... Aborting!");
  215. if( !mxIsChar( prhs[0] ) )
  216. mexErrMsgTxt("First argument needs to be the command, ie.e, the class method to call... Aborting!");
  217. std::string cmd = MatlabConversion::convertMatlabToString( prhs[0] );
  218. // create object
  219. if ( !strcmp("new", cmd.c_str() ) )
  220. {
  221. // check output variable
  222. if (nlhs != 1)
  223. mexErrMsgTxt("New: One output expected.");
  224. // read config settings
  225. NICE::Config conf = parseParametersGPHIKClassifier(prhs+1,nrhs-1);
  226. // create class instance
  227. NICE::GPHIKClassifier * classifier = new NICE::GPHIKClassifier ( &conf, "GPHIKClassifier" /*sectionName in config*/ );
  228. // handle to the C++ instance
  229. plhs[0] = MatlabConversion::convertPtr2Mat<NICE::GPHIKClassifier>( classifier );
  230. return;
  231. }
  232. // in all other cases, there should be a second input,
  233. // which the be the class instance handle
  234. if (nrhs < 2)
  235. mexErrMsgTxt("Second input should be a class instance handle.");
  236. // delete object
  237. if ( !strcmp("delete", cmd.c_str() ) )
  238. {
  239. // Destroy the C++ object
  240. MatlabConversion::destroyObject<NICE::GPHIKClassifier>(prhs[1]);
  241. return;
  242. }
  243. // get the class instance pointer from the second input
  244. // every following function needs the classifier object
  245. NICE::GPHIKClassifier * classifier = MatlabConversion::convertMat2Ptr<NICE::GPHIKClassifier>(prhs[1]);
  246. ////////////////////////////////////////
  247. // Check which class method to call //
  248. ////////////////////////////////////////
  249. // standard train - assumes initialized object
  250. if (!strcmp("train", cmd.c_str() ))
  251. {
  252. // Check parameters
  253. if (nlhs < 0 || nrhs < 4)
  254. {
  255. mexErrMsgTxt("Train: Unexpected arguments.");
  256. }
  257. //------------- read the data --------------
  258. std::vector< const NICE::SparseVector *> examplesTrain;
  259. NICE::Vector yMultiTrain;
  260. if ( mxIsSparse( prhs[2] ) )
  261. {
  262. examplesTrain = MatlabConversion::convertSparseMatrixToNice( prhs[2] );
  263. }
  264. else
  265. {
  266. NICE::Matrix dataTrain;
  267. dataTrain = MatlabConversion::convertDoubleMatrixToNice(prhs[2]);
  268. //----------------- convert data to sparse data structures ---------
  269. examplesTrain.resize( dataTrain.rows() );
  270. std::vector< const NICE::SparseVector *>::iterator exTrainIt = examplesTrain.begin();
  271. for (int i = 0; i < (int)dataTrain.rows(); i++, exTrainIt++)
  272. {
  273. *exTrainIt = new NICE::SparseVector( dataTrain.getRow(i) );
  274. }
  275. }
  276. yMultiTrain = MatlabConversion::convertDoubleVectorToNice(prhs[3]);
  277. //----------------- train our classifier -------------
  278. classifier->train ( examplesTrain , yMultiTrain );
  279. //----------------- clean up -------------
  280. for(int i=0;i<examplesTrain.size();i++)
  281. delete examplesTrain[i];
  282. return;
  283. }
  284. // Classify
  285. if ( !strcmp("classify", cmd.c_str() ) )
  286. {
  287. // Check parameters
  288. if ( (nlhs < 0) || (nrhs < 2) )
  289. {
  290. mexErrMsgTxt("Test: Unexpected arguments.");
  291. }
  292. //------------- read the data --------------
  293. uint result;
  294. NICE::SparseVector scores;
  295. double uncertainty;
  296. if ( mxIsSparse( prhs[2] ) )
  297. {
  298. NICE::SparseVector * example;
  299. example = new NICE::SparseVector ( MatlabConversion::convertSparseVectorToNice( prhs[2] ) );
  300. classifier->classify ( example, result, scores, uncertainty );
  301. //----------------- clean up -------------
  302. delete example;
  303. }
  304. else
  305. {
  306. NICE::Vector * example;
  307. example = new NICE::Vector ( MatlabConversion::convertDoubleVectorToNice(prhs[2]) );
  308. classifier->classify ( example, result, scores, uncertainty );
  309. //----------------- clean up -------------
  310. delete example;
  311. }
  312. // output
  313. plhs[0] = mxCreateDoubleScalar( result );
  314. if(nlhs >= 2)
  315. {
  316. plhs[1] = MatlabConversion::convertSparseVectorFromNice( scores, true /*b_adaptIndex*/);
  317. }
  318. if(nlhs >= 3)
  319. {
  320. plhs[2] = mxCreateDoubleScalar( uncertainty );
  321. }
  322. return;
  323. }
  324. // Uncertainty prediction
  325. if ( !strcmp("uncertainty", cmd.c_str() ) )
  326. {
  327. // Check parameters
  328. if ( (nlhs < 0) || (nrhs < 2) )
  329. {
  330. mexErrMsgTxt("Test: Unexpected arguments.");
  331. }
  332. double uncertainty;
  333. //------------- read the data --------------
  334. if ( mxIsSparse( prhs[2] ) )
  335. {
  336. NICE::SparseVector * example;
  337. example = new NICE::SparseVector ( MatlabConversion::convertSparseVectorToNice( prhs[2] ) );
  338. classifier->predictUncertainty( example, uncertainty );
  339. //----------------- clean up -------------
  340. delete example;
  341. }
  342. else
  343. {
  344. NICE::Vector * example;
  345. example = new NICE::Vector ( MatlabConversion::convertDoubleVectorToNice(prhs[2]) );
  346. classifier->predictUncertainty( example, uncertainty );
  347. //----------------- clean up -------------
  348. delete example;
  349. }
  350. // output
  351. plhs[0] = mxCreateDoubleScalar( uncertainty );
  352. return;
  353. }
  354. // Test - evaluate classifier on whole test set
  355. if ( !strcmp("test", cmd.c_str() ) )
  356. {
  357. // Check parameters
  358. if (nlhs < 0 || nrhs < 4)
  359. mexErrMsgTxt("Test: Unexpected arguments.");
  360. //------------- read the data --------------
  361. bool dataIsSparse ( mxIsSparse( prhs[2] ) );
  362. std::vector< const NICE::SparseVector *> dataTest_sparse;
  363. NICE::Matrix dataTest_dense;
  364. if ( dataIsSparse )
  365. {
  366. dataTest_sparse = MatlabConversion::convertSparseMatrixToNice( prhs[2] );
  367. }
  368. else
  369. {
  370. dataTest_dense = MatlabConversion::convertDoubleMatrixToNice(prhs[2]);
  371. }
  372. NICE::Vector yMultiTest;
  373. yMultiTest = MatlabConversion::convertDoubleVectorToNice(prhs[3]);
  374. // ------------------------------------------
  375. // ------------- PREPARATION --------------
  376. // ------------------------------------------
  377. // determine classes known during training and corresponding mapping
  378. // thereby allow for non-continous class labels
  379. std::set< uint > classesKnownTraining = classifier->getKnownClassNumbers();
  380. uint noClassesKnownTraining ( classesKnownTraining.size() );
  381. std::map< uint, uint > mapClNoToIdxTrain;
  382. std::set< uint >::const_iterator clTrIt = classesKnownTraining.begin();
  383. for ( uint i=0; i < noClassesKnownTraining; i++, clTrIt++ )
  384. mapClNoToIdxTrain.insert ( std::pair< uint, uint > ( *clTrIt, i ) );
  385. // determine classes known during testing and corresponding mapping
  386. // thereby allow for non-continous class labels
  387. std::set< uint > classesKnownTest;
  388. classesKnownTest.clear();
  389. // determine which classes we have in our label vector
  390. // -> MATLAB: myClasses = unique(y);
  391. for ( NICE::Vector::const_iterator it = yMultiTest.begin(); it != yMultiTest.end(); it++ )
  392. {
  393. if ( classesKnownTest.find ( *it ) == classesKnownTest.end() )
  394. {
  395. classesKnownTest.insert ( *it );
  396. }
  397. }
  398. int noClassesKnownTest ( classesKnownTest.size() );
  399. std::map< uint, uint> mapClNoToIdxTest;
  400. std::set< uint >::const_iterator clTestIt = classesKnownTest.begin();
  401. for ( uint i=0; i < noClassesKnownTest; i++, clTestIt++ )
  402. mapClNoToIdxTest.insert ( std::pair< uint, uint > ( *clTestIt, i ) );
  403. int i_numTestSamples;
  404. if ( dataIsSparse )
  405. i_numTestSamples = dataTest_sparse.size();
  406. else
  407. i_numTestSamples = (int) dataTest_dense.rows();
  408. NICE::Matrix confusionMatrix( noClassesKnownTraining, noClassesKnownTest, 0.0);
  409. NICE::Matrix scores( i_numTestSamples, noClassesKnownTraining, 0.0);
  410. // ------------------------------------------
  411. // ------------- CLASSIFICATION --------------
  412. // ------------------------------------------
  413. NICE::Timer t;
  414. double testTime (0.0);
  415. for (int i = 0; i < i_numTestSamples; i++)
  416. {
  417. //----------------- convert data to sparse data structures ---------
  418. uint result;
  419. NICE::SparseVector exampleScoresSparse;
  420. if ( dataIsSparse )
  421. {
  422. // and classify
  423. t.start();
  424. classifier->classify( dataTest_sparse[ i ], result, exampleScoresSparse );
  425. t.stop();
  426. testTime += t.getLast();
  427. }
  428. else
  429. {
  430. NICE::Vector example ( dataTest_dense.getRow(i) );
  431. // and classify
  432. t.start();
  433. classifier->classify( &example, result, exampleScoresSparse );
  434. t.stop();
  435. testTime += t.getLast();
  436. }
  437. confusionMatrix( mapClNoToIdxTrain.find(result)->second, mapClNoToIdxTest.find(yMultiTest[i])->second ) += 1.0;
  438. int scoreCnt ( 0 );
  439. for ( NICE::SparseVector::const_iterator scoreIt = exampleScoresSparse.begin(); scoreIt != exampleScoresSparse.end(); scoreIt++, scoreCnt++ )
  440. {
  441. scores(i,scoreCnt) = scoreIt->second;
  442. }
  443. }
  444. std::cerr << "Time for testing: " << testTime << std::endl;
  445. // clean up
  446. if ( dataIsSparse )
  447. {
  448. for ( std::vector<const NICE::SparseVector *>::iterator it = dataTest_sparse.begin(); it != dataTest_sparse.end(); it++)
  449. delete *it;
  450. }
  451. confusionMatrix.normalizeColumnsL1();
  452. double recRate = confusionMatrix.trace()/confusionMatrix.cols();
  453. plhs[0] = mxCreateDoubleScalar( recRate );
  454. if(nlhs >= 2)
  455. plhs[1] = MatlabConversion::convertMatrixFromNice(confusionMatrix);
  456. if(nlhs >= 3)
  457. plhs[2] = MatlabConversion::convertMatrixFromNice(scores);
  458. return;
  459. }
  460. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  461. // interface specific methods for incremental extensions
  462. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  463. // addExample
  464. if ( !strcmp("addExample", cmd.c_str() ) )
  465. {
  466. // Check parameters
  467. if ( (nlhs < 0) || (nrhs < 4) )
  468. {
  469. mexErrMsgTxt("Test: Unexpected arguments.");
  470. }
  471. //------------- read the data --------------
  472. NICE::SparseVector * newExample;
  473. double newLabel;
  474. if ( mxIsSparse( prhs[2] ) )
  475. {
  476. newExample = new NICE::SparseVector ( MatlabConversion::convertSparseVectorToNice( prhs[2] ) );
  477. }
  478. else
  479. {
  480. NICE::Vector * example;
  481. example = new NICE::Vector ( MatlabConversion::convertDoubleVectorToNice(prhs[2]) );
  482. newExample = new NICE::SparseVector ( *example );
  483. //----------------- clean up -------------
  484. delete example;
  485. }
  486. newLabel = MatlabConversion::convertMatlabToDouble( prhs[3] );
  487. // setting performOptimizationAfterIncrement is optional
  488. if ( nrhs > 4 )
  489. {
  490. bool performOptimizationAfterIncrement;
  491. performOptimizationAfterIncrement = MatlabConversion::convertMatlabToBool( prhs[4] );
  492. classifier->addExample ( newExample, newLabel, performOptimizationAfterIncrement );
  493. }
  494. else
  495. {
  496. classifier->addExample ( newExample, newLabel );
  497. }
  498. //----------------- clean up -------------
  499. delete newExample;
  500. return;
  501. }
  502. // addMultipleExamples
  503. if ( !strcmp("addMultipleExamples", cmd.c_str() ) )
  504. {
  505. // Check parameters
  506. if ( (nlhs < 0) || (nrhs < 4) )
  507. {
  508. mexErrMsgTxt("Test: Unexpected arguments.");
  509. }
  510. //------------- read the data --------------
  511. std::vector< const NICE::SparseVector *> newExamples;
  512. NICE::Vector newLabels;
  513. if ( mxIsSparse( prhs[2] ) )
  514. {
  515. newExamples = MatlabConversion::convertSparseMatrixToNice( prhs[2] );
  516. }
  517. else
  518. {
  519. NICE::Matrix newData;
  520. newData = MatlabConversion::convertDoubleMatrixToNice(prhs[2]);
  521. //----------------- convert data to sparse data structures ---------
  522. newExamples.resize( newData.rows() );
  523. std::vector< const NICE::SparseVector *>::iterator exTrainIt = newExamples.begin();
  524. for (int i = 0; i < (int)newData.rows(); i++, exTrainIt++)
  525. {
  526. *exTrainIt = new NICE::SparseVector( newData.getRow(i) );
  527. }
  528. }
  529. newLabels = MatlabConversion::convertDoubleVectorToNice(prhs[3]);
  530. // setting performOptimizationAfterIncrement is optional
  531. if ( nrhs > 4 )
  532. {
  533. bool performOptimizationAfterIncrement;
  534. performOptimizationAfterIncrement = MatlabConversion::convertMatlabToBool( prhs[4] );
  535. classifier->addMultipleExamples ( newExamples, newLabels, performOptimizationAfterIncrement );
  536. }
  537. else
  538. {
  539. classifier->addMultipleExamples ( newExamples, newLabels );
  540. }
  541. //----------------- clean up -------------
  542. for ( std::vector< const NICE::SparseVector *>::iterator exIt = newExamples.begin();
  543. exIt != newExamples.end(); exIt++
  544. )
  545. {
  546. delete *exIt;
  547. }
  548. return;
  549. }
  550. ///////////////////// INTERFACE PERSISTENT /////////////////////
  551. // interface specific methods for store and restore
  552. ///////////////////// INTERFACE PERSISTENT /////////////////////
  553. // store the classifier to an external file
  554. if ( !strcmp("store", cmd.c_str() ) || !strcmp("save", cmd.c_str() ) )
  555. {
  556. // Check parameters
  557. if ( nrhs < 3 )
  558. mexErrMsgTxt("store: no destination given.");
  559. std::string s_destination = MatlabConversion::convertMatlabToString( prhs[2] );
  560. std::filebuf fb;
  561. fb.open ( s_destination.c_str(), ios::out );
  562. std::ostream os(&fb);
  563. //
  564. classifier->store( os );
  565. //
  566. fb.close();
  567. return;
  568. }
  569. // load classifier from external file
  570. if ( !strcmp("restore", cmd.c_str() ) || !strcmp("load", cmd.c_str() ) )
  571. {
  572. // Check parameters
  573. if ( nrhs < 3 )
  574. mexErrMsgTxt("restore: no destination given.");
  575. std::string s_destination = MatlabConversion::convertMatlabToString( prhs[2] );
  576. std::cerr << " aim at restoring the classifier from " << s_destination << std::endl;
  577. std::filebuf fbIn;
  578. fbIn.open ( s_destination.c_str(), ios::in );
  579. std::istream is (&fbIn);
  580. //
  581. classifier->restore( is );
  582. //
  583. fbIn.close();
  584. return;
  585. }
  586. // Got here, so command not recognized
  587. std::string errorMsg (cmd.c_str() );
  588. errorMsg += " -- command not recognized.";
  589. mexErrMsgTxt( errorMsg.c_str() );
  590. }
  591. #endif