old_ml_tree.cpp 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153
  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. // Intel License Agreement
  11. //
  12. // Copyright (C) 2000, Intel Corporation, all rights reserved.
  13. // Third party copyrights are property of their respective owners.
  14. //
  15. // Redistribution and use in source and binary forms, with or without modification,
  16. // are permitted provided that the following conditions are met:
  17. //
  18. // * Redistribution's of source code must retain the above copyright notice,
  19. // this list of conditions and the following disclaimer.
  20. //
  21. // * Redistribution's in binary form must reproduce the above copyright notice,
  22. // this list of conditions and the following disclaimer in the documentation
  23. // and/or other materials provided with the distribution.
  24. //
  25. // * The name of Intel Corporation may not be used to endorse or promote products
  26. // derived from this software without specific prior written permission.
  27. //
  28. // This software is provided by the copyright holders and contributors "as is" and
  29. // any express or implied warranties, including, but not limited to, the implied
  30. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  31. // In no event shall the Intel Corporation or contributors be liable for any direct,
  32. // indirect, incidental, special, exemplary, or consequential damages
  33. // (including, but not limited to, procurement of substitute goods or services;
  34. // loss of use, data, or profits; or business interruption) however caused
  35. // and on any theory of liability, whether in contract, strict liability,
  36. // or tort (including negligence or otherwise) arising in any way out of
  37. // the use of this software, even if advised of the possibility of such damage.
  38. //
  39. //M*/
  40. #include "old_ml_precomp.hpp"
  41. #include <ctype.h>
  42. using namespace cv;
  43. static const float ord_nan = FLT_MAX*0.5f;
  44. static const int min_block_size = 1 << 16;
  45. static const int block_size_delta = 1 << 10;
  46. CvDTreeTrainData::CvDTreeTrainData()
  47. {
  48. var_idx = var_type = cat_count = cat_ofs = cat_map =
  49. priors = priors_mult = counts = direction = split_buf = responses_copy = 0;
  50. buf = 0;
  51. tree_storage = temp_storage = 0;
  52. clear();
  53. }
  54. CvDTreeTrainData::CvDTreeTrainData( const CvMat* _train_data, int _tflag,
  55. const CvMat* _responses, const CvMat* _var_idx,
  56. const CvMat* _sample_idx, const CvMat* _var_type,
  57. const CvMat* _missing_mask, const CvDTreeParams& _params,
  58. bool _shared, bool _add_labels )
  59. {
  60. var_idx = var_type = cat_count = cat_ofs = cat_map =
  61. priors = priors_mult = counts = direction = split_buf = responses_copy = 0;
  62. buf = 0;
  63. tree_storage = temp_storage = 0;
  64. set_data( _train_data, _tflag, _responses, _var_idx, _sample_idx,
  65. _var_type, _missing_mask, _params, _shared, _add_labels );
  66. }
  67. CvDTreeTrainData::~CvDTreeTrainData()
  68. {
  69. clear();
  70. }
  71. bool CvDTreeTrainData::set_params( const CvDTreeParams& _params )
  72. {
  73. bool ok = false;
  74. CV_FUNCNAME( "CvDTreeTrainData::set_params" );
  75. __BEGIN__;
  76. // set parameters
  77. params = _params;
  78. if( params.max_categories < 2 )
  79. CV_ERROR( CV_StsOutOfRange, "params.max_categories should be >= 2" );
  80. params.max_categories = MIN( params.max_categories, 15 );
  81. if( params.max_depth < 0 )
  82. CV_ERROR( CV_StsOutOfRange, "params.max_depth should be >= 0" );
  83. params.max_depth = MIN( params.max_depth, 25 );
  84. params.min_sample_count = MAX(params.min_sample_count,1);
  85. if( params.cv_folds < 0 )
  86. CV_ERROR( CV_StsOutOfRange,
  87. "params.cv_folds should be =0 (the tree is not pruned) "
  88. "or n>0 (tree is pruned using n-fold cross-validation)" );
  89. if( params.cv_folds == 1 )
  90. params.cv_folds = 0;
  91. if( params.regression_accuracy < 0 )
  92. CV_ERROR( CV_StsOutOfRange, "params.regression_accuracy should be >= 0" );
  93. ok = true;
  94. __END__;
  95. return ok;
  96. }
  97. template<typename T>
  98. class LessThanPtr
  99. {
  100. public:
  101. bool operator()(T* a, T* b) const { return *a < *b; }
  102. };
  103. template<typename T, typename Idx>
  104. class LessThanIdx
  105. {
  106. public:
  107. LessThanIdx( const T* _arr ) : arr(_arr) {}
  108. bool operator()(Idx a, Idx b) const { return arr[a] < arr[b]; }
  109. const T* arr;
  110. };
  111. class LessThanPairs
  112. {
  113. public:
  114. bool operator()(const CvPair16u32s& a, const CvPair16u32s& b) const { return *a.i < *b.i; }
  115. };
  116. void CvDTreeTrainData::set_data( const CvMat* _train_data, int _tflag,
  117. const CvMat* _responses, const CvMat* _var_idx, const CvMat* _sample_idx,
  118. const CvMat* _var_type, const CvMat* _missing_mask, const CvDTreeParams& _params,
  119. bool _shared, bool _add_labels, bool _update_data )
  120. {
  121. CvMat* sample_indices = 0;
  122. CvMat* var_type0 = 0;
  123. CvMat* tmp_map = 0;
  124. int** int_ptr = 0;
  125. CvPair16u32s* pair16u32s_ptr = 0;
  126. CvDTreeTrainData* data = 0;
  127. float *_fdst = 0;
  128. int *_idst = 0;
  129. unsigned short* udst = 0;
  130. int* idst = 0;
  131. CV_FUNCNAME( "CvDTreeTrainData::set_data" );
  132. __BEGIN__;
  133. int sample_all = 0, r_type, cv_n;
  134. int total_c_count = 0;
  135. int tree_block_size, temp_block_size, max_split_size, nv_size, cv_size = 0;
  136. int ds_step, dv_step, ms_step = 0, mv_step = 0; // {data|mask}{sample|var}_step
  137. int vi, i, size;
  138. char err[100];
  139. const int *sidx = 0, *vidx = 0;
  140. uint64 effective_buf_size = 0;
  141. int effective_buf_height = 0, effective_buf_width = 0;
  142. if( _update_data && data_root )
  143. {
  144. data = new CvDTreeTrainData( _train_data, _tflag, _responses, _var_idx,
  145. _sample_idx, _var_type, _missing_mask, _params, _shared, _add_labels );
  146. // compare new and old train data
  147. if( !(data->var_count == var_count &&
  148. cvNorm( data->var_type, var_type, CV_C ) < FLT_EPSILON &&
  149. cvNorm( data->cat_count, cat_count, CV_C ) < FLT_EPSILON &&
  150. cvNorm( data->cat_map, cat_map, CV_C ) < FLT_EPSILON) )
  151. CV_ERROR( CV_StsBadArg,
  152. "The new training data must have the same types and the input and output variables "
  153. "and the same categories for categorical variables" );
  154. cvReleaseMat( &priors );
  155. cvReleaseMat( &priors_mult );
  156. cvReleaseMat( &buf );
  157. cvReleaseMat( &direction );
  158. cvReleaseMat( &split_buf );
  159. cvReleaseMemStorage( &temp_storage );
  160. priors = data->priors; data->priors = 0;
  161. priors_mult = data->priors_mult; data->priors_mult = 0;
  162. buf = data->buf; data->buf = 0;
  163. buf_count = data->buf_count; buf_size = data->buf_size;
  164. sample_count = data->sample_count;
  165. direction = data->direction; data->direction = 0;
  166. split_buf = data->split_buf; data->split_buf = 0;
  167. temp_storage = data->temp_storage; data->temp_storage = 0;
  168. nv_heap = data->nv_heap; cv_heap = data->cv_heap;
  169. data_root = new_node( 0, sample_count, 0, 0 );
  170. EXIT;
  171. }
  172. clear();
  173. var_all = 0;
  174. rng = &cv::theRNG();
  175. CV_CALL( set_params( _params ));
  176. // check parameter types and sizes
  177. CV_CALL( cvCheckTrainData( _train_data, _tflag, _missing_mask, &var_all, &sample_all ));
  178. train_data = _train_data;
  179. responses = _responses;
  180. if( _tflag == CV_ROW_SAMPLE )
  181. {
  182. ds_step = _train_data->step/CV_ELEM_SIZE(_train_data->type);
  183. dv_step = 1;
  184. if( _missing_mask )
  185. ms_step = _missing_mask->step, mv_step = 1;
  186. }
  187. else
  188. {
  189. dv_step = _train_data->step/CV_ELEM_SIZE(_train_data->type);
  190. ds_step = 1;
  191. if( _missing_mask )
  192. mv_step = _missing_mask->step, ms_step = 1;
  193. }
  194. tflag = _tflag;
  195. sample_count = sample_all;
  196. var_count = var_all;
  197. if( _sample_idx )
  198. {
  199. CV_CALL( sample_indices = cvPreprocessIndexArray( _sample_idx, sample_all ));
  200. sidx = sample_indices->data.i;
  201. sample_count = sample_indices->rows + sample_indices->cols - 1;
  202. }
  203. if( _var_idx )
  204. {
  205. CV_CALL( var_idx = cvPreprocessIndexArray( _var_idx, var_all ));
  206. vidx = var_idx->data.i;
  207. var_count = var_idx->rows + var_idx->cols - 1;
  208. }
  209. is_buf_16u = false;
  210. if ( sample_count < 65536 )
  211. is_buf_16u = true;
  212. if( !CV_IS_MAT(_responses) ||
  213. (CV_MAT_TYPE(_responses->type) != CV_32SC1 &&
  214. CV_MAT_TYPE(_responses->type) != CV_32FC1) ||
  215. (_responses->rows != 1 && _responses->cols != 1) ||
  216. _responses->rows + _responses->cols - 1 != sample_all )
  217. CV_ERROR( CV_StsBadArg, "The array of _responses must be an integer or "
  218. "floating-point vector containing as many elements as "
  219. "the total number of samples in the training data matrix" );
  220. r_type = CV_VAR_CATEGORICAL;
  221. if( _var_type )
  222. CV_CALL( var_type0 = cvPreprocessVarType( _var_type, var_idx, var_count, &r_type ));
  223. CV_CALL( var_type = cvCreateMat( 1, var_count+2, CV_32SC1 ));
  224. cat_var_count = 0;
  225. ord_var_count = -1;
  226. is_classifier = r_type == CV_VAR_CATEGORICAL;
  227. // step 0. calc the number of categorical vars
  228. for( vi = 0; vi < var_count; vi++ )
  229. {
  230. char vt = var_type0 ? var_type0->data.ptr[vi] : CV_VAR_ORDERED;
  231. var_type->data.i[vi] = vt == CV_VAR_CATEGORICAL ? cat_var_count++ : ord_var_count--;
  232. }
  233. ord_var_count = ~ord_var_count;
  234. cv_n = params.cv_folds;
  235. // set the two last elements of var_type array to be able
  236. // to locate responses and cross-validation labels using
  237. // the corresponding get_* functions.
  238. var_type->data.i[var_count] = cat_var_count;
  239. var_type->data.i[var_count+1] = cat_var_count+1;
  240. // in case of single ordered predictor we need dummy cv_labels
  241. // for safe split_node_data() operation
  242. have_labels = cv_n > 0 || (ord_var_count == 1 && cat_var_count == 0) || _add_labels;
  243. work_var_count = var_count + (is_classifier ? 1 : 0) // for responses class_labels
  244. + (have_labels ? 1 : 0); // for cv_labels
  245. shared = _shared;
  246. buf_count = shared ? 2 : 1;
  247. buf_size = -1; // the member buf_size is obsolete
  248. effective_buf_size = (uint64)(work_var_count + 1)*(uint64)sample_count * buf_count; // this is the total size of "CvMat buf" to be allocated
  249. effective_buf_width = sample_count;
  250. effective_buf_height = work_var_count+1;
  251. if (effective_buf_width >= effective_buf_height)
  252. effective_buf_height *= buf_count;
  253. else
  254. effective_buf_width *= buf_count;
  255. if ((uint64)effective_buf_width * (uint64)effective_buf_height != effective_buf_size)
  256. {
  257. CV_Error(CV_StsBadArg, "The memory buffer cannot be allocated since its size exceeds integer fields limit");
  258. }
  259. if ( is_buf_16u )
  260. {
  261. CV_CALL( buf = cvCreateMat( effective_buf_height, effective_buf_width, CV_16UC1 ));
  262. CV_CALL( pair16u32s_ptr = (CvPair16u32s*)cvAlloc( sample_count*sizeof(pair16u32s_ptr[0]) ));
  263. }
  264. else
  265. {
  266. CV_CALL( buf = cvCreateMat( effective_buf_height, effective_buf_width, CV_32SC1 ));
  267. CV_CALL( int_ptr = (int**)cvAlloc( sample_count*sizeof(int_ptr[0]) ));
  268. }
  269. size = is_classifier ? (cat_var_count+1) : cat_var_count;
  270. size = !size ? 1 : size;
  271. CV_CALL( cat_count = cvCreateMat( 1, size, CV_32SC1 ));
  272. CV_CALL( cat_ofs = cvCreateMat( 1, size, CV_32SC1 ));
  273. size = is_classifier ? (cat_var_count + 1)*params.max_categories : cat_var_count*params.max_categories;
  274. size = !size ? 1 : size;
  275. CV_CALL( cat_map = cvCreateMat( 1, size, CV_32SC1 ));
  276. // now calculate the maximum size of split,
  277. // create memory storage that will keep nodes and splits of the decision tree
  278. // allocate root node and the buffer for the whole training data
  279. max_split_size = cvAlign(sizeof(CvDTreeSplit) +
  280. (MAX(0,sample_count - 33)/32)*sizeof(int),sizeof(void*));
  281. tree_block_size = MAX((int)sizeof(CvDTreeNode)*8, max_split_size);
  282. tree_block_size = MAX(tree_block_size + block_size_delta, min_block_size);
  283. CV_CALL( tree_storage = cvCreateMemStorage( tree_block_size ));
  284. CV_CALL( node_heap = cvCreateSet( 0, sizeof(*node_heap), sizeof(CvDTreeNode), tree_storage ));
  285. nv_size = var_count*sizeof(int);
  286. nv_size = cvAlign(MAX( nv_size, (int)sizeof(CvSetElem) ), sizeof(void*));
  287. temp_block_size = nv_size;
  288. if( cv_n )
  289. {
  290. if( sample_count < cv_n*MAX(params.min_sample_count,10) )
  291. CV_ERROR( CV_StsOutOfRange,
  292. "The many folds in cross-validation for such a small dataset" );
  293. cv_size = cvAlign( cv_n*(sizeof(int) + sizeof(double)*2), sizeof(double) );
  294. temp_block_size = MAX(temp_block_size, cv_size);
  295. }
  296. temp_block_size = MAX( temp_block_size + block_size_delta, min_block_size );
  297. CV_CALL( temp_storage = cvCreateMemStorage( temp_block_size ));
  298. CV_CALL( nv_heap = cvCreateSet( 0, sizeof(*nv_heap), nv_size, temp_storage ));
  299. if( cv_size )
  300. CV_CALL( cv_heap = cvCreateSet( 0, sizeof(*cv_heap), cv_size, temp_storage ));
  301. CV_CALL( data_root = new_node( 0, sample_count, 0, 0 ));
  302. max_c_count = 1;
  303. _fdst = 0;
  304. _idst = 0;
  305. if (ord_var_count)
  306. _fdst = (float*)cvAlloc(sample_count*sizeof(_fdst[0]));
  307. if (is_buf_16u && (cat_var_count || is_classifier))
  308. _idst = (int*)cvAlloc(sample_count*sizeof(_idst[0]));
  309. // transform the training data to convenient representation
  310. for( vi = 0; vi <= var_count; vi++ )
  311. {
  312. int ci;
  313. const uchar* mask = 0;
  314. int64 m_step = 0, step;
  315. const int* idata = 0;
  316. const float* fdata = 0;
  317. int num_valid = 0;
  318. if( vi < var_count ) // analyze i-th input variable
  319. {
  320. int vi0 = vidx ? vidx[vi] : vi;
  321. ci = get_var_type(vi);
  322. step = ds_step; m_step = ms_step;
  323. if( CV_MAT_TYPE(_train_data->type) == CV_32SC1 )
  324. idata = _train_data->data.i + vi0*dv_step;
  325. else
  326. fdata = _train_data->data.fl + vi0*dv_step;
  327. if( _missing_mask )
  328. mask = _missing_mask->data.ptr + vi0*mv_step;
  329. }
  330. else // analyze _responses
  331. {
  332. ci = cat_var_count;
  333. step = CV_IS_MAT_CONT(_responses->type) ?
  334. 1 : _responses->step / CV_ELEM_SIZE(_responses->type);
  335. if( CV_MAT_TYPE(_responses->type) == CV_32SC1 )
  336. idata = _responses->data.i;
  337. else
  338. fdata = _responses->data.fl;
  339. }
  340. if( (vi < var_count && ci>=0) ||
  341. (vi == var_count && is_classifier) ) // process categorical variable or response
  342. {
  343. int c_count, prev_label;
  344. int* c_map;
  345. if (is_buf_16u)
  346. udst = (unsigned short*)(buf->data.s + (size_t)vi*sample_count);
  347. else
  348. idst = buf->data.i + (size_t)vi*sample_count;
  349. // copy data
  350. for( i = 0; i < sample_count; i++ )
  351. {
  352. int val = INT_MAX, si = sidx ? sidx[i] : i;
  353. if( !mask || !mask[(size_t)si*m_step] )
  354. {
  355. if( idata )
  356. val = idata[(size_t)si*step];
  357. else
  358. {
  359. float t = fdata[(size_t)si*step];
  360. val = cvRound(t);
  361. if( fabs(t - val) > FLT_EPSILON )
  362. {
  363. snprintf( err, sizeof(err), "%d-th value of %d-th (categorical) "
  364. "variable is not an integer", i, vi );
  365. CV_ERROR( CV_StsBadArg, err );
  366. }
  367. }
  368. if( val == INT_MAX )
  369. {
  370. snprintf( err, sizeof(err), "%d-th value of %d-th (categorical) "
  371. "variable is too large", i, vi );
  372. CV_ERROR( CV_StsBadArg, err );
  373. }
  374. num_valid++;
  375. }
  376. if (is_buf_16u)
  377. {
  378. _idst[i] = val;
  379. pair16u32s_ptr[i].u = udst + i;
  380. pair16u32s_ptr[i].i = _idst + i;
  381. }
  382. else
  383. {
  384. idst[i] = val;
  385. int_ptr[i] = idst + i;
  386. }
  387. }
  388. c_count = num_valid > 0;
  389. if (is_buf_16u)
  390. {
  391. std::sort(pair16u32s_ptr, pair16u32s_ptr + sample_count, LessThanPairs());
  392. // count the categories
  393. for( i = 1; i < num_valid; i++ )
  394. if (*pair16u32s_ptr[i].i != *pair16u32s_ptr[i-1].i)
  395. c_count ++ ;
  396. }
  397. else
  398. {
  399. std::sort(int_ptr, int_ptr + sample_count, LessThanPtr<int>());
  400. // count the categories
  401. for( i = 1; i < num_valid; i++ )
  402. c_count += *int_ptr[i] != *int_ptr[i-1];
  403. }
  404. if( vi > 0 )
  405. max_c_count = MAX( max_c_count, c_count );
  406. cat_count->data.i[ci] = c_count;
  407. cat_ofs->data.i[ci] = total_c_count;
  408. // resize cat_map, if need
  409. if( cat_map->cols < total_c_count + c_count )
  410. {
  411. tmp_map = cat_map;
  412. CV_CALL( cat_map = cvCreateMat( 1,
  413. MAX(cat_map->cols*3/2,total_c_count+c_count), CV_32SC1 ));
  414. for( i = 0; i < total_c_count; i++ )
  415. cat_map->data.i[i] = tmp_map->data.i[i];
  416. cvReleaseMat( &tmp_map );
  417. }
  418. c_map = cat_map->data.i + total_c_count;
  419. total_c_count += c_count;
  420. c_count = -1;
  421. if (is_buf_16u)
  422. {
  423. // compact the class indices and build the map
  424. prev_label = ~*pair16u32s_ptr[0].i;
  425. for( i = 0; i < num_valid; i++ )
  426. {
  427. int cur_label = *pair16u32s_ptr[i].i;
  428. if( cur_label != prev_label )
  429. c_map[++c_count] = prev_label = cur_label;
  430. *pair16u32s_ptr[i].u = (unsigned short)c_count;
  431. }
  432. // replace labels for missing values with -1
  433. for( ; i < sample_count; i++ )
  434. *pair16u32s_ptr[i].u = 65535;
  435. }
  436. else
  437. {
  438. // compact the class indices and build the map
  439. prev_label = ~*int_ptr[0];
  440. for( i = 0; i < num_valid; i++ )
  441. {
  442. int cur_label = *int_ptr[i];
  443. if( cur_label != prev_label )
  444. c_map[++c_count] = prev_label = cur_label;
  445. *int_ptr[i] = c_count;
  446. }
  447. // replace labels for missing values with -1
  448. for( ; i < sample_count; i++ )
  449. *int_ptr[i] = -1;
  450. }
  451. }
  452. else if( ci < 0 ) // process ordered variable
  453. {
  454. if (is_buf_16u)
  455. udst = (unsigned short*)(buf->data.s + (size_t)vi*sample_count);
  456. else
  457. idst = buf->data.i + (size_t)vi*sample_count;
  458. for( i = 0; i < sample_count; i++ )
  459. {
  460. float val = ord_nan;
  461. int si = sidx ? sidx[i] : i;
  462. if( !mask || !mask[(size_t)si*m_step] )
  463. {
  464. if( idata )
  465. val = (float)idata[(size_t)si*step];
  466. else
  467. val = fdata[(size_t)si*step];
  468. if( fabs(val) >= ord_nan )
  469. {
  470. snprintf( err, sizeof(err), "%d-th value of %d-th (ordered) "
  471. "variable (=%g) is too large", i, vi, val );
  472. CV_ERROR( CV_StsBadArg, err );
  473. }
  474. num_valid++;
  475. }
  476. if (is_buf_16u)
  477. udst[i] = (unsigned short)i; // TODO: memory corruption may be here
  478. else
  479. idst[i] = i;
  480. _fdst[i] = val;
  481. }
  482. if (is_buf_16u)
  483. std::sort(udst, udst + sample_count, LessThanIdx<float, unsigned short>(_fdst));
  484. else
  485. std::sort(idst, idst + sample_count, LessThanIdx<float, int>(_fdst));
  486. }
  487. if( vi < var_count )
  488. data_root->set_num_valid(vi, num_valid);
  489. }
  490. // set sample labels
  491. if (is_buf_16u)
  492. udst = (unsigned short*)(buf->data.s + (size_t)work_var_count*sample_count);
  493. else
  494. idst = buf->data.i + (size_t)work_var_count*sample_count;
  495. for (i = 0; i < sample_count; i++)
  496. {
  497. if (udst)
  498. udst[i] = sidx ? (unsigned short)sidx[i] : (unsigned short)i;
  499. else
  500. idst[i] = sidx ? sidx[i] : i;
  501. }
  502. if( cv_n )
  503. {
  504. unsigned short* usdst = 0;
  505. int* idst2 = 0;
  506. if (is_buf_16u)
  507. {
  508. usdst = (unsigned short*)(buf->data.s + (size_t)(get_work_var_count()-1)*sample_count);
  509. for( i = vi = 0; i < sample_count; i++ )
  510. {
  511. usdst[i] = (unsigned short)vi++;
  512. vi &= vi < cv_n ? -1 : 0;
  513. }
  514. for( i = 0; i < sample_count; i++ )
  515. {
  516. int a = (*rng)(sample_count);
  517. int b = (*rng)(sample_count);
  518. unsigned short unsh = (unsigned short)vi;
  519. CV_SWAP( usdst[a], usdst[b], unsh );
  520. }
  521. }
  522. else
  523. {
  524. idst2 = buf->data.i + (size_t)(get_work_var_count()-1)*sample_count;
  525. for( i = vi = 0; i < sample_count; i++ )
  526. {
  527. idst2[i] = vi++;
  528. vi &= vi < cv_n ? -1 : 0;
  529. }
  530. for( i = 0; i < sample_count; i++ )
  531. {
  532. int a = (*rng)(sample_count);
  533. int b = (*rng)(sample_count);
  534. CV_SWAP( idst2[a], idst2[b], vi );
  535. }
  536. }
  537. }
  538. if ( cat_map )
  539. cat_map->cols = MAX( total_c_count, 1 );
  540. max_split_size = cvAlign(sizeof(CvDTreeSplit) +
  541. (MAX(0,max_c_count - 33)/32)*sizeof(int),sizeof(void*));
  542. CV_CALL( split_heap = cvCreateSet( 0, sizeof(*split_heap), max_split_size, tree_storage ));
  543. have_priors = is_classifier && params.priors;
  544. if( is_classifier )
  545. {
  546. int m = get_num_classes();
  547. double sum = 0;
  548. CV_CALL( priors = cvCreateMat( 1, m, CV_64F ));
  549. for( i = 0; i < m; i++ )
  550. {
  551. double val = have_priors ? params.priors[i] : 1.;
  552. if( val <= 0 )
  553. CV_ERROR( CV_StsOutOfRange, "Every class weight should be positive" );
  554. priors->data.db[i] = val;
  555. sum += val;
  556. }
  557. // normalize weights
  558. if( have_priors )
  559. cvScale( priors, priors, 1./sum );
  560. CV_CALL( priors_mult = cvCloneMat( priors ));
  561. CV_CALL( counts = cvCreateMat( 1, m, CV_32SC1 ));
  562. }
  563. CV_CALL( direction = cvCreateMat( 1, sample_count, CV_8UC1 ));
  564. CV_CALL( split_buf = cvCreateMat( 1, sample_count, CV_32SC1 ));
  565. __END__;
  566. if( data )
  567. delete data;
  568. if (_fdst)
  569. cvFree( &_fdst );
  570. if (_idst)
  571. cvFree( &_idst );
  572. cvFree( &int_ptr );
  573. cvFree( &pair16u32s_ptr);
  574. cvReleaseMat( &var_type0 );
  575. cvReleaseMat( &sample_indices );
  576. cvReleaseMat( &tmp_map );
  577. }
  578. void CvDTreeTrainData::do_responses_copy()
  579. {
  580. responses_copy = cvCreateMat( responses->rows, responses->cols, responses->type );
  581. cvCopy( responses, responses_copy);
  582. responses = responses_copy;
  583. }
  584. CvDTreeNode* CvDTreeTrainData::subsample_data( const CvMat* _subsample_idx )
  585. {
  586. CvDTreeNode* root = 0;
  587. CvMat* isubsample_idx = 0;
  588. CvMat* subsample_co = 0;
  589. bool isMakeRootCopy = true;
  590. CV_FUNCNAME( "CvDTreeTrainData::subsample_data" );
  591. __BEGIN__;
  592. if( !data_root )
  593. CV_ERROR( CV_StsError, "No training data has been set" );
  594. if( _subsample_idx )
  595. {
  596. CV_CALL( isubsample_idx = cvPreprocessIndexArray( _subsample_idx, sample_count ));
  597. if( isubsample_idx->cols + isubsample_idx->rows - 1 == sample_count )
  598. {
  599. const int* sidx = isubsample_idx->data.i;
  600. for( int i = 0; i < sample_count; i++ )
  601. {
  602. if( sidx[i] != i )
  603. {
  604. isMakeRootCopy = false;
  605. break;
  606. }
  607. }
  608. }
  609. else
  610. isMakeRootCopy = false;
  611. }
  612. if( isMakeRootCopy )
  613. {
  614. // make a copy of the root node
  615. CvDTreeNode temp;
  616. int i;
  617. root = new_node( 0, 1, 0, 0 );
  618. temp = *root;
  619. *root = *data_root;
  620. root->num_valid = temp.num_valid;
  621. if( root->num_valid )
  622. {
  623. for( i = 0; i < var_count; i++ )
  624. root->num_valid[i] = data_root->num_valid[i];
  625. }
  626. root->cv_Tn = temp.cv_Tn;
  627. root->cv_node_risk = temp.cv_node_risk;
  628. root->cv_node_error = temp.cv_node_error;
  629. }
  630. else
  631. {
  632. int* sidx = isubsample_idx->data.i;
  633. // co - array of count/offset pairs (to handle duplicated values in _subsample_idx)
  634. int* co, cur_ofs = 0;
  635. int vi, i;
  636. int workVarCount = get_work_var_count();
  637. int count = isubsample_idx->rows + isubsample_idx->cols - 1;
  638. root = new_node( 0, count, 1, 0 );
  639. CV_CALL( subsample_co = cvCreateMat( 1, sample_count*2, CV_32SC1 ));
  640. cvZero( subsample_co );
  641. co = subsample_co->data.i;
  642. for( i = 0; i < count; i++ )
  643. co[sidx[i]*2]++;
  644. for( i = 0; i < sample_count; i++ )
  645. {
  646. if( co[i*2] )
  647. {
  648. co[i*2+1] = cur_ofs;
  649. cur_ofs += co[i*2];
  650. }
  651. else
  652. co[i*2+1] = -1;
  653. }
  654. cv::AutoBuffer<uchar> inn_buf(sample_count*(2*sizeof(int) + sizeof(float)));
  655. for( vi = 0; vi < workVarCount; vi++ )
  656. {
  657. int ci = get_var_type(vi);
  658. if( ci >= 0 || vi >= var_count )
  659. {
  660. int num_valid = 0;
  661. const int* src = CvDTreeTrainData::get_cat_var_data(data_root, vi, (int*)inn_buf.data());
  662. if (is_buf_16u)
  663. {
  664. unsigned short* udst = (unsigned short*)(buf->data.s + root->buf_idx*get_length_subbuf() +
  665. (size_t)vi*sample_count + root->offset);
  666. for( i = 0; i < count; i++ )
  667. {
  668. int val = src[sidx[i]];
  669. udst[i] = (unsigned short)val;
  670. num_valid += val >= 0;
  671. }
  672. }
  673. else
  674. {
  675. int* idst = buf->data.i + root->buf_idx*get_length_subbuf() +
  676. (size_t)vi*sample_count + root->offset;
  677. for( i = 0; i < count; i++ )
  678. {
  679. int val = src[sidx[i]];
  680. idst[i] = val;
  681. num_valid += val >= 0;
  682. }
  683. }
  684. if( vi < var_count )
  685. root->set_num_valid(vi, num_valid);
  686. }
  687. else
  688. {
  689. int *src_idx_buf = (int*)inn_buf.data();
  690. float *src_val_buf = (float*)(src_idx_buf + sample_count);
  691. int* sample_indices_buf = (int*)(src_val_buf + sample_count);
  692. const int* src_idx = 0;
  693. const float* src_val = 0;
  694. get_ord_var_data( data_root, vi, src_val_buf, src_idx_buf, &src_val, &src_idx, sample_indices_buf );
  695. int j = 0, idx, count_i;
  696. int num_valid = data_root->get_num_valid(vi);
  697. if (is_buf_16u)
  698. {
  699. unsigned short* udst_idx = (unsigned short*)(buf->data.s + root->buf_idx*get_length_subbuf() +
  700. (size_t)vi*sample_count + data_root->offset);
  701. for( i = 0; i < num_valid; i++ )
  702. {
  703. idx = src_idx[i];
  704. count_i = co[idx*2];
  705. if( count_i )
  706. for( cur_ofs = co[idx*2+1]; count_i > 0; count_i--, j++, cur_ofs++ )
  707. udst_idx[j] = (unsigned short)cur_ofs;
  708. }
  709. root->set_num_valid(vi, j);
  710. for( ; i < sample_count; i++ )
  711. {
  712. idx = src_idx[i];
  713. count_i = co[idx*2];
  714. if( count_i )
  715. for( cur_ofs = co[idx*2+1]; count_i > 0; count_i--, j++, cur_ofs++ )
  716. udst_idx[j] = (unsigned short)cur_ofs;
  717. }
  718. }
  719. else
  720. {
  721. int* idst_idx = buf->data.i + root->buf_idx*get_length_subbuf() +
  722. (size_t)vi*sample_count + root->offset;
  723. for( i = 0; i < num_valid; i++ )
  724. {
  725. idx = src_idx[i];
  726. count_i = co[idx*2];
  727. if( count_i )
  728. for( cur_ofs = co[idx*2+1]; count_i > 0; count_i--, j++, cur_ofs++ )
  729. idst_idx[j] = cur_ofs;
  730. }
  731. root->set_num_valid(vi, j);
  732. for( ; i < sample_count; i++ )
  733. {
  734. idx = src_idx[i];
  735. count_i = co[idx*2];
  736. if( count_i )
  737. for( cur_ofs = co[idx*2+1]; count_i > 0; count_i--, j++, cur_ofs++ )
  738. idst_idx[j] = cur_ofs;
  739. }
  740. }
  741. }
  742. }
  743. // sample indices subsampling
  744. const int* sample_idx_src = get_sample_indices(data_root, (int*)inn_buf.data());
  745. if (is_buf_16u)
  746. {
  747. unsigned short* sample_idx_dst = (unsigned short*)(buf->data.s + root->buf_idx*get_length_subbuf() +
  748. (size_t)workVarCount*sample_count + root->offset);
  749. for (i = 0; i < count; i++)
  750. sample_idx_dst[i] = (unsigned short)sample_idx_src[sidx[i]];
  751. }
  752. else
  753. {
  754. int* sample_idx_dst = buf->data.i + root->buf_idx*get_length_subbuf() +
  755. (size_t)workVarCount*sample_count + root->offset;
  756. for (i = 0; i < count; i++)
  757. sample_idx_dst[i] = sample_idx_src[sidx[i]];
  758. }
  759. }
  760. __END__;
  761. cvReleaseMat( &isubsample_idx );
  762. cvReleaseMat( &subsample_co );
  763. return root;
  764. }
  765. void CvDTreeTrainData::get_vectors( const CvMat* _subsample_idx,
  766. float* values, uchar* missing,
  767. float* _responses, bool get_class_idx )
  768. {
  769. CvMat* subsample_idx = 0;
  770. CvMat* subsample_co = 0;
  771. CV_FUNCNAME( "CvDTreeTrainData::get_vectors" );
  772. __BEGIN__;
  773. int i, vi, total = sample_count, count = total, cur_ofs = 0;
  774. int* sidx = 0;
  775. int* co = 0;
  776. cv::AutoBuffer<uchar> inn_buf(sample_count*(2*sizeof(int) + sizeof(float)));
  777. if( _subsample_idx )
  778. {
  779. CV_CALL( subsample_idx = cvPreprocessIndexArray( _subsample_idx, sample_count ));
  780. sidx = subsample_idx->data.i;
  781. CV_CALL( subsample_co = cvCreateMat( 1, sample_count*2, CV_32SC1 ));
  782. co = subsample_co->data.i;
  783. cvZero( subsample_co );
  784. count = subsample_idx->cols + subsample_idx->rows - 1;
  785. for( i = 0; i < count; i++ )
  786. co[sidx[i]*2]++;
  787. for( i = 0; i < total; i++ )
  788. {
  789. int count_i = co[i*2];
  790. if( count_i )
  791. {
  792. co[i*2+1] = cur_ofs*var_count;
  793. cur_ofs += count_i;
  794. }
  795. }
  796. }
  797. if( missing )
  798. memset( missing, 1, count*var_count );
  799. for( vi = 0; vi < var_count; vi++ )
  800. {
  801. int ci = get_var_type(vi);
  802. if( ci >= 0 ) // categorical
  803. {
  804. float* dst = values + vi;
  805. uchar* m = missing ? missing + vi : 0;
  806. const int* src = get_cat_var_data(data_root, vi, (int*)inn_buf.data());
  807. for( i = 0; i < count; i++, dst += var_count )
  808. {
  809. int idx = sidx ? sidx[i] : i;
  810. int val = src[idx];
  811. *dst = (float)val;
  812. if( m )
  813. {
  814. *m = (!is_buf_16u && val < 0) || (is_buf_16u && (val == 65535));
  815. m += var_count;
  816. }
  817. }
  818. }
  819. else // ordered
  820. {
  821. float* dst = values + vi;
  822. uchar* m = missing ? missing + vi : 0;
  823. int count1 = data_root->get_num_valid(vi);
  824. float *src_val_buf = (float*)inn_buf.data();
  825. int* src_idx_buf = (int*)(src_val_buf + sample_count);
  826. int* sample_indices_buf = src_idx_buf + sample_count;
  827. const float *src_val = 0;
  828. const int* src_idx = 0;
  829. get_ord_var_data(data_root, vi, src_val_buf, src_idx_buf, &src_val, &src_idx, sample_indices_buf);
  830. for( i = 0; i < count1; i++ )
  831. {
  832. int idx = src_idx[i];
  833. int count_i = 1;
  834. if( co )
  835. {
  836. count_i = co[idx*2];
  837. cur_ofs = co[idx*2+1];
  838. }
  839. else
  840. cur_ofs = idx*var_count;
  841. if( count_i )
  842. {
  843. float val = src_val[i];
  844. for( ; count_i > 0; count_i--, cur_ofs += var_count )
  845. {
  846. dst[cur_ofs] = val;
  847. if( m )
  848. m[cur_ofs] = 0;
  849. }
  850. }
  851. }
  852. }
  853. }
  854. // copy responses
  855. if( _responses )
  856. {
  857. if( is_classifier )
  858. {
  859. const int* src = get_class_labels(data_root, (int*)inn_buf.data());
  860. for( i = 0; i < count; i++ )
  861. {
  862. int idx = sidx ? sidx[i] : i;
  863. int val = get_class_idx ? src[idx] :
  864. cat_map->data.i[cat_ofs->data.i[cat_var_count]+src[idx]];
  865. _responses[i] = (float)val;
  866. }
  867. }
  868. else
  869. {
  870. float* val_buf = (float*)inn_buf.data();
  871. int* sample_idx_buf = (int*)(val_buf + sample_count);
  872. const float* _values = get_ord_responses(data_root, val_buf, sample_idx_buf);
  873. for( i = 0; i < count; i++ )
  874. {
  875. int idx = sidx ? sidx[i] : i;
  876. _responses[i] = _values[idx];
  877. }
  878. }
  879. }
  880. __END__;
  881. cvReleaseMat( &subsample_idx );
  882. cvReleaseMat( &subsample_co );
  883. }
  884. CvDTreeNode* CvDTreeTrainData::new_node( CvDTreeNode* parent, int count,
  885. int storage_idx, int offset )
  886. {
  887. CvDTreeNode* node = (CvDTreeNode*)cvSetNew( node_heap );
  888. node->sample_count = count;
  889. node->depth = parent ? parent->depth + 1 : 0;
  890. node->parent = parent;
  891. node->left = node->right = 0;
  892. node->split = 0;
  893. node->value = 0;
  894. node->class_idx = 0;
  895. node->maxlr = 0.;
  896. node->buf_idx = storage_idx;
  897. node->offset = offset;
  898. if( nv_heap )
  899. node->num_valid = (int*)cvSetNew( nv_heap );
  900. else
  901. node->num_valid = 0;
  902. node->alpha = node->node_risk = node->tree_risk = node->tree_error = 0.;
  903. node->complexity = 0;
  904. if( params.cv_folds > 0 && cv_heap )
  905. {
  906. int cv_n = params.cv_folds;
  907. node->Tn = INT_MAX;
  908. node->cv_Tn = (int*)cvSetNew( cv_heap );
  909. node->cv_node_risk = (double*)cvAlignPtr(node->cv_Tn + cv_n, sizeof(double));
  910. node->cv_node_error = node->cv_node_risk + cv_n;
  911. }
  912. else
  913. {
  914. node->Tn = 0;
  915. node->cv_Tn = 0;
  916. node->cv_node_risk = 0;
  917. node->cv_node_error = 0;
  918. }
  919. return node;
  920. }
  921. CvDTreeSplit* CvDTreeTrainData::new_split_ord( int vi, float cmp_val,
  922. int split_point, int inversed, float quality )
  923. {
  924. CvDTreeSplit* split = (CvDTreeSplit*)cvSetNew( split_heap );
  925. split->var_idx = vi;
  926. split->condensed_idx = INT_MIN;
  927. split->ord.c = cmp_val;
  928. split->ord.split_point = split_point;
  929. split->inversed = inversed;
  930. split->quality = quality;
  931. split->next = 0;
  932. return split;
  933. }
  934. CvDTreeSplit* CvDTreeTrainData::new_split_cat( int vi, float quality )
  935. {
  936. CvDTreeSplit* split = (CvDTreeSplit*)cvSetNew( split_heap );
  937. int i, n = (max_c_count + 31)/32;
  938. split->var_idx = vi;
  939. split->condensed_idx = INT_MIN;
  940. split->inversed = 0;
  941. split->quality = quality;
  942. for( i = 0; i < n; i++ )
  943. split->subset[i] = 0;
  944. split->next = 0;
  945. return split;
  946. }
  947. void CvDTreeTrainData::free_node( CvDTreeNode* node )
  948. {
  949. CvDTreeSplit* split = node->split;
  950. free_node_data( node );
  951. while( split )
  952. {
  953. CvDTreeSplit* next = split->next;
  954. cvSetRemoveByPtr( split_heap, split );
  955. split = next;
  956. }
  957. node->split = 0;
  958. cvSetRemoveByPtr( node_heap, node );
  959. }
  960. void CvDTreeTrainData::free_node_data( CvDTreeNode* node )
  961. {
  962. if( node->num_valid )
  963. {
  964. cvSetRemoveByPtr( nv_heap, node->num_valid );
  965. node->num_valid = 0;
  966. }
  967. // do not free cv_* fields, as all the cross-validation related data is released at once.
  968. }
  969. void CvDTreeTrainData::free_train_data()
  970. {
  971. cvReleaseMat( &counts );
  972. cvReleaseMat( &buf );
  973. cvReleaseMat( &direction );
  974. cvReleaseMat( &split_buf );
  975. cvReleaseMemStorage( &temp_storage );
  976. cvReleaseMat( &responses_copy );
  977. cv_heap = nv_heap = 0;
  978. }
  979. void CvDTreeTrainData::clear()
  980. {
  981. free_train_data();
  982. cvReleaseMemStorage( &tree_storage );
  983. cvReleaseMat( &var_idx );
  984. cvReleaseMat( &var_type );
  985. cvReleaseMat( &cat_count );
  986. cvReleaseMat( &cat_ofs );
  987. cvReleaseMat( &cat_map );
  988. cvReleaseMat( &priors );
  989. cvReleaseMat( &priors_mult );
  990. node_heap = split_heap = 0;
  991. sample_count = var_all = var_count = max_c_count = ord_var_count = cat_var_count = 0;
  992. have_labels = have_priors = is_classifier = false;
  993. buf_count = buf_size = 0;
  994. shared = false;
  995. data_root = 0;
  996. rng = &cv::theRNG();
  997. }
  998. int CvDTreeTrainData::get_num_classes() const
  999. {
  1000. return is_classifier ? cat_count->data.i[cat_var_count] : 0;
  1001. }
  1002. int CvDTreeTrainData::get_var_type(int vi) const
  1003. {
  1004. return var_type->data.i[vi];
  1005. }
  1006. void CvDTreeTrainData::get_ord_var_data( CvDTreeNode* n, int vi, float* ord_values_buf, int* sorted_indices_buf,
  1007. const float** ord_values, const int** sorted_indices, int* sample_indices_buf )
  1008. {
  1009. int vidx = var_idx ? var_idx->data.i[vi] : vi;
  1010. int node_sample_count = n->sample_count;
  1011. int td_step = train_data->step/CV_ELEM_SIZE(train_data->type);
  1012. const int* sample_indices = get_sample_indices(n, sample_indices_buf);
  1013. if( !is_buf_16u )
  1014. *sorted_indices = buf->data.i + n->buf_idx*get_length_subbuf() +
  1015. (size_t)vi*sample_count + n->offset;
  1016. else {
  1017. const unsigned short* short_indices = (const unsigned short*)(buf->data.s + n->buf_idx*get_length_subbuf() +
  1018. (size_t)vi*sample_count + n->offset );
  1019. for( int i = 0; i < node_sample_count; i++ )
  1020. sorted_indices_buf[i] = short_indices[i];
  1021. *sorted_indices = sorted_indices_buf;
  1022. }
  1023. if( tflag == CV_ROW_SAMPLE )
  1024. {
  1025. for( int i = 0; i < node_sample_count &&
  1026. ((((*sorted_indices)[i] >= 0) && !is_buf_16u) || (((*sorted_indices)[i] != 65535) && is_buf_16u)); i++ )
  1027. {
  1028. int idx = (*sorted_indices)[i];
  1029. idx = sample_indices[idx];
  1030. ord_values_buf[i] = *(train_data->data.fl + idx * td_step + vidx);
  1031. }
  1032. }
  1033. else
  1034. for( int i = 0; i < node_sample_count &&
  1035. ((((*sorted_indices)[i] >= 0) && !is_buf_16u) || (((*sorted_indices)[i] != 65535) && is_buf_16u)); i++ )
  1036. {
  1037. int idx = (*sorted_indices)[i];
  1038. idx = sample_indices[idx];
  1039. ord_values_buf[i] = *(train_data->data.fl + vidx* td_step + idx);
  1040. }
  1041. *ord_values = ord_values_buf;
  1042. }
  1043. const int* CvDTreeTrainData::get_class_labels( CvDTreeNode* n, int* labels_buf )
  1044. {
  1045. if (is_classifier)
  1046. return get_cat_var_data( n, var_count, labels_buf);
  1047. return 0;
  1048. }
  1049. const int* CvDTreeTrainData::get_sample_indices( CvDTreeNode* n, int* indices_buf )
  1050. {
  1051. return get_cat_var_data( n, get_work_var_count(), indices_buf );
  1052. }
  1053. const float* CvDTreeTrainData::get_ord_responses( CvDTreeNode* n, float* values_buf, int*sample_indices_buf )
  1054. {
  1055. int _sample_count = n->sample_count;
  1056. int r_step = CV_IS_MAT_CONT(responses->type) ? 1 : responses->step/CV_ELEM_SIZE(responses->type);
  1057. const int* indices = get_sample_indices(n, sample_indices_buf);
  1058. for( int i = 0; i < _sample_count &&
  1059. (((indices[i] >= 0) && !is_buf_16u) || ((indices[i] != 65535) && is_buf_16u)); i++ )
  1060. {
  1061. int idx = indices[i];
  1062. values_buf[i] = *(responses->data.fl + idx * r_step);
  1063. }
  1064. return values_buf;
  1065. }
  1066. const int* CvDTreeTrainData::get_cv_labels( CvDTreeNode* n, int* labels_buf )
  1067. {
  1068. if (have_labels)
  1069. return get_cat_var_data( n, get_work_var_count()- 1, labels_buf);
  1070. return 0;
  1071. }
  1072. const int* CvDTreeTrainData::get_cat_var_data( CvDTreeNode* n, int vi, int* cat_values_buf)
  1073. {
  1074. const int* cat_values = 0;
  1075. if( !is_buf_16u )
  1076. cat_values = buf->data.i + n->buf_idx*get_length_subbuf() +
  1077. (size_t)vi*sample_count + n->offset;
  1078. else {
  1079. const unsigned short* short_values = (const unsigned short*)(buf->data.s + n->buf_idx*get_length_subbuf() +
  1080. (size_t)vi*sample_count + n->offset);
  1081. for( int i = 0; i < n->sample_count; i++ )
  1082. cat_values_buf[i] = short_values[i];
  1083. cat_values = cat_values_buf;
  1084. }
  1085. return cat_values;
  1086. }
  1087. int CvDTreeTrainData::get_child_buf_idx( CvDTreeNode* n )
  1088. {
  1089. int idx = n->buf_idx + 1;
  1090. if( idx >= buf_count )
  1091. idx = shared ? 1 : 0;
  1092. return idx;
  1093. }
  1094. void CvDTreeTrainData::write_params( cv::FileStorage& fs ) const
  1095. {
  1096. CV_FUNCNAME( "CvDTreeTrainData::write_params" );
  1097. __BEGIN__;
  1098. int vi, vcount = var_count;
  1099. fs.write( "is_classifier", is_classifier ? 1 : 0 );
  1100. fs.write( "var_all", var_all );
  1101. fs.write( "var_count", var_count );
  1102. fs.write( "ord_var_count", ord_var_count );
  1103. fs.write( "cat_var_count", cat_var_count );
  1104. fs.startWriteStruct( "training_params", FileNode::MAP );
  1105. fs.write( "use_surrogates", params.use_surrogates ? 1 : 0 );
  1106. if( is_classifier )
  1107. {
  1108. fs.write( "max_categories", params.max_categories );
  1109. }
  1110. else
  1111. {
  1112. fs.write( "regression_accuracy", params.regression_accuracy );
  1113. }
  1114. fs.write( "max_depth", params.max_depth );
  1115. fs.write( "min_sample_count", params.min_sample_count );
  1116. fs.write( "cross_validation_folds", params.cv_folds );
  1117. if( params.cv_folds > 1 )
  1118. {
  1119. fs.write( "use_1se_rule", params.use_1se_rule ? 1 : 0 );
  1120. fs.write( "truncate_pruned_tree", params.truncate_pruned_tree ? 1 : 0 );
  1121. }
  1122. if( priors )
  1123. fs.write( "priors", cvarrToMat(priors) );
  1124. fs.endWriteStruct();
  1125. if( var_idx )
  1126. fs.write( "var_idx", cvarrToMat(var_idx) );
  1127. fs.startWriteStruct("var_type", FileNode::SEQ + FileNode::FLOW );
  1128. for( vi = 0; vi < vcount; vi++ )
  1129. fs.write( 0, var_type->data.i[vi] >= 0 );
  1130. fs.endWriteStruct();
  1131. if( cat_count && (cat_var_count > 0 || is_classifier) )
  1132. {
  1133. CV_ASSERT( cat_count != 0 );
  1134. fs.write( "cat_count", cvarrToMat(cat_count) );
  1135. fs.write( "cat_map", cvarrToMat(cat_map) );
  1136. }
  1137. __END__;
  1138. }
  1139. void CvDTreeTrainData::read_params( const cv::FileNode& node )
  1140. {
  1141. CV_FUNCNAME( "CvDTreeTrainData::read_params" );
  1142. __BEGIN__;
  1143. cv::FileNode tparams_node, vartype_node;
  1144. FileNodeIterator reader;
  1145. int vi, max_split_size, tree_block_size;
  1146. is_classifier = (int) node[ "is_classifier" ] != 0;
  1147. var_all = (int) node[ "var_all" ];
  1148. var_count = node[ "var_count" ].empty() ? var_all : (int)node[ "var_count" ];
  1149. cat_var_count = (int) node[ "cat_var_count" ];
  1150. ord_var_count = (int) node[ "ord_var_count" ];
  1151. tparams_node = node[ "training_params" ];
  1152. if( !tparams_node.empty() ) // training parameters are not necessary
  1153. {
  1154. params.use_surrogates = (tparams_node[ "use_surrogates" ].empty() ? 1 : (int)tparams_node[ "use_surrogates" ] ) != 0;
  1155. if( is_classifier )
  1156. {
  1157. params.max_categories = (int) tparams_node[ "max_categories" ];
  1158. }
  1159. else
  1160. {
  1161. params.regression_accuracy = (float) tparams_node[ "regression_accuracy" ];
  1162. }
  1163. params.max_depth = (int) tparams_node[ "max_depth" ];
  1164. params.min_sample_count = (int) tparams_node[ "min_sample_count" ];
  1165. params.cv_folds = (int) tparams_node[ "cross_validation_folds" ];
  1166. if( params.cv_folds > 1 )
  1167. {
  1168. params.use_1se_rule = (int)tparams_node[ "use_1se_rule" ] != 0;
  1169. params.truncate_pruned_tree = (int) tparams_node[ "truncate_pruned_tree" ] != 0;
  1170. }
  1171. priors = nullptr;
  1172. if(!tparams_node[ "priors" ].empty())
  1173. {
  1174. auto tmat = cvMat( tparams_node[ "priors" ].mat() );
  1175. priors = cvCloneMat( &tmat );
  1176. if( !CV_IS_MAT(priors) )
  1177. CV_ERROR( CV_StsParseError, "priors must stored as a matrix" );
  1178. priors_mult = cvCloneMat( priors );
  1179. }
  1180. }
  1181. var_idx = nullptr;
  1182. if (!node[ "var_idx" ].empty())
  1183. {
  1184. auto tmat = cvMat( tparams_node[ "var_idx" ].mat() );
  1185. var_idx = cvCloneMat( &tmat );
  1186. }
  1187. if( var_idx )
  1188. {
  1189. if( !CV_IS_MAT(var_idx) ||
  1190. (var_idx->cols != 1 && var_idx->rows != 1) ||
  1191. var_idx->cols + var_idx->rows - 1 != var_count ||
  1192. CV_MAT_TYPE(var_idx->type) != CV_32SC1 )
  1193. CV_ERROR( CV_StsParseError,
  1194. "var_idx (if exist) must be valid 1d integer vector containing <var_count> elements" );
  1195. for( vi = 0; vi < var_count; vi++ )
  1196. if( (unsigned)var_idx->data.i[vi] >= (unsigned)var_all )
  1197. CV_ERROR( CV_StsOutOfRange, "some of var_idx elements are out of range" );
  1198. }
  1199. ////// read var type
  1200. CV_CALL( var_type = cvCreateMat( 1, var_count + 2, CV_32SC1 ));
  1201. cat_var_count = 0;
  1202. ord_var_count = -1;
  1203. vartype_node = node[ "var_type" ];
  1204. if( !vartype_node.empty() && vartype_node.isInt() && var_count == 1 )
  1205. var_type->data.i[0] = (int)vartype_node ? cat_var_count++ : ord_var_count--;
  1206. else
  1207. {
  1208. if( vartype_node.empty() || !vartype_node.isSeq() ||
  1209. vartype_node.size() != (size_t) var_count )
  1210. CV_ERROR( CV_StsParseError, "var_type must exist and be a sequence of 0's and 1's" );
  1211. reader = vartype_node.begin();
  1212. for( vi = 0; vi < var_count; vi++ )
  1213. {
  1214. cv::FileNode n = *reader;
  1215. if( !n.isInt() || ((int) n & ~1) )
  1216. CV_ERROR( CV_StsParseError, "var_type must exist and be a sequence of 0's and 1's" );
  1217. var_type->data.i[vi] = (int) n ? cat_var_count++ : ord_var_count--;
  1218. reader++;
  1219. }
  1220. }
  1221. var_type->data.i[var_count] = cat_var_count;
  1222. ord_var_count = ~ord_var_count;
  1223. //////
  1224. if( cat_var_count > 0 || is_classifier )
  1225. {
  1226. int ccount, total_c_count = 0;
  1227. auto cat_count_m = cvMat( node["cat_count"].mat() );
  1228. cat_count = cvCloneMat( &cat_count_m );
  1229. auto cat_map_m = cvMat( node[ "cat_map" ].mat() );
  1230. cat_map = cvCloneMat( &cat_map_m );
  1231. if( !CV_IS_MAT(cat_count) || !CV_IS_MAT(cat_map) ||
  1232. (cat_count->cols != 1 && cat_count->rows != 1) ||
  1233. CV_MAT_TYPE(cat_count->type) != CV_32SC1 ||
  1234. cat_count->cols + cat_count->rows - 1 != cat_var_count + is_classifier ||
  1235. (cat_map->cols != 1 && cat_map->rows != 1) ||
  1236. CV_MAT_TYPE(cat_map->type) != CV_32SC1 )
  1237. CV_ERROR( CV_StsParseError,
  1238. "Both cat_count and cat_map must exist and be valid 1d integer vectors of an appropriate size" );
  1239. ccount = cat_var_count + is_classifier;
  1240. CV_CALL( cat_ofs = cvCreateMat( 1, ccount + 1, CV_32SC1 ));
  1241. cat_ofs->data.i[0] = 0;
  1242. max_c_count = 1;
  1243. for( vi = 0; vi < ccount; vi++ )
  1244. {
  1245. int val = cat_count->data.i[vi];
  1246. if( val <= 0 )
  1247. CV_ERROR( CV_StsOutOfRange, "some of cat_count elements are out of range" );
  1248. max_c_count = MAX( max_c_count, val );
  1249. cat_ofs->data.i[vi+1] = total_c_count += val;
  1250. }
  1251. if( cat_map->cols + cat_map->rows - 1 != total_c_count )
  1252. CV_ERROR( CV_StsBadSize,
  1253. "cat_map vector length is not equal to the total number of categories in all categorical vars" );
  1254. }
  1255. max_split_size = cvAlign(sizeof(CvDTreeSplit) +
  1256. (MAX(0,max_c_count - 33)/32)*sizeof(int),sizeof(void*));
  1257. tree_block_size = MAX((int)sizeof(CvDTreeNode)*8, max_split_size);
  1258. tree_block_size = MAX(tree_block_size + block_size_delta, min_block_size);
  1259. CV_CALL( tree_storage = cvCreateMemStorage( tree_block_size ));
  1260. CV_CALL( node_heap = cvCreateSet( 0, sizeof(node_heap[0]),
  1261. sizeof(CvDTreeNode), tree_storage ));
  1262. CV_CALL( split_heap = cvCreateSet( 0, sizeof(split_heap[0]),
  1263. max_split_size, tree_storage ));
  1264. __END__;
  1265. }
  1266. /////////////////////// Decision Tree /////////////////////////
  1267. CvDTreeParams::CvDTreeParams() : max_categories(10), max_depth(INT_MAX), min_sample_count(10),
  1268. cv_folds(10), use_surrogates(true), use_1se_rule(true),
  1269. truncate_pruned_tree(true), regression_accuracy(0.01f), priors(0)
  1270. {}
  1271. CvDTreeParams::CvDTreeParams( int _max_depth, int _min_sample_count,
  1272. float _regression_accuracy, bool _use_surrogates,
  1273. int _max_categories, int _cv_folds,
  1274. bool _use_1se_rule, bool _truncate_pruned_tree,
  1275. const float* _priors ) :
  1276. max_categories(_max_categories), max_depth(_max_depth),
  1277. min_sample_count(_min_sample_count), cv_folds (_cv_folds),
  1278. use_surrogates(_use_surrogates), use_1se_rule(_use_1se_rule),
  1279. truncate_pruned_tree(_truncate_pruned_tree),
  1280. regression_accuracy(_regression_accuracy),
  1281. priors(_priors)
  1282. {}
  1283. CvDTree::CvDTree()
  1284. {
  1285. data = 0;
  1286. var_importance = 0;
  1287. default_model_name = "my_tree";
  1288. clear();
  1289. }
  1290. void CvDTree::clear()
  1291. {
  1292. cvReleaseMat( &var_importance );
  1293. if( data )
  1294. {
  1295. if( !data->shared )
  1296. delete data;
  1297. else
  1298. free_tree();
  1299. data = 0;
  1300. }
  1301. root = 0;
  1302. pruned_tree_idx = -1;
  1303. }
  1304. CvDTree::~CvDTree()
  1305. {
  1306. clear();
  1307. }
  1308. const CvDTreeNode* CvDTree::get_root() const
  1309. {
  1310. return root;
  1311. }
  1312. int CvDTree::get_pruned_tree_idx() const
  1313. {
  1314. return pruned_tree_idx;
  1315. }
  1316. CvDTreeTrainData* CvDTree::get_data()
  1317. {
  1318. return data;
  1319. }
  1320. bool CvDTree::train( const CvMat* _train_data, int _tflag,
  1321. const CvMat* _responses, const CvMat* _var_idx,
  1322. const CvMat* _sample_idx, const CvMat* _var_type,
  1323. const CvMat* _missing_mask, CvDTreeParams _params )
  1324. {
  1325. bool result = false;
  1326. CV_FUNCNAME( "CvDTree::train" );
  1327. __BEGIN__;
  1328. clear();
  1329. data = new CvDTreeTrainData( _train_data, _tflag, _responses,
  1330. _var_idx, _sample_idx, _var_type,
  1331. _missing_mask, _params, false );
  1332. CV_CALL( result = do_train(0) );
  1333. __END__;
  1334. return result;
  1335. }
  1336. bool CvDTree::train( const Mat& _train_data, int _tflag,
  1337. const Mat& _responses, const Mat& _var_idx,
  1338. const Mat& _sample_idx, const Mat& _var_type,
  1339. const Mat& _missing_mask, CvDTreeParams _params )
  1340. {
  1341. train_data_hdr = cvMat(_train_data);
  1342. train_data_mat = _train_data;
  1343. responses_hdr = cvMat(_responses);
  1344. responses_mat = _responses;
  1345. CvMat vidx=cvMat(_var_idx), sidx=cvMat(_sample_idx), vtype=cvMat(_var_type), mmask=cvMat(_missing_mask);
  1346. return train(&train_data_hdr, _tflag, &responses_hdr, vidx.data.ptr ? &vidx : 0, sidx.data.ptr ? &sidx : 0,
  1347. vtype.data.ptr ? &vtype : 0, mmask.data.ptr ? &mmask : 0, _params);
  1348. }
  1349. bool CvDTree::train( CvMLData* _data, CvDTreeParams _params )
  1350. {
  1351. bool result = false;
  1352. CV_FUNCNAME( "CvDTree::train" );
  1353. __BEGIN__;
  1354. const CvMat* values = _data->get_values();
  1355. const CvMat* response = _data->get_responses();
  1356. const CvMat* missing = _data->get_missing();
  1357. const CvMat* var_types = _data->get_var_types();
  1358. const CvMat* train_sidx = _data->get_train_sample_idx();
  1359. const CvMat* var_idx = _data->get_var_idx();
  1360. CV_CALL( result = train( values, CV_ROW_SAMPLE, response, var_idx,
  1361. train_sidx, var_types, missing, _params ) );
  1362. __END__;
  1363. return result;
  1364. }
  1365. bool CvDTree::train( CvDTreeTrainData* _data, const CvMat* _subsample_idx )
  1366. {
  1367. bool result = false;
  1368. CV_FUNCNAME( "CvDTree::train" );
  1369. __BEGIN__;
  1370. clear();
  1371. data = _data;
  1372. data->shared = true;
  1373. CV_CALL( result = do_train(_subsample_idx));
  1374. __END__;
  1375. return result;
  1376. }
  1377. bool CvDTree::do_train( const CvMat* _subsample_idx )
  1378. {
  1379. bool result = false;
  1380. CV_FUNCNAME( "CvDTree::do_train" );
  1381. __BEGIN__;
  1382. root = data->subsample_data( _subsample_idx );
  1383. CV_CALL( try_split_node(root));
  1384. if( root->split )
  1385. {
  1386. CV_Assert( root->left );
  1387. CV_Assert( root->right );
  1388. if( data->params.cv_folds > 0 )
  1389. CV_CALL( prune_cv() );
  1390. if( !data->shared )
  1391. data->free_train_data();
  1392. result = true;
  1393. }
  1394. __END__;
  1395. return result;
  1396. }
  1397. void CvDTree::try_split_node( CvDTreeNode* node )
  1398. {
  1399. CvDTreeSplit* best_split = 0;
  1400. int i, n = node->sample_count, vi;
  1401. bool can_split = true;
  1402. double quality_scale;
  1403. calc_node_value( node );
  1404. if( node->sample_count <= data->params.min_sample_count ||
  1405. node->depth >= data->params.max_depth )
  1406. can_split = false;
  1407. if( can_split && data->is_classifier )
  1408. {
  1409. // check if we have a "pure" node,
  1410. // we assume that cls_count is filled by calc_node_value()
  1411. int* cls_count = data->counts->data.i;
  1412. int nz = 0, m = data->get_num_classes();
  1413. for( i = 0; i < m; i++ )
  1414. nz += cls_count[i] != 0;
  1415. if( nz == 1 ) // there is only one class
  1416. can_split = false;
  1417. }
  1418. else if( can_split )
  1419. {
  1420. if( sqrt(node->node_risk)/n < data->params.regression_accuracy )
  1421. can_split = false;
  1422. }
  1423. if( can_split )
  1424. {
  1425. best_split = find_best_split(node);
  1426. // TODO: check the split quality ...
  1427. node->split = best_split;
  1428. }
  1429. if( !can_split || !best_split )
  1430. {
  1431. data->free_node_data(node);
  1432. return;
  1433. }
  1434. quality_scale = calc_node_dir( node );
  1435. if( data->params.use_surrogates )
  1436. {
  1437. // find all the surrogate splits
  1438. // and sort them by their similarity to the primary one
  1439. for( vi = 0; vi < data->var_count; vi++ )
  1440. {
  1441. CvDTreeSplit* split;
  1442. int ci = data->get_var_type(vi);
  1443. if( vi == best_split->var_idx )
  1444. continue;
  1445. if( ci >= 0 )
  1446. split = find_surrogate_split_cat( node, vi );
  1447. else
  1448. split = find_surrogate_split_ord( node, vi );
  1449. if( split )
  1450. {
  1451. // insert the split
  1452. CvDTreeSplit* prev_split = node->split;
  1453. split->quality = (float)(split->quality*quality_scale);
  1454. while( prev_split->next &&
  1455. prev_split->next->quality > split->quality )
  1456. prev_split = prev_split->next;
  1457. split->next = prev_split->next;
  1458. prev_split->next = split;
  1459. }
  1460. }
  1461. }
  1462. split_node_data( node );
  1463. try_split_node( node->left );
  1464. try_split_node( node->right );
  1465. }
  1466. // calculate direction (left(-1),right(1),missing(0))
  1467. // for each sample using the best split
  1468. // the function returns scale coefficients for surrogate split quality factors.
  1469. // the scale is applied to normalize surrogate split quality relatively to the
  1470. // best (primary) split quality. That is, if a surrogate split is absolutely
  1471. // identical to the primary split, its quality will be set to the maximum value =
  1472. // quality of the primary split; otherwise, it will be lower.
  1473. // besides, the function compute node->maxlr,
  1474. // minimum possible quality (w/o considering the above mentioned scale)
  1475. // for a surrogate split. Surrogate splits with quality less than node->maxlr
  1476. // are not discarded.
  1477. double CvDTree::calc_node_dir( CvDTreeNode* node )
  1478. {
  1479. char* dir = (char*)data->direction->data.ptr;
  1480. int i, n = node->sample_count, vi = node->split->var_idx;
  1481. double L, R;
  1482. assert( !node->split->inversed );
  1483. if( data->get_var_type(vi) >= 0 ) // split on categorical var
  1484. {
  1485. cv::AutoBuffer<int> inn_buf(n*(!data->have_priors ? 1 : 2));
  1486. int* labels_buf = inn_buf.data();
  1487. const int* labels = data->get_cat_var_data( node, vi, labels_buf );
  1488. const int* subset = node->split->subset;
  1489. if( !data->have_priors )
  1490. {
  1491. int sum = 0, sum_abs = 0;
  1492. for( i = 0; i < n; i++ )
  1493. {
  1494. int idx = labels[i];
  1495. int d = ( ((idx >= 0)&&(!data->is_buf_16u)) || ((idx != 65535)&&(data->is_buf_16u)) ) ?
  1496. CV_DTREE_CAT_DIR(idx,subset) : 0;
  1497. sum += d; sum_abs += d & 1;
  1498. dir[i] = (char)d;
  1499. }
  1500. R = (sum_abs + sum) >> 1;
  1501. L = (sum_abs - sum) >> 1;
  1502. }
  1503. else
  1504. {
  1505. const double* priors = data->priors_mult->data.db;
  1506. double sum = 0, sum_abs = 0;
  1507. int* responses_buf = labels_buf + n;
  1508. const int* responses = data->get_class_labels(node, responses_buf);
  1509. for( i = 0; i < n; i++ )
  1510. {
  1511. int idx = labels[i];
  1512. double w = priors[responses[i]];
  1513. int d = idx >= 0 ? CV_DTREE_CAT_DIR(idx,subset) : 0;
  1514. sum += d*w; sum_abs += (d & 1)*w;
  1515. dir[i] = (char)d;
  1516. }
  1517. R = (sum_abs + sum) * 0.5;
  1518. L = (sum_abs - sum) * 0.5;
  1519. }
  1520. }
  1521. else // split on ordered var
  1522. {
  1523. int split_point = node->split->ord.split_point;
  1524. int n1 = node->get_num_valid(vi);
  1525. cv::AutoBuffer<uchar> inn_buf(n*(sizeof(int)*(data->have_priors ? 3 : 2) + sizeof(float)));
  1526. float* val_buf = (float*)inn_buf.data();
  1527. int* sorted_buf = (int*)(val_buf + n);
  1528. int* sample_idx_buf = sorted_buf + n;
  1529. const float* val = 0;
  1530. const int* sorted = 0;
  1531. data->get_ord_var_data( node, vi, val_buf, sorted_buf, &val, &sorted, sample_idx_buf);
  1532. assert( 0 <= split_point && split_point < n1-1 );
  1533. if( !data->have_priors )
  1534. {
  1535. for( i = 0; i <= split_point; i++ )
  1536. dir[sorted[i]] = (char)-1;
  1537. for( ; i < n1; i++ )
  1538. dir[sorted[i]] = (char)1;
  1539. for( ; i < n; i++ )
  1540. dir[sorted[i]] = (char)0;
  1541. L = split_point-1;
  1542. R = n1 - split_point + 1;
  1543. }
  1544. else
  1545. {
  1546. const double* priors = data->priors_mult->data.db;
  1547. int* responses_buf = sample_idx_buf + n;
  1548. const int* responses = data->get_class_labels(node, responses_buf);
  1549. L = R = 0;
  1550. for( i = 0; i <= split_point; i++ )
  1551. {
  1552. int idx = sorted[i];
  1553. double w = priors[responses[idx]];
  1554. dir[idx] = (char)-1;
  1555. L += w;
  1556. }
  1557. for( ; i < n1; i++ )
  1558. {
  1559. int idx = sorted[i];
  1560. double w = priors[responses[idx]];
  1561. dir[idx] = (char)1;
  1562. R += w;
  1563. }
  1564. for( ; i < n; i++ )
  1565. dir[sorted[i]] = (char)0;
  1566. }
  1567. }
  1568. node->maxlr = MAX( L, R );
  1569. return node->split->quality/(L + R);
  1570. }
  1571. namespace cv
  1572. {
  1573. void DefaultDeleter<CvDTreeSplit>::operator ()(CvDTreeSplit* obj) const { fastFree(obj); }
  1574. DTreeBestSplitFinder::DTreeBestSplitFinder( CvDTree* _tree, CvDTreeNode* _node)
  1575. {
  1576. tree = _tree;
  1577. node = _node;
  1578. splitSize = tree->get_data()->split_heap->elem_size;
  1579. bestSplit.reset((CvDTreeSplit*)fastMalloc(splitSize));
  1580. memset(bestSplit.get(), 0, splitSize);
  1581. bestSplit->quality = -1;
  1582. bestSplit->condensed_idx = INT_MIN;
  1583. split.reset((CvDTreeSplit*)fastMalloc(splitSize));
  1584. memset(split.get(), 0, splitSize);
  1585. //haveSplit = false;
  1586. }
  1587. DTreeBestSplitFinder::DTreeBestSplitFinder( const DTreeBestSplitFinder& finder, Split )
  1588. {
  1589. tree = finder.tree;
  1590. node = finder.node;
  1591. splitSize = tree->get_data()->split_heap->elem_size;
  1592. bestSplit.reset((CvDTreeSplit*)fastMalloc(splitSize));
  1593. memcpy(bestSplit.get(), finder.bestSplit.get(), splitSize);
  1594. split.reset((CvDTreeSplit*)fastMalloc(splitSize));
  1595. memset(split.get(), 0, splitSize);
  1596. }
  1597. void DTreeBestSplitFinder::operator()(const BlockedRange& range)
  1598. {
  1599. int vi, vi1 = range.begin(), vi2 = range.end();
  1600. int n = node->sample_count;
  1601. CvDTreeTrainData* data = tree->get_data();
  1602. AutoBuffer<uchar> inn_buf(2*n*(sizeof(int) + sizeof(float)));
  1603. for( vi = vi1; vi < vi2; vi++ )
  1604. {
  1605. CvDTreeSplit *res;
  1606. int ci = data->get_var_type(vi);
  1607. if( node->get_num_valid(vi) <= 1 )
  1608. continue;
  1609. if( data->is_classifier )
  1610. {
  1611. if( ci >= 0 )
  1612. res = tree->find_split_cat_class( node, vi, bestSplit->quality, split, inn_buf.data() );
  1613. else
  1614. res = tree->find_split_ord_class( node, vi, bestSplit->quality, split, inn_buf.data() );
  1615. }
  1616. else
  1617. {
  1618. if( ci >= 0 )
  1619. res = tree->find_split_cat_reg( node, vi, bestSplit->quality, split, inn_buf.data() );
  1620. else
  1621. res = tree->find_split_ord_reg( node, vi, bestSplit->quality, split, inn_buf.data() );
  1622. }
  1623. if( res && bestSplit->quality < split->quality )
  1624. memcpy( bestSplit.get(), split.get(), splitSize );
  1625. }
  1626. }
  1627. void DTreeBestSplitFinder::join( DTreeBestSplitFinder& rhs )
  1628. {
  1629. if( bestSplit->quality < rhs.bestSplit->quality )
  1630. memcpy( bestSplit.get(), rhs.bestSplit.get(), splitSize );
  1631. }
  1632. }
  1633. CvDTreeSplit* CvDTree::find_best_split( CvDTreeNode* node )
  1634. {
  1635. DTreeBestSplitFinder finder( this, node );
  1636. cv::parallel_reduce(cv::BlockedRange(0, data->var_count), finder);
  1637. CvDTreeSplit *bestSplit = 0;
  1638. if( finder.bestSplit->quality > 0 )
  1639. {
  1640. bestSplit = data->new_split_cat( 0, -1.0f );
  1641. memcpy( bestSplit, finder.bestSplit, finder.splitSize );
  1642. }
  1643. return bestSplit;
  1644. }
  1645. CvDTreeSplit* CvDTree::find_split_ord_class( CvDTreeNode* node, int vi,
  1646. float init_quality, CvDTreeSplit* _split, uchar* _ext_buf )
  1647. {
  1648. const float epsilon = FLT_EPSILON*2;
  1649. int n = node->sample_count;
  1650. int n1 = node->get_num_valid(vi);
  1651. int m = data->get_num_classes();
  1652. int base_size = 2*m*sizeof(int);
  1653. cv::AutoBuffer<uchar> inn_buf(base_size);
  1654. if( !_ext_buf )
  1655. inn_buf.allocate(base_size + n*(3*sizeof(int)+sizeof(float)));
  1656. uchar* base_buf = inn_buf.data();
  1657. uchar* ext_buf = _ext_buf ? _ext_buf : base_buf + base_size;
  1658. float* values_buf = (float*)ext_buf;
  1659. int* sorted_indices_buf = (int*)(values_buf + n);
  1660. int* sample_indices_buf = sorted_indices_buf + n;
  1661. const float* values = 0;
  1662. const int* sorted_indices = 0;
  1663. data->get_ord_var_data( node, vi, values_buf, sorted_indices_buf, &values,
  1664. &sorted_indices, sample_indices_buf );
  1665. int* responses_buf = sample_indices_buf + n;
  1666. const int* responses = data->get_class_labels( node, responses_buf );
  1667. const int* rc0 = data->counts->data.i;
  1668. int* lc = (int*)base_buf;
  1669. int* rc = lc + m;
  1670. int i, best_i = -1;
  1671. double lsum2 = 0, rsum2 = 0, best_val = init_quality;
  1672. const double* priors = data->have_priors ? data->priors_mult->data.db : 0;
  1673. // init arrays of class instance counters on both sides of the split
  1674. for( i = 0; i < m; i++ )
  1675. {
  1676. lc[i] = 0;
  1677. rc[i] = rc0[i];
  1678. }
  1679. // compensate for missing values
  1680. for( i = n1; i < n; i++ )
  1681. {
  1682. rc[responses[sorted_indices[i]]]--;
  1683. }
  1684. if( !priors )
  1685. {
  1686. int L = 0, R = n1;
  1687. for( i = 0; i < m; i++ )
  1688. rsum2 += (double)rc[i]*rc[i];
  1689. for( i = 0; i < n1 - 1; i++ )
  1690. {
  1691. int idx = responses[sorted_indices[i]];
  1692. int lv, rv;
  1693. L++; R--;
  1694. lv = lc[idx]; rv = rc[idx];
  1695. lsum2 += lv*2 + 1;
  1696. rsum2 -= rv*2 - 1;
  1697. lc[idx] = lv + 1; rc[idx] = rv - 1;
  1698. if( values[i] + epsilon < values[i+1] )
  1699. {
  1700. double val = (lsum2*R + rsum2*L)/((double)L*R);
  1701. if( best_val < val )
  1702. {
  1703. best_val = val;
  1704. best_i = i;
  1705. }
  1706. }
  1707. }
  1708. }
  1709. else
  1710. {
  1711. double L = 0, R = 0;
  1712. for( i = 0; i < m; i++ )
  1713. {
  1714. double wv = rc[i]*priors[i];
  1715. R += wv;
  1716. rsum2 += wv*wv;
  1717. }
  1718. for( i = 0; i < n1 - 1; i++ )
  1719. {
  1720. int idx = responses[sorted_indices[i]];
  1721. int lv, rv;
  1722. double p = priors[idx], p2 = p*p;
  1723. L += p; R -= p;
  1724. lv = lc[idx]; rv = rc[idx];
  1725. lsum2 += p2*(lv*2 + 1);
  1726. rsum2 -= p2*(rv*2 - 1);
  1727. lc[idx] = lv + 1; rc[idx] = rv - 1;
  1728. if( values[i] + epsilon < values[i+1] )
  1729. {
  1730. double val = (lsum2*R + rsum2*L)/((double)L*R);
  1731. if( best_val < val )
  1732. {
  1733. best_val = val;
  1734. best_i = i;
  1735. }
  1736. }
  1737. }
  1738. }
  1739. CvDTreeSplit* split = 0;
  1740. if( best_i >= 0 )
  1741. {
  1742. split = _split ? _split : data->new_split_ord( 0, 0.0f, 0, 0, 0.0f );
  1743. split->var_idx = vi;
  1744. split->ord.c = (values[best_i] + values[best_i+1])*0.5f;
  1745. split->ord.split_point = best_i;
  1746. split->inversed = 0;
  1747. split->quality = (float)best_val;
  1748. }
  1749. return split;
  1750. }
  1751. void CvDTree::cluster_categories( const int* vectors, int n, int m,
  1752. int* csums, int k, int* labels )
  1753. {
  1754. // TODO: consider adding priors (class weights) and sample weights to the clustering algorithm
  1755. int iters = 0, max_iters = 100;
  1756. int i, j, idx;
  1757. cv::AutoBuffer<double> buf(n + k);
  1758. double *v_weights = buf.data(), *c_weights = buf.data() + n;
  1759. bool modified = true;
  1760. RNG* r = data->rng;
  1761. // assign labels randomly
  1762. for( i = 0; i < n; i++ )
  1763. {
  1764. int sum = 0;
  1765. const int* v = vectors + i*m;
  1766. labels[i] = i < k ? i : r->uniform(0, k);
  1767. // compute weight of each vector
  1768. for( j = 0; j < m; j++ )
  1769. sum += v[j];
  1770. v_weights[i] = sum ? 1./sum : 0.;
  1771. }
  1772. for( i = 0; i < n; i++ )
  1773. {
  1774. int i1 = (*r)(n);
  1775. int i2 = (*r)(n);
  1776. CV_SWAP( labels[i1], labels[i2], j );
  1777. }
  1778. for( iters = 0; iters <= max_iters; iters++ )
  1779. {
  1780. // calculate csums
  1781. for( i = 0; i < k; i++ )
  1782. {
  1783. for( j = 0; j < m; j++ )
  1784. csums[i*m + j] = 0;
  1785. }
  1786. for( i = 0; i < n; i++ )
  1787. {
  1788. const int* v = vectors + i*m;
  1789. int* s = csums + labels[i]*m;
  1790. for( j = 0; j < m; j++ )
  1791. s[j] += v[j];
  1792. }
  1793. // exit the loop here, when we have up-to-date csums
  1794. if( iters == max_iters || !modified )
  1795. break;
  1796. modified = false;
  1797. // calculate weight of each cluster
  1798. for( i = 0; i < k; i++ )
  1799. {
  1800. const int* s = csums + i*m;
  1801. int sum = 0;
  1802. for( j = 0; j < m; j++ )
  1803. sum += s[j];
  1804. c_weights[i] = sum ? 1./sum : 0;
  1805. }
  1806. // now for each vector determine the closest cluster
  1807. for( i = 0; i < n; i++ )
  1808. {
  1809. const int* v = vectors + i*m;
  1810. double alpha = v_weights[i];
  1811. double min_dist2 = DBL_MAX;
  1812. int min_idx = -1;
  1813. for( idx = 0; idx < k; idx++ )
  1814. {
  1815. const int* s = csums + idx*m;
  1816. double dist2 = 0., beta = c_weights[idx];
  1817. for( j = 0; j < m; j++ )
  1818. {
  1819. double t = v[j]*alpha - s[j]*beta;
  1820. dist2 += t*t;
  1821. }
  1822. if( min_dist2 > dist2 )
  1823. {
  1824. min_dist2 = dist2;
  1825. min_idx = idx;
  1826. }
  1827. }
  1828. if( min_idx != labels[i] )
  1829. modified = true;
  1830. labels[i] = min_idx;
  1831. }
  1832. }
  1833. }
  1834. CvDTreeSplit* CvDTree::find_split_cat_class( CvDTreeNode* node, int vi, float init_quality,
  1835. CvDTreeSplit* _split, uchar* _ext_buf )
  1836. {
  1837. int ci = data->get_var_type(vi);
  1838. int n = node->sample_count;
  1839. int m = data->get_num_classes();
  1840. int _mi = data->cat_count->data.i[ci], mi = _mi;
  1841. int base_size = m*(3 + mi)*sizeof(int) + (mi+1)*sizeof(double);
  1842. if( m > 2 && mi > data->params.max_categories )
  1843. base_size += (m*std::min(data->params.max_categories, n) + mi)*sizeof(int);
  1844. else
  1845. base_size += mi*sizeof(int*);
  1846. cv::AutoBuffer<uchar> inn_buf(base_size);
  1847. if( !_ext_buf )
  1848. inn_buf.allocate(base_size + 2*n*sizeof(int));
  1849. uchar* base_buf = inn_buf.data();
  1850. uchar* ext_buf = _ext_buf ? _ext_buf : base_buf + base_size;
  1851. int* lc = (int*)base_buf;
  1852. int* rc = lc + m;
  1853. int* _cjk = rc + m*2, *cjk = _cjk;
  1854. double* c_weights = (double*)alignPtr(cjk + m*mi, sizeof(double));
  1855. int* labels_buf = (int*)ext_buf;
  1856. const int* labels = data->get_cat_var_data(node, vi, labels_buf);
  1857. int* responses_buf = labels_buf + n;
  1858. const int* responses = data->get_class_labels(node, responses_buf);
  1859. int* cluster_labels = 0;
  1860. int** int_ptr = 0;
  1861. int i, j, k, idx;
  1862. double L = 0, R = 0;
  1863. double best_val = init_quality;
  1864. int prevcode = 0, best_subset = -1, subset_i, subset_n, subtract = 0;
  1865. const double* priors = data->priors_mult->data.db;
  1866. // init array of counters:
  1867. // c_{jk} - number of samples that have vi-th input variable = j and response = k.
  1868. for( j = -1; j < mi; j++ )
  1869. for( k = 0; k < m; k++ )
  1870. cjk[j*m + k] = 0;
  1871. for( i = 0; i < n; i++ )
  1872. {
  1873. j = ( labels[i] == 65535 && data->is_buf_16u) ? -1 : labels[i];
  1874. k = responses[i];
  1875. cjk[j*m + k]++;
  1876. }
  1877. if( m > 2 )
  1878. {
  1879. if( mi > data->params.max_categories )
  1880. {
  1881. mi = MIN(data->params.max_categories, n);
  1882. cjk = (int*)(c_weights + _mi);
  1883. cluster_labels = cjk + m*mi;
  1884. cluster_categories( _cjk, _mi, m, cjk, mi, cluster_labels );
  1885. }
  1886. subset_i = 1;
  1887. subset_n = 1 << mi;
  1888. }
  1889. else
  1890. {
  1891. assert( m == 2 );
  1892. int_ptr = (int**)(c_weights + _mi);
  1893. for( j = 0; j < mi; j++ )
  1894. int_ptr[j] = cjk + j*2 + 1;
  1895. std::sort(int_ptr, int_ptr + mi, LessThanPtr<int>());
  1896. subset_i = 0;
  1897. subset_n = mi;
  1898. }
  1899. for( k = 0; k < m; k++ )
  1900. {
  1901. int sum = 0;
  1902. for( j = 0; j < mi; j++ )
  1903. sum += cjk[j*m + k];
  1904. rc[k] = sum;
  1905. lc[k] = 0;
  1906. }
  1907. for( j = 0; j < mi; j++ )
  1908. {
  1909. double sum = 0;
  1910. for( k = 0; k < m; k++ )
  1911. sum += cjk[j*m + k]*priors[k];
  1912. c_weights[j] = sum;
  1913. R += c_weights[j];
  1914. }
  1915. for( ; subset_i < subset_n; subset_i++ )
  1916. {
  1917. double weight;
  1918. int* crow;
  1919. double lsum2 = 0, rsum2 = 0;
  1920. if( m == 2 )
  1921. idx = (int)(int_ptr[subset_i] - cjk)/2;
  1922. else
  1923. {
  1924. int graycode = (subset_i>>1)^subset_i;
  1925. int diff = graycode ^ prevcode;
  1926. // determine index of the changed bit.
  1927. Cv32suf u;
  1928. idx = diff >= (1 << 16) ? 16 : 0;
  1929. u.f = (float)(((diff >> 16) | diff) & 65535);
  1930. idx += (u.i >> 23) - 127;
  1931. subtract = graycode < prevcode;
  1932. prevcode = graycode;
  1933. }
  1934. crow = cjk + idx*m;
  1935. weight = c_weights[idx];
  1936. if( weight < FLT_EPSILON )
  1937. continue;
  1938. if( !subtract )
  1939. {
  1940. for( k = 0; k < m; k++ )
  1941. {
  1942. int t = crow[k];
  1943. int lval = lc[k] + t;
  1944. int rval = rc[k] - t;
  1945. double p = priors[k], p2 = p*p;
  1946. lsum2 += p2*lval*lval;
  1947. rsum2 += p2*rval*rval;
  1948. lc[k] = lval; rc[k] = rval;
  1949. }
  1950. L += weight;
  1951. R -= weight;
  1952. }
  1953. else
  1954. {
  1955. for( k = 0; k < m; k++ )
  1956. {
  1957. int t = crow[k];
  1958. int lval = lc[k] - t;
  1959. int rval = rc[k] + t;
  1960. double p = priors[k], p2 = p*p;
  1961. lsum2 += p2*lval*lval;
  1962. rsum2 += p2*rval*rval;
  1963. lc[k] = lval; rc[k] = rval;
  1964. }
  1965. L -= weight;
  1966. R += weight;
  1967. }
  1968. if( L > FLT_EPSILON && R > FLT_EPSILON )
  1969. {
  1970. double val = (lsum2*R + rsum2*L)/((double)L*R);
  1971. if( best_val < val )
  1972. {
  1973. best_val = val;
  1974. best_subset = subset_i;
  1975. }
  1976. }
  1977. }
  1978. CvDTreeSplit* split = 0;
  1979. if( best_subset >= 0 )
  1980. {
  1981. split = _split ? _split : data->new_split_cat( 0, -1.0f );
  1982. split->var_idx = vi;
  1983. split->quality = (float)best_val;
  1984. memset( split->subset, 0, (data->max_c_count + 31)/32 * sizeof(int));
  1985. if( m == 2 )
  1986. {
  1987. for( i = 0; i <= best_subset; i++ )
  1988. {
  1989. idx = (int)(int_ptr[i] - cjk) >> 1;
  1990. split->subset[idx >> 5] |= 1 << (idx & 31);
  1991. }
  1992. }
  1993. else
  1994. {
  1995. for( i = 0; i < _mi; i++ )
  1996. {
  1997. idx = cluster_labels ? cluster_labels[i] : i;
  1998. if( best_subset & (1 << idx) )
  1999. split->subset[i >> 5] |= 1 << (i & 31);
  2000. }
  2001. }
  2002. }
  2003. return split;
  2004. }
  2005. CvDTreeSplit* CvDTree::find_split_ord_reg( CvDTreeNode* node, int vi, float init_quality, CvDTreeSplit* _split, uchar* _ext_buf )
  2006. {
  2007. const float epsilon = FLT_EPSILON*2;
  2008. int n = node->sample_count;
  2009. int n1 = node->get_num_valid(vi);
  2010. cv::AutoBuffer<uchar> inn_buf;
  2011. if( !_ext_buf )
  2012. inn_buf.allocate(2*n*(sizeof(int) + sizeof(float)));
  2013. uchar* ext_buf = _ext_buf ? _ext_buf : inn_buf.data();
  2014. float* values_buf = (float*)ext_buf;
  2015. int* sorted_indices_buf = (int*)(values_buf + n);
  2016. int* sample_indices_buf = sorted_indices_buf + n;
  2017. const float* values = 0;
  2018. const int* sorted_indices = 0;
  2019. data->get_ord_var_data( node, vi, values_buf, sorted_indices_buf, &values, &sorted_indices, sample_indices_buf );
  2020. float* responses_buf = (float*)(sample_indices_buf + n);
  2021. const float* responses = data->get_ord_responses( node, responses_buf, sample_indices_buf );
  2022. int i, best_i = -1;
  2023. double best_val = init_quality, lsum = 0, rsum = node->value*n;
  2024. int L = 0, R = n1;
  2025. // compensate for missing values
  2026. for( i = n1; i < n; i++ )
  2027. rsum -= responses[sorted_indices[i]];
  2028. // find the optimal split
  2029. for( i = 0; i < n1 - 1; i++ )
  2030. {
  2031. float t = responses[sorted_indices[i]];
  2032. L++; R--;
  2033. lsum += t;
  2034. rsum -= t;
  2035. if( values[i] + epsilon < values[i+1] )
  2036. {
  2037. double val = (lsum*lsum*R + rsum*rsum*L)/((double)L*R);
  2038. if( best_val < val )
  2039. {
  2040. best_val = val;
  2041. best_i = i;
  2042. }
  2043. }
  2044. }
  2045. CvDTreeSplit* split = 0;
  2046. if( best_i >= 0 )
  2047. {
  2048. split = _split ? _split : data->new_split_ord( 0, 0.0f, 0, 0, 0.0f );
  2049. split->var_idx = vi;
  2050. split->ord.c = (values[best_i] + values[best_i+1])*0.5f;
  2051. split->ord.split_point = best_i;
  2052. split->inversed = 0;
  2053. split->quality = (float)best_val;
  2054. }
  2055. return split;
  2056. }
  2057. CvDTreeSplit* CvDTree::find_split_cat_reg( CvDTreeNode* node, int vi, float init_quality, CvDTreeSplit* _split, uchar* _ext_buf )
  2058. {
  2059. int ci = data->get_var_type(vi);
  2060. int n = node->sample_count;
  2061. int mi = data->cat_count->data.i[ci];
  2062. int base_size = (mi+2)*sizeof(double) + (mi+1)*(sizeof(int) + sizeof(double*));
  2063. cv::AutoBuffer<uchar> inn_buf(base_size);
  2064. if( !_ext_buf )
  2065. inn_buf.allocate(base_size + n*(2*sizeof(int) + sizeof(float)));
  2066. uchar* base_buf = inn_buf.data();
  2067. uchar* ext_buf = _ext_buf ? _ext_buf : base_buf + base_size;
  2068. int* labels_buf = (int*)ext_buf;
  2069. const int* labels = data->get_cat_var_data(node, vi, labels_buf);
  2070. float* responses_buf = (float*)(labels_buf + n);
  2071. int* sample_indices_buf = (int*)(responses_buf + n);
  2072. const float* responses = data->get_ord_responses(node, responses_buf, sample_indices_buf);
  2073. double* sum = (double*)cv::alignPtr(base_buf,sizeof(double)) + 1;
  2074. int* counts = (int*)(sum + mi) + 1;
  2075. double** sum_ptr = (double**)(counts + mi);
  2076. int i, L = 0, R = 0;
  2077. double best_val = init_quality, lsum = 0, rsum = 0;
  2078. int best_subset = -1, subset_i;
  2079. for( i = -1; i < mi; i++ )
  2080. sum[i] = counts[i] = 0;
  2081. // calculate sum response and weight of each category of the input var
  2082. for( i = 0; i < n; i++ )
  2083. {
  2084. int idx = ( (labels[i] == 65535) && data->is_buf_16u ) ? -1 : labels[i];
  2085. double s = sum[idx] + responses[i];
  2086. int nc = counts[idx] + 1;
  2087. sum[idx] = s;
  2088. counts[idx] = nc;
  2089. }
  2090. // calculate average response in each category
  2091. for( i = 0; i < mi; i++ )
  2092. {
  2093. R += counts[i];
  2094. rsum += sum[i];
  2095. sum[i] /= MAX(counts[i],1);
  2096. sum_ptr[i] = sum + i;
  2097. }
  2098. std::sort(sum_ptr, sum_ptr + mi, LessThanPtr<double>());
  2099. // revert back to unnormalized sums
  2100. // (there should be a very little loss of accuracy)
  2101. for( i = 0; i < mi; i++ )
  2102. sum[i] *= counts[i];
  2103. for( subset_i = 0; subset_i < mi-1; subset_i++ )
  2104. {
  2105. int idx = (int)(sum_ptr[subset_i] - sum);
  2106. int ni = counts[idx];
  2107. if( ni )
  2108. {
  2109. double s = sum[idx];
  2110. lsum += s; L += ni;
  2111. rsum -= s; R -= ni;
  2112. if( L && R )
  2113. {
  2114. double val = (lsum*lsum*R + rsum*rsum*L)/((double)L*R);
  2115. if( best_val < val )
  2116. {
  2117. best_val = val;
  2118. best_subset = subset_i;
  2119. }
  2120. }
  2121. }
  2122. }
  2123. CvDTreeSplit* split = 0;
  2124. if( best_subset >= 0 )
  2125. {
  2126. split = _split ? _split : data->new_split_cat( 0, -1.0f);
  2127. split->var_idx = vi;
  2128. split->quality = (float)best_val;
  2129. memset( split->subset, 0, (data->max_c_count + 31)/32 * sizeof(int));
  2130. for( i = 0; i <= best_subset; i++ )
  2131. {
  2132. int idx = (int)(sum_ptr[i] - sum);
  2133. split->subset[idx >> 5] |= 1 << (idx & 31);
  2134. }
  2135. }
  2136. return split;
  2137. }
  2138. CvDTreeSplit* CvDTree::find_surrogate_split_ord( CvDTreeNode* node, int vi, uchar* _ext_buf )
  2139. {
  2140. const float epsilon = FLT_EPSILON*2;
  2141. const char* dir = (char*)data->direction->data.ptr;
  2142. int n = node->sample_count, n1 = node->get_num_valid(vi);
  2143. cv::AutoBuffer<uchar> inn_buf;
  2144. if( !_ext_buf )
  2145. inn_buf.allocate( n*(sizeof(int)*(data->have_priors ? 3 : 2) + sizeof(float)) );
  2146. uchar* ext_buf = _ext_buf ? _ext_buf : inn_buf.data();
  2147. float* values_buf = (float*)ext_buf;
  2148. int* sorted_indices_buf = (int*)(values_buf + n);
  2149. int* sample_indices_buf = sorted_indices_buf + n;
  2150. const float* values = 0;
  2151. const int* sorted_indices = 0;
  2152. data->get_ord_var_data( node, vi, values_buf, sorted_indices_buf, &values, &sorted_indices, sample_indices_buf );
  2153. // LL - number of samples that both the primary and the surrogate splits send to the left
  2154. // LR - ... primary split sends to the left and the surrogate split sends to the right
  2155. // RL - ... primary split sends to the right and the surrogate split sends to the left
  2156. // RR - ... both send to the right
  2157. int i, best_i = -1, best_inversed = 0;
  2158. double best_val;
  2159. if( !data->have_priors )
  2160. {
  2161. int LL = 0, RL = 0, LR, RR;
  2162. int worst_val = cvFloor(node->maxlr), _best_val = worst_val;
  2163. int sum = 0, sum_abs = 0;
  2164. for( i = 0; i < n1; i++ )
  2165. {
  2166. int d = dir[sorted_indices[i]];
  2167. sum += d; sum_abs += d & 1;
  2168. }
  2169. // sum_abs = R + L; sum = R - L
  2170. RR = (sum_abs + sum) >> 1;
  2171. LR = (sum_abs - sum) >> 1;
  2172. // initially all the samples are sent to the right by the surrogate split,
  2173. // LR of them are sent to the left by primary split, and RR - to the right.
  2174. // now iteratively compute LL, LR, RL and RR for every possible surrogate split value.
  2175. for( i = 0; i < n1 - 1; i++ )
  2176. {
  2177. int d = dir[sorted_indices[i]];
  2178. if( d < 0 )
  2179. {
  2180. LL++; LR--;
  2181. if( LL + RR > _best_val && values[i] + epsilon < values[i+1] )
  2182. {
  2183. best_val = LL + RR;
  2184. best_i = i; best_inversed = 0;
  2185. }
  2186. }
  2187. else if( d > 0 )
  2188. {
  2189. RL++; RR--;
  2190. if( RL + LR > _best_val && values[i] + epsilon < values[i+1] )
  2191. {
  2192. best_val = RL + LR;
  2193. best_i = i; best_inversed = 1;
  2194. }
  2195. }
  2196. }
  2197. best_val = _best_val;
  2198. }
  2199. else
  2200. {
  2201. double LL = 0, RL = 0, LR, RR;
  2202. double worst_val = node->maxlr;
  2203. double sum = 0, sum_abs = 0;
  2204. const double* priors = data->priors_mult->data.db;
  2205. int* responses_buf = sample_indices_buf + n;
  2206. const int* responses = data->get_class_labels(node, responses_buf);
  2207. best_val = worst_val;
  2208. for( i = 0; i < n1; i++ )
  2209. {
  2210. int idx = sorted_indices[i];
  2211. double w = priors[responses[idx]];
  2212. int d = dir[idx];
  2213. sum += d*w; sum_abs += (d & 1)*w;
  2214. }
  2215. // sum_abs = R + L; sum = R - L
  2216. RR = (sum_abs + sum)*0.5;
  2217. LR = (sum_abs - sum)*0.5;
  2218. // initially all the samples are sent to the right by the surrogate split,
  2219. // LR of them are sent to the left by primary split, and RR - to the right.
  2220. // now iteratively compute LL, LR, RL and RR for every possible surrogate split value.
  2221. for( i = 0; i < n1 - 1; i++ )
  2222. {
  2223. int idx = sorted_indices[i];
  2224. double w = priors[responses[idx]];
  2225. int d = dir[idx];
  2226. if( d < 0 )
  2227. {
  2228. LL += w; LR -= w;
  2229. if( LL + RR > best_val && values[i] + epsilon < values[i+1] )
  2230. {
  2231. best_val = LL + RR;
  2232. best_i = i; best_inversed = 0;
  2233. }
  2234. }
  2235. else if( d > 0 )
  2236. {
  2237. RL += w; RR -= w;
  2238. if( RL + LR > best_val && values[i] + epsilon < values[i+1] )
  2239. {
  2240. best_val = RL + LR;
  2241. best_i = i; best_inversed = 1;
  2242. }
  2243. }
  2244. }
  2245. }
  2246. return best_i >= 0 && best_val > node->maxlr ? data->new_split_ord( vi,
  2247. (values[best_i] + values[best_i+1])*0.5f, best_i, best_inversed, (float)best_val ) : 0;
  2248. }
  2249. CvDTreeSplit* CvDTree::find_surrogate_split_cat( CvDTreeNode* node, int vi, uchar* _ext_buf )
  2250. {
  2251. const char* dir = (char*)data->direction->data.ptr;
  2252. int n = node->sample_count;
  2253. int i, mi = data->cat_count->data.i[data->get_var_type(vi)], l_win = 0;
  2254. int base_size = (2*(mi+1)+1)*sizeof(double) + (!data->have_priors ? 2*(mi+1)*sizeof(int) : 0);
  2255. cv::AutoBuffer<uchar> inn_buf(base_size);
  2256. if( !_ext_buf )
  2257. inn_buf.allocate(base_size + n*(sizeof(int) + (data->have_priors ? sizeof(int) : 0)));
  2258. uchar* base_buf = inn_buf.data();
  2259. uchar* ext_buf = _ext_buf ? _ext_buf : base_buf + base_size;
  2260. int* labels_buf = (int*)ext_buf;
  2261. const int* labels = data->get_cat_var_data(node, vi, labels_buf);
  2262. // LL - number of samples that both the primary and the surrogate splits send to the left
  2263. // LR - ... primary split sends to the left and the surrogate split sends to the right
  2264. // RL - ... primary split sends to the right and the surrogate split sends to the left
  2265. // RR - ... both send to the right
  2266. CvDTreeSplit* split = data->new_split_cat( vi, 0 );
  2267. double best_val = 0;
  2268. double* lc = (double*)cv::alignPtr(base_buf,sizeof(double)) + 1;
  2269. double* rc = lc + mi + 1;
  2270. for( i = -1; i < mi; i++ )
  2271. lc[i] = rc[i] = 0;
  2272. // for each category calculate the weight of samples
  2273. // sent to the left (lc) and to the right (rc) by the primary split
  2274. if( !data->have_priors )
  2275. {
  2276. int* _lc = (int*)rc + 1;
  2277. int* _rc = _lc + mi + 1;
  2278. for( i = -1; i < mi; i++ )
  2279. _lc[i] = _rc[i] = 0;
  2280. for( i = 0; i < n; i++ )
  2281. {
  2282. int idx = ( (labels[i] == 65535) && (data->is_buf_16u) ) ? -1 : labels[i];
  2283. int d = dir[i];
  2284. int sum = _lc[idx] + d;
  2285. int sum_abs = _rc[idx] + (d & 1);
  2286. _lc[idx] = sum; _rc[idx] = sum_abs;
  2287. }
  2288. for( i = 0; i < mi; i++ )
  2289. {
  2290. int sum = _lc[i];
  2291. int sum_abs = _rc[i];
  2292. lc[i] = (sum_abs - sum) >> 1;
  2293. rc[i] = (sum_abs + sum) >> 1;
  2294. }
  2295. }
  2296. else
  2297. {
  2298. const double* priors = data->priors_mult->data.db;
  2299. int* responses_buf = labels_buf + n;
  2300. const int* responses = data->get_class_labels(node, responses_buf);
  2301. for( i = 0; i < n; i++ )
  2302. {
  2303. int idx = ( (labels[i] == 65535) && (data->is_buf_16u) ) ? -1 : labels[i];
  2304. double w = priors[responses[i]];
  2305. int d = dir[i];
  2306. double sum = lc[idx] + d*w;
  2307. double sum_abs = rc[idx] + (d & 1)*w;
  2308. lc[idx] = sum; rc[idx] = sum_abs;
  2309. }
  2310. for( i = 0; i < mi; i++ )
  2311. {
  2312. double sum = lc[i];
  2313. double sum_abs = rc[i];
  2314. lc[i] = (sum_abs - sum) * 0.5;
  2315. rc[i] = (sum_abs + sum) * 0.5;
  2316. }
  2317. }
  2318. // 2. now form the split.
  2319. // in each category send all the samples to the same direction as majority
  2320. for( i = 0; i < mi; i++ )
  2321. {
  2322. double lval = lc[i], rval = rc[i];
  2323. if( lval > rval )
  2324. {
  2325. split->subset[i >> 5] |= 1 << (i & 31);
  2326. best_val += lval;
  2327. l_win++;
  2328. }
  2329. else
  2330. best_val += rval;
  2331. }
  2332. split->quality = (float)best_val;
  2333. if( split->quality <= node->maxlr || l_win == 0 || l_win == mi )
  2334. cvSetRemoveByPtr( data->split_heap, split ), split = 0;
  2335. return split;
  2336. }
  2337. void CvDTree::calc_node_value( CvDTreeNode* node )
  2338. {
  2339. int i, j, k, n = node->sample_count, cv_n = data->params.cv_folds;
  2340. int m = data->get_num_classes();
  2341. int base_size = data->is_classifier ? m*cv_n*sizeof(int) : 2*cv_n*sizeof(double)+cv_n*sizeof(int);
  2342. int ext_size = n*(sizeof(int) + (data->is_classifier ? sizeof(int) : sizeof(int)+sizeof(float)));
  2343. cv::AutoBuffer<uchar> inn_buf(base_size + ext_size);
  2344. uchar* base_buf = inn_buf.data();
  2345. uchar* ext_buf = base_buf + base_size;
  2346. int* cv_labels_buf = (int*)ext_buf;
  2347. const int* cv_labels = data->get_cv_labels(node, cv_labels_buf);
  2348. if( data->is_classifier )
  2349. {
  2350. // in case of classification tree:
  2351. // * node value is the label of the class that has the largest weight in the node.
  2352. // * node risk is the weighted number of misclassified samples,
  2353. // * j-th cross-validation fold value and risk are calculated as above,
  2354. // but using the samples with cv_labels(*)!=j.
  2355. // * j-th cross-validation fold error is calculated as the weighted number of
  2356. // misclassified samples with cv_labels(*)==j.
  2357. // compute the number of instances of each class
  2358. int* cls_count = data->counts->data.i;
  2359. int* responses_buf = cv_labels_buf + n;
  2360. const int* responses = data->get_class_labels(node, responses_buf);
  2361. int* cv_cls_count = (int*)base_buf;
  2362. double max_val = -1, total_weight = 0;
  2363. int max_k = -1;
  2364. double* priors = data->priors_mult->data.db;
  2365. for( k = 0; k < m; k++ )
  2366. cls_count[k] = 0;
  2367. if( cv_n == 0 )
  2368. {
  2369. for( i = 0; i < n; i++ )
  2370. cls_count[responses[i]]++;
  2371. }
  2372. else
  2373. {
  2374. for( j = 0; j < cv_n; j++ )
  2375. for( k = 0; k < m; k++ )
  2376. cv_cls_count[j*m + k] = 0;
  2377. for( i = 0; i < n; i++ )
  2378. {
  2379. j = cv_labels[i]; k = responses[i];
  2380. cv_cls_count[j*m + k]++;
  2381. }
  2382. for( j = 0; j < cv_n; j++ )
  2383. for( k = 0; k < m; k++ )
  2384. cls_count[k] += cv_cls_count[j*m + k];
  2385. }
  2386. if( data->have_priors && node->parent == 0 )
  2387. {
  2388. // compute priors_mult from priors, take the sample ratio into account.
  2389. double sum = 0;
  2390. for( k = 0; k < m; k++ )
  2391. {
  2392. int n_k = cls_count[k];
  2393. priors[k] = data->priors->data.db[k]*(n_k ? 1./n_k : 0.);
  2394. sum += priors[k];
  2395. }
  2396. sum = 1./sum;
  2397. for( k = 0; k < m; k++ )
  2398. priors[k] *= sum;
  2399. }
  2400. for( k = 0; k < m; k++ )
  2401. {
  2402. double val = cls_count[k]*priors[k];
  2403. total_weight += val;
  2404. if( max_val < val )
  2405. {
  2406. max_val = val;
  2407. max_k = k;
  2408. }
  2409. }
  2410. node->class_idx = max_k;
  2411. node->value = data->cat_map->data.i[
  2412. data->cat_ofs->data.i[data->cat_var_count] + max_k];
  2413. node->node_risk = total_weight - max_val;
  2414. for( j = 0; j < cv_n; j++ )
  2415. {
  2416. double sum_k = 0, sum = 0, max_val_k = 0;
  2417. max_val = -1; max_k = -1;
  2418. for( k = 0; k < m; k++ )
  2419. {
  2420. double w = priors[k];
  2421. double val_k = cv_cls_count[j*m + k]*w;
  2422. double val = cls_count[k]*w - val_k;
  2423. sum_k += val_k;
  2424. sum += val;
  2425. if( max_val < val )
  2426. {
  2427. max_val = val;
  2428. max_val_k = val_k;
  2429. max_k = k;
  2430. }
  2431. }
  2432. node->cv_Tn[j] = INT_MAX;
  2433. node->cv_node_risk[j] = sum - max_val;
  2434. node->cv_node_error[j] = sum_k - max_val_k;
  2435. }
  2436. }
  2437. else
  2438. {
  2439. // in case of regression tree:
  2440. // * node value is 1/n*sum_i(Y_i), where Y_i is i-th response,
  2441. // n is the number of samples in the node.
  2442. // * node risk is the sum of squared errors: sum_i((Y_i - <node_value>)^2)
  2443. // * j-th cross-validation fold value and risk are calculated as above,
  2444. // but using the samples with cv_labels(*)!=j.
  2445. // * j-th cross-validation fold error is calculated
  2446. // using samples with cv_labels(*)==j as the test subset:
  2447. // error_j = sum_(i,cv_labels(i)==j)((Y_i - <node_value_j>)^2),
  2448. // where node_value_j is the node value calculated
  2449. // as described in the previous bullet, and summation is done
  2450. // over the samples with cv_labels(*)==j.
  2451. double sum = 0, sum2 = 0;
  2452. float* values_buf = (float*)(cv_labels_buf + n);
  2453. int* sample_indices_buf = (int*)(values_buf + n);
  2454. const float* values = data->get_ord_responses(node, values_buf, sample_indices_buf);
  2455. double *cv_sum = 0, *cv_sum2 = 0;
  2456. int* cv_count = 0;
  2457. if( cv_n == 0 )
  2458. {
  2459. for( i = 0; i < n; i++ )
  2460. {
  2461. double t = values[i];
  2462. sum += t;
  2463. sum2 += t*t;
  2464. }
  2465. }
  2466. else
  2467. {
  2468. cv_sum = (double*)base_buf;
  2469. cv_sum2 = cv_sum + cv_n;
  2470. cv_count = (int*)(cv_sum2 + cv_n);
  2471. for( j = 0; j < cv_n; j++ )
  2472. {
  2473. cv_sum[j] = cv_sum2[j] = 0.;
  2474. cv_count[j] = 0;
  2475. }
  2476. for( i = 0; i < n; i++ )
  2477. {
  2478. j = cv_labels[i];
  2479. double t = values[i];
  2480. double s = cv_sum[j] + t;
  2481. double s2 = cv_sum2[j] + t*t;
  2482. int nc = cv_count[j] + 1;
  2483. cv_sum[j] = s;
  2484. cv_sum2[j] = s2;
  2485. cv_count[j] = nc;
  2486. }
  2487. for( j = 0; j < cv_n; j++ )
  2488. {
  2489. sum += cv_sum[j];
  2490. sum2 += cv_sum2[j];
  2491. }
  2492. }
  2493. node->node_risk = sum2 - (sum/n)*sum;
  2494. node->value = sum/n;
  2495. for( j = 0; j < cv_n; j++ )
  2496. {
  2497. double s = cv_sum[j], si = sum - s;
  2498. double s2 = cv_sum2[j], s2i = sum2 - s2;
  2499. int c = cv_count[j], ci = n - c;
  2500. double r = si/MAX(ci,1);
  2501. node->cv_node_risk[j] = s2i - r*r*ci;
  2502. node->cv_node_error[j] = s2 - 2*r*s + c*r*r;
  2503. node->cv_Tn[j] = INT_MAX;
  2504. }
  2505. }
  2506. }
  2507. void CvDTree::complete_node_dir( CvDTreeNode* node )
  2508. {
  2509. int vi, i, n = node->sample_count, nl, nr, d0 = 0, d1 = -1;
  2510. int nz = n - node->get_num_valid(node->split->var_idx);
  2511. char* dir = (char*)data->direction->data.ptr;
  2512. // try to complete direction using surrogate splits
  2513. if( nz && data->params.use_surrogates )
  2514. {
  2515. cv::AutoBuffer<uchar> inn_buf(n*(2*sizeof(int)+sizeof(float)));
  2516. CvDTreeSplit* split = node->split->next;
  2517. for( ; split != 0 && nz; split = split->next )
  2518. {
  2519. int inversed_mask = split->inversed ? -1 : 0;
  2520. vi = split->var_idx;
  2521. if( data->get_var_type(vi) >= 0 ) // split on categorical var
  2522. {
  2523. int* labels_buf = (int*)inn_buf.data();
  2524. const int* labels = data->get_cat_var_data(node, vi, labels_buf);
  2525. const int* subset = split->subset;
  2526. for( i = 0; i < n; i++ )
  2527. {
  2528. int idx = labels[i];
  2529. if( !dir[i] && ( ((idx >= 0)&&(!data->is_buf_16u)) || ((idx != 65535)&&(data->is_buf_16u)) ))
  2530. {
  2531. int d = CV_DTREE_CAT_DIR(idx,subset);
  2532. dir[i] = (char)((d ^ inversed_mask) - inversed_mask);
  2533. if( --nz )
  2534. break;
  2535. }
  2536. }
  2537. }
  2538. else // split on ordered var
  2539. {
  2540. float* values_buf = (float*)inn_buf.data();
  2541. int* sorted_indices_buf = (int*)(values_buf + n);
  2542. int* sample_indices_buf = sorted_indices_buf + n;
  2543. const float* values = 0;
  2544. const int* sorted_indices = 0;
  2545. data->get_ord_var_data( node, vi, values_buf, sorted_indices_buf, &values, &sorted_indices, sample_indices_buf );
  2546. int split_point = split->ord.split_point;
  2547. int n1 = node->get_num_valid(vi);
  2548. assert( 0 <= split_point && split_point < n-1 );
  2549. for( i = 0; i < n1; i++ )
  2550. {
  2551. int idx = sorted_indices[i];
  2552. if( !dir[idx] )
  2553. {
  2554. int d = i <= split_point ? -1 : 1;
  2555. dir[idx] = (char)((d ^ inversed_mask) - inversed_mask);
  2556. if( --nz )
  2557. break;
  2558. }
  2559. }
  2560. }
  2561. }
  2562. }
  2563. // find the default direction for the rest
  2564. if( nz )
  2565. {
  2566. for( i = nr = 0; i < n; i++ )
  2567. nr += dir[i] > 0;
  2568. nl = n - nr - nz;
  2569. d0 = nl > nr ? -1 : nr > nl;
  2570. }
  2571. // make sure that every sample is directed either to the left or to the right
  2572. for( i = 0; i < n; i++ )
  2573. {
  2574. int d = dir[i];
  2575. if( !d )
  2576. {
  2577. d = d0;
  2578. if( !d )
  2579. d = d1, d1 = -d1;
  2580. }
  2581. d = d > 0;
  2582. dir[i] = (char)d; // remap (-1,1) to (0,1)
  2583. }
  2584. }
  2585. void CvDTree::split_node_data( CvDTreeNode* node )
  2586. {
  2587. int vi, i, n = node->sample_count, nl, nr, scount = data->sample_count;
  2588. char* dir = (char*)data->direction->data.ptr;
  2589. CvDTreeNode *left = 0, *right = 0;
  2590. int* new_idx = data->split_buf->data.i;
  2591. int new_buf_idx = data->get_child_buf_idx( node );
  2592. int work_var_count = data->get_work_var_count();
  2593. CvMat* buf = data->buf;
  2594. size_t length_buf_row = data->get_length_subbuf();
  2595. cv::AutoBuffer<uchar> inn_buf(n*(3*sizeof(int) + sizeof(float)));
  2596. int* temp_buf = (int*)inn_buf.data();
  2597. complete_node_dir(node);
  2598. for( i = nl = nr = 0; i < n; i++ )
  2599. {
  2600. int d = dir[i];
  2601. // initialize new indices for splitting ordered variables
  2602. new_idx[i] = (nl & (d-1)) | (nr & -d); // d ? ri : li
  2603. nr += d;
  2604. nl += d^1;
  2605. }
  2606. bool split_input_data;
  2607. node->left = left = data->new_node( node, nl, new_buf_idx, node->offset );
  2608. node->right = right = data->new_node( node, nr, new_buf_idx, node->offset + nl );
  2609. split_input_data = node->depth + 1 < data->params.max_depth &&
  2610. (node->left->sample_count > data->params.min_sample_count ||
  2611. node->right->sample_count > data->params.min_sample_count);
  2612. // split ordered variables, keep both halves sorted.
  2613. for( vi = 0; vi < data->var_count; vi++ )
  2614. {
  2615. int ci = data->get_var_type(vi);
  2616. if( ci >= 0 || !split_input_data )
  2617. continue;
  2618. int n1 = node->get_num_valid(vi);
  2619. float* src_val_buf = (float*)(uchar*)(temp_buf + n);
  2620. int* src_sorted_idx_buf = (int*)(src_val_buf + n);
  2621. int* src_sample_idx_buf = src_sorted_idx_buf + n;
  2622. const float* src_val = 0;
  2623. const int* src_sorted_idx = 0;
  2624. data->get_ord_var_data(node, vi, src_val_buf, src_sorted_idx_buf, &src_val, &src_sorted_idx, src_sample_idx_buf);
  2625. for(i = 0; i < n; i++)
  2626. temp_buf[i] = src_sorted_idx[i];
  2627. if (data->is_buf_16u)
  2628. {
  2629. unsigned short *ldst, *rdst, *ldst0, *rdst0;
  2630. //unsigned short tl, tr;
  2631. ldst0 = ldst = (unsigned short*)(buf->data.s + left->buf_idx*length_buf_row +
  2632. vi*scount + left->offset);
  2633. rdst0 = rdst = (unsigned short*)(ldst + nl);
  2634. // split sorted
  2635. for( i = 0; i < n1; i++ )
  2636. {
  2637. int idx = temp_buf[i];
  2638. int d = dir[idx];
  2639. idx = new_idx[idx];
  2640. if (d)
  2641. {
  2642. *rdst = (unsigned short)idx;
  2643. rdst++;
  2644. }
  2645. else
  2646. {
  2647. *ldst = (unsigned short)idx;
  2648. ldst++;
  2649. }
  2650. }
  2651. left->set_num_valid(vi, (int)(ldst - ldst0));
  2652. right->set_num_valid(vi, (int)(rdst - rdst0));
  2653. // split missing
  2654. for( ; i < n; i++ )
  2655. {
  2656. int idx = temp_buf[i];
  2657. int d = dir[idx];
  2658. idx = new_idx[idx];
  2659. if (d)
  2660. {
  2661. *rdst = (unsigned short)idx;
  2662. rdst++;
  2663. }
  2664. else
  2665. {
  2666. *ldst = (unsigned short)idx;
  2667. ldst++;
  2668. }
  2669. }
  2670. }
  2671. else
  2672. {
  2673. int *ldst0, *ldst, *rdst0, *rdst;
  2674. ldst0 = ldst = buf->data.i + left->buf_idx*length_buf_row +
  2675. vi*scount + left->offset;
  2676. rdst0 = rdst = buf->data.i + right->buf_idx*length_buf_row +
  2677. vi*scount + right->offset;
  2678. // split sorted
  2679. for( i = 0; i < n1; i++ )
  2680. {
  2681. int idx = temp_buf[i];
  2682. int d = dir[idx];
  2683. idx = new_idx[idx];
  2684. if (d)
  2685. {
  2686. *rdst = idx;
  2687. rdst++;
  2688. }
  2689. else
  2690. {
  2691. *ldst = idx;
  2692. ldst++;
  2693. }
  2694. }
  2695. left->set_num_valid(vi, (int)(ldst - ldst0));
  2696. right->set_num_valid(vi, (int)(rdst - rdst0));
  2697. // split missing
  2698. for( ; i < n; i++ )
  2699. {
  2700. int idx = temp_buf[i];
  2701. int d = dir[idx];
  2702. idx = new_idx[idx];
  2703. if (d)
  2704. {
  2705. *rdst = idx;
  2706. rdst++;
  2707. }
  2708. else
  2709. {
  2710. *ldst = idx;
  2711. ldst++;
  2712. }
  2713. }
  2714. }
  2715. }
  2716. // split categorical vars, responses and cv_labels using new_idx relocation table
  2717. for( vi = 0; vi < work_var_count; vi++ )
  2718. {
  2719. int ci = data->get_var_type(vi);
  2720. int n1 = node->get_num_valid(vi), nr1 = 0;
  2721. if( ci < 0 || (vi < data->var_count && !split_input_data) )
  2722. continue;
  2723. int *src_lbls_buf = temp_buf + n;
  2724. const int* src_lbls = data->get_cat_var_data(node, vi, src_lbls_buf);
  2725. for(i = 0; i < n; i++)
  2726. temp_buf[i] = src_lbls[i];
  2727. if (data->is_buf_16u)
  2728. {
  2729. unsigned short *ldst = (unsigned short *)(buf->data.s + left->buf_idx*length_buf_row +
  2730. vi*scount + left->offset);
  2731. unsigned short *rdst = (unsigned short *)(buf->data.s + right->buf_idx*length_buf_row +
  2732. vi*scount + right->offset);
  2733. for( i = 0; i < n; i++ )
  2734. {
  2735. int d = dir[i];
  2736. int idx = temp_buf[i];
  2737. if (d)
  2738. {
  2739. *rdst = (unsigned short)idx;
  2740. rdst++;
  2741. nr1 += (idx != 65535 )&d;
  2742. }
  2743. else
  2744. {
  2745. *ldst = (unsigned short)idx;
  2746. ldst++;
  2747. }
  2748. }
  2749. if( vi < data->var_count )
  2750. {
  2751. left->set_num_valid(vi, n1 - nr1);
  2752. right->set_num_valid(vi, nr1);
  2753. }
  2754. }
  2755. else
  2756. {
  2757. int *ldst = buf->data.i + left->buf_idx*length_buf_row +
  2758. vi*scount + left->offset;
  2759. int *rdst = buf->data.i + right->buf_idx*length_buf_row +
  2760. vi*scount + right->offset;
  2761. for( i = 0; i < n; i++ )
  2762. {
  2763. int d = dir[i];
  2764. int idx = temp_buf[i];
  2765. if (d)
  2766. {
  2767. *rdst = idx;
  2768. rdst++;
  2769. nr1 += (idx >= 0)&d;
  2770. }
  2771. else
  2772. {
  2773. *ldst = idx;
  2774. ldst++;
  2775. }
  2776. }
  2777. if( vi < data->var_count )
  2778. {
  2779. left->set_num_valid(vi, n1 - nr1);
  2780. right->set_num_valid(vi, nr1);
  2781. }
  2782. }
  2783. }
  2784. // split sample indices
  2785. int *sample_idx_src_buf = temp_buf + n;
  2786. const int* sample_idx_src = data->get_sample_indices(node, sample_idx_src_buf);
  2787. for(i = 0; i < n; i++)
  2788. temp_buf[i] = sample_idx_src[i];
  2789. int pos = data->get_work_var_count();
  2790. if (data->is_buf_16u)
  2791. {
  2792. unsigned short* ldst = (unsigned short*)(buf->data.s + left->buf_idx*length_buf_row +
  2793. pos*scount + left->offset);
  2794. unsigned short* rdst = (unsigned short*)(buf->data.s + right->buf_idx*length_buf_row +
  2795. pos*scount + right->offset);
  2796. for (i = 0; i < n; i++)
  2797. {
  2798. int d = dir[i];
  2799. unsigned short idx = (unsigned short)temp_buf[i];
  2800. if (d)
  2801. {
  2802. *rdst = idx;
  2803. rdst++;
  2804. }
  2805. else
  2806. {
  2807. *ldst = idx;
  2808. ldst++;
  2809. }
  2810. }
  2811. }
  2812. else
  2813. {
  2814. int* ldst = buf->data.i + left->buf_idx*length_buf_row +
  2815. pos*scount + left->offset;
  2816. int* rdst = buf->data.i + right->buf_idx*length_buf_row +
  2817. pos*scount + right->offset;
  2818. for (i = 0; i < n; i++)
  2819. {
  2820. int d = dir[i];
  2821. int idx = temp_buf[i];
  2822. if (d)
  2823. {
  2824. *rdst = idx;
  2825. rdst++;
  2826. }
  2827. else
  2828. {
  2829. *ldst = idx;
  2830. ldst++;
  2831. }
  2832. }
  2833. }
  2834. // deallocate the parent node data that is not needed anymore
  2835. data->free_node_data(node);
  2836. }
  2837. float CvDTree::calc_error( CvMLData* _data, int type, std::vector<float> *resp )
  2838. {
  2839. float err = 0;
  2840. const CvMat* values = _data->get_values();
  2841. const CvMat* response = _data->get_responses();
  2842. const CvMat* missing = _data->get_missing();
  2843. const CvMat* sample_idx = (type == CV_TEST_ERROR) ? _data->get_test_sample_idx() : _data->get_train_sample_idx();
  2844. const CvMat* var_types = _data->get_var_types();
  2845. int* sidx = sample_idx ? sample_idx->data.i : 0;
  2846. int r_step = CV_IS_MAT_CONT(response->type) ?
  2847. 1 : response->step / CV_ELEM_SIZE(response->type);
  2848. bool is_classifier = var_types->data.ptr[var_types->cols-1] == CV_VAR_CATEGORICAL;
  2849. int sample_count = sample_idx ? sample_idx->cols : 0;
  2850. sample_count = (type == CV_TRAIN_ERROR && sample_count == 0) ? values->rows : sample_count;
  2851. float* pred_resp = 0;
  2852. if( resp && (sample_count > 0) )
  2853. {
  2854. resp->resize( sample_count );
  2855. pred_resp = &((*resp)[0]);
  2856. }
  2857. if ( is_classifier )
  2858. {
  2859. for( int i = 0; i < sample_count; i++ )
  2860. {
  2861. CvMat sample, miss;
  2862. int si = sidx ? sidx[i] : i;
  2863. cvGetRow( values, &sample, si );
  2864. if( missing )
  2865. cvGetRow( missing, &miss, si );
  2866. float r = (float)predict( &sample, missing ? &miss : 0 )->value;
  2867. if( pred_resp )
  2868. pred_resp[i] = r;
  2869. int d = fabs((double)r - response->data.fl[(size_t)si*r_step]) <= FLT_EPSILON ? 0 : 1;
  2870. err += d;
  2871. }
  2872. err = sample_count ? err / (float)sample_count * 100 : -FLT_MAX;
  2873. }
  2874. else
  2875. {
  2876. for( int i = 0; i < sample_count; i++ )
  2877. {
  2878. CvMat sample, miss;
  2879. int si = sidx ? sidx[i] : i;
  2880. cvGetRow( values, &sample, si );
  2881. if( missing )
  2882. cvGetRow( missing, &miss, si );
  2883. float r = (float)predict( &sample, missing ? &miss : 0 )->value;
  2884. if( pred_resp )
  2885. pred_resp[i] = r;
  2886. float d = r - response->data.fl[(size_t)si*r_step];
  2887. err += d*d;
  2888. }
  2889. err = sample_count ? err / (float)sample_count : -FLT_MAX;
  2890. }
  2891. return err;
  2892. }
  2893. void CvDTree::prune_cv()
  2894. {
  2895. CvMat* ab = 0;
  2896. CvMat* temp = 0;
  2897. CvMat* err_jk = 0;
  2898. // 1. build tree sequence for each cv fold, calculate error_{Tj,beta_k}.
  2899. // 2. choose the best tree index (if need, apply 1SE rule).
  2900. // 3. store the best index and cut the branches.
  2901. CV_FUNCNAME( "CvDTree::prune_cv" );
  2902. __BEGIN__;
  2903. int ti, j, tree_count = 0, cv_n = data->params.cv_folds, n = root->sample_count;
  2904. // currently, 1SE for regression is not implemented
  2905. bool use_1se = data->params.use_1se_rule != 0 && data->is_classifier;
  2906. double* err;
  2907. double min_err = 0, min_err_se = 0;
  2908. int min_idx = -1;
  2909. CV_CALL( ab = cvCreateMat( 1, 256, CV_64F ));
  2910. // build the main tree sequence, calculate alpha's
  2911. for(;;tree_count++)
  2912. {
  2913. double min_alpha = update_tree_rnc(tree_count, -1);
  2914. if( cut_tree(tree_count, -1, min_alpha) )
  2915. break;
  2916. if( ab->cols <= tree_count )
  2917. {
  2918. CV_CALL( temp = cvCreateMat( 1, ab->cols*3/2, CV_64F ));
  2919. for( ti = 0; ti < ab->cols; ti++ )
  2920. temp->data.db[ti] = ab->data.db[ti];
  2921. cvReleaseMat( &ab );
  2922. ab = temp;
  2923. temp = 0;
  2924. }
  2925. ab->data.db[tree_count] = min_alpha;
  2926. }
  2927. ab->data.db[0] = 0.;
  2928. if( tree_count > 0 )
  2929. {
  2930. for( ti = 1; ti < tree_count-1; ti++ )
  2931. ab->data.db[ti] = sqrt(ab->data.db[ti]*ab->data.db[ti+1]);
  2932. ab->data.db[tree_count-1] = DBL_MAX*0.5;
  2933. CV_CALL( err_jk = cvCreateMat( cv_n, tree_count, CV_64F ));
  2934. err = err_jk->data.db;
  2935. for( j = 0; j < cv_n; j++ )
  2936. {
  2937. int tj = 0, tk = 0;
  2938. for( ; tk < tree_count; tj++ )
  2939. {
  2940. double min_alpha = update_tree_rnc(tj, j);
  2941. if( cut_tree(tj, j, min_alpha) )
  2942. min_alpha = DBL_MAX;
  2943. for( ; tk < tree_count; tk++ )
  2944. {
  2945. if( ab->data.db[tk] > min_alpha )
  2946. break;
  2947. err[j*tree_count + tk] = root->tree_error;
  2948. }
  2949. }
  2950. }
  2951. for( ti = 0; ti < tree_count; ti++ )
  2952. {
  2953. double sum_err = 0;
  2954. for( j = 0; j < cv_n; j++ )
  2955. sum_err += err[j*tree_count + ti];
  2956. if( ti == 0 || sum_err < min_err )
  2957. {
  2958. min_err = sum_err;
  2959. min_idx = ti;
  2960. if( use_1se )
  2961. min_err_se = sqrt( sum_err*(n - sum_err) );
  2962. }
  2963. else if( sum_err < min_err + min_err_se )
  2964. min_idx = ti;
  2965. }
  2966. }
  2967. pruned_tree_idx = min_idx;
  2968. free_prune_data(data->params.truncate_pruned_tree != 0);
  2969. __END__;
  2970. cvReleaseMat( &err_jk );
  2971. cvReleaseMat( &ab );
  2972. cvReleaseMat( &temp );
  2973. }
  2974. double CvDTree::update_tree_rnc( int T, int fold )
  2975. {
  2976. CvDTreeNode* node = root;
  2977. double min_alpha = DBL_MAX;
  2978. for(;;)
  2979. {
  2980. CvDTreeNode* parent;
  2981. for(;;)
  2982. {
  2983. int t = fold >= 0 ? node->cv_Tn[fold] : node->Tn;
  2984. if( t <= T || !node->left )
  2985. {
  2986. node->complexity = 1;
  2987. node->tree_risk = node->node_risk;
  2988. node->tree_error = 0.;
  2989. if( fold >= 0 )
  2990. {
  2991. node->tree_risk = node->cv_node_risk[fold];
  2992. node->tree_error = node->cv_node_error[fold];
  2993. }
  2994. break;
  2995. }
  2996. node = node->left;
  2997. }
  2998. for( parent = node->parent; parent && parent->right == node;
  2999. node = parent, parent = parent->parent )
  3000. {
  3001. parent->complexity += node->complexity;
  3002. parent->tree_risk += node->tree_risk;
  3003. parent->tree_error += node->tree_error;
  3004. parent->alpha = ((fold >= 0 ? parent->cv_node_risk[fold] : parent->node_risk)
  3005. - parent->tree_risk)/(parent->complexity - 1);
  3006. min_alpha = MIN( min_alpha, parent->alpha );
  3007. }
  3008. if( !parent )
  3009. break;
  3010. parent->complexity = node->complexity;
  3011. parent->tree_risk = node->tree_risk;
  3012. parent->tree_error = node->tree_error;
  3013. node = parent->right;
  3014. }
  3015. return min_alpha;
  3016. }
  3017. int CvDTree::cut_tree( int T, int fold, double min_alpha )
  3018. {
  3019. CvDTreeNode* node = root;
  3020. if( !node->left )
  3021. return 1;
  3022. for(;;)
  3023. {
  3024. CvDTreeNode* parent;
  3025. for(;;)
  3026. {
  3027. int t = fold >= 0 ? node->cv_Tn[fold] : node->Tn;
  3028. if( t <= T || !node->left )
  3029. break;
  3030. if( node->alpha <= min_alpha + FLT_EPSILON )
  3031. {
  3032. if( fold >= 0 )
  3033. node->cv_Tn[fold] = T;
  3034. else
  3035. node->Tn = T;
  3036. if( node == root )
  3037. return 1;
  3038. break;
  3039. }
  3040. node = node->left;
  3041. }
  3042. for( parent = node->parent; parent && parent->right == node;
  3043. node = parent, parent = parent->parent )
  3044. ;
  3045. if( !parent )
  3046. break;
  3047. node = parent->right;
  3048. }
  3049. return 0;
  3050. }
  3051. void CvDTree::free_prune_data(bool _cut_tree)
  3052. {
  3053. CvDTreeNode* node = root;
  3054. for(;;)
  3055. {
  3056. CvDTreeNode* parent;
  3057. for(;;)
  3058. {
  3059. // do not call cvSetRemoveByPtr( cv_heap, node->cv_Tn )
  3060. // as we will clear the whole cross-validation heap at the end
  3061. node->cv_Tn = 0;
  3062. node->cv_node_error = node->cv_node_risk = 0;
  3063. if( !node->left )
  3064. break;
  3065. node = node->left;
  3066. }
  3067. for( parent = node->parent; parent && parent->right == node;
  3068. node = parent, parent = parent->parent )
  3069. {
  3070. if( _cut_tree && parent->Tn <= pruned_tree_idx )
  3071. {
  3072. data->free_node( parent->left );
  3073. data->free_node( parent->right );
  3074. parent->left = parent->right = 0;
  3075. }
  3076. }
  3077. if( !parent )
  3078. break;
  3079. node = parent->right;
  3080. }
  3081. if( data->cv_heap )
  3082. cvClearSet( data->cv_heap );
  3083. }
  3084. void CvDTree::free_tree()
  3085. {
  3086. if( root && data && data->shared )
  3087. {
  3088. pruned_tree_idx = INT_MIN;
  3089. free_prune_data(true);
  3090. data->free_node(root);
  3091. root = 0;
  3092. }
  3093. }
  3094. CvDTreeNode* CvDTree::predict( const CvMat* _sample,
  3095. const CvMat* _missing, bool preprocessed_input ) const
  3096. {
  3097. cv::AutoBuffer<int> catbuf;
  3098. int i, mstep = 0;
  3099. const uchar* m = 0;
  3100. CvDTreeNode* node = root;
  3101. if( !node )
  3102. CV_Error( CV_StsError, "The tree has not been trained yet" );
  3103. if( !CV_IS_MAT(_sample) || CV_MAT_TYPE(_sample->type) != CV_32FC1 ||
  3104. (_sample->cols != 1 && _sample->rows != 1) ||
  3105. (_sample->cols + _sample->rows - 1 != data->var_all && !preprocessed_input) ||
  3106. (_sample->cols + _sample->rows - 1 != data->var_count && preprocessed_input) )
  3107. CV_Error( CV_StsBadArg,
  3108. "the input sample must be 1d floating-point vector with the same "
  3109. "number of elements as the total number of variables used for training" );
  3110. const float* sample = _sample->data.fl;
  3111. int step = CV_IS_MAT_CONT(_sample->type) ? 1 : _sample->step/sizeof(sample[0]);
  3112. if( data->cat_count && !preprocessed_input ) // cache for categorical variables
  3113. {
  3114. int n = data->cat_count->cols;
  3115. catbuf.allocate(n);
  3116. for( i = 0; i < n; i++ )
  3117. catbuf[i] = -1;
  3118. }
  3119. if( _missing )
  3120. {
  3121. if( !CV_IS_MAT(_missing) || !CV_IS_MASK_ARR(_missing) ||
  3122. !CV_ARE_SIZES_EQ(_missing, _sample) )
  3123. CV_Error( CV_StsBadArg,
  3124. "the missing data mask must be 8-bit vector of the same size as input sample" );
  3125. m = _missing->data.ptr;
  3126. mstep = CV_IS_MAT_CONT(_missing->type) ? 1 : _missing->step/sizeof(m[0]);
  3127. }
  3128. const int* vtype = data->var_type->data.i;
  3129. const int* vidx = data->var_idx && !preprocessed_input ? data->var_idx->data.i : 0;
  3130. const int* cmap = data->cat_map ? data->cat_map->data.i : 0;
  3131. const int* cofs = data->cat_ofs ? data->cat_ofs->data.i : 0;
  3132. while( node->Tn > pruned_tree_idx && node->left )
  3133. {
  3134. CvDTreeSplit* split = node->split;
  3135. int dir = 0;
  3136. for( ; !dir && split != 0; split = split->next )
  3137. {
  3138. int vi = split->var_idx;
  3139. int ci = vtype[vi];
  3140. i = vidx ? vidx[vi] : vi;
  3141. float val = sample[(size_t)i*step];
  3142. if( m && m[(size_t)i*mstep] )
  3143. continue;
  3144. if( ci < 0 ) // ordered
  3145. dir = val <= split->ord.c ? -1 : 1;
  3146. else // categorical
  3147. {
  3148. int c;
  3149. if( preprocessed_input )
  3150. c = cvRound(val);
  3151. else
  3152. {
  3153. c = catbuf[ci];
  3154. if( c < 0 )
  3155. {
  3156. int a = c = cofs[ci];
  3157. int b = (ci+1 >= data->cat_ofs->cols) ? data->cat_map->cols : cofs[ci+1];
  3158. int ival = cvRound(val);
  3159. if( ival != val )
  3160. CV_Error( CV_StsBadArg,
  3161. "one of input categorical variable is not an integer" );
  3162. while( a < b )
  3163. {
  3164. c = (a + b) >> 1;
  3165. if( ival < cmap[c] )
  3166. b = c;
  3167. else if( ival > cmap[c] )
  3168. a = c+1;
  3169. else
  3170. break;
  3171. }
  3172. if( c < 0 || ival != cmap[c] )
  3173. continue;
  3174. catbuf[ci] = c -= cofs[ci];
  3175. }
  3176. }
  3177. c = ( (c == 65535) && data->is_buf_16u ) ? -1 : c;
  3178. dir = CV_DTREE_CAT_DIR(c, split->subset);
  3179. }
  3180. if( split->inversed )
  3181. dir = -dir;
  3182. }
  3183. if( !dir )
  3184. {
  3185. double diff = node->right->sample_count - node->left->sample_count;
  3186. dir = diff < 0 ? -1 : 1;
  3187. }
  3188. node = dir < 0 ? node->left : node->right;
  3189. }
  3190. return node;
  3191. }
  3192. CvDTreeNode* CvDTree::predict( const Mat& _sample, const Mat& _missing, bool preprocessed_input ) const
  3193. {
  3194. CvMat sample = cvMat(_sample), mmask = cvMat(_missing);
  3195. return predict(&sample, mmask.data.ptr ? &mmask : 0, preprocessed_input);
  3196. }
  3197. const CvMat* CvDTree::get_var_importance()
  3198. {
  3199. if( !var_importance )
  3200. {
  3201. CvDTreeNode* node = root;
  3202. double* importance;
  3203. if( !node )
  3204. return 0;
  3205. var_importance = cvCreateMat( 1, data->var_count, CV_64F );
  3206. cvZero( var_importance );
  3207. importance = var_importance->data.db;
  3208. for(;;)
  3209. {
  3210. CvDTreeNode* parent;
  3211. for( ;; node = node->left )
  3212. {
  3213. CvDTreeSplit* split = node->split;
  3214. if( !node->left || node->Tn <= pruned_tree_idx )
  3215. break;
  3216. for( ; split != 0; split = split->next )
  3217. importance[split->var_idx] += split->quality;
  3218. }
  3219. for( parent = node->parent; parent && parent->right == node;
  3220. node = parent, parent = parent->parent )
  3221. ;
  3222. if( !parent )
  3223. break;
  3224. node = parent->right;
  3225. }
  3226. cvNormalize( var_importance, var_importance, 1., 0, CV_L1 );
  3227. }
  3228. return var_importance;
  3229. }
  3230. void CvDTree::write_split( cv::FileStorage& fs, CvDTreeSplit* split ) const
  3231. {
  3232. int ci;
  3233. fs.startWriteStruct( 0, FileNode::MAP + FileNode::FLOW );
  3234. fs.write( "var", split->var_idx );
  3235. fs.write( "quality", split->quality );
  3236. ci = data->get_var_type(split->var_idx);
  3237. if( ci >= 0 ) // split on a categorical var
  3238. {
  3239. int i, n = data->cat_count->data.i[ci], to_right = 0, default_dir;
  3240. for( i = 0; i < n; i++ )
  3241. to_right += CV_DTREE_CAT_DIR(i,split->subset) > 0;
  3242. // ad-hoc rule when to use inverse categorical split notation
  3243. // to achieve more compact and clear representation
  3244. default_dir = to_right <= 1 || to_right <= MIN(3, n/2) || to_right <= n/3 ? -1 : 1;
  3245. fs.startWriteStruct( default_dir*(split->inversed ? -1 : 1) > 0 ?
  3246. "in" : "not_in", FileNode::SEQ+FileNode::FLOW );
  3247. for( i = 0; i < n; i++ )
  3248. {
  3249. int dir = CV_DTREE_CAT_DIR(i,split->subset);
  3250. if( dir*default_dir < 0 )
  3251. fs.write( 0, i );
  3252. }
  3253. fs.endWriteStruct();
  3254. }
  3255. else
  3256. fs.write( !split->inversed ? "le" : "gt", split->ord.c );
  3257. fs.endWriteStruct();
  3258. }
  3259. void CvDTree::write_node( cv::FileStorage& fs, CvDTreeNode* node ) const
  3260. {
  3261. fs.startWriteStruct( 0, FileNode::MAP );
  3262. fs.write( "depth", node->depth );
  3263. fs.write( "sample_count", node->sample_count );
  3264. fs.write( "value", node->value );
  3265. if( data->is_classifier )
  3266. fs.write( "norm_class_idx", node->class_idx );
  3267. fs.write( "Tn", node->Tn );
  3268. fs.write( "complexity", node->complexity );
  3269. fs.write( "alpha", node->alpha );
  3270. fs.write( "node_risk", node->node_risk );
  3271. fs.write( "tree_risk", node->tree_risk );
  3272. fs.write( "tree_error", node->tree_error );
  3273. if( node->left )
  3274. {
  3275. fs.startWriteStruct( "splits", FileNode::SEQ );
  3276. for( CvDTreeSplit* split = node->split; split != 0; split = split->next )
  3277. write_split( fs, split );
  3278. fs.endWriteStruct();
  3279. }
  3280. fs.endWriteStruct();
  3281. }
  3282. void CvDTree::write_tree_nodes( cv::FileStorage& fs ) const
  3283. {
  3284. //CV_FUNCNAME( "CvDTree::write_tree_nodes" );
  3285. __BEGIN__;
  3286. CvDTreeNode* node = root;
  3287. // traverse the tree and save all the nodes in depth-first order
  3288. for(;;)
  3289. {
  3290. CvDTreeNode* parent;
  3291. for(;;)
  3292. {
  3293. write_node( fs, node );
  3294. if( !node->left )
  3295. break;
  3296. node = node->left;
  3297. }
  3298. for( parent = node->parent; parent && parent->right == node;
  3299. node = parent, parent = parent->parent )
  3300. ;
  3301. if( !parent )
  3302. break;
  3303. node = parent->right;
  3304. }
  3305. __END__;
  3306. }
  3307. void CvDTree::write( cv::FileStorage& fs, const char* name ) const
  3308. {
  3309. //CV_FUNCNAME( "CvDTree::write" );
  3310. __BEGIN__;
  3311. fs.startWriteStruct( name, FileNode::MAP, CV_TYPE_NAME_ML_TREE );
  3312. //get_var_importance();
  3313. data->write_params( fs );
  3314. //if( var_importance )
  3315. //cvWrite( fs, "var_importance", var_importance );
  3316. write( fs );
  3317. fs.endWriteStruct();
  3318. __END__;
  3319. }
  3320. void CvDTree::write( cv::FileStorage& fs ) const
  3321. {
  3322. //CV_FUNCNAME( "CvDTree::write" );
  3323. __BEGIN__;
  3324. fs.write( "best_tree_idx", pruned_tree_idx );
  3325. fs.startWriteStruct( "nodes", FileNode::SEQ );
  3326. write_tree_nodes( fs );
  3327. fs.endWriteStruct();
  3328. __END__;
  3329. }
  3330. CvDTreeSplit* CvDTree::read_split( const cv::FileNode& fnode )
  3331. {
  3332. CvDTreeSplit* split = 0;
  3333. CV_FUNCNAME( "CvDTree::read_split" );
  3334. __BEGIN__;
  3335. int vi, ci;
  3336. if( fnode.empty() || !fnode.isMap() )
  3337. CV_ERROR( CV_StsParseError, "some of the splits are not stored properly" );
  3338. vi = fnode[ "var" ].empty() ? -1 : (int) fnode[ "var" ];
  3339. if( (unsigned)vi >= (unsigned)data->var_count )
  3340. CV_ERROR( CV_StsOutOfRange, "Split variable index is out of range" );
  3341. ci = data->get_var_type(vi);
  3342. if( ci >= 0 ) // split on categorical var
  3343. {
  3344. int i, n = data->cat_count->data.i[ci], inversed = 0, val;
  3345. FileNodeIterator reader;
  3346. cv::FileNode inseq;
  3347. split = data->new_split_cat( vi, 0 );
  3348. inseq = fnode[ "in" ];
  3349. if( inseq.empty() )
  3350. {
  3351. inseq = fnode[ "not_in" ];
  3352. inversed = 1;
  3353. }
  3354. if( inseq.empty() ||
  3355. (!inseq.isSeq() && !inseq.isInt()))
  3356. CV_ERROR( CV_StsParseError,
  3357. "Either 'in' or 'not_in' tags should be inside a categorical split data" );
  3358. if( inseq.isInt() )
  3359. {
  3360. val = (int) inseq;
  3361. if( (unsigned)val >= (unsigned)n )
  3362. CV_ERROR( CV_StsOutOfRange, "some of in/not_in elements are out of range" );
  3363. split->subset[val >> 5] |= 1 << (val & 31);
  3364. }
  3365. else
  3366. {
  3367. reader = inseq.begin();
  3368. for( i = 0; i < (int) (*reader).size(); i++ )
  3369. {
  3370. cv::FileNode inode = *reader;
  3371. val = (int) inode;
  3372. if( !inode.isInt() || (unsigned)val >= (unsigned)n )
  3373. CV_ERROR( CV_StsOutOfRange, "some of in/not_in elements are out of range" );
  3374. split->subset[val >> 5] |= 1 << (val & 31);
  3375. reader++;
  3376. }
  3377. }
  3378. // for categorical splits we do not use inversed splits,
  3379. // instead we inverse the variable set in the split
  3380. if( inversed )
  3381. for( i = 0; i < (n + 31) >> 5; i++ )
  3382. split->subset[i] ^= -1;
  3383. }
  3384. else
  3385. {
  3386. cv::FileNode cmp_node;
  3387. split = data->new_split_ord( vi, 0, 0, 0, 0 );
  3388. cmp_node = fnode[ "le" ];
  3389. if( cmp_node.empty() )
  3390. {
  3391. cmp_node = fnode[ "gt" ];
  3392. split->inversed = 1;
  3393. }
  3394. split->ord.c = (float) cmp_node;
  3395. }
  3396. split->quality = (float) fnode[ "quality" ];
  3397. __END__;
  3398. return split;
  3399. }
  3400. CvDTreeNode* CvDTree::read_node( const cv::FileNode& fnode, CvDTreeNode* parent )
  3401. {
  3402. CvDTreeNode* node = 0;
  3403. CV_FUNCNAME( "CvDTree::read_node" );
  3404. __BEGIN__;
  3405. cv::FileNode splits;
  3406. int i, depth;
  3407. if( fnode.empty() || !fnode.isMap() )
  3408. CV_ERROR( CV_StsParseError, "some of the tree elements are not stored properly" );
  3409. CV_CALL( node = data->new_node( parent, 0, 0, 0 ));
  3410. depth = fnode[ "depth" ].empty() ? -1 : (int) fnode[ "depth" ];
  3411. if( depth != node->depth )
  3412. CV_ERROR( CV_StsParseError, "incorrect node depth" );
  3413. node->sample_count = (int) fnode[ "sample_count" ];
  3414. node->value = (double) fnode[ "value" ];
  3415. if( data->is_classifier )
  3416. node->class_idx = (int) fnode[ "norm_class_idx" ];
  3417. node->Tn = (int) fnode[ "Tn" ];
  3418. node->complexity = (int) fnode[ "complexity" ];
  3419. node->alpha = (double) fnode[ "alpha" ];
  3420. node->node_risk = (double) fnode[ "node_risk" ];
  3421. node->tree_risk = (double) fnode[ "tree_risk" ];
  3422. node->tree_error = (double) fnode[ "tree_error" ];
  3423. splits = fnode[ "splits" ];
  3424. if( !splits.empty() )
  3425. {
  3426. FileNodeIterator reader;
  3427. CvDTreeSplit* last_split = 0;
  3428. if( !splits.isSeq() )
  3429. CV_ERROR( CV_StsParseError, "splits tag must stored as a sequence" );
  3430. reader = splits.begin();
  3431. for( i = 0; i < (int) (*reader).size(); i++ )
  3432. {
  3433. CvDTreeSplit* split;
  3434. CV_CALL( split = read_split( *reader ));
  3435. if( !last_split )
  3436. node->split = last_split = split;
  3437. else
  3438. last_split = last_split->next = split;
  3439. reader++;
  3440. }
  3441. }
  3442. __END__;
  3443. return node;
  3444. }
  3445. void CvDTree::read_tree_nodes( const cv::FileNode& fnode )
  3446. {
  3447. CV_FUNCNAME( "CvDTree::read_tree_nodes" );
  3448. __BEGIN__;
  3449. FileNodeIterator reader;
  3450. CvDTreeNode _root;
  3451. CvDTreeNode* parent = &_root;
  3452. int i;
  3453. parent->left = parent->right = parent->parent = 0;
  3454. reader = fnode.begin();
  3455. for( i = 0; i < (int) (*reader).size(); i++ )
  3456. {
  3457. CvDTreeNode* node;
  3458. CV_CALL( node = read_node( *reader, parent != &_root ? parent : 0 ));
  3459. if( !parent->left )
  3460. parent->left = node;
  3461. else
  3462. parent->right = node;
  3463. if( node->split )
  3464. parent = node;
  3465. else
  3466. {
  3467. while( parent && parent->right )
  3468. parent = parent->parent;
  3469. }
  3470. reader++;
  3471. }
  3472. root = _root.left;
  3473. __END__;
  3474. }
  3475. void CvDTree::read( const cv::FileNode& fnode )
  3476. {
  3477. CvDTreeTrainData* _data = new CvDTreeTrainData();
  3478. _data->read_params( fnode );
  3479. read( fnode, _data );
  3480. get_var_importance();
  3481. }
  3482. // a special entry point for reading weak decision trees from the tree ensembles
  3483. void CvDTree::read( const cv::FileNode& node, CvDTreeTrainData* _data )
  3484. {
  3485. CV_FUNCNAME( "CvDTree::read" );
  3486. __BEGIN__;
  3487. cv::FileNode tree_nodes;
  3488. clear();
  3489. data = _data;
  3490. tree_nodes = node[ "nodes" ];
  3491. if( tree_nodes.empty() || !tree_nodes.isSeq() )
  3492. CV_ERROR( CV_StsParseError, "nodes tag is missing" );
  3493. pruned_tree_idx = node[ "best_tree_idx" ].empty() ? -1 : node[ "best_tree_idx" ];
  3494. read_tree_nodes( tree_nodes );
  3495. __END__;
  3496. }
  3497. Mat CvDTree::getVarImportance()
  3498. {
  3499. return cvarrToMat(get_var_importance());
  3500. }
  3501. /* End of file. */