57 TMVA::RuleFit::RuleFit( const MethodBase *rfbase )
58 : fVisHistsUseImp(
kTRUE ),
59 fLogger( new MsgLogger("RuleFit") )
62 std::srand( randSEED );
73 , fVisHistsUseImp(
kTRUE )
92 UInt_t neve = fTrainingEvents.size();
95 fNEveEffTrain = CalcWeightSum( &fTrainingEvents );
104 this->SetMethodBase(rfbase);
105 fRuleEnsemble.Initialize(
this );
106 fRuleFitParams.SetRuleFit(
this );
118 UInt_t nevents = fMethodRuleFit->Data()->GetNTrainingEvents();
119 std::vector<const TMVA::Event*> tmp;
120 for (
Long64_t ievt=0; ievt<nevents; ievt++) {
121 const Event *
event = fMethodRuleFit->GetEvent(ievt);
122 tmp.push_back(event);
124 SetTrainingEvents( tmp );
133 fRuleEnsemble.MakeModel();
136 fRuleFitParams.Init();
145 fMethodBase = rfbase;
146 fMethodRuleFit =
dynamic_cast<const MethodRuleFit *
>(rfbase);
170 if (events==0)
return 0.0;
171 if (neve==0) neve=events->size();
174 for (
UInt_t ie=0; ie<neve; ie++) {
185 fLogger->SetMinType(t);
186 fRuleEnsemble.SetMsgType(t);
187 fRuleFitParams.SetMsgType(t);
196 if (fMethodRuleFit==0) {
197 Log() <<
kFATAL <<
"RuleFit::BuildTree() - Attempting to build a tree NOT from a MethodRuleFit" <<
Endl;
199 std::vector<const Event *> evevec;
200 for (
UInt_t ie=0; ie<fNTreeSample; ie++) {
201 evevec.push_back(fTrainingEventsRndm[ie]);
216 if (fMethodRuleFit==0) {
217 Log() <<
kFATAL <<
"RuleFit::BuildTree() - Attempting to build a tree NOT from a MethodRuleFit" <<
Endl;
219 Log() <<
kDEBUG <<
"Creating a forest with " << fMethodRuleFit->GetNTrees() <<
" decision trees" <<
Endl;
220 Log() <<
kDEBUG <<
"Each tree is built using a random subsample with " << fNTreeSample <<
" events" <<
Endl;
222 Timer timer( fMethodRuleFit->GetNTrees(),
"RuleFit" );
234 Bool_t useBoost = fMethodRuleFit->UseBoost();
236 if (useBoost) SaveEventWeights();
238 for (
Int_t i=0; i<fMethodRuleFit->GetNTrees(); i++) {
240 if (!useBoost) ReshuffleEvents();
243 for (
UInt_t ie = 0; ie<fNTreeSample; ie++) {
244 if (fMethodBase->DataInfo().IsSignal(fTrainingEventsRndm[ie])) nsig++;
253 const Int_t ntriesMax=10;
256 frnd = 100*rndGen.
Uniform( fMethodRuleFit->GetMinFracNEve(), 0.5*fMethodRuleFit->GetMaxFracNEve() );
258 Bool_t useRandomisedTree = !useBoost;
259 dt =
new DecisionTree( fMethodRuleFit->GetSeparationBase(), frnd, fMethodRuleFit->GetNCuts(), &(fMethodRuleFit->DataInfo()), iclass, useRandomisedTree);
260 dt->
SetNVars(fMethodBase->GetNvar());
268 tryAgain = ((dt==0) && (ntries<ntriesMax));
271 fForest.push_back(dt);
272 if (useBoost) Boost(dt);
276 Log() <<
kWARNING <<
"------------------------------------------------------------------" <<
Endl;
277 Log() <<
kWARNING <<
" Failed growing a tree even after " << ntriesMax <<
" trials" <<
Endl;
279 Log() <<
kWARNING <<
" 1. increase the number of training events" <<
Endl;
280 Log() <<
kWARNING <<
" 2. set a lower min fraction cut (fEventsMin)" <<
Endl;
281 Log() <<
kWARNING <<
" 3. maybe also decrease the max fraction cut (fEventsMax)" <<
Endl;
282 Log() <<
kWARNING <<
" If the above warning occurs rarely only, it can be ignored" <<
Endl;
283 Log() <<
kWARNING <<
"------------------------------------------------------------------" <<
Endl;
286 Log() <<
kDEBUG <<
"Built tree with minimum cut at N = " << frnd <<
"% events"
287 <<
" => N(nodes) = " << fForest.back()->GetNNodes()
288 <<
" ; n(tries) = " << ntries
293 if (useBoost) RestoreEventWeights();
304 fEventWeights.clear();
305 for (std::vector<const Event*>::iterator e=fTrainingEvents.begin(); e!=fTrainingEvents.end(); e++) {
307 fEventWeights.push_back(w);
317 if (fEventWeights.size() != fTrainingEvents.size()) {
318 Log() <<
kERROR <<
"RuleFit::RestoreEventWeights() called without having called SaveEventWeights() before!" <<
Endl;
321 for (std::vector<const Event*>::iterator e=fTrainingEvents.begin(); e!=fTrainingEvents.end(); e++) {
322 (*e)->SetBoostWeight(fEventWeights[ie]);
337 std::vector<Char_t> correctSelected;
339 for (std::vector<const Event*>::iterator e=fTrainingEvents.begin(); e!=fTrainingEvents.end(); e++) {
344 if (isSignalType == fMethodBase->DataInfo().IsSignal(*e)) {
345 correctSelected.push_back(
kTRUE);
349 correctSelected.push_back(
kFALSE);
357 Double_t boostWeight = (err>0 ? (1.0-err)/err : 1000.0);
361 for (std::vector<const Event*>::iterator e=fTrainingEvents.begin(); e!=fTrainingEvents.end(); e++) {
362 if (!correctSelected[ie])
363 (*e)->SetBoostWeight( (*e)->GetBoostWeight() * boostWeight);
364 newSumw+=(*e)->GetWeight();
369 for (std::vector<const Event*>::iterator e=fTrainingEvents.begin(); e!=fTrainingEvents.end(); e++) {
370 (*e)->SetBoostWeight( (*e)->GetBoostWeight() * scale);
372 Log() <<
kDEBUG <<
"boostWeight = " << boostWeight <<
" scale = " << scale <<
Endl;
381 UInt_t ntrees = fForest.size();
382 if (ntrees==0)
return;
387 for (
UInt_t i=0; i<ntrees; i++) {
394 Log() <<
kVERBOSE <<
"Nodes in trees: average & std dev = " << sumn/ntrees <<
" , " << sig <<
Endl;
405 fRuleFitParams.MakeGDPath();
414 fRuleEnsemble.CalcImportance();
415 fRuleEnsemble.CleanupRules();
416 fRuleEnsemble.CleanupLinear();
417 fRuleEnsemble.CalcVarImportance();
419 fRuleEnsemble.RuleResponseStats();
427 return fRuleEnsemble.EvalEvent( e );
435 if (fMethodRuleFit==0)
Log() <<
kFATAL <<
"RuleFit::SetTrainingEvents - MethodRuleFit not initialized" <<
Endl;
437 if (neve==0)
Log() <<
kWARNING <<
"An empty sample of training events was given" <<
Endl;
440 fTrainingEvents.clear();
441 fTrainingEventsRndm.clear();
442 for (
UInt_t i=0; i<neve; i++) {
443 fTrainingEvents.push_back(static_cast< const Event *>(el[i]));
444 fTrainingEventsRndm.push_back(static_cast< const Event *>(el[i]));
448 std::random_shuffle( fTrainingEventsRndm.begin(), fTrainingEventsRndm.end() );
451 fNTreeSample =
static_cast<UInt_t>(neve*fMethodRuleFit->GetTreeEveFrac());
452 Log() <<
kDEBUG <<
"Number of events per tree : " << fNTreeSample
453 <<
" ( N(events) = " << neve <<
" )"
454 <<
" randomly drawn without replacement" <<
Endl;
463 if ((nevents<fTrainingEventsRndm.size()) && (nevents>0)) {
464 evevec.resize(nevents);
465 for (
UInt_t ie=0; ie<nevents; ie++) {
466 evevec[ie] = fTrainingEventsRndm[ie];
470 Log() <<
kWARNING <<
"GetRndmSampleEvents() : requested sub sample size larger than total size (BUG!).";
482 if (hlist.empty())
return;
489 for (
UInt_t i=0; i<hlist.size(); i++) {
499 if (wm<wmin) wmin=wm;
516 for (
UInt_t i=0; i<hlist.size(); i++) {
535 if (!ruleHasVar)
return;
538 if(firstbin<0) firstbin=0;
546 Double_t fbfrac = (dormin ? ((fbmin+xbinw-rmin)/xbinw):1.0);
547 Double_t lbfrac = (dormax ? ((rmax-lbmax+xbinw)/xbinw):1.0);
552 for (
Int_t bin = binmin; bin<binmax+1; bin++) {
553 fbin = bin-firstbin+1;
557 else if (bin==binmax) {
565 if (fVisHistsUseImp) {
571 h2->
Fill(xc,0.5,val*f);
581 if (!fRuleEnsemble.DoLinear())
return;
587 if (fVisHistsUseImp) {
588 val = fRuleEnsemble.GetLinImportance(vind);
591 val = fRuleEnsemble.GetLinCoefficients(vind);
593 for (
Int_t bin = firstbin; bin<lastbin+1; bin++) {
595 h2->
Fill(xc,0.5,val);
607 if (fVisHistsUseImp) {
614 Double_t rxmin, rxmax, rymin, rymax;
615 Bool_t dorxmin, dorxmax, dorymin, dorymax;
621 if (!(ruleHasVarX || ruleHasVarY))
return;
640 Double_t fxbinmin = (dorxmin ? ((xbinmin+xbinw-vxmin)/xbinw):1.0);
641 Double_t fxbinmax = (dorxmax ? ((vxmax-xbinmax+xbinw)/xbinw):1.0);
642 Double_t fybinmin = (dorymin ? ((ybinmin+ybinw-vymin)/ybinw):1.0);
643 Double_t fybinmax = (dorymax ? ((vymax-ybinmax+ybinw)/ybinw):1.0);
648 for (
Int_t binx = binxmin; binx<binxmax+1; binx++) {
652 else if (binx==binxmax) {
659 for (
Int_t biny = binymin; biny<binymax+1; biny++) {
663 else if (biny==binymax) {
670 h2->
Fill(xc,yc,val*fx*fy);
680 Int_t nhists = hlist.size();
681 Int_t nvar = fMethodBase->GetNvar();
682 if (nhists!=nvar)
Log() <<
kFATAL <<
"BUG TRAP: number of hists is not equal the number of variables!" <<
Endl;
684 std::vector<Int_t> vindex;
687 for (
Int_t ih=0; ih<nhists; ih++) {
688 hstr = hlist[ih]->GetTitle();
689 for (
Int_t iv=0; iv<nvar; iv++) {
690 if (fMethodBase->GetInputTitle(iv) == hstr)
691 vindex.push_back(iv);
695 for (
Int_t iv=0; iv<nvar; iv++) {
698 FillCut(hlist[iv],rule,vindex[iv]);
702 FillLin(hlist[iv],vindex[iv]);
713 if (!(ruleimp>0))
return;
714 if (ruleimp<fRuleEnsemble.GetImportanceCut())
return;
716 Int_t nhists = hlist.size();
717 Int_t nvar = fMethodBase->GetNvar();
718 Int_t ncorr = (nvar*(nvar+1)/2)-nvar;
719 if (nhists!=ncorr)
Log() <<
kERROR <<
"BUG TRAP: number of corr hists is not correct! ncorr = "
720 << ncorr <<
" nvar = " << nvar <<
" nhists = " << nhists <<
Endl;
722 std::vector< std::pair<Int_t,Int_t> > vindex;
726 for (
Int_t ih=0; ih<nhists; ih++) {
727 hstr = hlist[ih]->GetName();
728 if (GetCorrVars( hstr, var1, var2 )) {
729 iv1 = fMethodBase->DataInfo().FindVarIndex( var1 );
730 iv2 = fMethodBase->DataInfo().FindVarIndex( var2 );
731 vindex.push_back( std::pair<Int_t,Int_t>(iv2,iv1) );
734 Log() <<
kERROR <<
"BUG TRAP: should not be here - failed getting var1 and var2" <<
Endl;
738 for (
Int_t ih=0; ih<nhists; ih++) {
741 FillCorr(hlist[ih],rule,vindex[ih].
first,vindex[ih].second);
759 var1 = titleCopy(0,splitPos);
760 var2 = titleCopy(splitPos+4, titleCopy.
Length());
773 const TString directories[5] = {
"InputVariables_Id",
774 "InputVariables_Deco",
775 "InputVariables_PCA",
776 "InputVariables_Gauss",
777 "InputVariables_Gauss_Deco" };
779 const TString corrDirName =
"CorrelationPlots";
785 TDirectory* methodDir = fMethodBase->BaseDir();
797 done = ((varDir!=0) || (type>4));
800 Log() <<
kWARNING <<
"No input variable directory found - BUG?" <<
Endl;
806 Log() <<
kWARNING <<
"Check for other warnings related to correlation histograms" <<
Endl;
810 Log() <<
kWARNING <<
"No rulefit method directory found - BUG?" <<
Endl;
814 varDirName = varDir->
GetName();
820 Log() <<
kWARNING <<
"No correlation directory found : " << corrDirName <<
Endl;
826 Log() <<
kDEBUG <<
"Got number of plots = " << noPlots <<
Endl;
829 std::vector<TH2F *> h1Vector;
830 std::vector<TH2F *> h2CorrVector;
853 h1Vector.push_back( newhist );
860 while ((key = (
TKey*)nextCorr())) {
877 TH2F *newhist =
new TH2F(newname,htitle,
880 if (GetCorrVars( newname, var1, var2 )) {
881 Int_t iv1 = fMethodBase->DataInfo().FindVarIndex(var1);
882 Int_t iv2 = fMethodBase->DataInfo().FindVarIndex(var2);
897 h2CorrVector.push_back( newhist );
904 UInt_t nrules = fRuleEnsemble.GetNRules();
906 for (
UInt_t i=0; i<nrules; i++) {
907 rule = fRuleEnsemble.GetRulesConst(i);
908 FillVisHistCut(rule, h1Vector);
911 FillVisHistCut(0, h1Vector);
912 NormVisHists(h1Vector);
917 for (
UInt_t i=0; i<nrules; i++) {
918 rule = fRuleEnsemble.GetRulesConst(i);
919 FillVisHistCorr(rule, h2CorrVector);
921 NormVisHists(h2CorrVector);
925 for (
UInt_t i=0; i<h1Vector.size(); i++) h1Vector[i]->Write();
926 for (
UInt_t i=0; i<h2CorrVector.size(); i++) h2CorrVector[i]->Write();
934 TDirectory* methodDir = fMethodBase->BaseDir();
936 Log() <<
kWARNING <<
"<MakeDebugHists> No rulefit method directory found - bug?" <<
Endl;
941 std::vector<Double_t> distances;
942 std::vector<Double_t> fncuts;
943 std::vector<Double_t> fnvars;
948 UInt_t nrules = fRuleEnsemble.GetNRules();
949 for (
UInt_t i=0; i<nrules; i++) {
950 ruleA = fRuleEnsemble.GetRulesConst(i);
951 for (
UInt_t j=i+1; j<nrules; j++) {
952 ruleB = fRuleEnsemble.GetRulesConst(j);
957 distances.push_back(dAB);
958 fncuts.push_back(static_cast<Double_t>(nc));
959 fnvars.push_back(static_cast<Double_t>(nv));
960 if (dAB<dABmin) dABmin=dAB;
961 if (dAB>dABmax) dABmax=dAB;
966 TH1F *histDist =
new TH1F(
"RuleDist",
"Rule distances",100,dABmin,dABmax);
967 TTree *distNtuple =
new TTree(
"RuleDistNtuple",
"RuleDist ntuple");
971 distNtuple->
Branch(
"dist", &ntDist,
"dist/D");
972 distNtuple->
Branch(
"ncuts",&ntNcuts,
"ncuts/D");
973 distNtuple->
Branch(
"nvars",&ntNvars,
"nvars/D");
975 for (
UInt_t i=0; i<distances.size(); i++) {
976 histDist->
Fill(distances[i]);
977 ntDist = distances[i];
void ForestStatistics()
summary of statistics of all trees
virtual const char * GetTitle() const
Returns title of object.
void SetPruneMethod(EPruneMethod m=kCostComplexityPruning)
void MakeForest()
make a forest of decisiontrees
virtual Int_t FindBin(Double_t x, Double_t y=0, Double_t z=0)
Return Global bin number corresponding to x,y,z.
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
static TDirectory * RootBaseDir()
Random number generator class based on M.
MsgLogger & Endl(MsgLogger &ml)
virtual void SetMaximum(Double_t maximum=-1111)
const std::vector< const TMVA::Event * > & GetTrainingEvents() const
void CalcImportance()
calculates the importance of each rule
virtual TList * GetListOfKeys() const
virtual TObject * Get(const char *namecycle)
Return pointer to object identified by namecycle.
ClassImp(TSeqCollection) Int_t TSeqCollection TIter next(this)
Return index of object in collection.
void FillVisHistCorr(const Rule *rule, std::vector< TH2F * > &hlist)
help routine to MakeVisHists() - fills for all correlation plots
TString & ReplaceAll(const TString &s1, const TString &s2)
virtual Int_t Fill()
Fill all branches.
void SetMsgType(EMsgType t)
set the current message type to that of mlog for this class and all other subtools ...
Bool_t GetCorrVars(TString &title, TString &var1, TString &var2)
get first and second variables from title
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
void InitNEveEff()
init effective number of events (using event weights)
virtual void SetMinimum(Double_t minimum=-1111)
void FitCoefficients()
Fit the coefficients for the rule ensemble.
1-D histogram with a float per channel (see TH1 documentation)}
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
virtual Int_t GetNbinsX() const
Bool_t BeginsWith(const char *s, ECaseCompare cmp=kExact) const
ClassImp(TMVA::RuleFit) TMVA
constructor
Double_t RuleDist(const Rule &other, Bool_t useCutValue) const
Returns: -1.0 : rules are NOT equal, i.e, variables and/or cut directions are wrong >=0: rules are eq...
RuleFit(void)
default constructor
void BuildTree(TMVA::DecisionTree *dt)
build the decision tree using fNTreeSample events from fTrainingEventsRndm
const MethodBase * GetMethodBase() const
void SetTrainingEvents(const std::vector< const TMVA::Event * > &el)
set the training events randomly
void GetRndmSampleEvents(std::vector< const TMVA::Event * > &evevec, UInt_t nevents)
draw a random subsample of the training events without replacement
Book space in a file, create I/O buffers, to fill them, (un)compress them.
virtual ~RuleFit(void)
destructor
ROOT::Math::KDTree< _DataPoint > * BuildTree(const std::vector< const _DataPoint * > &vDataPoints, const unsigned int iBucketSize)
const RuleCut * GetRuleCut() const
void SetMethodBase(const MethodBase *rfbase)
set MethodBase
Double_t CheckEvent(const TMVA::Event *, Bool_t UseYesNoLeaf=kFALSE) const
the event e is put into the decision tree (starting at the root node) and the output is NodeType (sig...
const std::vector< const TMVA::DecisionTree * > & GetForest() const
virtual Int_t Write(const char *name=0, Int_t option=0, Int_t bufsize=0)
Write this object to the current directory.
void RestoreEventWeights()
save event weights - must be done before making the forest
void FillVisHistCut(const Rule *rule, std::vector< TH2F * > &hlist)
help routine to MakeVisHists() - fills for all variables
void Copy(const RuleFit &other)
copy method
void Initialize(Bool_t useTMVAStyle=kTRUE)
Bool_t ContainsVariable(UInt_t iv) const
check if variable in node
TPaveLabel title(3, 27.1, 15, 28.7,"ROOT Environment and Tools")
void FillCorr(TH2F *h2, const TMVA::Rule *rule, Int_t v1, Int_t v2)
fill rule correlation between vx and vy, weighted with either the importance or the coefficient ...
void MakeDebugHists()
this will create a histograms intended rather for debugging or for the curious user ...
static const Int_t randSEED
2-D histogram with a float per channel (see TH1 documentation)}
Double_t GetImportance() const
const RuleEnsemble & GetRuleEnsemble() const
void SetPruneStrength(Double_t p)
void FillLin(TH2F *h2, Int_t vind)
fill lin
virtual const char * GetName() const
Returns name of object.
Double_t GetWeight(Double_t x) const
The ROOT global object gROOT contains a list of all defined classes.
Bool_t GetCutRange(Int_t sel, Double_t &rmin, Double_t &rmax, Bool_t &dormin, Bool_t &dormax) const
get cut range for a given selector
const MethodRuleFit * GetMethodRuleFit() const
void Boost(TMVA::DecisionTree *dt)
Boost the events.
virtual Int_t GetBin(Int_t binx, Int_t biny, Int_t binz=0) const
Return Global bin number corresponding to binx,y,z.
virtual Int_t FindBin(Double_t x)
Find bin number corresponding to abscissa x.
TString & Remove(Ssiz_t pos)
void SaveEventWeights()
save event weights - must be done before making the forest
Describe directory structure in memory.
void MakeVisHists()
this will create histograms visualizing the rule ensemble
UInt_t GetNumVarsUsed() const
virtual Double_t Uniform(Double_t x1=1)
Returns a uniform deviate on the interval (0, x1).
void InitPtrs(const TMVA::MethodBase *rfbase)
initialize pointers
Double_t GetCoefficient() const
Double_t CalcWeightSum(const std::vector< const TMVA::Event * > *events, UInt_t neve=0)
calculate the sum of weights
void NormVisHists(std::vector< TH2F * > &hlist)
normalize rule importance hists
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
virtual Int_t Branch(TCollection *list, Int_t bufsize=32000, Int_t splitlevel=99, const char *name="")
Create one branch for each element in the collection.
virtual Int_t GetNbinsY() const
Double_t PruneTree(const EventConstList *validationSample=NULL)
prune (get rid of internal nodes) the Decision tree to avoid overtraining serveral different pruning ...
void FillCut(TH2F *h2, const TMVA::Rule *rule, Int_t vind)
Fill cut.
virtual Bool_t cd(const char *path=0)
Change current directory to "this" directory.
Double_t GetSupport() const
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
UInt_t BuildTree(const EventConstList &eventSample, DecisionTreeNode *node=NULL)
building the decision tree by recursively calling the splitting of one (root-) node into two daughter...
Double_t EvalEvent(const Event &e)
evaluate single event
A TTree object has a header with a name and a title.
Bool_t InheritsFrom(const char *cl) const
Return kTRUE if this class inherits from a class with name "classname".
void Initialize(const TMVA::MethodBase *rfbase)
initialize the parameters of the RuleFit method and make rules
Double_t Sqrt(Double_t x)
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
virtual Double_t GetMaximum(Double_t maxval=FLT_MAX) const
Return maximum value smaller than maxval of bins in the range, unless the value has been overridden b...
Int_t Fill(Double_t)
Invalid Fill method.
virtual void SetTitle(const char *title="")
Change (i.e. set) the title of the TNamed.
virtual Double_t GetMinimum(Double_t minval=-FLT_MAX) const
Return minimum value larger than minval of bins in the range, unless the value has been overridden by...