49 TMVA::RuleFit::RuleFit( const MethodBase *rfbase )
50 : fVisHistsUseImp(
kTRUE ),
51 fLogger( new MsgLogger("RuleFit") )
54 std::srand( randSEED );
65 , fVisHistsUseImp(
kTRUE )
84 UInt_t neve = fTrainingEvents.size();
87 fNEveEffTrain = CalcWeightSum( &fTrainingEvents );
96 this->SetMethodBase(rfbase);
97 fRuleEnsemble.Initialize(
this );
98 fRuleFitParams.SetRuleFit(
this );
110 UInt_t nevents = fMethodRuleFit->Data()->GetNTrainingEvents();
111 std::vector<const TMVA::Event*> tmp;
112 for (
Long64_t ievt=0; ievt<nevents; ievt++) {
113 const Event *
event = fMethodRuleFit->GetEvent(ievt);
114 tmp.push_back(event);
116 SetTrainingEvents( tmp );
125 fRuleEnsemble.MakeModel();
128 fRuleFitParams.Init();
137 fMethodBase = rfbase;
138 fMethodRuleFit =
dynamic_cast<const MethodRuleFit *
>(rfbase);
162 if (events==0)
return 0.0;
163 if (neve==0) neve=events->size();
166 for (
UInt_t ie=0; ie<neve; ie++) {
177 fLogger->SetMinType(t);
178 fRuleEnsemble.SetMsgType(t);
179 fRuleFitParams.SetMsgType(t);
188 if (fMethodRuleFit==0) {
189 Log() <<
kFATAL <<
"RuleFit::BuildTree() - Attempting to build a tree NOT from a MethodRuleFit" <<
Endl;
191 std::vector<const Event *> evevec;
192 for (
UInt_t ie=0; ie<fNTreeSample; ie++) {
193 evevec.push_back(fTrainingEventsRndm[ie]);
208 if (fMethodRuleFit==0) {
209 Log() <<
kFATAL <<
"RuleFit::BuildTree() - Attempting to build a tree NOT from a MethodRuleFit" <<
Endl;
211 Log() <<
kDEBUG <<
"Creating a forest with " << fMethodRuleFit->GetNTrees() <<
" decision trees" <<
Endl;
212 Log() <<
kDEBUG <<
"Each tree is built using a random subsample with " << fNTreeSample <<
" events" <<
Endl;
214 Timer timer( fMethodRuleFit->GetNTrees(),
"RuleFit" );
226 Bool_t useBoost = fMethodRuleFit->UseBoost();
228 if (useBoost) SaveEventWeights();
230 for (
Int_t i=0; i<fMethodRuleFit->GetNTrees(); i++) {
232 if (!useBoost) ReshuffleEvents();
235 for (
UInt_t ie = 0; ie<fNTreeSample; ie++) {
236 if (fMethodBase->DataInfo().IsSignal(fTrainingEventsRndm[ie])) nsig++;
245 const Int_t ntriesMax=10;
248 frnd = 100*rndGen.
Uniform( fMethodRuleFit->GetMinFracNEve(), 0.5*fMethodRuleFit->GetMaxFracNEve() );
250 Bool_t useRandomisedTree = !useBoost;
251 dt =
new DecisionTree( fMethodRuleFit->GetSeparationBase(), frnd, fMethodRuleFit->GetNCuts(), &(fMethodRuleFit->DataInfo()), iclass, useRandomisedTree);
252 dt->
SetNVars(fMethodBase->GetNvar());
260 tryAgain = ((dt==0) && (ntries<ntriesMax));
263 fForest.push_back(dt);
264 if (useBoost) Boost(dt);
268 Log() <<
kWARNING <<
"------------------------------------------------------------------" <<
Endl;
269 Log() <<
kWARNING <<
" Failed growing a tree even after " << ntriesMax <<
" trials" <<
Endl;
271 Log() <<
kWARNING <<
" 1. increase the number of training events" <<
Endl;
272 Log() <<
kWARNING <<
" 2. set a lower min fraction cut (fEventsMin)" <<
Endl;
273 Log() <<
kWARNING <<
" 3. maybe also decrease the max fraction cut (fEventsMax)" <<
Endl;
274 Log() <<
kWARNING <<
" If the above warning occurs rarely only, it can be ignored" <<
Endl;
275 Log() <<
kWARNING <<
"------------------------------------------------------------------" <<
Endl;
278 Log() <<
kDEBUG <<
"Built tree with minimum cut at N = " << frnd <<
"% events"
279 <<
" => N(nodes) = " << fForest.back()->GetNNodes()
280 <<
" ; n(tries) = " << ntries
285 if (useBoost) RestoreEventWeights();
296 fEventWeights.clear();
297 for (std::vector<const Event*>::iterator e=fTrainingEvents.begin(); e!=fTrainingEvents.end(); e++) {
298 Double_t w = (*e)->GetBoostWeight();
299 fEventWeights.push_back(w);
309 if (fEventWeights.size() != fTrainingEvents.size()) {
310 Log() <<
kERROR <<
"RuleFit::RestoreEventWeights() called without having called SaveEventWeights() before!" <<
Endl;
313 for (std::vector<const Event*>::iterator e=fTrainingEvents.begin(); e!=fTrainingEvents.end(); e++) {
314 (*e)->SetBoostWeight(fEventWeights[ie]);
329 std::vector<Char_t> correctSelected;
331 for (std::vector<const Event*>::iterator e=fTrainingEvents.begin(); e!=fTrainingEvents.end(); e++) {
336 if (isSignalType == fMethodBase->DataInfo().IsSignal(*e)) {
337 correctSelected.push_back(
kTRUE);
341 correctSelected.push_back(
kFALSE);
349 Double_t boostWeight = (err>0 ? (1.0-err)/err : 1000.0);
353 for (std::vector<const Event*>::iterator e=fTrainingEvents.begin(); e!=fTrainingEvents.end(); e++) {
354 if (!correctSelected[ie])
355 (*e)->SetBoostWeight( (*e)->GetBoostWeight() * boostWeight);
356 newSumw+=(*e)->GetWeight();
361 for (std::vector<const Event*>::iterator e=fTrainingEvents.begin(); e!=fTrainingEvents.end(); e++) {
362 (*e)->SetBoostWeight( (*e)->GetBoostWeight() * scale);
364 Log() <<
kDEBUG <<
"boostWeight = " << boostWeight <<
" scale = " << scale <<
Endl;
373 UInt_t ntrees = fForest.size();
374 if (ntrees==0)
return;
379 for (
UInt_t i=0; i<ntrees; i++) {
386 Log() <<
kVERBOSE <<
"Nodes in trees: average & std dev = " << sumn/ntrees <<
" , " << sig <<
Endl;
397 fRuleFitParams.MakeGDPath();
406 fRuleEnsemble.CalcImportance();
407 fRuleEnsemble.CleanupRules();
408 fRuleEnsemble.CleanupLinear();
409 fRuleEnsemble.CalcVarImportance();
411 fRuleEnsemble.RuleResponseStats();
419 return fRuleEnsemble.EvalEvent( e );
427 if (fMethodRuleFit==0)
Log() <<
kFATAL <<
"RuleFit::SetTrainingEvents - MethodRuleFit not initialized" <<
Endl;
429 if (neve==0)
Log() <<
kWARNING <<
"An empty sample of training events was given" <<
Endl;
432 fTrainingEvents.clear();
433 fTrainingEventsRndm.clear();
434 for (
UInt_t i=0; i<neve; i++) {
435 fTrainingEvents.push_back(static_cast< const Event *>(el[i]));
436 fTrainingEventsRndm.push_back(static_cast< const Event *>(el[i]));
440 std::random_shuffle( fTrainingEventsRndm.begin(), fTrainingEventsRndm.end() );
443 fNTreeSample =
static_cast<UInt_t>(neve*fMethodRuleFit->GetTreeEveFrac());
444 Log() <<
kDEBUG <<
"Number of events per tree : " << fNTreeSample
445 <<
" ( N(events) = " << neve <<
" )"
446 <<
" randomly drawn without replacement" <<
Endl;
455 if ((nevents<fTrainingEventsRndm.size()) && (nevents>0)) {
456 evevec.resize(nevents);
457 for (
UInt_t ie=0; ie<nevents; ie++) {
458 evevec[ie] = fTrainingEventsRndm[ie];
462 Log() <<
kWARNING <<
"GetRndmSampleEvents() : requested sub sample size larger than total size (BUG!).";
474 if (hlist.empty())
return;
481 for (
UInt_t i=0; i<hlist.size(); i++) {
491 if (wm<wmin) wmin=wm;
508 for (
UInt_t i=0; i<hlist.size(); i++) {
527 if (!ruleHasVar)
return;
530 if(firstbin<0) firstbin=0;
538 Double_t fbfrac = (dormin ? ((fbmin+xbinw-rmin)/xbinw):1.0);
539 Double_t lbfrac = (dormax ? ((rmax-lbmax+xbinw)/xbinw):1.0);
544 for (
Int_t bin = binmin; bin<binmax+1; bin++) {
545 fbin = bin-firstbin+1;
549 else if (bin==binmax) {
557 if (fVisHistsUseImp) {
563 h2->
Fill(xc,0.5,val*f);
573 if (!fRuleEnsemble.DoLinear())
return;
579 if (fVisHistsUseImp) {
580 val = fRuleEnsemble.GetLinImportance(vind);
583 val = fRuleEnsemble.GetLinCoefficients(vind);
585 for (
Int_t bin = firstbin; bin<lastbin+1; bin++) {
587 h2->
Fill(xc,0.5,val);
599 if (fVisHistsUseImp) {
606 Double_t rxmin, rxmax, rymin, rymax;
607 Bool_t dorxmin, dorxmax, dorymin, dorymax;
613 if (!(ruleHasVarX || ruleHasVarY))
return;
632 Double_t fxbinmin = (dorxmin ? ((xbinmin+xbinw-vxmin)/xbinw):1.0);
633 Double_t fxbinmax = (dorxmax ? ((vxmax-xbinmax+xbinw)/xbinw):1.0);
634 Double_t fybinmin = (dorymin ? ((ybinmin+ybinw-vymin)/ybinw):1.0);
635 Double_t fybinmax = (dorymax ? ((vymax-ybinmax+ybinw)/ybinw):1.0);
640 for (
Int_t binx = binxmin; binx<binxmax+1; binx++) {
644 else if (binx==binxmax) {
651 for (
Int_t biny = binymin; biny<binymax+1; biny++) {
655 else if (biny==binymax) {
662 h2->
Fill(xc,yc,val*fx*fy);
672 Int_t nhists = hlist.size();
673 Int_t nvar = fMethodBase->GetNvar();
674 if (nhists!=nvar)
Log() <<
kFATAL <<
"BUG TRAP: number of hists is not equal the number of variables!" <<
Endl;
676 std::vector<Int_t> vindex;
679 for (
Int_t ih=0; ih<nhists; ih++) {
680 hstr = hlist[ih]->GetTitle();
681 for (
Int_t iv=0; iv<nvar; iv++) {
682 if (fMethodBase->GetInputTitle(iv) == hstr)
683 vindex.push_back(iv);
687 for (
Int_t iv=0; iv<nvar; iv++) {
690 FillCut(hlist[iv],rule,vindex[iv]);
694 FillLin(hlist[iv],vindex[iv]);
705 if (!(ruleimp>0))
return;
706 if (ruleimp<fRuleEnsemble.GetImportanceCut())
return;
708 Int_t nhists = hlist.size();
709 Int_t nvar = fMethodBase->GetNvar();
710 Int_t ncorr = (nvar*(nvar+1)/2)-nvar;
711 if (nhists!=ncorr)
Log() <<
kERROR <<
"BUG TRAP: number of corr hists is not correct! ncorr = "
712 << ncorr <<
" nvar = " << nvar <<
" nhists = " << nhists <<
Endl;
714 std::vector< std::pair<Int_t,Int_t> > vindex;
718 for (
Int_t ih=0; ih<nhists; ih++) {
719 hstr = hlist[ih]->GetName();
720 if (GetCorrVars( hstr, var1, var2 )) {
721 iv1 = fMethodBase->DataInfo().FindVarIndex( var1 );
722 iv2 = fMethodBase->DataInfo().FindVarIndex( var2 );
723 vindex.push_back( std::pair<Int_t,Int_t>(iv2,iv1) );
726 Log() <<
kERROR <<
"BUG TRAP: should not be here - failed getting var1 and var2" <<
Endl;
730 for (
Int_t ih=0; ih<nhists; ih++) {
733 FillCorr(hlist[ih],rule,vindex[ih].first,vindex[ih].second);
751 var1 = titleCopy(0,splitPos);
752 var2 = titleCopy(splitPos+4, titleCopy.
Length());
765 const TString directories[5] = {
"InputVariables_Id",
766 "InputVariables_Deco",
767 "InputVariables_PCA",
768 "InputVariables_Gauss",
769 "InputVariables_Gauss_Deco" };
771 const TString corrDirName =
"CorrelationPlots";
777 TDirectory* methodDir = fMethodBase->BaseDir();
789 done = ((varDir!=0) || (type>4));
792 Log() <<
kWARNING <<
"No input variable directory found - BUG?" <<
Endl;
798 Log() <<
kWARNING <<
"Check for other warnings related to correlation histograms" <<
Endl;
802 Log() <<
kWARNING <<
"No rulefit method directory found - BUG?" <<
Endl;
806 varDirName = varDir->
GetName();
812 Log() <<
kWARNING <<
"No correlation directory found : " << corrDirName <<
Endl;
818 Log() <<
kDEBUG <<
"Got number of plots = " << noPlots <<
Endl;
821 std::vector<TH2F *> h1Vector;
822 std::vector<TH2F *> h2CorrVector;
845 h1Vector.push_back( newhist );
852 while ((key = (
TKey*)nextCorr())) {
869 TH2F *newhist =
new TH2F(newname,htitle,
872 if (GetCorrVars( newname, var1, var2 )) {
873 Int_t iv1 = fMethodBase->DataInfo().FindVarIndex(var1);
874 Int_t iv2 = fMethodBase->DataInfo().FindVarIndex(var2);
889 h2CorrVector.push_back( newhist );
896 UInt_t nrules = fRuleEnsemble.GetNRules();
898 for (
UInt_t i=0; i<nrules; i++) {
899 rule = fRuleEnsemble.GetRulesConst(i);
900 FillVisHistCut(rule, h1Vector);
903 FillVisHistCut(0, h1Vector);
904 NormVisHists(h1Vector);
909 for (
UInt_t i=0; i<nrules; i++) {
910 rule = fRuleEnsemble.GetRulesConst(i);
911 FillVisHistCorr(rule, h2CorrVector);
913 NormVisHists(h2CorrVector);
917 for (
UInt_t i=0; i<h1Vector.size(); i++) h1Vector[i]->Write();
918 for (
UInt_t i=0; i<h2CorrVector.size(); i++) h2CorrVector[i]->Write();
926 TDirectory* methodDir = fMethodBase->BaseDir();
928 Log() <<
kWARNING <<
"<MakeDebugHists> No rulefit method directory found - bug?" <<
Endl;
933 std::vector<Double_t> distances;
934 std::vector<Double_t> fncuts;
935 std::vector<Double_t> fnvars;
940 UInt_t nrules = fRuleEnsemble.GetNRules();
941 for (
UInt_t i=0; i<nrules; i++) {
942 ruleA = fRuleEnsemble.GetRulesConst(i);
943 for (
UInt_t j=i+1; j<nrules; j++) {
944 ruleB = fRuleEnsemble.GetRulesConst(j);
949 distances.push_back(dAB);
950 fncuts.push_back(static_cast<Double_t>(nc));
951 fnvars.push_back(static_cast<Double_t>(nv));
952 if (dAB<dABmin) dABmin=dAB;
953 if (dAB>dABmax) dABmax=dAB;
958 TH1F *histDist =
new TH1F(
"RuleDist",
"Rule distances",100,dABmin,dABmax);
959 TTree *distNtuple =
new TTree(
"RuleDistNtuple",
"RuleDist ntuple");
963 distNtuple->
Branch(
"dist", &ntDist,
"dist/D");
964 distNtuple->
Branch(
"ncuts",&ntNcuts,
"ncuts/D");
965 distNtuple->
Branch(
"nvars",&ntNvars,
"nvars/D");
967 for (
UInt_t i=0; i<distances.size(); i++) {
968 histDist->
Fill(distances[i]);
969 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
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 ...
Abstract ClassifierFactory template that handles arbitrary types.
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...