83 if (a<b) {
Int_t tmp =
a; a=
b; b=tmp; }
96 fVerboseLevel(TString(
"Info")),
97 fScaleWithPreselEff(0),
101 fLogger( new
MsgLogger(
"DataSetFactory", kINFO) )
110 std::vector<TTreeFormula*>::const_iterator formIt;
152 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"Build DataSet consisting of one Event with dynamically changing variables" <<
Endl;
162 std::vector<Float_t*>* evdyn =
new std::vector<Float_t*>(0);
166 if (varinfos.empty())
167 Log() << kFATAL <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"Dynamic data set cannot be built, since no variable informations are present. Apparently no variables have been set. This should not happen, please contact the TMVA authors." <<
Endl;
169 std::vector<VariableInfo>::iterator it = varinfos.begin(), itEnd=varinfos.end();
170 for (;it!=itEnd;++it) {
173 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"The link to the external variable is NULL while I am trying to build a dynamic data set. In this case fTmpEvent from MethodBase HAS TO BE USED in the method to get useful values in variables." <<
Endl;
174 else evdyn->push_back (external);
178 it = spectatorinfos.begin();
179 for (;it!=spectatorinfos.end();it++) evdyn->push_back( (
Float_t*)(*it).GetExternalLink() );
181 TMVA::Event * ev =
new Event((
const std::vector<Float_t*>*&)evdyn, varinfos.size());
182 std::vector<Event*>* newEventVector =
new std::vector<Event*>;
183 newEventVector->push_back(ev);
187 ds->SetCurrentEvent( 0 );
189 delete newEventVector;
206 std::vector< TString >* classList = dataInput.
GetClassList();
207 for (std::vector<TString>::iterator it = classList->begin(); it< classList->end(); it++) {
218 InitOptions( dsi, eventCounts, normMode, splitSeed, splitMode , mixMode );
224 splitMode, mixMode, normMode, splitSeed );
227 if (showCollectedOutput) {
248 const TString& expression,
254 Log() << kFATAL <<
"Expression " << expression.Data()
255 <<
" could not be resolved to a valid formula. " <<
Endl;
257 Log() << kWARNING <<
"Expression: " << expression.Data()
258 <<
" does not provide data for this event. " 259 <<
"This event is not taken into account. --> please check if you use as a variable " 260 <<
"an entry of an array which is not filled for some events " 261 <<
"(e.g. arr[4] when arr has only 3 elements)." <<
Endl;
262 Log() << kWARNING <<
"If you want to take the event into account you can do something like: " 263 <<
"\"Alt$(arr[4],0)\" where in cases where arr doesn't have a 4th element, " 264 <<
" 0 is taken as an alternative." <<
Endl;
267 if( expression.Contains(
"$") )
271 for (
int i = 0, iEnd = ttf->
GetNcodes (); i < iEnd; ++i)
291 TTree *tr = tinfo.
GetTree()->GetTree();
293 tr->SetBranchStatus(
"*",1);
294 tr->ResetBranchAddresses();
299 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"transform input variables" <<
Endl;
300 std::vector<TTreeFormula*>::const_iterator formIt, formItEnd;
315 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"transform regression targets" <<
Endl;
328 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"transform spectator variables" <<
Endl;
342 for (formIt =
fCutFormulas.begin(), formItEnd =
fCutFormulas.end(); formIt!=formItEnd; formIt++)
if (*formIt)
delete *formIt;
346 const TString tmpCutExp(tmpCut.GetTitle());
362 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"transform weights" <<
Endl;
375 ttf =
new TTreeFormula(
"FormulaWeight", tmpWeight, tr );
391 tr->SetBranchStatus(
"*",0);
392 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"enable branches: input variables" <<
Endl;
401 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"enable branches: targets" <<
Endl;
408 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"enable branches: spectators" <<
Endl;
415 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"enable branches: cuts" <<
Endl;
423 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"enable branches: weights" <<
Endl;
431 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"tree initialized" <<
Endl;
451 for (
UInt_t ivar=0; ivar<nvar ; ivar++) { min[ivar] = FLT_MAX; max[ivar] = -FLT_MAX; }
452 for (
UInt_t ivar=0; ivar<ntgts; ivar++) { tgmin[ivar] = FLT_MAX; tgmax[ivar] = -FLT_MAX; }
453 for (
UInt_t ivar=0; ivar<nvis; ivar++) { vmin[ivar] = FLT_MAX; vmax[ivar] = -FLT_MAX; }
459 for (
UInt_t ivar=0; ivar<nvar; ivar++) {
461 if (v<min[ivar]) min[ivar] =
v;
462 if (v>max[ivar]) max[ivar] =
v;
464 for (
UInt_t itgt=0; itgt<ntgts; itgt++) {
466 if (v<tgmin[itgt]) tgmin[itgt] =
v;
467 if (v>tgmax[itgt]) tgmax[itgt] =
v;
469 for (
UInt_t ivis=0; ivis<nvis; ivis++) {
471 if (v<vmin[ivis]) vmin[ivis] =
v;
472 if (v>vmax[ivis]) vmax[ivis] =
v;
476 for (
UInt_t ivar=0; ivar<nvar; ivar++) {
479 if(
TMath::Abs(max[ivar]-min[ivar]) <= FLT_MIN )
482 for (
UInt_t ivar=0; ivar<ntgts; ivar++) {
485 if(
TMath::Abs(tgmax[ivar]-tgmin[ivar]) <= FLT_MIN )
488 for (
UInt_t ivar=0; ivar<nvis; ivar++) {
515 for (ivar=0; ivar<nvar; ivar++) {
516 for (jvar=0; jvar<nvar; jvar++) {
518 Double_t d = (*mat)(ivar, ivar)*(*mat)(jvar, jvar);
519 if (d > 0) (*mat)(ivar, jvar) /=
sqrt(d);
521 Log() << kWARNING <<
Form(
"Dataset[%s] : ",
DataSetInfo().
GetName())<<
"<GetCorrelationMatrix> Zero variances for variables " 522 <<
"(" << ivar <<
", " << jvar <<
") = " << d
524 (*mat)(ivar, jvar) = 0;
530 for (ivar=0; ivar<nvar; ivar++) (*mat)(ivar, ivar) = 1.0;
541 UInt_t ivar = 0, jvar = 0;
548 for (ivar=0; ivar<nvar; ivar++) {
550 for (jvar=0; jvar<nvar; jvar++) mat2(ivar, jvar) = 0;
558 if (ev->
GetClass() != classNumber )
continue;
563 for (ivar=0; ivar<nvar; ivar++) {
566 vec(ivar) += xi*weight;
567 mat2(ivar, ivar) += (xi*xi*weight);
569 for (jvar=ivar+1; jvar<nvar; jvar++) {
571 mat2(ivar, jvar) += (xi*xj*weight);
576 for (ivar=0; ivar<nvar; ivar++)
577 for (jvar=ivar+1; jvar<nvar; jvar++)
578 mat2(jvar, ivar) = mat2(ivar, jvar);
582 for (ivar=0; ivar<nvar; ivar++) {
583 for (jvar=0; jvar<nvar; jvar++) {
584 (*mat)(ivar, jvar) = mat2(ivar, jvar)/ic - vec(ivar)*vec(jvar)/(ic*ic);
606 splitSpecs.SetConfigDescription(
"Configuration options given in the \"PrepareForTrainingAndTesting\" call; these options define the creation of the data sets used for training and expert validation by TMVA" );
608 splitMode =
"Random";
609 splitSpecs.DeclareOptionRef( splitMode,
"SplitMode",
610 "Method of picking training and testing events (default: random)" );
611 splitSpecs.AddPreDefVal(TString(
"Random"));
612 splitSpecs.AddPreDefVal(TString(
"Alternate"));
613 splitSpecs.AddPreDefVal(TString(
"Block"));
615 mixMode =
"SameAsSplitMode";
616 splitSpecs.DeclareOptionRef( mixMode,
"MixMode",
617 "Method of mixing events of different classes into one dataset (default: SameAsSplitMode)" );
618 splitSpecs.AddPreDefVal(TString(
"SameAsSplitMode"));
619 splitSpecs.AddPreDefVal(TString(
"Random"));
620 splitSpecs.AddPreDefVal(TString(
"Alternate"));
621 splitSpecs.AddPreDefVal(TString(
"Block"));
624 splitSpecs.DeclareOptionRef( splitSeed,
"SplitSeed",
625 "Seed for random event shuffling" );
627 normMode =
"EqualNumEvents";
628 splitSpecs.DeclareOptionRef( normMode,
"NormMode",
629 "Overall renormalisation of event-by-event weights used in the training (NumEvents: average weight of 1 per event, independently for signal and background; EqualNumEvents: average weight of 1 per event for signal, and sum of weights for background equal to sum of weights for signal)" );
630 splitSpecs.AddPreDefVal(TString(
"None"));
631 splitSpecs.AddPreDefVal(TString(
"NumEvents"));
632 splitSpecs.AddPreDefVal(TString(
"EqualNumEvents"));
634 splitSpecs.DeclareOptionRef(
fScaleWithPreselEff=
kFALSE,
"ScaleWithPreselEff",
"Scale the number of requested events by the eff. of the preselection cuts (or not)" );
641 TString titleTrain = TString().Format(
"Number of training events of class %s (default: 0 = all)",clName.Data()).Data();
642 TString titleTest = TString().Format(
"Number of test events of class %s (default: 0 = all)",clName.Data()).Data();
643 TString titleSplit = TString().Format(
"Split in training and test events of class %s (default: 0 = deactivated)",clName.Data()).Data();
645 splitSpecs.DeclareOptionRef( nEventRequests.at(cl).nTrainingEventsRequested, TString(
"nTrain_")+clName, titleTrain );
646 splitSpecs.DeclareOptionRef( nEventRequests.at(cl).nTestingEventsRequested , TString(
"nTest_")+clName , titleTest );
647 splitSpecs.DeclareOptionRef( nEventRequests.at(cl).TrainTestSplitRequested , TString(
"TrainTestSplit_")+clName , titleTest );
650 splitSpecs.DeclareOptionRef(
fVerbose,
"V",
"Verbosity (default: true)" );
652 splitSpecs.DeclareOptionRef(
fVerboseLevel=TString(
"Info"),
"VerboseLevel",
"VerboseLevel (Debug/Verbose/Info)" );
653 splitSpecs.AddPreDefVal(TString(
"Debug"));
654 splitSpecs.AddPreDefVal(TString(
"Verbose"));
655 splitSpecs.AddPreDefVal(TString(
"Info"));
658 splitSpecs.DeclareOptionRef(
fCorrelations,
"Correlations",
"Boolean to show correlation output (Default: true)");
660 splitSpecs.ParseOptions();
661 splitSpecs.CheckForUnusedOptions();
670 splitMode.ToUpper(); mixMode.ToUpper(); normMode.ToUpper();
673 <<
"\tSplitmode is: \"" << splitMode <<
"\" the mixmode is: \"" << mixMode <<
"\"" <<
Endl;
674 if (mixMode==
"SAMEASSPLITMODE") mixMode = splitMode;
675 else if (mixMode!=splitMode)
676 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"DataSet splitmode="<<splitMode
677 <<
" differs from mixmode="<<mixMode<<Endl;
701 for (
size_t i=0; i<nclasses; i++) {
702 eventCounts[i].varAvLength =
new Float_t[nvars];
703 for (
UInt_t ivar=0; ivar<nvars; ivar++)
704 eventCounts[i].varAvLength[ivar] = 0;
714 std::map<TString, int> nanInfWarnings;
715 std::map<TString, int> nanInfErrors;
719 for (
UInt_t cl=0; cl<nclasses; cl++) {
723 EventStats& classEventCounts = eventCounts[cl];
731 TString currentFileName(
"");
737 std::vector<Float_t> vars(nvars);
738 std::vector<Float_t> tgts(ntgts);
739 std::vector<Float_t> vis(nvis);
746 Bool_t isChain = (TString(
"TChain") == currentInfo.
GetTree()->ClassName());
747 currentInfo.
GetTree()->LoadTree(0);
755 for (
Long64_t evtIdx = 0; evtIdx < nEvts; evtIdx++) {
756 currentInfo.
GetTree()->LoadTree(evtIdx);
760 if (currentInfo.
GetTree()->GetTree()->GetDirectory()->GetFile()->GetName() != currentFileName) {
761 currentFileName = currentInfo.
GetTree()->GetTree()->GetDirectory()->GetFile()->GetName();
765 currentInfo.
GetTree()->GetEntry(evtIdx);
766 Int_t sizeOfArrays = 1;
767 Int_t prevArrExpr = 0;
772 for (
UInt_t ivar=0; ivar<nvars; ivar++) {
775 if (ndata == 1)
continue;
777 varIsArray[ivar] =
kTRUE;
778 if (sizeOfArrays == 1) {
779 sizeOfArrays = ndata;
782 else if (sizeOfArrays!=ndata) {
783 Log() << kERROR <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"ERROR while preparing training and testing trees:" <<
Endl;
784 Log() <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
" multiple array-type expressions of different length were encountered" <<
Endl;
785 Log() <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
" location of error: event " << evtIdx
786 <<
" in tree " << currentInfo.
GetTree()->GetName()
787 <<
" of file " << currentInfo.
GetTree()->GetCurrentFile()->GetName() <<
Endl;
789 <<
Form(
"Dataset[%s] : ",dsi.
GetName()) << ndata <<
" entries, while" <<
Endl;
792 Log() << kFATAL <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"Need to abort" << Endl;
797 for (
Int_t idata = 0; idata<sizeOfArrays; idata++) {
800 auto checkNanInf = [&](std::map<TString, int> &msgMap,
Float_t value,
const char *what,
const char *formulaTitle) {
802 contains_NaN_or_inf =
kTRUE;
803 ++msgMap[
TString::Format(
"Dataset[%s] : %s expression resolves to indeterminate value (NaN): %s", dsi.
GetName(), what, formulaTitle)];
805 contains_NaN_or_inf =
kTRUE;
806 ++msgMap[
TString::Format(
"Dataset[%s] : %s expression resolves to infinite value (+inf or -inf): %s", dsi.
GetName(), what, formulaTitle)];
820 checkNanInf(nanInfErrors, cutVal,
"Cut", formula->
GetTitle());
824 auto &nanMessages = cutVal < 0.5 ? nanInfWarnings : nanInfErrors;
827 for (
UInt_t ivar=0; ivar<nvars; ivar++) {
830 vars[ivar] = (ndata == 1 ?
833 checkNanInf(nanMessages, vars[ivar],
"Input", formula->
GetTitle());
837 for (
UInt_t itrgt=0; itrgt<ntgts; itrgt++) {
840 tgts[itrgt] = (ndata == 1 ?
843 checkNanInf(nanMessages, tgts[itrgt],
"Target", formula->
GetTitle());
847 for (
UInt_t itVis=0; itVis<nvis; itVis++) {
850 vis[itVis] = (ndata == 1 ?
853 checkNanInf(nanMessages, vis[itVis],
"Spectator", formula->
GetTitle());
862 weight *= (ndata == 1 ?
865 checkNanInf(nanMessages, weight,
"Weight", formula->
GetTitle());
875 if (cutVal<0.5)
continue;
884 if (contains_NaN_or_inf) {
885 Log() << kWARNING <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"NaN or +-inf in Event " << evtIdx <<
Endl;
886 if (sizeOfArrays>1)
Log() << kWARNING <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
" rejected" <<
Endl;
896 event_v.push_back(
new Event(vars, tgts , vis, cl , weight));
899 currentInfo.
GetTree()->ResetBranchAddresses();
903 if (!nanInfWarnings.empty()) {
904 Log() << kWARNING <<
"Found events with NaN and/or +-inf values" <<
Endl;
905 for (
const auto &warning : nanInfWarnings) {
906 auto &
log =
Log() << kWARNING << warning.first;
907 if (warning.second > 1)
log <<
" (" << warning.second <<
" times)";
910 Log() << kWARNING <<
"These NaN and/or +-infs were all removed by the specified cut, continuing." <<
Endl;
914 if (!nanInfErrors.empty()) {
915 Log() << kWARNING <<
"Found events with NaN and/or +-inf values (not removed by cut)" <<
Endl;
916 for (
const auto &error : nanInfErrors) {
917 auto &
log =
Log() << kWARNING << error.first;
918 if (error.second > 1)
log <<
" (" << error.second <<
" times)";
921 Log() << kFATAL <<
"How am I supposed to train a NaN or +-inf?!" <<
Endl;
927 Log() << kHEADER <<
Form(
"[%s] : ",dsi.
GetName()) <<
"Number of events in input trees" <<
Endl;
928 Log() << kDEBUG <<
"(after possible flattening of arrays):" <<
Endl;
935 <<
" -- number of events : " 936 << std::setw(5) << eventCounts[cl].nEvBeforeCut
937 <<
" / sum of weights: " << std::setw(5) << eventCounts[cl].nWeEvBeforeCut <<
Endl;
943 <<
" tree -- total number of entries: " 949 <<
"\tPreselection: (will affect number of requested training and testing events)" <<
Endl;
952 <<
"\tPreselection: (will NOT affect number of requested training and testing events)" <<
Endl;
960 <<
" -- number of events passed: " 961 << std::setw(5) << eventCounts[cl].nEvAfterCut
962 <<
" / sum of weights: " << std::setw(5) << eventCounts[cl].nWeEvAfterCut <<
Endl;
965 <<
" -- efficiency : " 966 << std::setw(6) << eventCounts[cl].nWeEvAfterCut/eventCounts[cl].nWeEvBeforeCut <<
Endl;
970 <<
" No preselection cuts applied on event classes" <<
Endl;
983 const TString& splitMode,
984 const TString& mixMode,
985 const TString& normMode,
993 if (splitMode.Contains(
"RANDOM" ) ) {
997 if( ! unspecifiedEvents.empty() ) {
998 Log() << kDEBUG <<
"randomly shuffling " 999 << unspecifiedEvents.size()
1000 <<
" events of class " << cls
1001 <<
" which are not yet associated to testing or training" <<
Endl;
1002 std::shuffle(unspecifiedEvents.begin(), unspecifiedEvents.end(), rndm);
1008 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"SPLITTING ========" <<
Endl;
1010 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"---- class " << cls <<
Endl;
1011 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"check number of training/testing events, requested and available number of events and for class " << cls <<
Endl;
1018 Int_t availableTraining = eventVectorTraining.size();
1019 Int_t availableTesting = eventVectorTesting.size();
1020 Int_t availableUndefined = eventVectorUndefined.size();
1024 presel_scale = eventCounts[cls].cutScaling();
1025 if (presel_scale < 1)
1026 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
" you have opted for scaling the number of requested training/testing events\n to be scaled by the preselection efficiency"<<
Endl;
1029 if (eventCounts[cls].cutScaling() < 1)
1030 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
" you have opted for interpreting the requested number of training/testing events\n to be the number of events AFTER your preselection cuts" <<
Endl;
1037 if(eventCounts[cls].TrainTestSplitRequested < 1.0 && eventCounts[cls].TrainTestSplitRequested > 0.0){
1038 eventCounts[cls].nTrainingEventsRequested =
Int_t(eventCounts[cls].TrainTestSplitRequested*(availableTraining+availableTesting+availableUndefined));
1039 eventCounts[cls].nTestingEventsRequested =
Int_t(0);
1041 else if(eventCounts[cls].TrainTestSplitRequested != 0.0)
Log() << kFATAL <<
Form(
"The option TrainTestSplit_<class> has to be in range (0, 1] but is set to %f.",eventCounts[cls].TrainTestSplitRequested) <<
Endl;
1042 Int_t requestedTraining =
Int_t(eventCounts[cls].nTrainingEventsRequested * presel_scale);
1043 Int_t requestedTesting =
Int_t(eventCounts[cls].nTestingEventsRequested * presel_scale);
1045 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"events in training trees : " << availableTraining << Endl;
1046 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"events in testing trees : " << availableTesting << Endl;
1047 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"events in unspecified trees : " << availableUndefined << Endl;
1048 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"requested for training : " << requestedTraining << Endl;;
1051 Log() <<
" ( " << eventCounts[cls].nTrainingEventsRequested
1052 <<
" * " << presel_scale <<
" preselection efficiency)" <<
Endl;
1055 Log() << kDEBUG <<
"requested for testing : " << requestedTesting;
1057 Log() <<
" ( " << eventCounts[cls].nTestingEventsRequested
1058 <<
" * " << presel_scale <<
" preselection efficiency)" <<
Endl;
1109 Int_t useForTesting(0),useForTraining(0);
1110 Int_t allAvailable(availableUndefined + availableTraining + availableTesting);
1112 if( (requestedTraining == 0) && (requestedTesting == 0)){
1116 if ( availableUndefined >=
TMath::Abs(availableTraining - availableTesting) ) {
1118 useForTraining = useForTesting = allAvailable/2;
1121 useForTraining = availableTraining;
1122 useForTesting = availableTesting;
1123 if (availableTraining < availableTesting)
1124 useForTraining += availableUndefined;
1126 useForTesting += availableUndefined;
1128 requestedTraining = useForTraining;
1129 requestedTesting = useForTesting;
1132 else if (requestedTesting == 0){
1134 useForTraining =
TMath::Max(requestedTraining,availableTraining);
1135 if (allAvailable < useForTraining) {
1136 Log() << kFATAL <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"More events requested for training (" 1137 << requestedTraining <<
") than available (" 1138 << allAvailable <<
")!" << Endl;
1140 useForTesting = allAvailable - useForTraining;
1141 requestedTesting = useForTesting;
1144 else if (requestedTraining == 0){
1145 useForTesting =
TMath::Max(requestedTesting,availableTesting);
1146 if (allAvailable < useForTesting) {
1147 Log() << kFATAL <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"More events requested for testing (" 1148 << requestedTesting <<
") than available (" 1149 << allAvailable <<
")!" << Endl;
1151 useForTraining= allAvailable - useForTesting;
1152 requestedTraining = useForTraining;
1161 Int_t stillNeedForTraining =
TMath::Max(requestedTraining-availableTraining,0);
1162 Int_t stillNeedForTesting =
TMath::Max(requestedTesting-availableTesting,0);
1164 int NFree = availableUndefined - stillNeedForTraining - stillNeedForTesting;
1165 if (NFree <0) NFree = 0;
1166 useForTraining =
TMath::Max(requestedTraining,availableTraining) + NFree/2;
1167 useForTesting= allAvailable - useForTraining;
1170 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"determined event sample size to select training sample from="<<useForTraining<<Endl;
1171 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"determined event sample size to select test sample from="<<useForTesting<<Endl;
1176 if( splitMode ==
"ALTERNATE" ){
1177 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"split 'ALTERNATE'" << Endl;
1178 Int_t nTraining = availableTraining;
1179 Int_t nTesting = availableTesting;
1180 for( EventVector::iterator it = eventVectorUndefined.begin(), itEnd = eventVectorUndefined.end(); it != itEnd; ){
1182 if( nTraining <= requestedTraining ){
1183 eventVectorTraining.insert( eventVectorTraining.end(), (*it) );
1188 eventVectorTesting.insert( eventVectorTesting.end(), (*it) );
1193 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"split '" << splitMode <<
"'" << Endl;
1196 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"availableundefined : " << availableUndefined << Endl;
1197 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"useForTraining : " << useForTraining << Endl;
1198 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"useForTesting : " << useForTesting << Endl;
1199 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"availableTraining : " << availableTraining << Endl;
1200 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"availableTesting : " << availableTesting << Endl;
1202 if( availableUndefined<(useForTraining-availableTraining) ||
1203 availableUndefined<(useForTesting -availableTesting ) ||
1204 availableUndefined<(useForTraining+useForTesting-availableTraining-availableTesting ) ){
1205 Log() << kFATAL <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"More events requested than available!" << Endl;
1209 if (useForTraining>availableTraining){
1210 eventVectorTraining.insert( eventVectorTraining.end() , eventVectorUndefined.begin(), eventVectorUndefined.begin()+ useForTraining- availableTraining );
1211 eventVectorUndefined.erase( eventVectorUndefined.begin(), eventVectorUndefined.begin() + useForTraining- availableTraining);
1213 if (useForTesting>availableTesting){
1214 eventVectorTesting.insert( eventVectorTesting.end() , eventVectorUndefined.begin(), eventVectorUndefined.begin()+ useForTesting- availableTesting );
1217 eventVectorUndefined.clear();
1220 if (splitMode.Contains(
"RANDOM" )){
1221 UInt_t sizeTraining = eventVectorTraining.size();
1222 if( sizeTraining >
UInt_t(requestedTraining) ){
1223 std::vector<UInt_t> indicesTraining( sizeTraining );
1227 std::shuffle(indicesTraining.begin(), indicesTraining.end(), rndm);
1229 indicesTraining.erase( indicesTraining.begin()+sizeTraining-
UInt_t(requestedTraining), indicesTraining.end() );
1231 for( std::vector<UInt_t>::iterator it = indicesTraining.begin(), itEnd = indicesTraining.end(); it != itEnd; ++it ){
1232 delete eventVectorTraining.at( (*it) );
1233 eventVectorTraining.at( (*it) ) = NULL;
1236 eventVectorTraining.erase( std::remove( eventVectorTraining.begin(), eventVectorTraining.end(), (
void*)NULL ), eventVectorTraining.end() );
1239 UInt_t sizeTesting = eventVectorTesting.size();
1240 if( sizeTesting >
UInt_t(requestedTesting) ){
1241 std::vector<UInt_t> indicesTesting( sizeTesting );
1245 std::shuffle(indicesTesting.begin(), indicesTesting.end(), rndm);
1247 indicesTesting.erase( indicesTesting.begin()+sizeTesting-
UInt_t(requestedTesting), indicesTesting.end() );
1249 for( std::vector<UInt_t>::iterator it = indicesTesting.begin(), itEnd = indicesTesting.end(); it != itEnd; ++it ){
1250 delete eventVectorTesting.at( (*it) );
1251 eventVectorTesting.at( (*it) ) = NULL;
1254 eventVectorTesting.erase( std::remove( eventVectorTesting.begin(), eventVectorTesting.end(), (
void*)NULL ), eventVectorTesting.end() );
1258 if( eventVectorTraining.size() <
UInt_t(requestedTraining) )
1259 Log() << kWARNING <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"DataSetFactory/requested number of training samples larger than size of eventVectorTraining.\n" 1260 <<
"There is probably an issue. Please contact the TMVA developers." << Endl;
1261 std::for_each( eventVectorTraining.begin()+requestedTraining, eventVectorTraining.end(), DeleteFunctor<Event>() );
1262 eventVectorTraining.erase(eventVectorTraining.begin()+requestedTraining,eventVectorTraining.end());
1264 if( eventVectorTesting.size() <
UInt_t(requestedTesting) )
1265 Log() << kWARNING <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"DataSetFactory/requested number of testing samples larger than size of eventVectorTesting.\n" 1266 <<
"There is probably an issue. Please contact the TMVA developers." << Endl;
1267 std::for_each( eventVectorTesting.begin()+requestedTesting, eventVectorTesting.end(), DeleteFunctor<Event>() );
1268 eventVectorTesting.erase(eventVectorTesting.begin()+requestedTesting,eventVectorTesting.end());
1274 Int_t trainingSize = 0;
1275 Int_t testingSize = 0;
1289 trainingEventVector->reserve( trainingSize );
1290 testingEventVector->reserve( testingSize );
1296 Log() << kDEBUG <<
" MIXING ============= " <<
Endl;
1298 if( mixMode ==
"ALTERNATE" ){
1303 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"Training sample: You are trying to mix events in alternate mode although the classes have different event numbers. This works but the alternation stops at the last event of the smaller class."<<Endl;
1306 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"Testing sample: You are trying to mix events in alternate mode although the classes have different event numbers. This works but the alternation stops at the last event of the smaller class."<<Endl;
1309 typedef EventVector::iterator EvtVecIt;
1310 EvtVecIt itEvent, itEventEnd;
1313 Log() << kDEBUG <<
"insert class 0 into training and test vector" <<
Endl;
1315 testingEventVector->insert( testingEventVector->end(), tmpEventVector[
Types::kTesting].at(0).begin(), tmpEventVector[
Types::kTesting].at(0).end() );
1320 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"insert class " << cls << Endl;
1322 itTarget = trainingEventVector->begin() - 1;
1324 for( itEvent = tmpEventVector[
Types::kTraining].at(cls).begin(), itEventEnd = tmpEventVector[
Types::kTraining].at(cls).end(); itEvent != itEventEnd; ++itEvent ){
1326 if( (trainingEventVector->end() - itTarget) <
Int_t(cls+1) ) {
1327 itTarget = trainingEventVector->end();
1328 trainingEventVector->insert( itTarget, itEvent, itEventEnd );
1332 trainingEventVector->insert( itTarget, (*itEvent) );
1336 itTarget = testingEventVector->begin() - 1;
1338 for( itEvent = tmpEventVector[
Types::kTesting].at(cls).begin(), itEventEnd = tmpEventVector[
Types::kTesting].at(cls).end(); itEvent != itEventEnd; ++itEvent ){
1340 if( ( testingEventVector->end() - itTarget ) <
Int_t(cls+1) ) {
1341 itTarget = testingEventVector->end();
1342 testingEventVector->insert( itTarget, itEvent, itEventEnd );
1346 testingEventVector->insert( itTarget, (*itEvent) );
1352 trainingEventVector->insert( trainingEventVector->end(), tmpEventVector[
Types::kTraining].at(cls).begin(), tmpEventVector[
Types::kTraining].at(cls).end() );
1353 testingEventVector->insert ( testingEventVector->end(), tmpEventVector[
Types::kTesting].at(cls).begin(), tmpEventVector[
Types::kTesting].at(cls).end() );
1362 if (mixMode ==
"RANDOM") {
1363 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"shuffling events"<<Endl;
1365 std::shuffle(trainingEventVector->begin(), trainingEventVector->end(), rndm);
1366 std::shuffle(testingEventVector->begin(), testingEventVector->end(), rndm);
1369 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"trainingEventVector " << trainingEventVector->size() <<
Endl;
1370 Log() << kDEBUG <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"testingEventVector " << testingEventVector->size() <<
Endl;
1382 Log() << kFATAL <<
"Dataset " << std::string(dsi.
GetName()) <<
" does not have any training events, I better stop here and let you fix that one first " << Endl;
1386 Log() << kERROR <<
"Dataset " << std::string(dsi.
GetName()) <<
" does not have any testing events, guess that will cause problems later..but for now, I continue " << Endl;
1389 delete trainingEventVector;
1390 delete testingEventVector;
1407 const TString& normMode )
1414 Int_t trainingSize = 0;
1415 Int_t testingSize = 0;
1423 Double_t trainingSumSignalWeights = 0;
1424 Double_t trainingSumBackgrWeights = 0;
1425 Double_t testingSumSignalWeights = 0;
1426 Double_t testingSumBackgrWeights = 0;
1431 trainingSizePerClass.at(cls) = tmpEventVector[
Types::kTraining].at(cls).size();
1432 testingSizePerClass.at(cls) = tmpEventVector[
Types::kTesting].at(cls).size();
1434 trainingSize += trainingSizePerClass.back();
1435 testingSize += testingSizePerClass.back();
1448 trainingSumWeightsPerClass.at(cls) =
1453 testingSumWeightsPerClass.at(cls) =
1459 trainingSumSignalWeights += trainingSumWeightsPerClass.at(cls);
1460 testingSumSignalWeights += testingSumWeightsPerClass.at(cls);
1462 trainingSumBackgrWeights += trainingSumWeightsPerClass.at(cls);
1463 testingSumBackgrWeights += testingSumWeightsPerClass.at(cls);
1483 if (normMode ==
"NONE") {
1484 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"No weight renormalisation applied: use original global and event weights" <<
Endl;
1490 else if (normMode ==
"NUMEVENTS") {
1492 <<
"\tWeight renormalisation mode: \"NumEvents\": renormalises all event classes " <<
Endl;
1494 <<
" such that the effective (weighted) number of events in each class equals the respective " <<
Endl;
1496 <<
" number of events (entries) that you demanded in PrepareTrainingAndTestTree(\"\",\"nTrain_Signal=.. )" <<
Endl;
1498 <<
" ... i.e. such that Sum[i=1..N_j]{w_i} = N_j, j=0,1,2..." <<
Endl;
1500 <<
" ... (note that N_j is the sum of TRAINING events (nTrain_j...with j=Signal,Background.." <<
Endl;
1502 <<
" ..... Testing events are not renormalised nor included in the renormalisation factor! )"<<
Endl;
1508 renormFactor.at(cls) = ((
Float_t)trainingSizePerClass.at(cls) )/
1509 (trainingSumWeightsPerClass.at(cls)) ;
1512 else if (normMode ==
"EQUALNUMEVENTS") {
1518 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"Weight renormalisation mode: \"EqualNumEvents\": renormalises all event classes ..." <<
Endl;
1519 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
" such that the effective (weighted) number of events in each class is the same " <<
Endl;
1520 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
" (and equals the number of events (entries) given for class=0 )" <<
Endl;
1521 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"... i.e. such that Sum[i=1..N_j]{w_i} = N_classA, j=classA, classB, ..." <<
Endl;
1522 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
"... (note that N_j is the sum of TRAINING events" <<
Endl;
1523 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) <<
" ..... Testing events are not renormalised nor included in the renormalisation factor!)" <<
Endl;
1526 UInt_t referenceClass = 0;
1528 renormFactor.at(cls) =
Float_t(trainingSizePerClass.at(referenceClass))/
1529 (trainingSumWeightsPerClass.at(cls));
1533 Log() << kFATAL <<
Form(
"Dataset[%s] : ",dsi.
GetName())<<
"<PrepareForTrainingAndTesting> Unknown NormMode: " << normMode <<
Endl;
1541 <<
"--> Rescale " << setiosflags(ios::left) << std::setw(maxL)
1543 for (EventVector::iterator it = tmpEventVector[
Types::kTraining].at(cls).begin(),
1544 itEnd = tmpEventVector[
Types::kTraining].at(cls).end(); it != itEnd; ++it){
1545 (*it)->SetWeight ((*it)->GetWeight() * renormFactor.at(cls));
1556 <<
"Number of training and testing events" <<
Endl;
1557 Log() << kDEBUG <<
"\tafter rescaling:" <<
Endl;
1559 <<
"---------------------------------------------------------------------------" <<
Endl;
1561 trainingSumSignalWeights = 0;
1562 trainingSumBackgrWeights = 0;
1563 testingSumSignalWeights = 0;
1564 testingSumBackgrWeights = 0;
1567 trainingSumWeightsPerClass.at(cls) =
1572 testingSumWeightsPerClass.at(cls) =
1578 trainingSumSignalWeights += trainingSumWeightsPerClass.at(cls);
1579 testingSumSignalWeights += testingSumWeightsPerClass.at(cls);
1581 trainingSumBackgrWeights += trainingSumWeightsPerClass.at(cls);
1582 testingSumBackgrWeights += testingSumWeightsPerClass.at(cls);
1588 << setiosflags(ios::left) << std::setw(maxL)
1590 <<
"training events : " << trainingSizePerClass.at(cls) <<
Endl;
1591 Log() << kDEBUG <<
"\t(sum of weights: " << trainingSumWeightsPerClass.at(cls) <<
")" 1592 <<
" - requested were " << eventCounts[cls].nTrainingEventsRequested <<
" events" <<
Endl;
1594 << setiosflags(ios::left) << std::setw(maxL)
1596 <<
"testing events : " << testingSizePerClass.at(cls) <<
Endl;
1597 Log() << kDEBUG <<
"\t(sum of weights: " << testingSumWeightsPerClass.at(cls) <<
")" 1598 <<
" - requested were " << eventCounts[cls].nTestingEventsRequested <<
" events" <<
Endl;
1600 << setiosflags(ios::left) << std::setw(maxL)
1602 <<
"training and testing events: " 1603 << (trainingSizePerClass.at(cls)+testingSizePerClass.at(cls)) << Endl;
1604 Log() << kDEBUG <<
"\t(sum of weights: " 1605 << (trainingSumWeightsPerClass.at(cls)+testingSumWeightsPerClass.at(cls)) <<
")" << Endl;
1606 if(eventCounts[cls].nEvAfterCut<eventCounts[cls].nEvBeforeCut) {
1607 Log() << kINFO <<
Form(
"Dataset[%s] : ",dsi.
GetName()) << setiosflags(ios::left) << std::setw(maxL)
1609 <<
"due to the preselection a scaling factor has been applied to the numbers of requested events: " 1610 << eventCounts[cls].cutScaling() <<
Endl;
virtual const char * GetName() const
Returns name of object.
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
UInt_t GetNVariables() const
std::vector< EventVector > EventVectorOfClasses
void SetTrainingSumBackgrWeights(Double_t trainingSumBackgrWeights)
MsgLogger & Endl(MsgLogger &ml)
const TString & GetInternalName() const
std::vector< VariableInfo > & GetSpectatorInfos()
std::vector< TTreeFormula * > fInputFormulas
std::vector< TTreeFormula * > fCutFormulas
std::vector< Double_t > ValuePerClass
UInt_t GetNVariables() const
access the number of variables through the datasetinfo
void SetTrainingSumSignalWeights(Double_t trainingSumSignalWeights)
void SetTestingSumBackgrWeights(Double_t testingSumBackgrWeights)
void BuildEventVector(DataSetInfo &dsi, DataInputHandler &dataInput, EventVectorOfClassesOfTreeType &eventsmap, EvtStatsPerClass &eventCounts)
build empty event vectors distributes events between kTraining/kTesting/kMaxTreeType ...
UInt_t GetNClasses() const
void CalcMinMax(DataSet *, DataSetInfo &dsi)
compute covariance matrix
const TString & GetExpression() const
std::vector< int > NumberPerClass
std::map< Types::ETreeType, EventVectorOfClasses > EventVectorOfClassesOfTreeType
void InitOptions(DataSetInfo &dsi, EvtStatsPerClass &eventsmap, TString &normMode, UInt_t &splitSeed, TString &splitMode, TString &mixMode)
the dataset splitting
DataSet * BuildDynamicDataSet(DataSetInfo &)
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString...
UInt_t GetNSpectators() const
access the number of targets through the datasetinfo
MsgLogger & Log() const
message logger
std::vector< TTreeFormula * > fWeightFormula
void SetTestingSumSignalWeights(Double_t testingSumSignalWeights)
void PrintCorrelationMatrix(const TString &className)
calculates the correlation matrices for signal and background, prints them to standard output...
void SetMinType(EMsgType minType)
void RenormEvents(DataSetInfo &dsi, EventVectorOfClassesOfTreeType &eventsmap, const EvtStatsPerClass &eventCounts, const TString &normMode)
renormalisation of the TRAINING event weights
Class that contains all the data information.
Double_t GetWeight() const
return the event weight - depending on whether the flag IgnoreNegWeightsInTraining is or not...
Long64_t GetNTrainingEvents() const
void ChangeToNewTree(TreeInfo &, const DataSetInfo &)
While the data gets copied into the local training and testing trees, the input tree can change (for ...
TMatrixT< Double_t > TMatrixD
void SetCorrelationMatrix(const TString &className, TMatrixD *matrix)
Class that contains all the data information.
DataSetFactory()
constructor
TMatrixD * CalcCorrelationMatrix(DataSet *, const UInt_t classNumber)
computes correlation matrix for variables "theVars" in tree; "theType" defines the required event "ty...
Float_t GetTarget(UInt_t itgt) const
Int_t LargestCommonDivider(Int_t a, Int_t b)
UInt_t GetNTargets() const
Bool_t fScaleWithPreselEff
Types::ETreeType GetTreeType() const
ClassInfo * GetClassInfo(Int_t clNum) const
std::vector< TTreeFormula * > fSpectatorFormulas
DataSet * CreateDataSet(DataSetInfo &, DataInputHandler &)
steering the creation of a new dataset
VariableInfo & GetTargetInfo(Int_t i)
char * Form(const char *fmt,...)
UInt_t GetNSpectators(bool all=kTRUE) const
UInt_t GetSignalClassIndex()
std::vector< TTreeFormula * > fTargetFormulas
std::vector< Event *> EventVector
Long64_t GetNTestEvents() const
Float_t GetValue(UInt_t ivar) const
return value of i'th variable
DataSet * BuildInitialDataSet(DataSetInfo &, TMVA::DataInputHandler &)
if no entries, than create a DataSet with one Event which uses dynamic variables (pointers to variabl...
~DataSetFactory()
destructor
const TString & GetClassName() const
VariableInfo & GetSpectatorInfo(Int_t i)
void SetEventCollection(std::vector< Event *> *, Types::ETreeType, Bool_t deleteEvents=true)
Sets the event collection (by DataSetFactory)
VariableInfo & GetVariableInfo(Int_t i)
ClassInfo * AddClass(const TString &className)
Int_t GetClassNameMaxLength() const
virtual const char * GetName() const
Returns name of object.
Long64_t GetNClassEvents(Int_t type, UInt_t classNumber)
ostringstream derivative to redirect and format output
void SetConfigName(const char *n)
virtual const char * GetTitle() const
Returns title of object.
Abstract ClassifierFactory template that handles arbitrary types.
const TCut & GetCut() const
std::vector< EventStats > EvtStatsPerClass
const TString & GetSplitOptions() const
Short_t Max(Short_t a, Short_t b)
Double_t GetOriginalWeight() const
Bool_t CheckTTreeFormula(TTreeFormula *ttf, const TString &expression, Bool_t &hasDollar)
checks a TTreeFormula for problems
void SetNumber(const UInt_t index)
you should not use this method at all Int_t Int_t Double_t Double_t Double_t Int_t Double_t Double_t Double_t Double_t b
Long64_t GetNEvents(Types::ETreeType type=Types::kMaxTreeType) const
const TString & GetWeight() const
DataSet * MixEvents(DataSetInfo &dsi, EventVectorOfClassesOfTreeType &eventsmap, EvtStatsPerClass &eventCounts, const TString &splitMode, const TString &mixMode, const TString &normMode, UInt_t splitSeed)
Select and distribute unassigned events to kTraining and kTesting.
TBranch * GetBranch() const
virtual const char * GetName() const
Returns name of object.
virtual Bool_t IsOnTerminalBranch() const
Double_t GetWeight() const
UInt_t GetNTargets() const
access the number of targets through the datasetinfo
Float_t GetSpectator(UInt_t ivar) const
return spectator content
void SetNormalization(const TString &norm)
TMatrixD * CalcCovarianceMatrix(DataSet *, const UInt_t classNumber)
compute covariance matrix
const Event * GetEvent() const
std::vector< VariableInfo > & GetVariableInfos()
virtual const char * GetTitle() const
Returns title of object.