ml.hpp 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940
  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_W ParamGrid
  92. {
  93. public:
  94. /** @brief Default constructor */
  95. ParamGrid();
  96. /** @brief Constructor with parameters */
  97. ParamGrid(double _minVal, double _maxVal, double _logStep);
  98. CV_PROP_RW double minVal; //!< Minimum value of the statmodel parameter. Default value is 0.
  99. CV_PROP_RW 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 than 1. Default value is 1.
  106. */
  107. CV_PROP_RW double logStep;
  108. /** @brief Creates a ParamGrid Ptr that can be given to the %SVM::trainAuto method
  109. @param minVal minimum value of the parameter grid
  110. @param maxVal maximum value of the parameter grid
  111. @param logstep Logarithmic step for iterating the statmodel parameter
  112. */
  113. CV_WRAP static Ptr<ParamGrid> create(double minVal=0., double maxVal=0., double logstep=1.);
  114. };
  115. /** @brief Class encapsulating training data.
  116. Please note that the class only specifies the interface of training data, but not implementation.
  117. All the statistical model classes in _ml_ module accepts Ptr\<TrainData\> as parameter. In other
  118. words, you can create your own class derived from TrainData and pass smart pointer to the instance
  119. of this class into StatModel::train.
  120. @sa @ref ml_intro_data
  121. */
  122. class CV_EXPORTS_W TrainData
  123. {
  124. public:
  125. static inline float missingValue() { return FLT_MAX; }
  126. virtual ~TrainData();
  127. CV_WRAP virtual int getLayout() const = 0;
  128. CV_WRAP virtual int getNTrainSamples() const = 0;
  129. CV_WRAP virtual int getNTestSamples() const = 0;
  130. CV_WRAP virtual int getNSamples() const = 0;
  131. CV_WRAP virtual int getNVars() const = 0;
  132. CV_WRAP virtual int getNAllVars() const = 0;
  133. CV_WRAP virtual void getSample(InputArray varIdx, int sidx, float* buf) const = 0;
  134. CV_WRAP virtual Mat getSamples() const = 0;
  135. CV_WRAP virtual Mat getMissing() const = 0;
  136. /** @brief Returns matrix of train samples
  137. @param layout The requested layout. If it's different from the initial one, the matrix is
  138. transposed. See ml::SampleTypes.
  139. @param compressSamples if true, the function returns only the training samples (specified by
  140. sampleIdx)
  141. @param compressVars if true, the function returns the shorter training samples, containing only
  142. the active variables.
  143. In current implementation the function tries to avoid physical data copying and returns the
  144. matrix stored inside TrainData (unless the transposition or compression is needed).
  145. */
  146. CV_WRAP virtual Mat getTrainSamples(int layout=ROW_SAMPLE,
  147. bool compressSamples=true,
  148. bool compressVars=true) const = 0;
  149. /** @brief Returns the vector of responses
  150. The function returns ordered or the original categorical responses. Usually it's used in
  151. regression algorithms.
  152. */
  153. CV_WRAP virtual Mat getTrainResponses() const = 0;
  154. /** @brief Returns the vector of normalized categorical responses
  155. The function returns vector of responses. Each response is integer from `0` to `<number of
  156. classes>-1`. The actual label value can be retrieved then from the class label vector, see
  157. TrainData::getClassLabels.
  158. */
  159. CV_WRAP virtual Mat getTrainNormCatResponses() const = 0;
  160. CV_WRAP virtual Mat getTestResponses() const = 0;
  161. CV_WRAP virtual Mat getTestNormCatResponses() const = 0;
  162. CV_WRAP virtual Mat getResponses() const = 0;
  163. CV_WRAP virtual Mat getNormCatResponses() const = 0;
  164. CV_WRAP virtual Mat getSampleWeights() const = 0;
  165. CV_WRAP virtual Mat getTrainSampleWeights() const = 0;
  166. CV_WRAP virtual Mat getTestSampleWeights() const = 0;
  167. CV_WRAP virtual Mat getVarIdx() const = 0;
  168. CV_WRAP virtual Mat getVarType() const = 0;
  169. CV_WRAP virtual Mat getVarSymbolFlags() const = 0;
  170. CV_WRAP virtual int getResponseType() const = 0;
  171. CV_WRAP virtual Mat getTrainSampleIdx() const = 0;
  172. CV_WRAP virtual Mat getTestSampleIdx() const = 0;
  173. CV_WRAP virtual void getValues(int vi, InputArray sidx, float* values) const = 0;
  174. virtual void getNormCatValues(int vi, InputArray sidx, int* values) const = 0;
  175. CV_WRAP virtual Mat getDefaultSubstValues() const = 0;
  176. CV_WRAP virtual int getCatCount(int vi) const = 0;
  177. /** @brief Returns the vector of class labels
  178. The function returns vector of unique labels occurred in the responses.
  179. */
  180. CV_WRAP virtual Mat getClassLabels() const = 0;
  181. CV_WRAP virtual Mat getCatOfs() const = 0;
  182. CV_WRAP virtual Mat getCatMap() const = 0;
  183. /** @brief Splits the training data into the training and test parts
  184. @sa TrainData::setTrainTestSplitRatio
  185. */
  186. CV_WRAP virtual void setTrainTestSplit(int count, bool shuffle=true) = 0;
  187. /** @brief Splits the training data into the training and test parts
  188. The function selects a subset of specified relative size and then returns it as the training
  189. set. If the function is not called, all the data is used for training. Please, note that for
  190. each of TrainData::getTrain\* there is corresponding TrainData::getTest\*, so that the test
  191. subset can be retrieved and processed as well.
  192. @sa TrainData::setTrainTestSplit
  193. */
  194. CV_WRAP virtual void setTrainTestSplitRatio(double ratio, bool shuffle=true) = 0;
  195. CV_WRAP virtual void shuffleTrainTest() = 0;
  196. /** @brief Returns matrix of test samples */
  197. CV_WRAP virtual Mat getTestSamples() const = 0;
  198. /** @brief Returns vector of symbolic names captured in loadFromCSV() */
  199. CV_WRAP virtual void getNames(std::vector<String>& names) const = 0;
  200. /** @brief Extract from 1D vector elements specified by passed indexes.
  201. @param vec input vector (supported types: CV_32S, CV_32F, CV_64F)
  202. @param idx 1D index vector
  203. */
  204. static CV_WRAP Mat getSubVector(const Mat& vec, const Mat& idx);
  205. /** @brief Extract from matrix rows/cols specified by passed indexes.
  206. @param matrix input matrix (supported types: CV_32S, CV_32F, CV_64F)
  207. @param idx 1D index vector
  208. @param layout specifies to extract rows (cv::ml::ROW_SAMPLES) or to extract columns (cv::ml::COL_SAMPLES)
  209. */
  210. static CV_WRAP Mat getSubMatrix(const Mat& matrix, const Mat& idx, int layout);
  211. /** @brief Reads the dataset from a .csv file and returns the ready-to-use training data.
  212. @param filename The input file name
  213. @param headerLineCount The number of lines in the beginning to skip; besides the header, the
  214. function also skips empty lines and lines staring with `#`
  215. @param responseStartIdx Index of the first output variable. If -1, the function considers the
  216. last variable as the response
  217. @param responseEndIdx Index of the last output variable + 1. If -1, then there is single
  218. response variable at responseStartIdx.
  219. @param varTypeSpec The optional text string that specifies the variables' types. It has the
  220. format `ord[n1-n2,n3,n4-n5,...]cat[n6,n7-n8,...]`. That is, variables from `n1 to n2`
  221. (inclusive range), `n3`, `n4 to n5` ... are considered ordered and `n6`, `n7 to n8` ... are
  222. considered as categorical. The range `[n1..n2] + [n3] + [n4..n5] + ... + [n6] + [n7..n8]`
  223. should cover all the variables. If varTypeSpec is not specified, then algorithm uses the
  224. following rules:
  225. - all input variables are considered ordered by default. If some column contains has non-
  226. numerical values, e.g. 'apple', 'pear', 'apple', 'apple', 'mango', the corresponding
  227. variable is considered categorical.
  228. - if there are several output variables, they are all considered as ordered. Error is
  229. reported when non-numerical values are used.
  230. - if there is a single output variable, then if its values are non-numerical or are all
  231. integers, then it's considered categorical. Otherwise, it's considered ordered.
  232. @param delimiter The character used to separate values in each line.
  233. @param missch The character used to specify missing measurements. It should not be a digit.
  234. Although it's a non-numerical value, it surely does not affect the decision of whether the
  235. variable ordered or categorical.
  236. @note If the dataset only contains input variables and no responses, use responseStartIdx = -2
  237. and responseEndIdx = 0. The output variables vector will just contain zeros.
  238. */
  239. static Ptr<TrainData> loadFromCSV(const String& filename,
  240. int headerLineCount,
  241. int responseStartIdx=-1,
  242. int responseEndIdx=-1,
  243. const String& varTypeSpec=String(),
  244. char delimiter=',',
  245. char missch='?');
  246. /** @brief Creates training data from in-memory arrays.
  247. @param samples matrix of samples. It should have CV_32F type.
  248. @param layout see ml::SampleTypes.
  249. @param responses matrix of responses. If the responses are scalar, they should be stored as a
  250. single row or as a single column. The matrix should have type CV_32F or CV_32S (in the
  251. former case the responses are considered as ordered by default; in the latter case - as
  252. categorical)
  253. @param varIdx vector specifying which variables to use for training. It can be an integer vector
  254. (CV_32S) containing 0-based variable indices or byte vector (CV_8U) containing a mask of
  255. active variables.
  256. @param sampleIdx vector specifying which samples to use for training. It can be an integer
  257. vector (CV_32S) containing 0-based sample indices or byte vector (CV_8U) containing a mask
  258. of training samples.
  259. @param sampleWeights optional vector with weights for each sample. It should have CV_32F type.
  260. @param varType optional vector of type CV_8U and size `<number_of_variables_in_samples> +
  261. <number_of_variables_in_responses>`, containing types of each input and output variable. See
  262. ml::VariableTypes.
  263. */
  264. CV_WRAP static Ptr<TrainData> create(InputArray samples, int layout, InputArray responses,
  265. InputArray varIdx=noArray(), InputArray sampleIdx=noArray(),
  266. InputArray sampleWeights=noArray(), InputArray varType=noArray());
  267. };
  268. /** @brief Base class for statistical models in OpenCV ML.
  269. */
  270. class CV_EXPORTS_W StatModel : public Algorithm
  271. {
  272. public:
  273. /** Predict options */
  274. enum Flags {
  275. UPDATE_MODEL = 1,
  276. RAW_OUTPUT=1, //!< makes the method return the raw results (the sum), not the class label
  277. COMPRESSED_INPUT=2,
  278. PREPROCESSED_INPUT=4
  279. };
  280. /** @brief Returns the number of variables in training samples */
  281. CV_WRAP virtual int getVarCount() const = 0;
  282. CV_WRAP virtual bool empty() const CV_OVERRIDE;
  283. /** @brief Returns true if the model is trained */
  284. CV_WRAP virtual bool isTrained() const = 0;
  285. /** @brief Returns true if the model is classifier */
  286. CV_WRAP virtual bool isClassifier() const = 0;
  287. /** @brief Trains the statistical model
  288. @param trainData training data that can be loaded from file using TrainData::loadFromCSV or
  289. created with TrainData::create.
  290. @param flags optional flags, depending on the model. Some of the models can be updated with the
  291. new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP).
  292. */
  293. CV_WRAP virtual bool train( const Ptr<TrainData>& trainData, int flags=0 );
  294. /** @brief Trains the statistical model
  295. @param samples training samples
  296. @param layout See ml::SampleTypes.
  297. @param responses vector of responses associated with the training samples.
  298. */
  299. CV_WRAP virtual bool train( InputArray samples, int layout, InputArray responses );
  300. /** @brief Computes error on the training or test dataset
  301. @param data the training data
  302. @param test if true, the error is computed over the test subset of the data, otherwise it's
  303. computed over the training subset of the data. Please note that if you loaded a completely
  304. different dataset to evaluate already trained classifier, you will probably want not to set
  305. the test subset at all with TrainData::setTrainTestSplitRatio and specify test=false, so
  306. that the error is computed for the whole new set. Yes, this sounds a bit confusing.
  307. @param resp the optional output responses.
  308. The method uses StatModel::predict to compute the error. For regression models the error is
  309. computed as RMS, for classifiers - as a percent of missclassified samples (0%-100%).
  310. */
  311. CV_WRAP virtual float calcError( const Ptr<TrainData>& data, bool test, OutputArray resp ) const;
  312. /** @brief Predicts response(s) for the provided sample(s)
  313. @param samples The input samples, floating-point matrix
  314. @param results The optional output matrix of results.
  315. @param flags The optional flags, model-dependent. See cv::ml::StatModel::Flags.
  316. */
  317. CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const = 0;
  318. /** @brief Create and train model with default parameters
  319. The class must implement static `create()` method with no parameters or with all default parameter values
  320. */
  321. template<typename _Tp> static Ptr<_Tp> train(const Ptr<TrainData>& data, int flags=0)
  322. {
  323. Ptr<_Tp> model = _Tp::create();
  324. return !model.empty() && model->train(data, flags) ? model : Ptr<_Tp>();
  325. }
  326. };
  327. /****************************************************************************************\
  328. * Normal Bayes Classifier *
  329. \****************************************************************************************/
  330. /** @brief Bayes classifier for normally distributed data.
  331. @sa @ref ml_intro_bayes
  332. */
  333. class CV_EXPORTS_W NormalBayesClassifier : public StatModel
  334. {
  335. public:
  336. /** @brief Predicts the response for sample(s).
  337. The method estimates the most probable classes for input vectors. Input vectors (one or more)
  338. are stored as rows of the matrix inputs. In case of multiple input vectors, there should be one
  339. output vector outputs. The predicted class for a single input vector is returned by the method.
  340. The vector outputProbs contains the output probabilities corresponding to each element of
  341. result.
  342. */
  343. CV_WRAP virtual float predictProb( InputArray inputs, OutputArray outputs,
  344. OutputArray outputProbs, int flags=0 ) const = 0;
  345. /** Creates empty model
  346. Use StatModel::train to train the model after creation. */
  347. CV_WRAP static Ptr<NormalBayesClassifier> create();
  348. /** @brief Loads and creates a serialized NormalBayesClassifier from a file
  349. *
  350. * Use NormalBayesClassifier::save to serialize and store an NormalBayesClassifier to disk.
  351. * Load the NormalBayesClassifier from this file again, by calling this function with the path to the file.
  352. * Optionally specify the node for the file containing the classifier
  353. *
  354. * @param filepath path to serialized NormalBayesClassifier
  355. * @param nodeName name of node containing the classifier
  356. */
  357. CV_WRAP static Ptr<NormalBayesClassifier> load(const String& filepath , const String& nodeName = String());
  358. };
  359. /****************************************************************************************\
  360. * K-Nearest Neighbour Classifier *
  361. \****************************************************************************************/
  362. /** @brief The class implements K-Nearest Neighbors model
  363. @sa @ref ml_intro_knn
  364. */
  365. class CV_EXPORTS_W KNearest : public StatModel
  366. {
  367. public:
  368. /** Default number of neighbors to use in predict method. */
  369. /** @see setDefaultK */
  370. CV_WRAP virtual int getDefaultK() const = 0;
  371. /** @copybrief getDefaultK @see getDefaultK */
  372. CV_WRAP virtual void setDefaultK(int val) = 0;
  373. /** Whether classification or regression model should be trained. */
  374. /** @see setIsClassifier */
  375. CV_WRAP virtual bool getIsClassifier() const = 0;
  376. /** @copybrief getIsClassifier @see getIsClassifier */
  377. CV_WRAP virtual void setIsClassifier(bool val) = 0;
  378. /** Parameter for KDTree implementation. */
  379. /** @see setEmax */
  380. CV_WRAP virtual int getEmax() const = 0;
  381. /** @copybrief getEmax @see getEmax */
  382. CV_WRAP virtual void setEmax(int val) = 0;
  383. /** %Algorithm type, one of KNearest::Types. */
  384. /** @see setAlgorithmType */
  385. CV_WRAP virtual int getAlgorithmType() const = 0;
  386. /** @copybrief getAlgorithmType @see getAlgorithmType */
  387. CV_WRAP virtual void setAlgorithmType(int val) = 0;
  388. /** @brief Finds the neighbors and predicts responses for input vectors.
  389. @param samples Input samples stored by rows. It is a single-precision floating-point matrix of
  390. `<number_of_samples> * k` size.
  391. @param k Number of used nearest neighbors. Should be greater than 1.
  392. @param results Vector with results of prediction (regression or classification) for each input
  393. sample. It is a single-precision floating-point vector with `<number_of_samples>` elements.
  394. @param neighborResponses Optional output values for corresponding neighbors. It is a single-
  395. precision floating-point matrix of `<number_of_samples> * k` size.
  396. @param dist Optional output distances from the input vectors to the corresponding neighbors. It
  397. is a single-precision floating-point matrix of `<number_of_samples> * k` size.
  398. For each input vector (a row of the matrix samples), the method finds the k nearest neighbors.
  399. In case of regression, the predicted result is a mean value of the particular vector's neighbor
  400. responses. In case of classification, the class is determined by voting.
  401. For each input vector, the neighbors are sorted by their distances to the vector.
  402. In case of C++ interface you can use output pointers to empty matrices and the function will
  403. allocate memory itself.
  404. If only a single input vector is passed, all output matrices are optional and the predicted
  405. value is returned by the method.
  406. The function is parallelized with the TBB library.
  407. */
  408. CV_WRAP virtual float findNearest( InputArray samples, int k,
  409. OutputArray results,
  410. OutputArray neighborResponses=noArray(),
  411. OutputArray dist=noArray() ) const = 0;
  412. /** @brief Implementations of KNearest algorithm
  413. */
  414. enum Types
  415. {
  416. BRUTE_FORCE=1,
  417. KDTREE=2
  418. };
  419. /** @brief Creates the empty model
  420. The static method creates empty %KNearest classifier. It should be then trained using StatModel::train method.
  421. */
  422. CV_WRAP static Ptr<KNearest> create();
  423. };
  424. /****************************************************************************************\
  425. * Support Vector Machines *
  426. \****************************************************************************************/
  427. /** @brief Support Vector Machines.
  428. @sa @ref ml_intro_svm
  429. */
  430. class CV_EXPORTS_W SVM : public StatModel
  431. {
  432. public:
  433. class CV_EXPORTS Kernel : public Algorithm
  434. {
  435. public:
  436. virtual int getType() const = 0;
  437. virtual void calc( int vcount, int n, const float* vecs, const float* another, float* results ) = 0;
  438. };
  439. /** Type of a %SVM formulation.
  440. See SVM::Types. Default value is SVM::C_SVC. */
  441. /** @see setType */
  442. CV_WRAP virtual int getType() const = 0;
  443. /** @copybrief getType @see getType */
  444. CV_WRAP virtual void setType(int val) = 0;
  445. /** Parameter \f$\gamma\f$ of a kernel function.
  446. For SVM::POLY, SVM::RBF, SVM::SIGMOID or SVM::CHI2. Default value is 1. */
  447. /** @see setGamma */
  448. CV_WRAP virtual double getGamma() const = 0;
  449. /** @copybrief getGamma @see getGamma */
  450. CV_WRAP virtual void setGamma(double val) = 0;
  451. /** Parameter _coef0_ of a kernel function.
  452. For SVM::POLY or SVM::SIGMOID. Default value is 0.*/
  453. /** @see setCoef0 */
  454. CV_WRAP virtual double getCoef0() const = 0;
  455. /** @copybrief getCoef0 @see getCoef0 */
  456. CV_WRAP virtual void setCoef0(double val) = 0;
  457. /** Parameter _degree_ of a kernel function.
  458. For SVM::POLY. Default value is 0. */
  459. /** @see setDegree */
  460. CV_WRAP virtual double getDegree() const = 0;
  461. /** @copybrief getDegree @see getDegree */
  462. CV_WRAP virtual void setDegree(double val) = 0;
  463. /** Parameter _C_ of a %SVM optimization problem.
  464. For SVM::C_SVC, SVM::EPS_SVR or SVM::NU_SVR. Default value is 0. */
  465. /** @see setC */
  466. CV_WRAP virtual double getC() const = 0;
  467. /** @copybrief getC @see getC */
  468. CV_WRAP virtual void setC(double val) = 0;
  469. /** Parameter \f$\nu\f$ of a %SVM optimization problem.
  470. For SVM::NU_SVC, SVM::ONE_CLASS or SVM::NU_SVR. Default value is 0. */
  471. /** @see setNu */
  472. CV_WRAP virtual double getNu() const = 0;
  473. /** @copybrief getNu @see getNu */
  474. CV_WRAP virtual void setNu(double val) = 0;
  475. /** Parameter \f$\epsilon\f$ of a %SVM optimization problem.
  476. For SVM::EPS_SVR. Default value is 0. */
  477. /** @see setP */
  478. CV_WRAP virtual double getP() const = 0;
  479. /** @copybrief getP @see getP */
  480. CV_WRAP virtual void setP(double val) = 0;
  481. /** Optional weights in the SVM::C_SVC problem, assigned to particular classes.
  482. They are multiplied by _C_ so the parameter _C_ of class _i_ becomes `classWeights(i) * C`. Thus
  483. these weights affect the misclassification penalty for different classes. The larger weight,
  484. the larger penalty on misclassification of data from the corresponding class. Default value is
  485. empty Mat. */
  486. /** @see setClassWeights */
  487. CV_WRAP virtual cv::Mat getClassWeights() const = 0;
  488. /** @copybrief getClassWeights @see getClassWeights */
  489. CV_WRAP virtual void setClassWeights(const cv::Mat &val) = 0;
  490. /** Termination criteria of the iterative %SVM training procedure which solves a partial
  491. case of constrained quadratic optimization problem.
  492. You can specify tolerance and/or the maximum number of iterations. Default value is
  493. `TermCriteria( TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, FLT_EPSILON )`; */
  494. /** @see setTermCriteria */
  495. CV_WRAP virtual cv::TermCriteria getTermCriteria() const = 0;
  496. /** @copybrief getTermCriteria @see getTermCriteria */
  497. CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0;
  498. /** Type of a %SVM kernel.
  499. See SVM::KernelTypes. Default value is SVM::RBF. */
  500. CV_WRAP virtual int getKernelType() const = 0;
  501. /** Initialize with one of predefined kernels.
  502. See SVM::KernelTypes. */
  503. CV_WRAP virtual void setKernel(int kernelType) = 0;
  504. /** Initialize with custom kernel.
  505. See SVM::Kernel class for implementation details */
  506. virtual void setCustomKernel(const Ptr<Kernel> &_kernel) = 0;
  507. //! %SVM type
  508. enum Types {
  509. /** C-Support Vector Classification. n-class classification (n \f$\geq\f$ 2), allows
  510. imperfect separation of classes with penalty multiplier C for outliers. */
  511. C_SVC=100,
  512. /** \f$\nu\f$-Support Vector Classification. n-class classification with possible
  513. imperfect separation. Parameter \f$\nu\f$ (in the range 0..1, the larger the value, the smoother
  514. the decision boundary) is used instead of C. */
  515. NU_SVC=101,
  516. /** Distribution Estimation (One-class %SVM). All the training data are from
  517. the same class, %SVM builds a boundary that separates the class from the rest of the feature
  518. space. */
  519. ONE_CLASS=102,
  520. /** \f$\epsilon\f$-Support Vector Regression. The distance between feature vectors
  521. from the training set and the fitting hyper-plane must be less than p. For outliers the
  522. penalty multiplier C is used. */
  523. EPS_SVR=103,
  524. /** \f$\nu\f$-Support Vector Regression. \f$\nu\f$ is used instead of p.
  525. See @cite LibSVM for details. */
  526. NU_SVR=104
  527. };
  528. /** @brief %SVM kernel type
  529. A comparison of different kernels on the following 2D test case with four classes. Four
  530. SVM::C_SVC SVMs have been trained (one against rest) with auto_train. Evaluation on three
  531. different kernels (SVM::CHI2, SVM::INTER, SVM::RBF). The color depicts the class with max score.
  532. Bright means max-score \> 0, dark means max-score \< 0.
  533. ![image](pics/SVM_Comparison.png)
  534. */
  535. enum KernelTypes {
  536. /** Returned by SVM::getKernelType in case when custom kernel has been set */
  537. CUSTOM=-1,
  538. /** Linear kernel. No mapping is done, linear discrimination (or regression) is
  539. done in the original feature space. It is the fastest option. \f$K(x_i, x_j) = x_i^T x_j\f$. */
  540. LINEAR=0,
  541. /** Polynomial kernel:
  542. \f$K(x_i, x_j) = (\gamma x_i^T x_j + coef0)^{degree}, \gamma > 0\f$. */
  543. POLY=1,
  544. /** Radial basis function (RBF), a good choice in most cases.
  545. \f$K(x_i, x_j) = e^{-\gamma ||x_i - x_j||^2}, \gamma > 0\f$. */
  546. RBF=2,
  547. /** Sigmoid kernel: \f$K(x_i, x_j) = \tanh(\gamma x_i^T x_j + coef0)\f$. */
  548. SIGMOID=3,
  549. /** Exponential Chi2 kernel, similar to the RBF kernel:
  550. \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$. */
  551. CHI2=4,
  552. /** Histogram intersection kernel. A fast kernel. \f$K(x_i, x_j) = min(x_i,x_j)\f$. */
  553. INTER=5
  554. };
  555. //! %SVM params type
  556. enum ParamTypes {
  557. C=0,
  558. GAMMA=1,
  559. P=2,
  560. NU=3,
  561. COEF=4,
  562. DEGREE=5
  563. };
  564. /** @brief Trains an %SVM with optimal parameters.
  565. @param data the training data that can be constructed using TrainData::create or
  566. TrainData::loadFromCSV.
  567. @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One
  568. subset is used to test the model, the others form the train set. So, the %SVM algorithm is
  569. executed kFold times.
  570. @param Cgrid grid for C
  571. @param gammaGrid grid for gamma
  572. @param pGrid grid for p
  573. @param nuGrid grid for nu
  574. @param coeffGrid grid for coeff
  575. @param degreeGrid grid for degree
  576. @param balanced If true and the problem is 2-class classification then the method creates more
  577. balanced cross-validation subsets that is proportions between classes in subsets are close
  578. to such proportion in the whole train dataset.
  579. The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p,
  580. nu, coef0, degree. Parameters are considered optimal when the cross-validation
  581. estimate of the test set error is minimal.
  582. If there is no need to optimize a parameter, the corresponding grid step should be set to any
  583. value less than or equal to 1. For example, to avoid optimization in gamma, set `gammaGrid.step
  584. = 0`, `gammaGrid.minVal`, `gamma_grid.maxVal` as arbitrary numbers. In this case, the value
  585. `Gamma` is taken for gamma.
  586. And, finally, if the optimization in a parameter is required but the corresponding grid is
  587. unknown, you may call the function SVM::getDefaultGrid. To generate a grid, for example, for
  588. gamma, call `SVM::getDefaultGrid(SVM::GAMMA)`.
  589. This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the
  590. regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and
  591. the usual %SVM with parameters specified in params is executed.
  592. */
  593. virtual bool trainAuto( const Ptr<TrainData>& data, int kFold = 10,
  594. ParamGrid Cgrid = getDefaultGrid(C),
  595. ParamGrid gammaGrid = getDefaultGrid(GAMMA),
  596. ParamGrid pGrid = getDefaultGrid(P),
  597. ParamGrid nuGrid = getDefaultGrid(NU),
  598. ParamGrid coeffGrid = getDefaultGrid(COEF),
  599. ParamGrid degreeGrid = getDefaultGrid(DEGREE),
  600. bool balanced=false) = 0;
  601. /** @brief Trains an %SVM with optimal parameters
  602. @param samples training samples
  603. @param layout See ml::SampleTypes.
  604. @param responses vector of responses associated with the training samples.
  605. @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One
  606. subset is used to test the model, the others form the train set. So, the %SVM algorithm is
  607. @param Cgrid grid for C
  608. @param gammaGrid grid for gamma
  609. @param pGrid grid for p
  610. @param nuGrid grid for nu
  611. @param coeffGrid grid for coeff
  612. @param degreeGrid grid for degree
  613. @param balanced If true and the problem is 2-class classification then the method creates more
  614. balanced cross-validation subsets that is proportions between classes in subsets are close
  615. to such proportion in the whole train dataset.
  616. The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p,
  617. nu, coef0, degree. Parameters are considered optimal when the cross-validation
  618. estimate of the test set error is minimal.
  619. This function only makes use of SVM::getDefaultGrid for parameter optimization and thus only
  620. offers rudimentary parameter options.
  621. This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the
  622. regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and
  623. the usual %SVM with parameters specified in params is executed.
  624. */
  625. CV_WRAP virtual bool trainAuto(InputArray samples,
  626. int layout,
  627. InputArray responses,
  628. int kFold = 10,
  629. Ptr<ParamGrid> Cgrid = SVM::getDefaultGridPtr(SVM::C),
  630. Ptr<ParamGrid> gammaGrid = SVM::getDefaultGridPtr(SVM::GAMMA),
  631. Ptr<ParamGrid> pGrid = SVM::getDefaultGridPtr(SVM::P),
  632. Ptr<ParamGrid> nuGrid = SVM::getDefaultGridPtr(SVM::NU),
  633. Ptr<ParamGrid> coeffGrid = SVM::getDefaultGridPtr(SVM::COEF),
  634. Ptr<ParamGrid> degreeGrid = SVM::getDefaultGridPtr(SVM::DEGREE),
  635. bool balanced=false) = 0;
  636. /** @brief Retrieves all the support vectors
  637. The method returns all the support vectors as a floating-point matrix, where support vectors are
  638. stored as matrix rows.
  639. */
  640. CV_WRAP virtual Mat getSupportVectors() const = 0;
  641. /** @brief Retrieves all the uncompressed support vectors of a linear %SVM
  642. The method returns all the uncompressed support vectors of a linear %SVM that the compressed
  643. support vector, used for prediction, was derived from. They are returned in a floating-point
  644. matrix, where the support vectors are stored as matrix rows.
  645. */
  646. CV_WRAP virtual Mat getUncompressedSupportVectors() const = 0;
  647. /** @brief Retrieves the decision function
  648. @param i the index of the decision function. If the problem solved is regression, 1-class or
  649. 2-class classification, then there will be just one decision function and the index should
  650. always be 0. Otherwise, in the case of N-class classification, there will be \f$N(N-1)/2\f$
  651. decision functions.
  652. @param alpha the optional output vector for weights, corresponding to different support vectors.
  653. In the case of linear %SVM all the alpha's will be 1's.
  654. @param svidx the optional output vector of indices of support vectors within the matrix of
  655. support vectors (which can be retrieved by SVM::getSupportVectors). In the case of linear
  656. %SVM each decision function consists of a single "compressed" support vector.
  657. The method returns rho parameter of the decision function, a scalar subtracted from the weighted
  658. sum of kernel responses.
  659. */
  660. CV_WRAP virtual double getDecisionFunction(int i, OutputArray alpha, OutputArray svidx) const = 0;
  661. /** @brief Generates a grid for %SVM parameters.
  662. @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is
  663. generated for the parameter with this ID.
  664. The function generates a grid for the specified parameter of the %SVM algorithm. The grid may be
  665. passed to the function SVM::trainAuto.
  666. */
  667. static ParamGrid getDefaultGrid( int param_id );
  668. /** @brief Generates a grid for %SVM parameters.
  669. @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is
  670. generated for the parameter with this ID.
  671. The function generates a grid pointer for the specified parameter of the %SVM algorithm.
  672. The grid may be passed to the function SVM::trainAuto.
  673. */
  674. CV_WRAP static Ptr<ParamGrid> getDefaultGridPtr( int param_id );
  675. /** Creates empty model.
  676. Use StatModel::train to train the model. Since %SVM has several parameters, you may want to
  677. find the best parameters for your problem, it can be done with SVM::trainAuto. */
  678. CV_WRAP static Ptr<SVM> create();
  679. /** @brief Loads and creates a serialized svm from a file
  680. *
  681. * Use SVM::save to serialize and store an SVM to disk.
  682. * Load the SVM from this file again, by calling this function with the path to the file.
  683. *
  684. * @param filepath path to serialized svm
  685. */
  686. CV_WRAP static Ptr<SVM> load(const String& filepath);
  687. };
  688. /****************************************************************************************\
  689. * Expectation - Maximization *
  690. \****************************************************************************************/
  691. /** @brief The class implements the Expectation Maximization algorithm.
  692. @sa @ref ml_intro_em
  693. */
  694. class CV_EXPORTS_W EM : public StatModel
  695. {
  696. public:
  697. //! Type of covariation matrices
  698. enum Types {
  699. /** A scaled identity matrix \f$\mu_k * I\f$. There is the only
  700. parameter \f$\mu_k\f$ to be estimated for each matrix. The option may be used in special cases,
  701. when the constraint is relevant, or as a first step in the optimization (for example in case
  702. when the data is preprocessed with PCA). The results of such preliminary estimation may be
  703. passed again to the optimization procedure, this time with
  704. covMatType=EM::COV_MAT_DIAGONAL. */
  705. COV_MAT_SPHERICAL=0,
  706. /** A diagonal matrix with positive diagonal elements. The number of
  707. free parameters is d for each matrix. This is most commonly used option yielding good
  708. estimation results. */
  709. COV_MAT_DIAGONAL=1,
  710. /** A symmetric positively defined matrix. The number of free
  711. parameters in each matrix is about \f$d^2/2\f$. It is not recommended to use this option, unless
  712. there is pretty accurate initial estimation of the parameters and/or a huge number of
  713. training samples. */
  714. COV_MAT_GENERIC=2,
  715. COV_MAT_DEFAULT=COV_MAT_DIAGONAL
  716. };
  717. //! Default parameters
  718. enum {DEFAULT_NCLUSTERS=5, DEFAULT_MAX_ITERS=100};
  719. //! The initial step
  720. enum {START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0};
  721. /** The number of mixture components in the Gaussian mixture model.
  722. Default value of the parameter is EM::DEFAULT_NCLUSTERS=5. Some of %EM implementation could
  723. determine the optimal number of mixtures within a specified value range, but that is not the
  724. case in ML yet. */
  725. /** @see setClustersNumber */
  726. CV_WRAP virtual int getClustersNumber() const = 0;
  727. /** @copybrief getClustersNumber @see getClustersNumber */
  728. CV_WRAP virtual void setClustersNumber(int val) = 0;
  729. /** Constraint on covariance matrices which defines type of matrices.
  730. See EM::Types. */
  731. /** @see setCovarianceMatrixType */
  732. CV_WRAP virtual int getCovarianceMatrixType() const = 0;
  733. /** @copybrief getCovarianceMatrixType @see getCovarianceMatrixType */
  734. CV_WRAP virtual void setCovarianceMatrixType(int val) = 0;
  735. /** The termination criteria of the %EM algorithm.
  736. The %EM algorithm can be terminated by the number of iterations termCrit.maxCount (number of
  737. M-steps) or when relative change of likelihood logarithm is less than termCrit.epsilon. Default
  738. maximum number of iterations is EM::DEFAULT_MAX_ITERS=100. */
  739. /** @see setTermCriteria */
  740. CV_WRAP virtual TermCriteria getTermCriteria() const = 0;
  741. /** @copybrief getTermCriteria @see getTermCriteria */
  742. CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0;
  743. /** @brief Returns weights of the mixtures
  744. Returns vector with the number of elements equal to the number of mixtures.
  745. */
  746. CV_WRAP virtual Mat getWeights() const = 0;
  747. /** @brief Returns the cluster centers (means of the Gaussian mixture)
  748. Returns matrix with the number of rows equal to the number of mixtures and number of columns
  749. equal to the space dimensionality.
  750. */
  751. CV_WRAP virtual Mat getMeans() const = 0;
  752. /** @brief Returns covariation matrices
  753. Returns vector of covariation matrices. Number of matrices is the number of gaussian mixtures,
  754. each matrix is a square floating-point matrix NxN, where N is the space dimensionality.
  755. */
  756. CV_WRAP virtual void getCovs(CV_OUT std::vector<Mat>& covs) const = 0;
  757. /** @brief Returns posterior probabilities for the provided samples
  758. @param samples The input samples, floating-point matrix
  759. @param results The optional output \f$ nSamples \times nClusters\f$ matrix of results. It contains
  760. posterior probabilities for each sample from the input
  761. @param flags This parameter will be ignored
  762. */
  763. CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const CV_OVERRIDE = 0;
  764. /** @brief Returns a likelihood logarithm value and an index of the most probable mixture component
  765. for the given sample.
  766. @param sample A sample for classification. It should be a one-channel matrix of
  767. \f$1 \times dims\f$ or \f$dims \times 1\f$ size.
  768. @param probs Optional output matrix that contains posterior probabilities of each component
  769. given the sample. It has \f$1 \times nclusters\f$ size and CV_64FC1 type.
  770. The method returns a two-element double vector. Zero element is a likelihood logarithm value for
  771. the sample. First element is an index of the most probable mixture component for the given
  772. sample.
  773. */
  774. CV_WRAP virtual Vec2d predict2(InputArray sample, OutputArray probs) const = 0;
  775. /** @brief Estimate the Gaussian mixture parameters from a samples set.
  776. This variation starts with Expectation step. Initial values of the model parameters will be
  777. estimated by the k-means algorithm.
  778. Unlike many of the ML models, %EM is an unsupervised learning algorithm and it does not take
  779. responses (class labels or function values) as input. Instead, it computes the *Maximum
  780. Likelihood Estimate* of the Gaussian mixture parameters from an input sample set, stores all the
  781. parameters inside the structure: \f$p_{i,k}\f$ in probs, \f$a_k\f$ in means , \f$S_k\f$ in
  782. covs[k], \f$\pi_k\f$ in weights , and optionally computes the output "class label" for each
  783. sample: \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most
  784. probable mixture component for each sample).
  785. The trained model can be used further for prediction, just like any other classifier. The
  786. trained model is similar to the NormalBayesClassifier.
  787. @param samples Samples from which the Gaussian mixture model will be estimated. It should be a
  788. one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type
  789. it will be converted to the inner matrix of such type for the further computing.
  790. @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for
  791. each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type.
  792. @param labels The optional output "class label" for each sample:
  793. \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable
  794. mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type.
  795. @param probs The optional output matrix that contains posterior probabilities of each Gaussian
  796. mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and
  797. CV_64FC1 type.
  798. */
  799. CV_WRAP virtual bool trainEM(InputArray samples,
  800. OutputArray logLikelihoods=noArray(),
  801. OutputArray labels=noArray(),
  802. OutputArray probs=noArray()) = 0;
  803. /** @brief Estimate the Gaussian mixture parameters from a samples set.
  804. This variation starts with Expectation step. You need to provide initial means \f$a_k\f$ of
  805. mixture components. Optionally you can pass initial weights \f$\pi_k\f$ and covariance matrices
  806. \f$S_k\f$ of mixture components.
  807. @param samples Samples from which the Gaussian mixture model will be estimated. It should be a
  808. one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type
  809. it will be converted to the inner matrix of such type for the further computing.
  810. @param means0 Initial means \f$a_k\f$ of mixture components. It is a one-channel matrix of
  811. \f$nclusters \times dims\f$ size. If the matrix does not have CV_64F type it will be
  812. converted to the inner matrix of such type for the further computing.
  813. @param covs0 The vector of initial covariance matrices \f$S_k\f$ of mixture components. Each of
  814. covariance matrices is a one-channel matrix of \f$dims \times dims\f$ size. If the matrices
  815. do not have CV_64F type they will be converted to the inner matrices of such type for the
  816. further computing.
  817. @param weights0 Initial weights \f$\pi_k\f$ of mixture components. It should be a one-channel
  818. floating-point matrix with \f$1 \times nclusters\f$ or \f$nclusters \times 1\f$ size.
  819. @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for
  820. each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type.
  821. @param labels The optional output "class label" for each sample:
  822. \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable
  823. mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type.
  824. @param probs The optional output matrix that contains posterior probabilities of each Gaussian
  825. mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and
  826. CV_64FC1 type.
  827. */
  828. CV_WRAP virtual bool trainE(InputArray samples, InputArray means0,
  829. InputArray covs0=noArray(),
  830. InputArray weights0=noArray(),
  831. OutputArray logLikelihoods=noArray(),
  832. OutputArray labels=noArray(),
  833. OutputArray probs=noArray()) = 0;
  834. /** @brief Estimate the Gaussian mixture parameters from a samples set.
  835. This variation starts with Maximization step. You need to provide initial probabilities
  836. \f$p_{i,k}\f$ to use this option.
  837. @param samples Samples from which the Gaussian mixture model will be estimated. It should be a
  838. one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type
  839. it will be converted to the inner matrix of such type for the further computing.
  840. @param probs0
  841. @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for
  842. each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type.
  843. @param labels The optional output "class label" for each sample:
  844. \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable
  845. mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type.
  846. @param probs The optional output matrix that contains posterior probabilities of each Gaussian
  847. mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and
  848. CV_64FC1 type.
  849. */
  850. CV_WRAP virtual bool trainM(InputArray samples, InputArray probs0,
  851. OutputArray logLikelihoods=noArray(),
  852. OutputArray labels=noArray(),
  853. OutputArray probs=noArray()) = 0;
  854. /** Creates empty %EM model.
  855. The model should be trained then using StatModel::train(traindata, flags) method. Alternatively, you
  856. can use one of the EM::train\* methods or load it from file using Algorithm::load\<EM\>(filename).
  857. */
  858. CV_WRAP static Ptr<EM> create();
  859. /** @brief Loads and creates a serialized EM from a file
  860. *
  861. * Use EM::save to serialize and store an EM to disk.
  862. * Load the EM from this file again, by calling this function with the path to the file.
  863. * Optionally specify the node for the file containing the classifier
  864. *
  865. * @param filepath path to serialized EM
  866. * @param nodeName name of node containing the classifier
  867. */
  868. CV_WRAP static Ptr<EM> load(const String& filepath , const String& nodeName = String());
  869. };
  870. /****************************************************************************************\
  871. * Decision Tree *
  872. \****************************************************************************************/
  873. /** @brief The class represents a single decision tree or a collection of decision trees.
  874. The current public interface of the class allows user to train only a single decision tree, however
  875. the class is capable of storing multiple decision trees and using them for prediction (by summing
  876. responses or using a voting schemes), and the derived from DTrees classes (such as RTrees and Boost)
  877. use this capability to implement decision tree ensembles.
  878. @sa @ref ml_intro_trees
  879. */
  880. class CV_EXPORTS_W DTrees : public StatModel
  881. {
  882. public:
  883. /** Predict options */
  884. enum Flags { PREDICT_AUTO=0, PREDICT_SUM=(1<<8), PREDICT_MAX_VOTE=(2<<8), PREDICT_MASK=(3<<8) };
  885. /** Cluster possible values of a categorical variable into K\<=maxCategories clusters to
  886. find a suboptimal split.
  887. If a discrete variable, on which the training procedure tries to make a split, takes more than
  888. maxCategories values, the precise best subset estimation may take a very long time because the
  889. algorithm is exponential. Instead, many decision trees engines (including our implementation)
  890. try to find sub-optimal split in this case by clustering all the samples into maxCategories
  891. clusters that is some categories are merged together. The clustering is applied only in n \>
  892. 2-class classification problems for categorical variables with N \> max_categories possible
  893. values. In case of regression and 2-class classification the optimal split can be found
  894. efficiently without employing clustering, thus the parameter is not used in these cases.
  895. Default value is 10.*/
  896. /** @see setMaxCategories */
  897. CV_WRAP virtual int getMaxCategories() const = 0;
  898. /** @copybrief getMaxCategories @see getMaxCategories */
  899. CV_WRAP virtual void setMaxCategories(int val) = 0;
  900. /** The maximum possible depth of the tree.
  901. That is the training algorithms attempts to split a node while its depth is less than maxDepth.
  902. The root node has zero depth. The actual depth may be smaller if the other termination criteria
  903. are met (see the outline of the training procedure @ref ml_intro_trees "here"), and/or if the
  904. tree is pruned. Default value is INT_MAX.*/
  905. /** @see setMaxDepth */
  906. CV_WRAP virtual int getMaxDepth() const = 0;
  907. /** @copybrief getMaxDepth @see getMaxDepth */
  908. CV_WRAP virtual void setMaxDepth(int val) = 0;
  909. /** If the number of samples in a node is less than this parameter then the node will not be split.
  910. Default value is 10.*/
  911. /** @see setMinSampleCount */
  912. CV_WRAP virtual int getMinSampleCount() const = 0;
  913. /** @copybrief getMinSampleCount @see getMinSampleCount */
  914. CV_WRAP virtual void setMinSampleCount(int val) = 0;
  915. /** If CVFolds \> 1 then algorithms prunes the built decision tree using K-fold
  916. cross-validation procedure where K is equal to CVFolds.
  917. Default value is 10.*/
  918. /** @see setCVFolds */
  919. CV_WRAP virtual int getCVFolds() const = 0;
  920. /** @copybrief getCVFolds @see getCVFolds */
  921. CV_WRAP virtual void setCVFolds(int val) = 0;
  922. /** If true then surrogate splits will be built.
  923. These splits allow to work with missing data and compute variable importance correctly.
  924. Default value is false.
  925. @note currently it's not implemented.*/
  926. /** @see setUseSurrogates */
  927. CV_WRAP virtual bool getUseSurrogates() const = 0;
  928. /** @copybrief getUseSurrogates @see getUseSurrogates */
  929. CV_WRAP virtual void setUseSurrogates(bool val) = 0;
  930. /** If true then a pruning will be harsher.
  931. This will make a tree more compact and more resistant to the training data noise but a bit less
  932. accurate. Default value is true.*/
  933. /** @see setUse1SERule */
  934. CV_WRAP virtual bool getUse1SERule() const = 0;
  935. /** @copybrief getUse1SERule @see getUse1SERule */
  936. CV_WRAP virtual void setUse1SERule(bool val) = 0;
  937. /** If true then pruned branches are physically removed from the tree.
  938. Otherwise they are retained and it is possible to get results from the original unpruned (or
  939. pruned less aggressively) tree. Default value is true.*/
  940. /** @see setTruncatePrunedTree */
  941. CV_WRAP virtual bool getTruncatePrunedTree() const = 0;
  942. /** @copybrief getTruncatePrunedTree @see getTruncatePrunedTree */
  943. CV_WRAP virtual void setTruncatePrunedTree(bool val) = 0;
  944. /** Termination criteria for regression trees.
  945. If all absolute differences between an estimated value in a node and values of train samples
  946. in this node are less than this parameter then the node will not be split further. Default
  947. value is 0.01f*/
  948. /** @see setRegressionAccuracy */
  949. CV_WRAP virtual float getRegressionAccuracy() const = 0;
  950. /** @copybrief getRegressionAccuracy @see getRegressionAccuracy */
  951. CV_WRAP virtual void setRegressionAccuracy(float val) = 0;
  952. /** @brief The array of a priori class probabilities, sorted by the class label value.
  953. The parameter can be used to tune the decision tree preferences toward a certain class. For
  954. example, if you want to detect some rare anomaly occurrence, the training base will likely
  955. contain much more normal cases than anomalies, so a very good classification performance
  956. will be achieved just by considering every case as normal. To avoid this, the priors can be
  957. specified, where the anomaly probability is artificially increased (up to 0.5 or even
  958. greater), so the weight of the misclassified anomalies becomes much bigger, and the tree is
  959. adjusted properly.
  960. You can also think about this parameter as weights of prediction categories which determine
  961. relative weights that you give to misclassification. That is, if the weight of the first
  962. category is 1 and the weight of the second category is 10, then each mistake in predicting
  963. the second category is equivalent to making 10 mistakes in predicting the first category.
  964. Default value is empty Mat.*/
  965. /** @see setPriors */
  966. CV_WRAP virtual cv::Mat getPriors() const = 0;
  967. /** @copybrief getPriors @see getPriors */
  968. CV_WRAP virtual void setPriors(const cv::Mat &val) = 0;
  969. /** @brief The class represents a decision tree node.
  970. */
  971. class CV_EXPORTS Node
  972. {
  973. public:
  974. Node();
  975. double value; //!< Value at the node: a class label in case of classification or estimated
  976. //!< function value in case of regression.
  977. int classIdx; //!< Class index normalized to 0..class_count-1 range and assigned to the
  978. //!< node. It is used internally in classification trees and tree ensembles.
  979. int parent; //!< Index of the parent node
  980. int left; //!< Index of the left child node
  981. int right; //!< Index of right child node
  982. int defaultDir; //!< Default direction where to go (-1: left or +1: right). It helps in the
  983. //!< case of missing values.
  984. int split; //!< Index of the first split
  985. };
  986. /** @brief The class represents split in a decision tree.
  987. */
  988. class CV_EXPORTS Split
  989. {
  990. public:
  991. Split();
  992. int varIdx; //!< Index of variable on which the split is created.
  993. bool inversed; //!< If true, then the inverse split rule is used (i.e. left and right
  994. //!< branches are exchanged in the rule expressions below).
  995. float quality; //!< The split quality, a positive number. It is used to choose the best split.
  996. int next; //!< Index of the next split in the list of splits for the node
  997. float c; /**< The threshold value in case of split on an ordered variable.
  998. The rule is:
  999. @code{.none}
  1000. if var_value < c
  1001. then next_node <- left
  1002. else next_node <- right
  1003. @endcode */
  1004. int subsetOfs; /**< Offset of the bitset used by the split on a categorical variable.
  1005. The rule is:
  1006. @code{.none}
  1007. if bitset[var_value] == 1
  1008. then next_node <- left
  1009. else next_node <- right
  1010. @endcode */
  1011. };
  1012. /** @brief Returns indices of root nodes
  1013. */
  1014. virtual const std::vector<int>& getRoots() const = 0;
  1015. /** @brief Returns all the nodes
  1016. all the node indices are indices in the returned vector
  1017. */
  1018. virtual const std::vector<Node>& getNodes() const = 0;
  1019. /** @brief Returns all the splits
  1020. all the split indices are indices in the returned vector
  1021. */
  1022. virtual const std::vector<Split>& getSplits() const = 0;
  1023. /** @brief Returns all the bitsets for categorical splits
  1024. Split::subsetOfs is an offset in the returned vector
  1025. */
  1026. virtual const std::vector<int>& getSubsets() const = 0;
  1027. /** @brief Creates the empty model
  1028. The static method creates empty decision tree with the specified parameters. It should be then
  1029. trained using train method (see StatModel::train). Alternatively, you can load the model from
  1030. file using Algorithm::load\<DTrees\>(filename).
  1031. */
  1032. CV_WRAP static Ptr<DTrees> create();
  1033. /** @brief Loads and creates a serialized DTrees from a file
  1034. *
  1035. * Use DTree::save to serialize and store an DTree to disk.
  1036. * Load the DTree from this file again, by calling this function with the path to the file.
  1037. * Optionally specify the node for the file containing the classifier
  1038. *
  1039. * @param filepath path to serialized DTree
  1040. * @param nodeName name of node containing the classifier
  1041. */
  1042. CV_WRAP static Ptr<DTrees> load(const String& filepath , const String& nodeName = String());
  1043. };
  1044. /****************************************************************************************\
  1045. * Random Trees Classifier *
  1046. \****************************************************************************************/
  1047. /** @brief The class implements the random forest predictor.
  1048. @sa @ref ml_intro_rtrees
  1049. */
  1050. class CV_EXPORTS_W RTrees : public DTrees
  1051. {
  1052. public:
  1053. /** If true then variable importance will be calculated and then it can be retrieved by RTrees::getVarImportance.
  1054. Default value is false.*/
  1055. /** @see setCalculateVarImportance */
  1056. CV_WRAP virtual bool getCalculateVarImportance() const = 0;
  1057. /** @copybrief getCalculateVarImportance @see getCalculateVarImportance */
  1058. CV_WRAP virtual void setCalculateVarImportance(bool val) = 0;
  1059. /** The size of the randomly selected subset of features at each tree node and that are used
  1060. to find the best split(s).
  1061. If you set it to 0 then the size will be set to the square root of the total number of
  1062. features. Default value is 0.*/
  1063. /** @see setActiveVarCount */
  1064. CV_WRAP virtual int getActiveVarCount() const = 0;
  1065. /** @copybrief getActiveVarCount @see getActiveVarCount */
  1066. CV_WRAP virtual void setActiveVarCount(int val) = 0;
  1067. /** The termination criteria that specifies when the training algorithm stops.
  1068. Either when the specified number of trees is trained and added to the ensemble or when
  1069. sufficient accuracy (measured as OOB error) is achieved. Typically the more trees you have the
  1070. better the accuracy. However, the improvement in accuracy generally diminishes and asymptotes
  1071. pass a certain number of trees. Also to keep in mind, the number of tree increases the
  1072. prediction time linearly. Default value is TermCriteria(TermCriteria::MAX_ITERS +
  1073. TermCriteria::EPS, 50, 0.1)*/
  1074. /** @see setTermCriteria */
  1075. CV_WRAP virtual TermCriteria getTermCriteria() const = 0;
  1076. /** @copybrief getTermCriteria @see getTermCriteria */
  1077. CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0;
  1078. /** Returns the variable importance array.
  1079. The method returns the variable importance vector, computed at the training stage when
  1080. CalculateVarImportance is set to true. If this flag was set to false, the empty matrix is
  1081. returned.
  1082. */
  1083. CV_WRAP virtual Mat getVarImportance() const = 0;
  1084. /** Returns the result of each individual tree in the forest.
  1085. In case the model is a regression problem, the method will return each of the trees'
  1086. results for each of the sample cases. If the model is a classifier, it will return
  1087. a Mat with samples + 1 rows, where the first row gives the class number and the
  1088. following rows return the votes each class had for each sample.
  1089. @param samples Array containing the samples for which votes will be calculated.
  1090. @param results Array where the result of the calculation will be written.
  1091. @param flags Flags for defining the type of RTrees.
  1092. */
  1093. CV_WRAP virtual void getVotes(InputArray samples, OutputArray results, int flags) const = 0;
  1094. /** Creates the empty model.
  1095. Use StatModel::train to train the model, StatModel::train to create and train the model,
  1096. Algorithm::load to load the pre-trained model.
  1097. */
  1098. CV_WRAP static Ptr<RTrees> create();
  1099. /** @brief Loads and creates a serialized RTree from a file
  1100. *
  1101. * Use RTree::save to serialize and store an RTree to disk.
  1102. * Load the RTree from this file again, by calling this function with the path to the file.
  1103. * Optionally specify the node for the file containing the classifier
  1104. *
  1105. * @param filepath path to serialized RTree
  1106. * @param nodeName name of node containing the classifier
  1107. */
  1108. CV_WRAP static Ptr<RTrees> load(const String& filepath , const String& nodeName = String());
  1109. };
  1110. /****************************************************************************************\
  1111. * Boosted tree classifier *
  1112. \****************************************************************************************/
  1113. /** @brief Boosted tree classifier derived from DTrees
  1114. @sa @ref ml_intro_boost
  1115. */
  1116. class CV_EXPORTS_W Boost : public DTrees
  1117. {
  1118. public:
  1119. /** Type of the boosting algorithm.
  1120. See Boost::Types. Default value is Boost::REAL. */
  1121. /** @see setBoostType */
  1122. CV_WRAP virtual int getBoostType() const = 0;
  1123. /** @copybrief getBoostType @see getBoostType */
  1124. CV_WRAP virtual void setBoostType(int val) = 0;
  1125. /** The number of weak classifiers.
  1126. Default value is 100. */
  1127. /** @see setWeakCount */
  1128. CV_WRAP virtual int getWeakCount() const = 0;
  1129. /** @copybrief getWeakCount @see getWeakCount */
  1130. CV_WRAP virtual void setWeakCount(int val) = 0;
  1131. /** A threshold between 0 and 1 used to save computational time.
  1132. Samples with summary weight \f$\leq 1 - weight_trim_rate\f$ do not participate in the *next*
  1133. iteration of training. Set this parameter to 0 to turn off this functionality. Default value is 0.95.*/
  1134. /** @see setWeightTrimRate */
  1135. CV_WRAP virtual double getWeightTrimRate() const = 0;
  1136. /** @copybrief getWeightTrimRate @see getWeightTrimRate */
  1137. CV_WRAP virtual void setWeightTrimRate(double val) = 0;
  1138. /** Boosting type.
  1139. Gentle AdaBoost and Real AdaBoost are often the preferable choices. */
  1140. enum Types {
  1141. DISCRETE=0, //!< Discrete AdaBoost.
  1142. REAL=1, //!< Real AdaBoost. It is a technique that utilizes confidence-rated predictions
  1143. //!< and works well with categorical data.
  1144. LOGIT=2, //!< LogitBoost. It can produce good regression fits.
  1145. GENTLE=3 //!< Gentle AdaBoost. It puts less weight on outlier data points and for that
  1146. //!<reason is often good with regression data.
  1147. };
  1148. /** Creates the empty model.
  1149. Use StatModel::train to train the model, Algorithm::load\<Boost\>(filename) to load the pre-trained model. */
  1150. CV_WRAP static Ptr<Boost> create();
  1151. /** @brief Loads and creates a serialized Boost from a file
  1152. *
  1153. * Use Boost::save to serialize and store an RTree to disk.
  1154. * Load the Boost from this file again, by calling this function with the path to the file.
  1155. * Optionally specify the node for the file containing the classifier
  1156. *
  1157. * @param filepath path to serialized Boost
  1158. * @param nodeName name of node containing the classifier
  1159. */
  1160. CV_WRAP static Ptr<Boost> load(const String& filepath , const String& nodeName = String());
  1161. };
  1162. /****************************************************************************************\
  1163. * Gradient Boosted Trees *
  1164. \****************************************************************************************/
  1165. /*class CV_EXPORTS_W GBTrees : public DTrees
  1166. {
  1167. public:
  1168. struct CV_EXPORTS_W_MAP Params : public DTrees::Params
  1169. {
  1170. CV_PROP_RW int weakCount;
  1171. CV_PROP_RW int lossFunctionType;
  1172. CV_PROP_RW float subsamplePortion;
  1173. CV_PROP_RW float shrinkage;
  1174. Params();
  1175. Params( int lossFunctionType, int weakCount, float shrinkage,
  1176. float subsamplePortion, int maxDepth, bool useSurrogates );
  1177. };
  1178. enum {SQUARED_LOSS=0, ABSOLUTE_LOSS, HUBER_LOSS=3, DEVIANCE_LOSS};
  1179. virtual void setK(int k) = 0;
  1180. virtual float predictSerial( InputArray samples,
  1181. OutputArray weakResponses, int flags) const = 0;
  1182. static Ptr<GBTrees> create(const Params& p);
  1183. };*/
  1184. /****************************************************************************************\
  1185. * Artificial Neural Networks (ANN) *
  1186. \****************************************************************************************/
  1187. /////////////////////////////////// Multi-Layer Perceptrons //////////////////////////////
  1188. /** @brief Artificial Neural Networks - Multi-Layer Perceptrons.
  1189. Unlike many other models in ML that are constructed and trained at once, in the MLP model these
  1190. steps are separated. First, a network with the specified topology is created using the non-default
  1191. constructor or the method ANN_MLP::create. All the weights are set to zeros. Then, the network is
  1192. trained using a set of input and output vectors. The training procedure can be repeated more than
  1193. once, that is, the weights can be adjusted based on the new training data.
  1194. Additional flags for StatModel::train are available: ANN_MLP::TrainFlags.
  1195. @sa @ref ml_intro_ann
  1196. */
  1197. class CV_EXPORTS_W ANN_MLP : public StatModel
  1198. {
  1199. public:
  1200. /** Available training methods */
  1201. enum TrainingMethods {
  1202. BACKPROP=0, //!< The back-propagation algorithm.
  1203. RPROP = 1, //!< The RPROP algorithm. See @cite RPROP93 for details.
  1204. ANNEAL = 2 //!< The simulated annealing algorithm. See @cite Kirkpatrick83 for details.
  1205. };
  1206. /** Sets training method and common parameters.
  1207. @param method Default value is ANN_MLP::RPROP. See ANN_MLP::TrainingMethods.
  1208. @param param1 passed to setRpropDW0 for ANN_MLP::RPROP and to setBackpropWeightScale for ANN_MLP::BACKPROP and to initialT for ANN_MLP::ANNEAL.
  1209. @param param2 passed to setRpropDWMin for ANN_MLP::RPROP and to setBackpropMomentumScale for ANN_MLP::BACKPROP and to finalT for ANN_MLP::ANNEAL.
  1210. */
  1211. CV_WRAP virtual void setTrainMethod(int method, double param1 = 0, double param2 = 0) = 0;
  1212. /** Returns current training method */
  1213. CV_WRAP virtual int getTrainMethod() const = 0;
  1214. /** Initialize the activation function for each neuron.
  1215. Currently the default and the only fully supported activation function is ANN_MLP::SIGMOID_SYM.
  1216. @param type The type of activation function. See ANN_MLP::ActivationFunctions.
  1217. @param param1 The first parameter of the activation function, \f$\alpha\f$. Default value is 0.
  1218. @param param2 The second parameter of the activation function, \f$\beta\f$. Default value is 0.
  1219. */
  1220. CV_WRAP virtual void setActivationFunction(int type, double param1 = 0, double param2 = 0) = 0;
  1221. /** Integer vector specifying the number of neurons in each layer including the input and output layers.
  1222. The very first element specifies the number of elements in the input layer.
  1223. The last element - number of elements in the output layer. Default value is empty Mat.
  1224. @sa getLayerSizes */
  1225. CV_WRAP virtual void setLayerSizes(InputArray _layer_sizes) = 0;
  1226. /** Integer vector specifying the number of neurons in each layer including the input and output layers.
  1227. The very first element specifies the number of elements in the input layer.
  1228. The last element - number of elements in the output layer.
  1229. @sa setLayerSizes */
  1230. CV_WRAP virtual cv::Mat getLayerSizes() const = 0;
  1231. /** Termination criteria of the training algorithm.
  1232. You can specify the maximum number of iterations (maxCount) and/or how much the error could
  1233. change between the iterations to make the algorithm continue (epsilon). Default value is
  1234. TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, 0.01).*/
  1235. /** @see setTermCriteria */
  1236. CV_WRAP virtual TermCriteria getTermCriteria() const = 0;
  1237. /** @copybrief getTermCriteria @see getTermCriteria */
  1238. CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0;
  1239. /** BPROP: Strength of the weight gradient term.
  1240. The recommended value is about 0.1. Default value is 0.1.*/
  1241. /** @see setBackpropWeightScale */
  1242. CV_WRAP virtual double getBackpropWeightScale() const = 0;
  1243. /** @copybrief getBackpropWeightScale @see getBackpropWeightScale */
  1244. CV_WRAP virtual void setBackpropWeightScale(double val) = 0;
  1245. /** BPROP: Strength of the momentum term (the difference between weights on the 2 previous iterations).
  1246. This parameter provides some inertia to smooth the random fluctuations of the weights. It can
  1247. vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough.
  1248. Default value is 0.1.*/
  1249. /** @see setBackpropMomentumScale */
  1250. CV_WRAP virtual double getBackpropMomentumScale() const = 0;
  1251. /** @copybrief getBackpropMomentumScale @see getBackpropMomentumScale */
  1252. CV_WRAP virtual void setBackpropMomentumScale(double val) = 0;
  1253. /** RPROP: Initial value \f$\Delta_0\f$ of update-values \f$\Delta_{ij}\f$.
  1254. Default value is 0.1.*/
  1255. /** @see setRpropDW0 */
  1256. CV_WRAP virtual double getRpropDW0() const = 0;
  1257. /** @copybrief getRpropDW0 @see getRpropDW0 */
  1258. CV_WRAP virtual void setRpropDW0(double val) = 0;
  1259. /** RPROP: Increase factor \f$\eta^+\f$.
  1260. It must be \>1. Default value is 1.2.*/
  1261. /** @see setRpropDWPlus */
  1262. CV_WRAP virtual double getRpropDWPlus() const = 0;
  1263. /** @copybrief getRpropDWPlus @see getRpropDWPlus */
  1264. CV_WRAP virtual void setRpropDWPlus(double val) = 0;
  1265. /** RPROP: Decrease factor \f$\eta^-\f$.
  1266. It must be \<1. Default value is 0.5.*/
  1267. /** @see setRpropDWMinus */
  1268. CV_WRAP virtual double getRpropDWMinus() const = 0;
  1269. /** @copybrief getRpropDWMinus @see getRpropDWMinus */
  1270. CV_WRAP virtual void setRpropDWMinus(double val) = 0;
  1271. /** RPROP: Update-values lower limit \f$\Delta_{min}\f$.
  1272. It must be positive. Default value is FLT_EPSILON.*/
  1273. /** @see setRpropDWMin */
  1274. CV_WRAP virtual double getRpropDWMin() const = 0;
  1275. /** @copybrief getRpropDWMin @see getRpropDWMin */
  1276. CV_WRAP virtual void setRpropDWMin(double val) = 0;
  1277. /** RPROP: Update-values upper limit \f$\Delta_{max}\f$.
  1278. It must be \>1. Default value is 50.*/
  1279. /** @see setRpropDWMax */
  1280. CV_WRAP virtual double getRpropDWMax() const = 0;
  1281. /** @copybrief getRpropDWMax @see getRpropDWMax */
  1282. CV_WRAP virtual void setRpropDWMax(double val) = 0;
  1283. /** ANNEAL: Update initial temperature.
  1284. It must be \>=0. Default value is 10.*/
  1285. /** @see setAnnealInitialT */
  1286. CV_WRAP virtual double getAnnealInitialT() const = 0;
  1287. /** @copybrief getAnnealInitialT @see getAnnealInitialT */
  1288. CV_WRAP virtual void setAnnealInitialT(double val) = 0;
  1289. /** ANNEAL: Update final temperature.
  1290. It must be \>=0 and less than initialT. Default value is 0.1.*/
  1291. /** @see setAnnealFinalT */
  1292. CV_WRAP virtual double getAnnealFinalT() const = 0;
  1293. /** @copybrief getAnnealFinalT @see getAnnealFinalT */
  1294. CV_WRAP virtual void setAnnealFinalT(double val) = 0;
  1295. /** ANNEAL: Update cooling ratio.
  1296. It must be \>0 and less than 1. Default value is 0.95.*/
  1297. /** @see setAnnealCoolingRatio */
  1298. CV_WRAP virtual double getAnnealCoolingRatio() const = 0;
  1299. /** @copybrief getAnnealCoolingRatio @see getAnnealCoolingRatio */
  1300. CV_WRAP virtual void setAnnealCoolingRatio(double val) = 0;
  1301. /** ANNEAL: Update iteration per step.
  1302. It must be \>0 . Default value is 10.*/
  1303. /** @see setAnnealItePerStep */
  1304. CV_WRAP virtual int getAnnealItePerStep() const = 0;
  1305. /** @copybrief getAnnealItePerStep @see getAnnealItePerStep */
  1306. CV_WRAP virtual void setAnnealItePerStep(int val) = 0;
  1307. /** @brief Set/initialize anneal RNG */
  1308. virtual void setAnnealEnergyRNG(const RNG& rng) = 0;
  1309. /** possible activation functions */
  1310. enum ActivationFunctions {
  1311. /** Identity function: \f$f(x)=x\f$ */
  1312. IDENTITY = 0,
  1313. /** Symmetrical sigmoid: \f$f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x})\f$
  1314. @note
  1315. If you are using the default sigmoid activation function with the default parameter values
  1316. fparam1=0 and fparam2=0 then the function used is y = 1.7159\*tanh(2/3 \* x), so the output
  1317. will range from [-1.7159, 1.7159], instead of [0,1].*/
  1318. SIGMOID_SYM = 1,
  1319. /** Gaussian function: \f$f(x)=\beta e^{-\alpha x*x}\f$ */
  1320. GAUSSIAN = 2,
  1321. /** ReLU function: \f$f(x)=max(0,x)\f$ */
  1322. RELU = 3,
  1323. /** Leaky ReLU function: for x>0 \f$f(x)=x \f$ and x<=0 \f$f(x)=\alpha x \f$*/
  1324. LEAKYRELU= 4
  1325. };
  1326. /** Train options */
  1327. enum TrainFlags {
  1328. /** Update the network weights, rather than compute them from scratch. In the latter case
  1329. the weights are initialized using the Nguyen-Widrow algorithm. */
  1330. UPDATE_WEIGHTS = 1,
  1331. /** Do not normalize the input vectors. If this flag is not set, the training algorithm
  1332. normalizes each input feature independently, shifting its mean value to 0 and making the
  1333. standard deviation equal to 1. If the network is assumed to be updated frequently, the new
  1334. training data could be much different from original one. In this case, you should take care
  1335. of proper normalization. */
  1336. NO_INPUT_SCALE = 2,
  1337. /** Do not normalize the output vectors. If the flag is not set, the training algorithm
  1338. normalizes each output feature independently, by transforming it to the certain range
  1339. depending on the used activation function. */
  1340. NO_OUTPUT_SCALE = 4
  1341. };
  1342. CV_WRAP virtual Mat getWeights(int layerIdx) const = 0;
  1343. /** @brief Creates empty model
  1344. Use StatModel::train to train the model, Algorithm::load\<ANN_MLP\>(filename) to load the pre-trained model.
  1345. Note that the train method has optional flags: ANN_MLP::TrainFlags.
  1346. */
  1347. CV_WRAP static Ptr<ANN_MLP> create();
  1348. /** @brief Loads and creates a serialized ANN from a file
  1349. *
  1350. * Use ANN::save to serialize and store an ANN to disk.
  1351. * Load the ANN from this file again, by calling this function with the path to the file.
  1352. *
  1353. * @param filepath path to serialized ANN
  1354. */
  1355. CV_WRAP static Ptr<ANN_MLP> load(const String& filepath);
  1356. };
  1357. #ifndef DISABLE_OPENCV_3_COMPATIBILITY
  1358. typedef ANN_MLP ANN_MLP_ANNEAL;
  1359. #endif
  1360. /****************************************************************************************\
  1361. * Logistic Regression *
  1362. \****************************************************************************************/
  1363. /** @brief Implements Logistic Regression classifier.
  1364. @sa @ref ml_intro_lr
  1365. */
  1366. class CV_EXPORTS_W LogisticRegression : public StatModel
  1367. {
  1368. public:
  1369. /** Learning rate. */
  1370. /** @see setLearningRate */
  1371. CV_WRAP virtual double getLearningRate() const = 0;
  1372. /** @copybrief getLearningRate @see getLearningRate */
  1373. CV_WRAP virtual void setLearningRate(double val) = 0;
  1374. /** Number of iterations. */
  1375. /** @see setIterations */
  1376. CV_WRAP virtual int getIterations() const = 0;
  1377. /** @copybrief getIterations @see getIterations */
  1378. CV_WRAP virtual void setIterations(int val) = 0;
  1379. /** Kind of regularization to be applied. See LogisticRegression::RegKinds. */
  1380. /** @see setRegularization */
  1381. CV_WRAP virtual int getRegularization() const = 0;
  1382. /** @copybrief getRegularization @see getRegularization */
  1383. CV_WRAP virtual void setRegularization(int val) = 0;
  1384. /** Kind of training method used. See LogisticRegression::Methods. */
  1385. /** @see setTrainMethod */
  1386. CV_WRAP virtual int getTrainMethod() const = 0;
  1387. /** @copybrief getTrainMethod @see getTrainMethod */
  1388. CV_WRAP virtual void setTrainMethod(int val) = 0;
  1389. /** Specifies the number of training samples taken in each step of Mini-Batch Gradient
  1390. Descent. Will only be used if using LogisticRegression::MINI_BATCH training algorithm. It
  1391. has to take values less than the total number of training samples. */
  1392. /** @see setMiniBatchSize */
  1393. CV_WRAP virtual int getMiniBatchSize() const = 0;
  1394. /** @copybrief getMiniBatchSize @see getMiniBatchSize */
  1395. CV_WRAP virtual void setMiniBatchSize(int val) = 0;
  1396. /** Termination criteria of the algorithm. */
  1397. /** @see setTermCriteria */
  1398. CV_WRAP virtual TermCriteria getTermCriteria() const = 0;
  1399. /** @copybrief getTermCriteria @see getTermCriteria */
  1400. CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0;
  1401. //! Regularization kinds
  1402. enum RegKinds {
  1403. REG_DISABLE = -1, //!< Regularization disabled
  1404. REG_L1 = 0, //!< %L1 norm
  1405. REG_L2 = 1 //!< %L2 norm
  1406. };
  1407. //! Training methods
  1408. enum Methods {
  1409. BATCH = 0,
  1410. MINI_BATCH = 1 //!< Set MiniBatchSize to a positive integer when using this method.
  1411. };
  1412. /** @brief Predicts responses for input samples and returns a float type.
  1413. @param samples The input data for the prediction algorithm. Matrix [m x n], where each row
  1414. contains variables (features) of one object being classified. Should have data type CV_32F.
  1415. @param results Predicted labels as a column matrix of type CV_32S.
  1416. @param flags Not used.
  1417. */
  1418. CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const CV_OVERRIDE = 0;
  1419. /** @brief This function returns the trained parameters arranged across rows.
  1420. For a two class classifcation problem, it returns a row matrix. It returns learnt parameters of
  1421. the Logistic Regression as a matrix of type CV_32F.
  1422. */
  1423. CV_WRAP virtual Mat get_learnt_thetas() const = 0;
  1424. /** @brief Creates empty model.
  1425. Creates Logistic Regression model with parameters given.
  1426. */
  1427. CV_WRAP static Ptr<LogisticRegression> create();
  1428. /** @brief Loads and creates a serialized LogisticRegression from a file
  1429. *
  1430. * Use LogisticRegression::save to serialize and store an LogisticRegression to disk.
  1431. * Load the LogisticRegression from this file again, by calling this function with the path to the file.
  1432. * Optionally specify the node for the file containing the classifier
  1433. *
  1434. * @param filepath path to serialized LogisticRegression
  1435. * @param nodeName name of node containing the classifier
  1436. */
  1437. CV_WRAP static Ptr<LogisticRegression> load(const String& filepath , const String& nodeName = String());
  1438. };
  1439. /****************************************************************************************\
  1440. * Stochastic Gradient Descent SVM Classifier *
  1441. \****************************************************************************************/
  1442. /*!
  1443. @brief Stochastic Gradient Descent SVM classifier
  1444. SVMSGD provides a fast and easy-to-use implementation of the SVM classifier using the Stochastic Gradient Descent approach,
  1445. as presented in @cite bottou2010large.
  1446. The classifier has following parameters:
  1447. - model type,
  1448. - margin type,
  1449. - margin regularization (\f$\lambda\f$),
  1450. - initial step size (\f$\gamma_0\f$),
  1451. - step decreasing power (\f$c\f$),
  1452. - and termination criteria.
  1453. The model type may have one of the following values: \ref SGD and \ref ASGD.
  1454. - \ref SGD is the classic version of SVMSGD classifier: every next step is calculated by the formula
  1455. \f[w_{t+1} = w_t - \gamma(t) \frac{dQ_i}{dw} |_{w = w_t}\f]
  1456. where
  1457. - \f$w_t\f$ is the weights vector for decision function at step \f$t\f$,
  1458. - \f$\gamma(t)\f$ is the step size of model parameters at the iteration \f$t\f$, it is decreased on each step by the formula
  1459. \f$\gamma(t) = \gamma_0 (1 + \lambda \gamma_0 t) ^ {-c}\f$
  1460. - \f$Q_i\f$ is the target functional from SVM task for sample with number \f$i\f$, this sample is chosen stochastically on each step of the algorithm.
  1461. - \ref ASGD is Average Stochastic Gradient Descent SVM Classifier. ASGD classifier averages weights vector on each step of algorithm by the formula
  1462. \f$\widehat{w}_{t+1} = \frac{t}{1+t}\widehat{w}_{t} + \frac{1}{1+t}w_{t+1}\f$
  1463. The recommended model type is ASGD (following @cite bottou2010large).
  1464. The margin type may have one of the following values: \ref SOFT_MARGIN or \ref HARD_MARGIN.
  1465. - You should use \ref HARD_MARGIN type, if you have linearly separable sets.
  1466. - You should use \ref SOFT_MARGIN type, if you have non-linearly separable sets or sets with outliers.
  1467. - In the general case (if you know nothing about linear separability of your sets), use SOFT_MARGIN.
  1468. The other parameters may be described as follows:
  1469. - Margin regularization parameter is responsible for weights decreasing at each step and for the strength of restrictions on outliers
  1470. (the less the parameter, the less probability that an outlier will be ignored).
  1471. Recommended value for SGD model is 0.0001, for ASGD model is 0.00001.
  1472. - Initial step size parameter is the initial value for the step size \f$\gamma(t)\f$.
  1473. You will have to find the best initial step for your problem.
  1474. - Step decreasing power is the power parameter for \f$\gamma(t)\f$ decreasing by the formula, mentioned above.
  1475. Recommended value for SGD model is 1, for ASGD model is 0.75.
  1476. - Termination criteria can be TermCriteria::COUNT, TermCriteria::EPS or TermCriteria::COUNT + TermCriteria::EPS.
  1477. You will have to find the best termination criteria for your problem.
  1478. Note that the parameters margin regularization, initial step size, and step decreasing power should be positive.
  1479. To use SVMSGD algorithm do as follows:
  1480. - first, create the SVMSGD object. The algoorithm will set optimal parameters by default, but you can set your own parameters via functions setSvmsgdType(),
  1481. setMarginType(), setMarginRegularization(), setInitialStepSize(), and setStepDecreasingPower().
  1482. - then the SVM model can be trained using the train features and the correspondent labels by the method train().
  1483. - after that, the label of a new feature vector can be predicted using the method predict().
  1484. @code
  1485. // Create empty object
  1486. cv::Ptr<SVMSGD> svmsgd = SVMSGD::create();
  1487. // Train the Stochastic Gradient Descent SVM
  1488. svmsgd->train(trainData);
  1489. // Predict labels for the new samples
  1490. svmsgd->predict(samples, responses);
  1491. @endcode
  1492. */
  1493. class CV_EXPORTS_W SVMSGD : public cv::ml::StatModel
  1494. {
  1495. public:
  1496. /** SVMSGD type.
  1497. ASGD is often the preferable choice. */
  1498. enum SvmsgdType
  1499. {
  1500. SGD, //!< Stochastic Gradient Descent
  1501. ASGD //!< Average Stochastic Gradient Descent
  1502. };
  1503. /** Margin type.*/
  1504. enum MarginType
  1505. {
  1506. SOFT_MARGIN, //!< General case, suits to the case of non-linearly separable sets, allows outliers.
  1507. HARD_MARGIN //!< More accurate for the case of linearly separable sets.
  1508. };
  1509. /**
  1510. * @return the weights of the trained model (decision function f(x) = weights * x + shift).
  1511. */
  1512. CV_WRAP virtual Mat getWeights() = 0;
  1513. /**
  1514. * @return the shift of the trained model (decision function f(x) = weights * x + shift).
  1515. */
  1516. CV_WRAP virtual float getShift() = 0;
  1517. /** @brief Creates empty model.
  1518. * Use StatModel::train to train the model. Since %SVMSGD has several parameters, you may want to
  1519. * find the best parameters for your problem or use setOptimalParameters() to set some default parameters.
  1520. */
  1521. CV_WRAP static Ptr<SVMSGD> create();
  1522. /** @brief Loads and creates a serialized SVMSGD from a file
  1523. *
  1524. * Use SVMSGD::save to serialize and store an SVMSGD to disk.
  1525. * Load the SVMSGD from this file again, by calling this function with the path to the file.
  1526. * Optionally specify the node for the file containing the classifier
  1527. *
  1528. * @param filepath path to serialized SVMSGD
  1529. * @param nodeName name of node containing the classifier
  1530. */
  1531. CV_WRAP static Ptr<SVMSGD> load(const String& filepath , const String& nodeName = String());
  1532. /** @brief Function sets optimal parameters values for chosen SVM SGD model.
  1533. * @param svmsgdType is the type of SVMSGD classifier.
  1534. * @param marginType is the type of margin constraint.
  1535. */
  1536. CV_WRAP virtual void setOptimalParameters(int svmsgdType = SVMSGD::ASGD, int marginType = SVMSGD::SOFT_MARGIN) = 0;
  1537. /** @brief %Algorithm type, one of SVMSGD::SvmsgdType. */
  1538. /** @see setSvmsgdType */
  1539. CV_WRAP virtual int getSvmsgdType() const = 0;
  1540. /** @copybrief getSvmsgdType @see getSvmsgdType */
  1541. CV_WRAP virtual void setSvmsgdType(int svmsgdType) = 0;
  1542. /** @brief %Margin type, one of SVMSGD::MarginType. */
  1543. /** @see setMarginType */
  1544. CV_WRAP virtual int getMarginType() const = 0;
  1545. /** @copybrief getMarginType @see getMarginType */
  1546. CV_WRAP virtual void setMarginType(int marginType) = 0;
  1547. /** @brief Parameter marginRegularization of a %SVMSGD optimization problem. */
  1548. /** @see setMarginRegularization */
  1549. CV_WRAP virtual float getMarginRegularization() const = 0;
  1550. /** @copybrief getMarginRegularization @see getMarginRegularization */
  1551. CV_WRAP virtual void setMarginRegularization(float marginRegularization) = 0;
  1552. /** @brief Parameter initialStepSize of a %SVMSGD optimization problem. */
  1553. /** @see setInitialStepSize */
  1554. CV_WRAP virtual float getInitialStepSize() const = 0;
  1555. /** @copybrief getInitialStepSize @see getInitialStepSize */
  1556. CV_WRAP virtual void setInitialStepSize(float InitialStepSize) = 0;
  1557. /** @brief Parameter stepDecreasingPower of a %SVMSGD optimization problem. */
  1558. /** @see setStepDecreasingPower */
  1559. CV_WRAP virtual float getStepDecreasingPower() const = 0;
  1560. /** @copybrief getStepDecreasingPower @see getStepDecreasingPower */
  1561. CV_WRAP virtual void setStepDecreasingPower(float stepDecreasingPower) = 0;
  1562. /** @brief Termination criteria of the training algorithm.
  1563. You can specify the maximum number of iterations (maxCount) and/or how much the error could
  1564. change between the iterations to make the algorithm continue (epsilon).*/
  1565. /** @see setTermCriteria */
  1566. CV_WRAP virtual TermCriteria getTermCriteria() const = 0;
  1567. /** @copybrief getTermCriteria @see getTermCriteria */
  1568. CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0;
  1569. };
  1570. /****************************************************************************************\
  1571. * Auxiliary functions declarations *
  1572. \****************************************************************************************/
  1573. /** @brief Generates _sample_ from multivariate normal distribution
  1574. @param mean an average row vector
  1575. @param cov symmetric covariation matrix
  1576. @param nsamples returned samples count
  1577. @param samples returned samples array
  1578. */
  1579. CV_EXPORTS void randMVNormal( InputArray mean, InputArray cov, int nsamples, OutputArray samples);
  1580. /** @brief Creates test set */
  1581. CV_EXPORTS void createConcentricSpheresTestSet( int nsamples, int nfeatures, int nclasses,
  1582. OutputArray samples, OutputArray responses);
  1583. /****************************************************************************************\
  1584. * Simulated annealing solver *
  1585. \****************************************************************************************/
  1586. #ifdef CV_DOXYGEN
  1587. /** @brief This class declares example interface for system state used in simulated annealing optimization algorithm.
  1588. @note This class is not defined in C++ code and can't be use directly - you need your own implementation with the same methods.
  1589. */
  1590. struct SimulatedAnnealingSolverSystem
  1591. {
  1592. /** Give energy value for a state of system.*/
  1593. double energy() const;
  1594. /** Function which change the state of system (random perturbation).*/
  1595. void changeState();
  1596. /** Function to reverse to the previous state. Can be called once only after changeState(). */
  1597. void reverseState();
  1598. };
  1599. #endif // CV_DOXYGEN
  1600. /** @brief The class implements simulated annealing for optimization.
  1601. @cite Kirkpatrick83 for details
  1602. @param solverSystem optimization system (see SimulatedAnnealingSolverSystem)
  1603. @param initialTemperature initial temperature
  1604. @param finalTemperature final temperature
  1605. @param coolingRatio temperature step multiplies
  1606. @param iterationsPerStep number of iterations per temperature changing step
  1607. @param lastTemperature optional output for last used temperature
  1608. @param rngEnergy specify custom random numbers generator (cv::theRNG() by default)
  1609. */
  1610. template<class SimulatedAnnealingSolverSystem>
  1611. int simulatedAnnealingSolver(SimulatedAnnealingSolverSystem& solverSystem,
  1612. double initialTemperature, double finalTemperature, double coolingRatio,
  1613. size_t iterationsPerStep,
  1614. CV_OUT double* lastTemperature = NULL,
  1615. cv::RNG& rngEnergy = cv::theRNG()
  1616. );
  1617. //! @} ml
  1618. }
  1619. }
  1620. #include <opencv2/ml/ml.inl.hpp>
  1621. #endif // __cplusplus
  1622. #endif // OPENCV_ML_HPP
  1623. /* End of file. */