ml.hpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499
  1. /*M///////////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. //
  5. // By downloading, copying, installing or using the software you agree to this license.
  6. // If you do not agree to this license, do not download, install,
  7. // copy or use the software.
  8. //
  9. //
  10. // License Agreement
  11. // For Open Source Computer Vision Library
  12. //
  13. // Copyright (C) 2000, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  15. // Copyright (C) 2014, Itseez Inc, all rights reserved.
  16. // Third party copyrights are property of their respective owners.
  17. //
  18. // Redistribution and use in source and binary forms, with or without modification,
  19. // are permitted provided that the following conditions are met:
  20. //
  21. // * Redistribution's of source code must retain the above copyright notice,
  22. // this list of conditions and the following disclaimer.
  23. //
  24. // * Redistribution's in binary form must reproduce the above copyright notice,
  25. // this list of conditions and the following disclaimer in the documentation
  26. // and/or other materials provided with the distribution.
  27. //
  28. // * The name of the copyright holders may not be used to endorse or promote products
  29. // derived from this software without specific prior written permission.
  30. //
  31. // This software is provided by the copyright holders and contributors "as is" and
  32. // any express or implied warranties, including, but not limited to, the implied
  33. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  34. // In no event shall the Intel Corporation or contributors be liable for any direct,
  35. // indirect, incidental, special, exemplary, or consequential damages
  36. // (including, but not limited to, procurement of substitute goods or services;
  37. // loss of use, data, or profits; or business interruption) however caused
  38. // and on any theory of liability, whether in contract, strict liability,
  39. // or tort (including negligence or otherwise) arising in any way out of
  40. // the use of this software, even if advised of the possibility of such damage.
  41. //
  42. //M*/
  43. #ifndef __OPENCV_ML_HPP__
  44. #define __OPENCV_ML_HPP__
  45. #ifdef __cplusplus
  46. # include "opencv2/core.hpp"
  47. #endif
  48. #ifdef __cplusplus
  49. #include <float.h>
  50. #include <map>
  51. #include <iostream>
  52. /**
  53. @defgroup ml Machine Learning
  54. The Machine Learning Library (MLL) is a set of classes and functions for statistical
  55. classification, regression, and clustering of data.
  56. Most of the classification and regression algorithms are implemented as C++ classes. As the
  57. algorithms have different sets of features (like an ability to handle missing measurements or
  58. categorical input variables), there is a little common ground between the classes. This common
  59. ground is defined by the class cv::ml::StatModel that all the other ML classes are derived from.
  60. See detailed overview here: @ref ml_intro.
  61. */
  62. namespace cv
  63. {
  64. namespace ml
  65. {
  66. //! @addtogroup ml
  67. //! @{
  68. /** @brief Variable types */
  69. enum VariableTypes
  70. {
  71. VAR_NUMERICAL =0, //!< same as VAR_ORDERED
  72. VAR_ORDERED =0, //!< ordered variables
  73. VAR_CATEGORICAL =1 //!< categorical variables
  74. };
  75. /** @brief %Error types */
  76. enum ErrorTypes
  77. {
  78. TEST_ERROR = 0,
  79. TRAIN_ERROR = 1
  80. };
  81. /** @brief Sample types */
  82. enum SampleTypes
  83. {
  84. ROW_SAMPLE = 0, //!< each training sample is a row of samples
  85. COL_SAMPLE = 1 //!< each training sample occupies a column of samples
  86. };
  87. /** @brief The structure represents the logarithmic grid range of statmodel parameters.
  88. It is used for optimizing statmodel accuracy by varying model parameters, the accuracy estimate
  89. being computed by cross-validation.
  90. */
  91. class CV_EXPORTS ParamGrid
  92. {
  93. public:
  94. /** @brief Default constructor */
  95. ParamGrid();
  96. /** @brief Constructor with parameters */
  97. ParamGrid(double _minVal, double _maxVal, double _logStep);
  98. double minVal; //!< Minimum value of the statmodel parameter. Default value is 0.
  99. double maxVal; //!< Maximum value of the statmodel parameter. Default value is 0.
  100. /** @brief Logarithmic step for iterating the statmodel parameter.
  101. The grid determines the following iteration sequence of the statmodel parameter values:
  102. \f[(minVal, minVal*step, minVal*{step}^2, \dots, minVal*{logStep}^n),\f]
  103. where \f$n\f$ is the maximal index satisfying
  104. \f[\texttt{minVal} * \texttt{logStep} ^n < \texttt{maxVal}\f]
  105. The grid is logarithmic, so logStep must always be greater then 1. Default value is 1.
  106. */
  107. double logStep;
  108. };
  109. /** @brief Class encapsulating training data.
  110. Please note that the class only specifies the interface of training data, but not implementation.
  111. All the statistical model classes in _ml_ module accepts Ptr\<TrainData\> as parameter. In other
  112. words, you can create your own class derived from TrainData and pass smart pointer to the instance
  113. of this class into StatModel::train.
  114. @sa @ref ml_intro_data
  115. */
  116. class CV_EXPORTS_W TrainData
  117. {
  118. public:
  119. static inline float missingValue() { return FLT_MAX; }
  120. virtual ~TrainData();
  121. CV_WRAP virtual int getLayout() const = 0;
  122. CV_WRAP virtual int getNTrainSamples() const = 0;
  123. CV_WRAP virtual int getNTestSamples() const = 0;
  124. CV_WRAP virtual int getNSamples() const = 0;
  125. CV_WRAP virtual int getNVars() const = 0;
  126. CV_WRAP virtual int getNAllVars() const = 0;
  127. CV_WRAP virtual void getSample(InputArray varIdx, int sidx, float* buf) const = 0;
  128. CV_WRAP virtual Mat getSamples() const = 0;
  129. CV_WRAP virtual Mat getMissing() const = 0;
  130. /** @brief Returns matrix of train samples
  131. @param layout The requested layout. If it's different from the initial one, the matrix is
  132. transposed. See ml::SampleTypes.
  133. @param compressSamples if true, the function returns only the training samples (specified by
  134. sampleIdx)
  135. @param compressVars if true, the function returns the shorter training samples, containing only
  136. the active variables.
  137. In current implementation the function tries to avoid physical data copying and returns the
  138. matrix stored inside TrainData (unless the transposition or compression is needed).
  139. */
  140. CV_WRAP virtual Mat getTrainSamples(int layout=ROW_SAMPLE,
  141. bool compressSamples=true,
  142. bool compressVars=true) const = 0;
  143. /** @brief Returns the vector of responses
  144. The function returns ordered or the original categorical responses. Usually it's used in
  145. regression algorithms.
  146. */
  147. CV_WRAP virtual Mat getTrainResponses() const = 0;
  148. /** @brief Returns the vector of normalized categorical responses
  149. The function returns vector of responses. Each response is integer from `0` to `<number of
  150. classes>-1`. The actual label value can be retrieved then from the class label vector, see
  151. TrainData::getClassLabels.
  152. */
  153. CV_WRAP virtual Mat getTrainNormCatResponses() const = 0;
  154. CV_WRAP virtual Mat getTestResponses() const = 0;
  155. CV_WRAP virtual Mat getTestNormCatResponses() const = 0;
  156. CV_WRAP virtual Mat getResponses() const = 0;
  157. CV_WRAP virtual Mat getNormCatResponses() const = 0;
  158. CV_WRAP virtual Mat getSampleWeights() const = 0;
  159. CV_WRAP virtual Mat getTrainSampleWeights() const = 0;
  160. CV_WRAP virtual Mat getTestSampleWeights() const = 0;
  161. CV_WRAP virtual Mat getVarIdx() const = 0;
  162. CV_WRAP virtual Mat getVarType() const = 0;
  163. CV_WRAP virtual int getResponseType() const = 0;
  164. CV_WRAP virtual Mat getTrainSampleIdx() const = 0;
  165. CV_WRAP virtual Mat getTestSampleIdx() const = 0;
  166. CV_WRAP virtual void getValues(int vi, InputArray sidx, float* values) const = 0;
  167. virtual void getNormCatValues(int vi, InputArray sidx, int* values) const = 0;
  168. CV_WRAP virtual Mat getDefaultSubstValues() const = 0;
  169. CV_WRAP virtual int getCatCount(int vi) const = 0;
  170. /** @brief Returns the vector of class labels
  171. The function returns vector of unique labels occurred in the responses.
  172. */
  173. CV_WRAP virtual Mat getClassLabels() const = 0;
  174. CV_WRAP virtual Mat getCatOfs() const = 0;
  175. CV_WRAP virtual Mat getCatMap() const = 0;
  176. /** @brief Splits the training data into the training and test parts
  177. @sa TrainData::setTrainTestSplitRatio
  178. */
  179. CV_WRAP virtual void setTrainTestSplit(int count, bool shuffle=true) = 0;
  180. /** @brief Splits the training data into the training and test parts
  181. The function selects a subset of specified relative size and then returns it as the training
  182. set. If the function is not called, all the data is used for training. Please, note that for
  183. each of TrainData::getTrain\* there is corresponding TrainData::getTest\*, so that the test
  184. subset can be retrieved and processed as well.
  185. @sa TrainData::setTrainTestSplit
  186. */
  187. CV_WRAP virtual void setTrainTestSplitRatio(double ratio, bool shuffle=true) = 0;
  188. CV_WRAP virtual void shuffleTrainTest() = 0;
  189. CV_WRAP static Mat getSubVector(const Mat& vec, const Mat& idx);
  190. /** @brief Reads the dataset from a .csv file and returns the ready-to-use training data.
  191. @param filename The input file name
  192. @param headerLineCount The number of lines in the beginning to skip; besides the header, the
  193. function also skips empty lines and lines staring with `#`
  194. @param responseStartIdx Index of the first output variable. If -1, the function considers the
  195. last variable as the response
  196. @param responseEndIdx Index of the last output variable + 1. If -1, then there is single
  197. response variable at responseStartIdx.
  198. @param varTypeSpec The optional text string that specifies the variables' types. It has the
  199. format `ord[n1-n2,n3,n4-n5,...]cat[n6,n7-n8,...]`. That is, variables from `n1 to n2`
  200. (inclusive range), `n3`, `n4 to n5` ... are considered ordered and `n6`, `n7 to n8` ... are
  201. considered as categorical. The range `[n1..n2] + [n3] + [n4..n5] + ... + [n6] + [n7..n8]`
  202. should cover all the variables. If varTypeSpec is not specified, then algorithm uses the
  203. following rules:
  204. - all input variables are considered ordered by default. If some column contains has non-
  205. numerical values, e.g. 'apple', 'pear', 'apple', 'apple', 'mango', the corresponding
  206. variable is considered categorical.
  207. - if there are several output variables, they are all considered as ordered. Error is
  208. reported when non-numerical values are used.
  209. - if there is a single output variable, then if its values are non-numerical or are all
  210. integers, then it's considered categorical. Otherwise, it's considered ordered.
  211. @param delimiter The character used to separate values in each line.
  212. @param missch The character used to specify missing measurements. It should not be a digit.
  213. Although it's a non-numerical value, it surely does not affect the decision of whether the
  214. variable ordered or categorical.
  215. */
  216. static Ptr<TrainData> loadFromCSV(const String& filename,
  217. int headerLineCount,
  218. int responseStartIdx=-1,
  219. int responseEndIdx=-1,
  220. const String& varTypeSpec=String(),
  221. char delimiter=',',
  222. char missch='?');
  223. /** @brief Creates training data from in-memory arrays.
  224. @param samples matrix of samples. It should have CV_32F type.
  225. @param layout see ml::SampleTypes.
  226. @param responses matrix of responses. If the responses are scalar, they should be stored as a
  227. single row or as a single column. The matrix should have type CV_32F or CV_32S (in the
  228. former case the responses are considered as ordered by default; in the latter case - as
  229. categorical)
  230. @param varIdx vector specifying which variables to use for training. It can be an integer vector
  231. (CV_32S) containing 0-based variable indices or byte vector (CV_8U) containing a mask of
  232. active variables.
  233. @param sampleIdx vector specifying which samples to use for training. It can be an integer
  234. vector (CV_32S) containing 0-based sample indices or byte vector (CV_8U) containing a mask
  235. of training samples.
  236. @param sampleWeights optional vector with weights for each sample. It should have CV_32F type.
  237. @param varType optional vector of type CV_8U and size `<number_of_variables_in_samples> +
  238. <number_of_variables_in_responses>`, containing types of each input and output variable. See
  239. ml::VariableTypes.
  240. */
  241. CV_WRAP static Ptr<TrainData> create(InputArray samples, int layout, InputArray responses,
  242. InputArray varIdx=noArray(), InputArray sampleIdx=noArray(),
  243. InputArray sampleWeights=noArray(), InputArray varType=noArray());
  244. };
  245. /** @brief Base class for statistical models in OpenCV ML.
  246. */
  247. class CV_EXPORTS_W StatModel : public Algorithm
  248. {
  249. public:
  250. /** Predict options */
  251. enum Flags {
  252. UPDATE_MODEL = 1,
  253. RAW_OUTPUT=1, //!< makes the method return the raw results (the sum), not the class label
  254. COMPRESSED_INPUT=2,
  255. PREPROCESSED_INPUT=4
  256. };
  257. /** @brief Returns the number of variables in training samples */
  258. CV_WRAP virtual int getVarCount() const = 0;
  259. CV_WRAP virtual bool empty() const;
  260. /** @brief Returns true if the model is trained */
  261. CV_WRAP virtual bool isTrained() const = 0;
  262. /** @brief Returns true if the model is classifier */
  263. CV_WRAP virtual bool isClassifier() const = 0;
  264. /** @brief Trains the statistical model
  265. @param trainData training data that can be loaded from file using TrainData::loadFromCSV or
  266. created with TrainData::create.
  267. @param flags optional flags, depending on the model. Some of the models can be updated with the
  268. new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP).
  269. */
  270. CV_WRAP virtual bool train( const Ptr<TrainData>& trainData, int flags=0 );
  271. /** @brief Trains the statistical model
  272. @param samples training samples
  273. @param layout See ml::SampleTypes.
  274. @param responses vector of responses associated with the training samples.
  275. */
  276. CV_WRAP virtual bool train( InputArray samples, int layout, InputArray responses );
  277. /** @brief Computes error on the training or test dataset
  278. @param data the training data
  279. @param test if true, the error is computed over the test subset of the data, otherwise it's
  280. computed over the training subset of the data. Please note that if you loaded a completely
  281. different dataset to evaluate already trained classifier, you will probably want not to set
  282. the test subset at all with TrainData::setTrainTestSplitRatio and specify test=false, so
  283. that the error is computed for the whole new set. Yes, this sounds a bit confusing.
  284. @param resp the optional output responses.
  285. The method uses StatModel::predict to compute the error. For regression models the error is
  286. computed as RMS, for classifiers - as a percent of missclassified samples (0%-100%).
  287. */
  288. CV_WRAP virtual float calcError( const Ptr<TrainData>& data, bool test, OutputArray resp ) const;
  289. /** @brief Predicts response(s) for the provided sample(s)
  290. @param samples The input samples, floating-point matrix
  291. @param results The optional output matrix of results.
  292. @param flags The optional flags, model-dependent. See cv::ml::StatModel::Flags.
  293. */
  294. CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const = 0;
  295. /** @brief Create and train model with default parameters
  296. The class must implement static `create()` method with no parameters or with all default parameter values
  297. */
  298. template<typename _Tp> static Ptr<_Tp> train(const Ptr<TrainData>& data, int flags=0)
  299. {
  300. Ptr<_Tp> model = _Tp::create();
  301. return !model.empty() && model->train(data, flags) ? model : Ptr<_Tp>();
  302. }
  303. };
  304. /****************************************************************************************\
  305. * Normal Bayes Classifier *
  306. \****************************************************************************************/
  307. /** @brief Bayes classifier for normally distributed data.
  308. @sa @ref ml_intro_bayes
  309. */
  310. class CV_EXPORTS_W NormalBayesClassifier : public StatModel
  311. {
  312. public:
  313. /** @brief Predicts the response for sample(s).
  314. The method estimates the most probable classes for input vectors. Input vectors (one or more)
  315. are stored as rows of the matrix inputs. In case of multiple input vectors, there should be one
  316. output vector outputs. The predicted class for a single input vector is returned by the method.
  317. The vector outputProbs contains the output probabilities corresponding to each element of
  318. result.
  319. */
  320. CV_WRAP virtual float predictProb( InputArray inputs, OutputArray outputs,
  321. OutputArray outputProbs, int flags=0 ) const = 0;
  322. /** Creates empty model
  323. Use StatModel::train to train the model after creation. */
  324. CV_WRAP static Ptr<NormalBayesClassifier> create();
  325. };
  326. /****************************************************************************************\
  327. * K-Nearest Neighbour Classifier *
  328. \****************************************************************************************/
  329. /** @brief The class implements K-Nearest Neighbors model
  330. @sa @ref ml_intro_knn
  331. */
  332. class CV_EXPORTS_W KNearest : public StatModel
  333. {
  334. public:
  335. /** Default number of neighbors to use in predict method. */
  336. /** @see setDefaultK */
  337. CV_WRAP virtual int getDefaultK() const = 0;
  338. /** @copybrief getDefaultK @see getDefaultK */
  339. CV_WRAP virtual void setDefaultK(int val) = 0;
  340. /** Whether classification or regression model should be trained. */
  341. /** @see setIsClassifier */
  342. CV_WRAP virtual bool getIsClassifier() const = 0;
  343. /** @copybrief getIsClassifier @see getIsClassifier */
  344. CV_WRAP virtual void setIsClassifier(bool val) = 0;
  345. /** Parameter for KDTree implementation. */
  346. /** @see setEmax */
  347. CV_WRAP virtual int getEmax() const = 0;
  348. /** @copybrief getEmax @see getEmax */
  349. CV_WRAP virtual void setEmax(int val) = 0;
  350. /** %Algorithm type, one of KNearest::Types. */
  351. /** @see setAlgorithmType */
  352. CV_WRAP virtual int getAlgorithmType() const = 0;
  353. /** @copybrief getAlgorithmType @see getAlgorithmType */
  354. CV_WRAP virtual void setAlgorithmType(int val) = 0;
  355. /** @brief Finds the neighbors and predicts responses for input vectors.
  356. @param samples Input samples stored by rows. It is a single-precision floating-point matrix of
  357. `<number_of_samples> * k` size.
  358. @param k Number of used nearest neighbors. Should be greater than 1.
  359. @param results Vector with results of prediction (regression or classification) for each input
  360. sample. It is a single-precision floating-point vector with `<number_of_samples>` elements.
  361. @param neighborResponses Optional output values for corresponding neighbors. It is a single-
  362. precision floating-point matrix of `<number_of_samples> * k` size.
  363. @param dist Optional output distances from the input vectors to the corresponding neighbors. It
  364. is a single-precision floating-point matrix of `<number_of_samples> * k` size.
  365. For each input vector (a row of the matrix samples), the method finds the k nearest neighbors.
  366. In case of regression, the predicted result is a mean value of the particular vector's neighbor
  367. responses. In case of classification, the class is determined by voting.
  368. For each input vector, the neighbors are sorted by their distances to the vector.
  369. In case of C++ interface you can use output pointers to empty matrices and the function will
  370. allocate memory itself.
  371. If only a single input vector is passed, all output matrices are optional and the predicted
  372. value is returned by the method.
  373. The function is parallelized with the TBB library.
  374. */
  375. CV_WRAP virtual float findNearest( InputArray samples, int k,
  376. OutputArray results,
  377. OutputArray neighborResponses=noArray(),
  378. OutputArray dist=noArray() ) const = 0;
  379. /** @brief Implementations of KNearest algorithm
  380. */
  381. enum Types
  382. {
  383. BRUTE_FORCE=1,
  384. KDTREE=2
  385. };
  386. /** @brief Creates the empty model
  387. The static method creates empty %KNearest classifier. It should be then trained using StatModel::train method.
  388. */
  389. CV_WRAP static Ptr<KNearest> create();
  390. };
  391. /****************************************************************************************\
  392. * Support Vector Machines *
  393. \****************************************************************************************/
  394. /** @brief Support Vector Machines.
  395. @sa @ref ml_intro_svm
  396. */
  397. class CV_EXPORTS_W SVM : public StatModel
  398. {
  399. public:
  400. class CV_EXPORTS Kernel : public Algorithm
  401. {
  402. public:
  403. virtual int getType() const = 0;
  404. virtual void calc( int vcount, int n, const float* vecs, const float* another, float* results ) = 0;
  405. };
  406. /** Type of a %SVM formulation.
  407. See SVM::Types. Default value is SVM::C_SVC. */
  408. /** @see setType */
  409. CV_WRAP virtual int getType() const = 0;
  410. /** @copybrief getType @see getType */
  411. CV_WRAP virtual void setType(int val) = 0;
  412. /** Parameter \f$\gamma\f$ of a kernel function.
  413. For SVM::POLY, SVM::RBF, SVM::SIGMOID or SVM::CHI2. Default value is 1. */
  414. /** @see setGamma */
  415. CV_WRAP virtual double getGamma() const = 0;
  416. /** @copybrief getGamma @see getGamma */
  417. CV_WRAP virtual void setGamma(double val) = 0;
  418. /** Parameter _coef0_ of a kernel function.
  419. For SVM::POLY or SVM::SIGMOID. Default value is 0.*/
  420. /** @see setCoef0 */
  421. CV_WRAP virtual double getCoef0() const = 0;
  422. /** @copybrief getCoef0 @see getCoef0 */
  423. CV_WRAP virtual void setCoef0(double val) = 0;
  424. /** Parameter _degree_ of a kernel function.
  425. For SVM::POLY. Default value is 0. */
  426. /** @see setDegree */
  427. CV_WRAP virtual double getDegree() const = 0;
  428. /** @copybrief getDegree @see getDegree */
  429. CV_WRAP virtual void setDegree(double val) = 0;
  430. /** Parameter _C_ of a %SVM optimization problem.
  431. For SVM::C_SVC, SVM::EPS_SVR or SVM::NU_SVR. Default value is 0. */
  432. /** @see setC */
  433. CV_WRAP virtual double getC() const = 0;
  434. /** @copybrief getC @see getC */
  435. CV_WRAP virtual void setC(double val) = 0;
  436. /** Parameter \f$\nu\f$ of a %SVM optimization problem.
  437. For SVM::NU_SVC, SVM::ONE_CLASS or SVM::NU_SVR. Default value is 0. */
  438. /** @see setNu */
  439. CV_WRAP virtual double getNu() const = 0;
  440. /** @copybrief getNu @see getNu */
  441. CV_WRAP virtual void setNu(double val) = 0;
  442. /** Parameter \f$\epsilon\f$ of a %SVM optimization problem.
  443. For SVM::EPS_SVR. Default value is 0. */
  444. /** @see setP */
  445. CV_WRAP virtual double getP() const = 0;
  446. /** @copybrief getP @see getP */
  447. CV_WRAP virtual void setP(double val) = 0;
  448. /** Optional weights in the SVM::C_SVC problem, assigned to particular classes.
  449. They are multiplied by _C_ so the parameter _C_ of class _i_ becomes `classWeights(i) * C`. Thus
  450. these weights affect the misclassification penalty for different classes. The larger weight,
  451. the larger penalty on misclassification of data from the corresponding class. Default value is
  452. empty Mat. */
  453. /** @see setClassWeights */
  454. CV_WRAP virtual cv::Mat getClassWeights() const = 0;
  455. /** @copybrief getClassWeights @see getClassWeights */
  456. CV_WRAP virtual void setClassWeights(const cv::Mat &val) = 0;
  457. /** Termination criteria of the iterative %SVM training procedure which solves a partial
  458. case of constrained quadratic optimization problem.
  459. You can specify tolerance and/or the maximum number of iterations. Default value is
  460. `TermCriteria( TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, FLT_EPSILON )`; */
  461. /** @see setTermCriteria */
  462. CV_WRAP virtual cv::TermCriteria getTermCriteria() const = 0;
  463. /** @copybrief getTermCriteria @see getTermCriteria */
  464. CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0;
  465. /** Type of a %SVM kernel.
  466. See SVM::KernelTypes. Default value is SVM::RBF. */
  467. CV_WRAP virtual int getKernelType() const = 0;
  468. /** Initialize with one of predefined kernels.
  469. See SVM::KernelTypes. */
  470. CV_WRAP virtual void setKernel(int kernelType) = 0;
  471. /** Initialize with custom kernel.
  472. See SVM::Kernel class for implementation details */
  473. virtual void setCustomKernel(const Ptr<Kernel> &_kernel) = 0;
  474. //! %SVM type
  475. enum Types {
  476. /** C-Support Vector Classification. n-class classification (n \f$\geq\f$ 2), allows
  477. imperfect separation of classes with penalty multiplier C for outliers. */
  478. C_SVC=100,
  479. /** \f$\nu\f$-Support Vector Classification. n-class classification with possible
  480. imperfect separation. Parameter \f$\nu\f$ (in the range 0..1, the larger the value, the smoother
  481. the decision boundary) is used instead of C. */
  482. NU_SVC=101,
  483. /** Distribution Estimation (One-class %SVM). All the training data are from
  484. the same class, %SVM builds a boundary that separates the class from the rest of the feature
  485. space. */
  486. ONE_CLASS=102,
  487. /** \f$\epsilon\f$-Support Vector Regression. The distance between feature vectors
  488. from the training set and the fitting hyper-plane must be less than p. For outliers the
  489. penalty multiplier C is used. */
  490. EPS_SVR=103,
  491. /** \f$\nu\f$-Support Vector Regression. \f$\nu\f$ is used instead of p.
  492. See @cite LibSVM for details. */
  493. NU_SVR=104
  494. };
  495. /** @brief %SVM kernel type
  496. A comparison of different kernels on the following 2D test case with four classes. Four
  497. SVM::C_SVC SVMs have been trained (one against rest) with auto_train. Evaluation on three
  498. different kernels (SVM::CHI2, SVM::INTER, SVM::RBF). The color depicts the class with max score.
  499. Bright means max-score \> 0, dark means max-score \< 0.
  500. ![image](pics/SVM_Comparison.png)
  501. */
  502. enum KernelTypes {
  503. /** Returned by SVM::getKernelType in case when custom kernel has been set */
  504. CUSTOM=-1,
  505. /** Linear kernel. No mapping is done, linear discrimination (or regression) is
  506. done in the original feature space. It is the fastest option. \f$K(x_i, x_j) = x_i^T x_j\f$. */
  507. LINEAR=0,
  508. /** Polynomial kernel:
  509. \f$K(x_i, x_j) = (\gamma x_i^T x_j + coef0)^{degree}, \gamma > 0\f$. */
  510. POLY=1,
  511. /** Radial basis function (RBF), a good choice in most cases.
  512. \f$K(x_i, x_j) = e^{-\gamma ||x_i - x_j||^2}, \gamma > 0\f$. */
  513. RBF=2,
  514. /** Sigmoid kernel: \f$K(x_i, x_j) = \tanh(\gamma x_i^T x_j + coef0)\f$. */
  515. SIGMOID=3,
  516. /** Exponential Chi2 kernel, similar to the RBF kernel:
  517. \f$K(x_i, x_j) = e^{-\gamma \chi^2(x_i,x_j)}, \chi^2(x_i,x_j) = (x_i-x_j)^2/(x_i+x_j), \gamma > 0\f$. */
  518. CHI2=4,
  519. /** Histogram intersection kernel. A fast kernel. \f$K(x_i, x_j) = min(x_i,x_j)\f$. */
  520. INTER=5
  521. };
  522. //! %SVM params type
  523. enum ParamTypes {
  524. C=0,
  525. GAMMA=1,
  526. P=2,
  527. NU=3,
  528. COEF=4,
  529. DEGREE=5
  530. };
  531. /** @brief Trains an %SVM with optimal parameters.
  532. @param data the training data that can be constructed using TrainData::create or
  533. TrainData::loadFromCSV.
  534. @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One
  535. subset is used to test the model, the others form the train set. So, the %SVM algorithm is
  536. executed kFold times.
  537. @param Cgrid grid for C
  538. @param gammaGrid grid for gamma
  539. @param pGrid grid for p
  540. @param nuGrid grid for nu
  541. @param coeffGrid grid for coeff
  542. @param degreeGrid grid for degree
  543. @param balanced If true and the problem is 2-class classification then the method creates more
  544. balanced cross-validation subsets that is proportions between classes in subsets are close
  545. to such proportion in the whole train dataset.
  546. The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p,
  547. nu, coef0, degree. Parameters are considered optimal when the cross-validation
  548. estimate of the test set error is minimal.
  549. If there is no need to optimize a parameter, the corresponding grid step should be set to any
  550. value less than or equal to 1. For example, to avoid optimization in gamma, set `gammaGrid.step
  551. = 0`, `gammaGrid.minVal`, `gamma_grid.maxVal` as arbitrary numbers. In this case, the value
  552. `Gamma` is taken for gamma.
  553. And, finally, if the optimization in a parameter is required but the corresponding grid is
  554. unknown, you may call the function SVM::getDefaultGrid. To generate a grid, for example, for
  555. gamma, call `SVM::getDefaultGrid(SVM::GAMMA)`.
  556. This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the
  557. regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and
  558. the usual %SVM with parameters specified in params is executed.
  559. */
  560. virtual bool trainAuto( const Ptr<TrainData>& data, int kFold = 10,
  561. ParamGrid Cgrid = SVM::getDefaultGrid(SVM::C),
  562. ParamGrid gammaGrid = SVM::getDefaultGrid(SVM::GAMMA),
  563. ParamGrid pGrid = SVM::getDefaultGrid(SVM::P),
  564. ParamGrid nuGrid = SVM::getDefaultGrid(SVM::NU),
  565. ParamGrid coeffGrid = SVM::getDefaultGrid(SVM::COEF),
  566. ParamGrid degreeGrid = SVM::getDefaultGrid(SVM::DEGREE),
  567. bool balanced=false) = 0;
  568. /** @brief Retrieves all the support vectors
  569. The method returns all the support vector as floating-point matrix, where support vectors are
  570. stored as matrix rows.
  571. */
  572. CV_WRAP virtual Mat getSupportVectors() const = 0;
  573. /** @brief Retrieves the decision function
  574. @param i the index of the decision function. If the problem solved is regression, 1-class or
  575. 2-class classification, then there will be just one decision function and the index should
  576. always be 0. Otherwise, in the case of N-class classification, there will be \f$N(N-1)/2\f$
  577. decision functions.
  578. @param alpha the optional output vector for weights, corresponding to different support vectors.
  579. In the case of linear %SVM all the alpha's will be 1's.
  580. @param svidx the optional output vector of indices of support vectors within the matrix of
  581. support vectors (which can be retrieved by SVM::getSupportVectors). In the case of linear
  582. %SVM each decision function consists of a single "compressed" support vector.
  583. The method returns rho parameter of the decision function, a scalar subtracted from the weighted
  584. sum of kernel responses.
  585. */
  586. CV_WRAP virtual double getDecisionFunction(int i, OutputArray alpha, OutputArray svidx) const = 0;
  587. /** @brief Generates a grid for %SVM parameters.
  588. @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is
  589. generated for the parameter with this ID.
  590. The function generates a grid for the specified parameter of the %SVM algorithm. The grid may be
  591. passed to the function SVM::trainAuto.
  592. */
  593. static ParamGrid getDefaultGrid( int param_id );
  594. /** Creates empty model.
  595. Use StatModel::train to train the model. Since %SVM has several parameters, you may want to
  596. find the best parameters for your problem, it can be done with SVM::trainAuto. */
  597. CV_WRAP static Ptr<SVM> create();
  598. };
  599. /****************************************************************************************\
  600. * Expectation - Maximization *
  601. \****************************************************************************************/
  602. /** @brief The class implements the Expectation Maximization algorithm.
  603. @sa @ref ml_intro_em
  604. */
  605. class CV_EXPORTS_W EM : public StatModel
  606. {
  607. public:
  608. //! Type of covariation matrices
  609. enum Types {
  610. /** A scaled identity matrix \f$\mu_k * I\f$. There is the only
  611. parameter \f$\mu_k\f$ to be estimated for each matrix. The option may be used in special cases,
  612. when the constraint is relevant, or as a first step in the optimization (for example in case
  613. when the data is preprocessed with PCA). The results of such preliminary estimation may be
  614. passed again to the optimization procedure, this time with
  615. covMatType=EM::COV_MAT_DIAGONAL. */
  616. COV_MAT_SPHERICAL=0,
  617. /** A diagonal matrix with positive diagonal elements. The number of
  618. free parameters is d for each matrix. This is most commonly used option yielding good
  619. estimation results. */
  620. COV_MAT_DIAGONAL=1,
  621. /** A symmetric positively defined matrix. The number of free
  622. parameters in each matrix is about \f$d^2/2\f$. It is not recommended to use this option, unless
  623. there is pretty accurate initial estimation of the parameters and/or a huge number of
  624. training samples. */
  625. COV_MAT_GENERIC=2,
  626. COV_MAT_DEFAULT=COV_MAT_DIAGONAL
  627. };
  628. //! Default parameters
  629. enum {DEFAULT_NCLUSTERS=5, DEFAULT_MAX_ITERS=100};
  630. //! The initial step
  631. enum {START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0};
  632. /** The number of mixture components in the Gaussian mixture model.
  633. Default value of the parameter is EM::DEFAULT_NCLUSTERS=5. Some of %EM implementation could
  634. determine the optimal number of mixtures within a specified value range, but that is not the
  635. case in ML yet. */
  636. /** @see setClustersNumber */
  637. CV_WRAP virtual int getClustersNumber() const = 0;
  638. /** @copybrief getClustersNumber @see getClustersNumber */
  639. CV_WRAP virtual void setClustersNumber(int val) = 0;
  640. /** Constraint on covariance matrices which defines type of matrices.
  641. See EM::Types. */
  642. /** @see setCovarianceMatrixType */
  643. CV_WRAP virtual int getCovarianceMatrixType() const = 0;
  644. /** @copybrief getCovarianceMatrixType @see getCovarianceMatrixType */
  645. CV_WRAP virtual void setCovarianceMatrixType(int val) = 0;
  646. /** The termination criteria of the %EM algorithm.
  647. The %EM algorithm can be terminated by the number of iterations termCrit.maxCount (number of
  648. M-steps) or when relative change of likelihood logarithm is less than termCrit.epsilon. Default
  649. maximum number of iterations is EM::DEFAULT_MAX_ITERS=100. */
  650. /** @see setTermCriteria */
  651. CV_WRAP virtual TermCriteria getTermCriteria() const = 0;
  652. /** @copybrief getTermCriteria @see getTermCriteria */
  653. CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0;
  654. /** @brief Returns weights of the mixtures
  655. Returns vector with the number of elements equal to the number of mixtures.
  656. */
  657. CV_WRAP virtual Mat getWeights() const = 0;
  658. /** @brief Returns the cluster centers (means of the Gaussian mixture)
  659. Returns matrix with the number of rows equal to the number of mixtures and number of columns
  660. equal to the space dimensionality.
  661. */
  662. CV_WRAP virtual Mat getMeans() const = 0;
  663. /** @brief Returns covariation matrices
  664. Returns vector of covariation matrices. Number of matrices is the number of gaussian mixtures,
  665. each matrix is a square floating-point matrix NxN, where N is the space dimensionality.
  666. */
  667. virtual void getCovs(std::vector<Mat>& covs) const = 0;
  668. /** @brief Returns a likelihood logarithm value and an index of the most probable mixture component
  669. for the given sample.
  670. @param sample A sample for classification. It should be a one-channel matrix of
  671. \f$1 \times dims\f$ or \f$dims \times 1\f$ size.
  672. @param probs Optional output matrix that contains posterior probabilities of each component
  673. given the sample. It has \f$1 \times nclusters\f$ size and CV_64FC1 type.
  674. The method returns a two-element double vector. Zero element is a likelihood logarithm value for
  675. the sample. First element is an index of the most probable mixture component for the given
  676. sample.
  677. */
  678. CV_WRAP CV_WRAP virtual Vec2d predict2(InputArray sample, OutputArray probs) const = 0;
  679. /** @brief Estimate the Gaussian mixture parameters from a samples set.
  680. This variation starts with Expectation step. Initial values of the model parameters will be
  681. estimated by the k-means algorithm.
  682. Unlike many of the ML models, %EM is an unsupervised learning algorithm and it does not take
  683. responses (class labels or function values) as input. Instead, it computes the *Maximum
  684. Likelihood Estimate* of the Gaussian mixture parameters from an input sample set, stores all the
  685. parameters inside the structure: \f$p_{i,k}\f$ in probs, \f$a_k\f$ in means , \f$S_k\f$ in
  686. covs[k], \f$\pi_k\f$ in weights , and optionally computes the output "class label" for each
  687. sample: \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most
  688. probable mixture component for each sample).
  689. The trained model can be used further for prediction, just like any other classifier. The
  690. trained model is similar to the NormalBayesClassifier.
  691. @param samples Samples from which the Gaussian mixture model will be estimated. It should be a
  692. one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type
  693. it will be converted to the inner matrix of such type for the further computing.
  694. @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for
  695. each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type.
  696. @param labels The optional output "class label" for each sample:
  697. \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable
  698. mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type.
  699. @param probs The optional output matrix that contains posterior probabilities of each Gaussian
  700. mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and
  701. CV_64FC1 type.
  702. */
  703. CV_WRAP virtual bool trainEM(InputArray samples,
  704. OutputArray logLikelihoods=noArray(),
  705. OutputArray labels=noArray(),
  706. OutputArray probs=noArray()) = 0;
  707. /** @brief Estimate the Gaussian mixture parameters from a samples set.
  708. This variation starts with Expectation step. You need to provide initial means \f$a_k\f$ of
  709. mixture components. Optionally you can pass initial weights \f$\pi_k\f$ and covariance matrices
  710. \f$S_k\f$ of mixture components.
  711. @param samples Samples from which the Gaussian mixture model will be estimated. It should be a
  712. one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type
  713. it will be converted to the inner matrix of such type for the further computing.
  714. @param means0 Initial means \f$a_k\f$ of mixture components. It is a one-channel matrix of
  715. \f$nclusters \times dims\f$ size. If the matrix does not have CV_64F type it will be
  716. converted to the inner matrix of such type for the further computing.
  717. @param covs0 The vector of initial covariance matrices \f$S_k\f$ of mixture components. Each of
  718. covariance matrices is a one-channel matrix of \f$dims \times dims\f$ size. If the matrices
  719. do not have CV_64F type they will be converted to the inner matrices of such type for the
  720. further computing.
  721. @param weights0 Initial weights \f$\pi_k\f$ of mixture components. It should be a one-channel
  722. floating-point matrix with \f$1 \times nclusters\f$ or \f$nclusters \times 1\f$ size.
  723. @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for
  724. each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type.
  725. @param labels The optional output "class label" for each sample:
  726. \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable
  727. mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type.
  728. @param probs The optional output matrix that contains posterior probabilities of each Gaussian
  729. mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and
  730. CV_64FC1 type.
  731. */
  732. CV_WRAP virtual bool trainE(InputArray samples, InputArray means0,
  733. InputArray covs0=noArray(),
  734. InputArray weights0=noArray(),
  735. OutputArray logLikelihoods=noArray(),
  736. OutputArray labels=noArray(),
  737. OutputArray probs=noArray()) = 0;
  738. /** @brief Estimate the Gaussian mixture parameters from a samples set.
  739. This variation starts with Maximization step. You need to provide initial probabilities
  740. \f$p_{i,k}\f$ to use this option.
  741. @param samples Samples from which the Gaussian mixture model will be estimated. It should be a
  742. one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type
  743. it will be converted to the inner matrix of such type for the further computing.
  744. @param probs0
  745. @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for
  746. each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type.
  747. @param labels The optional output "class label" for each sample:
  748. \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable
  749. mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type.
  750. @param probs The optional output matrix that contains posterior probabilities of each Gaussian
  751. mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and
  752. CV_64FC1 type.
  753. */
  754. CV_WRAP virtual bool trainM(InputArray samples, InputArray probs0,
  755. OutputArray logLikelihoods=noArray(),
  756. OutputArray labels=noArray(),
  757. OutputArray probs=noArray()) = 0;
  758. /** Creates empty %EM model.
  759. The model should be trained then using StatModel::train(traindata, flags) method. Alternatively, you
  760. can use one of the EM::train\* methods or load it from file using Algorithm::load\<EM\>(filename).
  761. */
  762. CV_WRAP static Ptr<EM> create();
  763. };
  764. /****************************************************************************************\
  765. * Decision Tree *
  766. \****************************************************************************************/
  767. /** @brief The class represents a single decision tree or a collection of decision trees.
  768. The current public interface of the class allows user to train only a single decision tree, however
  769. the class is capable of storing multiple decision trees and using them for prediction (by summing
  770. responses or using a voting schemes), and the derived from DTrees classes (such as RTrees and Boost)
  771. use this capability to implement decision tree ensembles.
  772. @sa @ref ml_intro_trees
  773. */
  774. class CV_EXPORTS_W DTrees : public StatModel
  775. {
  776. public:
  777. /** Predict options */
  778. enum Flags { PREDICT_AUTO=0, PREDICT_SUM=(1<<8), PREDICT_MAX_VOTE=(2<<8), PREDICT_MASK=(3<<8) };
  779. /** Cluster possible values of a categorical variable into K\<=maxCategories clusters to
  780. find a suboptimal split.
  781. If a discrete variable, on which the training procedure tries to make a split, takes more than
  782. maxCategories values, the precise best subset estimation may take a very long time because the
  783. algorithm is exponential. Instead, many decision trees engines (including our implementation)
  784. try to find sub-optimal split in this case by clustering all the samples into maxCategories
  785. clusters that is some categories are merged together. The clustering is applied only in n \>
  786. 2-class classification problems for categorical variables with N \> max_categories possible
  787. values. In case of regression and 2-class classification the optimal split can be found
  788. efficiently without employing clustering, thus the parameter is not used in these cases.
  789. Default value is 10.*/
  790. /** @see setMaxCategories */
  791. CV_WRAP virtual int getMaxCategories() const = 0;
  792. /** @copybrief getMaxCategories @see getMaxCategories */
  793. CV_WRAP virtual void setMaxCategories(int val) = 0;
  794. /** The maximum possible depth of the tree.
  795. That is the training algorithms attempts to split a node while its depth is less than maxDepth.
  796. The root node has zero depth. The actual depth may be smaller if the other termination criteria
  797. are met (see the outline of the training procedure @ref ml_intro_trees "here"), and/or if the
  798. tree is pruned. Default value is INT_MAX.*/
  799. /** @see setMaxDepth */
  800. CV_WRAP virtual int getMaxDepth() const = 0;
  801. /** @copybrief getMaxDepth @see getMaxDepth */
  802. CV_WRAP virtual void setMaxDepth(int val) = 0;
  803. /** If the number of samples in a node is less than this parameter then the node will not be split.
  804. Default value is 10.*/
  805. /** @see setMinSampleCount */
  806. CV_WRAP virtual int getMinSampleCount() const = 0;
  807. /** @copybrief getMinSampleCount @see getMinSampleCount */
  808. CV_WRAP virtual void setMinSampleCount(int val) = 0;
  809. /** If CVFolds \> 1 then algorithms prunes the built decision tree using K-fold
  810. cross-validation procedure where K is equal to CVFolds.
  811. Default value is 10.*/
  812. /** @see setCVFolds */
  813. CV_WRAP virtual int getCVFolds() const = 0;
  814. /** @copybrief getCVFolds @see getCVFolds */
  815. CV_WRAP virtual void setCVFolds(int val) = 0;
  816. /** If true then surrogate splits will be built.
  817. These splits allow to work with missing data and compute variable importance correctly.
  818. Default value is false.
  819. @note currently it's not implemented.*/
  820. /** @see setUseSurrogates */
  821. CV_WRAP virtual bool getUseSurrogates() const = 0;
  822. /** @copybrief getUseSurrogates @see getUseSurrogates */
  823. CV_WRAP virtual void setUseSurrogates(bool val) = 0;
  824. /** If true then a pruning will be harsher.
  825. This will make a tree more compact and more resistant to the training data noise but a bit less
  826. accurate. Default value is true.*/
  827. /** @see setUse1SERule */
  828. CV_WRAP virtual bool getUse1SERule() const = 0;
  829. /** @copybrief getUse1SERule @see getUse1SERule */
  830. CV_WRAP virtual void setUse1SERule(bool val) = 0;
  831. /** If true then pruned branches are physically removed from the tree.
  832. Otherwise they are retained and it is possible to get results from the original unpruned (or
  833. pruned less aggressively) tree. Default value is true.*/
  834. /** @see setTruncatePrunedTree */
  835. CV_WRAP virtual bool getTruncatePrunedTree() const = 0;
  836. /** @copybrief getTruncatePrunedTree @see getTruncatePrunedTree */
  837. CV_WRAP virtual void setTruncatePrunedTree(bool val) = 0;
  838. /** Termination criteria for regression trees.
  839. If all absolute differences between an estimated value in a node and values of train samples
  840. in this node are less than this parameter then the node will not be split further. Default
  841. value is 0.01f*/
  842. /** @see setRegressionAccuracy */
  843. CV_WRAP virtual float getRegressionAccuracy() const = 0;
  844. /** @copybrief getRegressionAccuracy @see getRegressionAccuracy */
  845. CV_WRAP virtual void setRegressionAccuracy(float val) = 0;
  846. /** @brief The array of a priori class probabilities, sorted by the class label value.
  847. The parameter can be used to tune the decision tree preferences toward a certain class. For
  848. example, if you want to detect some rare anomaly occurrence, the training base will likely
  849. contain much more normal cases than anomalies, so a very good classification performance
  850. will be achieved just by considering every case as normal. To avoid this, the priors can be
  851. specified, where the anomaly probability is artificially increased (up to 0.5 or even
  852. greater), so the weight of the misclassified anomalies becomes much bigger, and the tree is
  853. adjusted properly.
  854. You can also think about this parameter as weights of prediction categories which determine
  855. relative weights that you give to misclassification. That is, if the weight of the first
  856. category is 1 and the weight of the second category is 10, then each mistake in predicting
  857. the second category is equivalent to making 10 mistakes in predicting the first category.
  858. Default value is empty Mat.*/
  859. /** @see setPriors */
  860. CV_WRAP virtual cv::Mat getPriors() const = 0;
  861. /** @copybrief getPriors @see getPriors */
  862. CV_WRAP virtual void setPriors(const cv::Mat &val) = 0;
  863. /** @brief The class represents a decision tree node.
  864. */
  865. class CV_EXPORTS Node
  866. {
  867. public:
  868. Node();
  869. double value; //!< Value at the node: a class label in case of classification or estimated
  870. //!< function value in case of regression.
  871. int classIdx; //!< Class index normalized to 0..class_count-1 range and assigned to the
  872. //!< node. It is used internally in classification trees and tree ensembles.
  873. int parent; //!< Index of the parent node
  874. int left; //!< Index of the left child node
  875. int right; //!< Index of right child node
  876. int defaultDir; //!< Default direction where to go (-1: left or +1: right). It helps in the
  877. //!< case of missing values.
  878. int split; //!< Index of the first split
  879. };
  880. /** @brief The class represents split in a decision tree.
  881. */
  882. class CV_EXPORTS Split
  883. {
  884. public:
  885. Split();
  886. int varIdx; //!< Index of variable on which the split is created.
  887. bool inversed; //!< If true, then the inverse split rule is used (i.e. left and right
  888. //!< branches are exchanged in the rule expressions below).
  889. float quality; //!< The split quality, a positive number. It is used to choose the best split.
  890. int next; //!< Index of the next split in the list of splits for the node
  891. float c; /**< The threshold value in case of split on an ordered variable.
  892. The rule is:
  893. @code{.none}
  894. if var_value < c
  895. then next_node <- left
  896. else next_node <- right
  897. @endcode */
  898. int subsetOfs; /**< Offset of the bitset used by the split on a categorical variable.
  899. The rule is:
  900. @code{.none}
  901. if bitset[var_value] == 1
  902. then next_node <- left
  903. else next_node <- right
  904. @endcode */
  905. };
  906. /** @brief Returns indices of root nodes
  907. */
  908. virtual const std::vector<int>& getRoots() const = 0;
  909. /** @brief Returns all the nodes
  910. all the node indices are indices in the returned vector
  911. */
  912. virtual const std::vector<Node>& getNodes() const = 0;
  913. /** @brief Returns all the splits
  914. all the split indices are indices in the returned vector
  915. */
  916. virtual const std::vector<Split>& getSplits() const = 0;
  917. /** @brief Returns all the bitsets for categorical splits
  918. Split::subsetOfs is an offset in the returned vector
  919. */
  920. virtual const std::vector<int>& getSubsets() const = 0;
  921. /** @brief Creates the empty model
  922. The static method creates empty decision tree with the specified parameters. It should be then
  923. trained using train method (see StatModel::train). Alternatively, you can load the model from
  924. file using Algorithm::load\<DTrees\>(filename).
  925. */
  926. CV_WRAP static Ptr<DTrees> create();
  927. };
  928. /****************************************************************************************\
  929. * Random Trees Classifier *
  930. \****************************************************************************************/
  931. /** @brief The class implements the random forest predictor.
  932. @sa @ref ml_intro_rtrees
  933. */
  934. class CV_EXPORTS_W RTrees : public DTrees
  935. {
  936. public:
  937. /** If true then variable importance will be calculated and then it can be retrieved by RTrees::getVarImportance.
  938. Default value is false.*/
  939. /** @see setCalculateVarImportance */
  940. CV_WRAP virtual bool getCalculateVarImportance() const = 0;
  941. /** @copybrief getCalculateVarImportance @see getCalculateVarImportance */
  942. CV_WRAP virtual void setCalculateVarImportance(bool val) = 0;
  943. /** The size of the randomly selected subset of features at each tree node and that are used
  944. to find the best split(s).
  945. If you set it to 0 then the size will be set to the square root of the total number of
  946. features. Default value is 0.*/
  947. /** @see setActiveVarCount */
  948. CV_WRAP virtual int getActiveVarCount() const = 0;
  949. /** @copybrief getActiveVarCount @see getActiveVarCount */
  950. CV_WRAP virtual void setActiveVarCount(int val) = 0;
  951. /** The termination criteria that specifies when the training algorithm stops.
  952. Either when the specified number of trees is trained and added to the ensemble or when
  953. sufficient accuracy (measured as OOB error) is achieved. Typically the more trees you have the
  954. better the accuracy. However, the improvement in accuracy generally diminishes and asymptotes
  955. pass a certain number of trees. Also to keep in mind, the number of tree increases the
  956. prediction time linearly. Default value is TermCriteria(TermCriteria::MAX_ITERS +
  957. TermCriteria::EPS, 50, 0.1)*/
  958. /** @see setTermCriteria */
  959. CV_WRAP virtual TermCriteria getTermCriteria() const = 0;
  960. /** @copybrief getTermCriteria @see getTermCriteria */
  961. CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0;
  962. /** Returns the variable importance array.
  963. The method returns the variable importance vector, computed at the training stage when
  964. CalculateVarImportance is set to true. If this flag was set to false, the empty matrix is
  965. returned.
  966. */
  967. CV_WRAP virtual Mat getVarImportance() const = 0;
  968. /** Creates the empty model.
  969. Use StatModel::train to train the model, StatModel::train to create and train the model,
  970. Algorithm::load to load the pre-trained model.
  971. */
  972. CV_WRAP static Ptr<RTrees> create();
  973. };
  974. /****************************************************************************************\
  975. * Boosted tree classifier *
  976. \****************************************************************************************/
  977. /** @brief Boosted tree classifier derived from DTrees
  978. @sa @ref ml_intro_boost
  979. */
  980. class CV_EXPORTS_W Boost : public DTrees
  981. {
  982. public:
  983. /** Type of the boosting algorithm.
  984. See Boost::Types. Default value is Boost::REAL. */
  985. /** @see setBoostType */
  986. CV_WRAP virtual int getBoostType() const = 0;
  987. /** @copybrief getBoostType @see getBoostType */
  988. CV_WRAP virtual void setBoostType(int val) = 0;
  989. /** The number of weak classifiers.
  990. Default value is 100. */
  991. /** @see setWeakCount */
  992. CV_WRAP virtual int getWeakCount() const = 0;
  993. /** @copybrief getWeakCount @see getWeakCount */
  994. CV_WRAP virtual void setWeakCount(int val) = 0;
  995. /** A threshold between 0 and 1 used to save computational time.
  996. Samples with summary weight \f$\leq 1 - weight_trim_rate\f$ do not participate in the *next*
  997. iteration of training. Set this parameter to 0 to turn off this functionality. Default value is 0.95.*/
  998. /** @see setWeightTrimRate */
  999. CV_WRAP virtual double getWeightTrimRate() const = 0;
  1000. /** @copybrief getWeightTrimRate @see getWeightTrimRate */
  1001. CV_WRAP virtual void setWeightTrimRate(double val) = 0;
  1002. /** Boosting type.
  1003. Gentle AdaBoost and Real AdaBoost are often the preferable choices. */
  1004. enum Types {
  1005. DISCRETE=0, //!< Discrete AdaBoost.
  1006. REAL=1, //!< Real AdaBoost. It is a technique that utilizes confidence-rated predictions
  1007. //!< and works well with categorical data.
  1008. LOGIT=2, //!< LogitBoost. It can produce good regression fits.
  1009. GENTLE=3 //!< Gentle AdaBoost. It puts less weight on outlier data points and for that
  1010. //!<reason is often good with regression data.
  1011. };
  1012. /** Creates the empty model.
  1013. Use StatModel::train to train the model, Algorithm::load\<Boost\>(filename) to load the pre-trained model. */
  1014. CV_WRAP static Ptr<Boost> create();
  1015. };
  1016. /****************************************************************************************\
  1017. * Gradient Boosted Trees *
  1018. \****************************************************************************************/
  1019. /*class CV_EXPORTS_W GBTrees : public DTrees
  1020. {
  1021. public:
  1022. struct CV_EXPORTS_W_MAP Params : public DTrees::Params
  1023. {
  1024. CV_PROP_RW int weakCount;
  1025. CV_PROP_RW int lossFunctionType;
  1026. CV_PROP_RW float subsamplePortion;
  1027. CV_PROP_RW float shrinkage;
  1028. Params();
  1029. Params( int lossFunctionType, int weakCount, float shrinkage,
  1030. float subsamplePortion, int maxDepth, bool useSurrogates );
  1031. };
  1032. enum {SQUARED_LOSS=0, ABSOLUTE_LOSS, HUBER_LOSS=3, DEVIANCE_LOSS};
  1033. virtual void setK(int k) = 0;
  1034. virtual float predictSerial( InputArray samples,
  1035. OutputArray weakResponses, int flags) const = 0;
  1036. static Ptr<GBTrees> create(const Params& p);
  1037. };*/
  1038. /****************************************************************************************\
  1039. * Artificial Neural Networks (ANN) *
  1040. \****************************************************************************************/
  1041. /////////////////////////////////// Multi-Layer Perceptrons //////////////////////////////
  1042. /** @brief Artificial Neural Networks - Multi-Layer Perceptrons.
  1043. Unlike many other models in ML that are constructed and trained at once, in the MLP model these
  1044. steps are separated. First, a network with the specified topology is created using the non-default
  1045. constructor or the method ANN_MLP::create. All the weights are set to zeros. Then, the network is
  1046. trained using a set of input and output vectors. The training procedure can be repeated more than
  1047. once, that is, the weights can be adjusted based on the new training data.
  1048. Additional flags for StatModel::train are available: ANN_MLP::TrainFlags.
  1049. @sa @ref ml_intro_ann
  1050. */
  1051. class CV_EXPORTS_W ANN_MLP : public StatModel
  1052. {
  1053. public:
  1054. /** Available training methods */
  1055. enum TrainingMethods {
  1056. BACKPROP=0, //!< The back-propagation algorithm.
  1057. RPROP=1 //!< The RPROP algorithm. See @cite RPROP93 for details.
  1058. };
  1059. /** Sets training method and common parameters.
  1060. @param method Default value is ANN_MLP::RPROP. See ANN_MLP::TrainingMethods.
  1061. @param param1 passed to setRpropDW0 for ANN_MLP::RPROP and to setBackpropWeightScale for ANN_MLP::BACKPROP
  1062. @param param2 passed to setRpropDWMin for ANN_MLP::RPROP and to setBackpropMomentumScale for ANN_MLP::BACKPROP.
  1063. */
  1064. CV_WRAP virtual void setTrainMethod(int method, double param1 = 0, double param2 = 0) = 0;
  1065. /** Returns current training method */
  1066. CV_WRAP virtual int getTrainMethod() const = 0;
  1067. /** Initialize the activation function for each neuron.
  1068. Currently the default and the only fully supported activation function is ANN_MLP::SIGMOID_SYM.
  1069. @param type The type of activation function. See ANN_MLP::ActivationFunctions.
  1070. @param param1 The first parameter of the activation function, \f$\alpha\f$. Default value is 0.
  1071. @param param2 The second parameter of the activation function, \f$\beta\f$. Default value is 0.
  1072. */
  1073. CV_WRAP virtual void setActivationFunction(int type, double param1 = 0, double param2 = 0) = 0;
  1074. /** Integer vector specifying the number of neurons in each layer including the input and output layers.
  1075. The very first element specifies the number of elements in the input layer.
  1076. The last element - number of elements in the output layer. Default value is empty Mat.
  1077. @sa getLayerSizes */
  1078. CV_WRAP virtual void setLayerSizes(InputArray _layer_sizes) = 0;
  1079. /** Integer vector specifying the number of neurons in each layer including the input and output layers.
  1080. The very first element specifies the number of elements in the input layer.
  1081. The last element - number of elements in the output layer.
  1082. @sa setLayerSizes */
  1083. CV_WRAP virtual cv::Mat getLayerSizes() const = 0;
  1084. /** Termination criteria of the training algorithm.
  1085. You can specify the maximum number of iterations (maxCount) and/or how much the error could
  1086. change between the iterations to make the algorithm continue (epsilon). Default value is
  1087. TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, 0.01).*/
  1088. /** @see setTermCriteria */
  1089. CV_WRAP virtual TermCriteria getTermCriteria() const = 0;
  1090. /** @copybrief getTermCriteria @see getTermCriteria */
  1091. CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0;
  1092. /** BPROP: Strength of the weight gradient term.
  1093. The recommended value is about 0.1. Default value is 0.1.*/
  1094. /** @see setBackpropWeightScale */
  1095. CV_WRAP virtual double getBackpropWeightScale() const = 0;
  1096. /** @copybrief getBackpropWeightScale @see getBackpropWeightScale */
  1097. CV_WRAP virtual void setBackpropWeightScale(double val) = 0;
  1098. /** BPROP: Strength of the momentum term (the difference between weights on the 2 previous iterations).
  1099. This parameter provides some inertia to smooth the random fluctuations of the weights. It can
  1100. vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.
  1101. Default value is 0.1.*/
  1102. /** @see setBackpropMomentumScale */
  1103. CV_WRAP virtual double getBackpropMomentumScale() const = 0;
  1104. /** @copybrief getBackpropMomentumScale @see getBackpropMomentumScale */
  1105. CV_WRAP virtual void setBackpropMomentumScale(double val) = 0;
  1106. /** RPROP: Initial value \f$\Delta_0\f$ of update-values \f$\Delta_{ij}\f$.
  1107. Default value is 0.1.*/
  1108. /** @see setRpropDW0 */
  1109. CV_WRAP virtual double getRpropDW0() const = 0;
  1110. /** @copybrief getRpropDW0 @see getRpropDW0 */
  1111. CV_WRAP virtual void setRpropDW0(double val) = 0;
  1112. /** RPROP: Increase factor \f$\eta^+\f$.
  1113. It must be \>1. Default value is 1.2.*/
  1114. /** @see setRpropDWPlus */
  1115. CV_WRAP virtual double getRpropDWPlus() const = 0;
  1116. /** @copybrief getRpropDWPlus @see getRpropDWPlus */
  1117. CV_WRAP virtual void setRpropDWPlus(double val) = 0;
  1118. /** RPROP: Decrease factor \f$\eta^-\f$.
  1119. It must be \<1. Default value is 0.5.*/
  1120. /** @see setRpropDWMinus */
  1121. CV_WRAP virtual double getRpropDWMinus() const = 0;
  1122. /** @copybrief getRpropDWMinus @see getRpropDWMinus */
  1123. CV_WRAP virtual void setRpropDWMinus(double val) = 0;
  1124. /** RPROP: Update-values lower limit \f$\Delta_{min}\f$.
  1125. It must be positive. Default value is FLT_EPSILON.*/
  1126. /** @see setRpropDWMin */
  1127. CV_WRAP virtual double getRpropDWMin() const = 0;
  1128. /** @copybrief getRpropDWMin @see getRpropDWMin */
  1129. CV_WRAP virtual void setRpropDWMin(double val) = 0;
  1130. /** RPROP: Update-values upper limit \f$\Delta_{max}\f$.
  1131. It must be \>1. Default value is 50.*/
  1132. /** @see setRpropDWMax */
  1133. CV_WRAP virtual double getRpropDWMax() const = 0;
  1134. /** @copybrief getRpropDWMax @see getRpropDWMax */
  1135. CV_WRAP virtual void setRpropDWMax(double val) = 0;
  1136. /** possible activation functions */
  1137. enum ActivationFunctions {
  1138. /** Identity function: \f$f(x)=x\f$ */
  1139. IDENTITY = 0,
  1140. /** Symmetrical sigmoid: \f$f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x}\f$
  1141. @note
  1142. If you are using the default sigmoid activation function with the default parameter values
  1143. fparam1=0 and fparam2=0 then the function used is y = 1.7159\*tanh(2/3 \* x), so the output
  1144. will range from [-1.7159, 1.7159], instead of [0,1].*/
  1145. SIGMOID_SYM = 1,
  1146. /** Gaussian function: \f$f(x)=\beta e^{-\alpha x*x}\f$ */
  1147. GAUSSIAN = 2
  1148. };
  1149. /** Train options */
  1150. enum TrainFlags {
  1151. /** Update the network weights, rather than compute them from scratch. In the latter case
  1152. the weights are initialized using the Nguyen-Widrow algorithm. */
  1153. UPDATE_WEIGHTS = 1,
  1154. /** Do not normalize the input vectors. If this flag is not set, the training algorithm
  1155. normalizes each input feature independently, shifting its mean value to 0 and making the
  1156. standard deviation equal to 1. If the network is assumed to be updated frequently, the new
  1157. training data could be much different from original one. In this case, you should take care
  1158. of proper normalization. */
  1159. NO_INPUT_SCALE = 2,
  1160. /** Do not normalize the output vectors. If the flag is not set, the training algorithm
  1161. normalizes each output feature independently, by transforming it to the certain range
  1162. depending on the used activation function. */
  1163. NO_OUTPUT_SCALE = 4
  1164. };
  1165. CV_WRAP virtual Mat getWeights(int layerIdx) const = 0;
  1166. /** @brief Creates empty model
  1167. Use StatModel::train to train the model, Algorithm::load\<ANN_MLP\>(filename) to load the pre-trained model.
  1168. Note that the train method has optional flags: ANN_MLP::TrainFlags.
  1169. */
  1170. CV_WRAP static Ptr<ANN_MLP> create();
  1171. };
  1172. /****************************************************************************************\
  1173. * Logistic Regression *
  1174. \****************************************************************************************/
  1175. /** @brief Implements Logistic Regression classifier.
  1176. @sa @ref ml_intro_lr
  1177. */
  1178. class CV_EXPORTS_W LogisticRegression : public StatModel
  1179. {
  1180. public:
  1181. /** Learning rate. */
  1182. /** @see setLearningRate */
  1183. CV_WRAP virtual double getLearningRate() const = 0;
  1184. /** @copybrief getLearningRate @see getLearningRate */
  1185. CV_WRAP virtual void setLearningRate(double val) = 0;
  1186. /** Number of iterations. */
  1187. /** @see setIterations */
  1188. CV_WRAP virtual int getIterations() const = 0;
  1189. /** @copybrief getIterations @see getIterations */
  1190. CV_WRAP virtual void setIterations(int val) = 0;
  1191. /** Kind of regularization to be applied. See LogisticRegression::RegKinds. */
  1192. /** @see setRegularization */
  1193. CV_WRAP virtual int getRegularization() const = 0;
  1194. /** @copybrief getRegularization @see getRegularization */
  1195. CV_WRAP virtual void setRegularization(int val) = 0;
  1196. /** Kind of training method used. See LogisticRegression::Methods. */
  1197. /** @see setTrainMethod */
  1198. CV_WRAP virtual int getTrainMethod() const = 0;
  1199. /** @copybrief getTrainMethod @see getTrainMethod */
  1200. CV_WRAP virtual void setTrainMethod(int val) = 0;
  1201. /** Specifies the number of training samples taken in each step of Mini-Batch Gradient
  1202. Descent. Will only be used if using LogisticRegression::MINI_BATCH training algorithm. It
  1203. has to take values less than the total number of training samples. */
  1204. /** @see setMiniBatchSize */
  1205. CV_WRAP virtual int getMiniBatchSize() const = 0;
  1206. /** @copybrief getMiniBatchSize @see getMiniBatchSize */
  1207. CV_WRAP virtual void setMiniBatchSize(int val) = 0;
  1208. /** Termination criteria of the algorithm. */
  1209. /** @see setTermCriteria */
  1210. CV_WRAP virtual TermCriteria getTermCriteria() const = 0;
  1211. /** @copybrief getTermCriteria @see getTermCriteria */
  1212. CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0;
  1213. //! Regularization kinds
  1214. enum RegKinds {
  1215. REG_DISABLE = -1, //!< Regularization disabled
  1216. REG_L1 = 0, //!< %L1 norm
  1217. REG_L2 = 1 //!< %L2 norm
  1218. };
  1219. //! Training methods
  1220. enum Methods {
  1221. BATCH = 0,
  1222. MINI_BATCH = 1 //!< Set MiniBatchSize to a positive integer when using this method.
  1223. };
  1224. /** @brief Predicts responses for input samples and returns a float type.
  1225. @param samples The input data for the prediction algorithm. Matrix [m x n], where each row
  1226. contains variables (features) of one object being classified. Should have data type CV_32F.
  1227. @param results Predicted labels as a column matrix of type CV_32S.
  1228. @param flags Not used.
  1229. */
  1230. CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const = 0;
  1231. /** @brief This function returns the trained paramters arranged across rows.
  1232. For a two class classifcation problem, it returns a row matrix. It returns learnt paramters of
  1233. the Logistic Regression as a matrix of type CV_32F.
  1234. */
  1235. CV_WRAP virtual Mat get_learnt_thetas() const = 0;
  1236. /** @brief Creates empty model.
  1237. Creates Logistic Regression model with parameters given.
  1238. */
  1239. CV_WRAP static Ptr<LogisticRegression> create();
  1240. };
  1241. /****************************************************************************************\
  1242. * Auxilary functions declarations *
  1243. \****************************************************************************************/
  1244. /** @brief Generates _sample_ from multivariate normal distribution
  1245. @param mean an average row vector
  1246. @param cov symmetric covariation matrix
  1247. @param nsamples returned samples count
  1248. @param samples returned samples array
  1249. */
  1250. CV_EXPORTS void randMVNormal( InputArray mean, InputArray cov, int nsamples, OutputArray samples);
  1251. /** @brief Generates sample from gaussian mixture distribution */
  1252. CV_EXPORTS void randGaussMixture( InputArray means, InputArray covs, InputArray weights,
  1253. int nsamples, OutputArray samples, OutputArray sampClasses );
  1254. /** @brief Creates test set */
  1255. CV_EXPORTS void createConcentricSpheresTestSet( int nsamples, int nfeatures, int nclasses,
  1256. OutputArray samples, OutputArray responses);
  1257. //! @} ml
  1258. }
  1259. }
  1260. #endif // __cplusplus
  1261. #endif // __OPENCV_ML_HPP__
  1262. /* End of file. */