GPHIKClassifierMex.cpp 25 KB

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