Logo ROOT   6.12/07
Reference Guide
TMVARegressionApplication.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_tmva
3 /// \notebook -nodraw
4 /// This macro provides a simple example on how to use the trained regression MVAs
5 /// within an analysis module
6 ///
7 /// - Project : TMVA - a Root-integrated toolkit for multivariate data analysis
8 /// - Package : TMVA
9 /// - Exectuable: TMVARegressionApplication
10 ///
11 /// \macro_output
12 /// \macro_code
13 /// \author Andreas Hoecker
14 
15 #include <cstdlib>
16 #include <vector>
17 #include <iostream>
18 #include <map>
19 #include <string>
20 
21 #include "TFile.h"
22 #include "TTree.h"
23 #include "TString.h"
24 #include "TSystem.h"
25 #include "TROOT.h"
26 #include "TStopwatch.h"
27 
28 #include "TMVA/Tools.h"
29 #include "TMVA/Reader.h"
30 
31 using namespace TMVA;
32 
33 void TMVARegressionApplication( TString myMethodList = "" )
34 {
35  //---------------------------------------------------------------
36  // This loads the library
38 
39  // Default MVA methods to be trained + tested
40  std::map<std::string,int> Use;
41 
42  // --- Mutidimensional likelihood and Nearest-Neighbour methods
43  Use["PDERS"] = 0;
44  Use["PDEFoam"] = 1;
45  Use["KNN"] = 1;
46  //
47  // --- Linear Discriminant Analysis
48  Use["LD"] = 1;
49  //
50  // --- Function Discriminant analysis
51  Use["FDA_GA"] = 1;
52  Use["FDA_MC"] = 0;
53  Use["FDA_MT"] = 0;
54  Use["FDA_GAMT"] = 0;
55  //
56  // --- Neural Network
57  Use["MLP"] = 1;
58  Use["DNN_CPU"] = 0;
59  //
60  // --- Support Vector Machine
61  Use["SVM"] = 0;
62  //
63  // --- Boosted Decision Trees
64  Use["BDT"] = 0;
65  Use["BDTG"] = 1;
66  // ---------------------------------------------------------------
67 
68  std::cout << std::endl;
69  std::cout << "==> Start TMVARegressionApplication" << std::endl;
70 
71  // Select methods (don't look at this code - not of interest)
72  if (myMethodList != "") {
73  for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
74 
75  std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
76  for (UInt_t i=0; i<mlist.size(); i++) {
77  std::string regMethod(mlist[i]);
78 
79  if (Use.find(regMethod) == Use.end()) {
80  std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
81  for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
82  std::cout << std::endl;
83  return;
84  }
85  Use[regMethod] = 1;
86  }
87  }
88 
89  // --------------------------------------------------------------------------------------------------
90 
91  // --- Create the Reader object
92 
93  TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );
94 
95  // Create a set of variables and declare them to the reader
96  // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
97  Float_t var1, var2;
98  reader->AddVariable( "var1", &var1 );
99  reader->AddVariable( "var2", &var2 );
100 
101  // Spectator variables declared in the training have to be added to the reader, too
102  Float_t spec1,spec2;
103  reader->AddSpectator( "spec1:=var1*2", &spec1 );
104  reader->AddSpectator( "spec2:=var1*3", &spec2 );
105 
106  // --- Book the MVA methods
107 
108  TString dir = "dataset/weights/";
109  TString prefix = "TMVARegression";
110 
111  // Book method(s)
112  for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
113  if (it->second) {
114  TString methodName = it->first + " method";
115  TString weightfile = dir + prefix + "_" + TString(it->first) + ".weights.xml";
116  reader->BookMVA( methodName, weightfile );
117  }
118  }
119 
120  // Book output histograms
121  TH1* hists[100];
122  Int_t nhists = -1;
123  for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
124  TH1* h = new TH1F( it->first.c_str(), TString(it->first) + " method", 100, -100, 600 );
125  if (it->second) hists[++nhists] = h;
126  }
127  nhists++;
128 
129  // Prepare input tree (this must be replaced by your data source)
130  // in this example, there is a toy tree with signal and one with background events
131  // we'll later on use only the "signal" events for the test in this example.
132  //
133  TFile *input(0);
134  TString fname = "./tmva_reg_example.root";
135  if (!gSystem->AccessPathName( fname )) {
136  input = TFile::Open( fname ); // check if file in local directory exists
137  }
138  else {
140  input = TFile::Open("http://root.cern.ch/files/tmva_reg_example.root", "CACHEREAD"); // if not: download from ROOT server
141  }
142  if (!input) {
143  std::cout << "ERROR: could not open data file" << std::endl;
144  exit(1);
145  }
146  std::cout << "--- TMVARegressionApp : Using input file: " << input->GetName() << std::endl;
147 
148  // --- Event loop
149 
150  // Prepare the tree
151  // - here the variable names have to corresponds to your tree
152  // - you can use the same variables as above which is slightly faster,
153  // but of course you can use different ones and copy the values inside the event loop
154  //
155  TTree* theTree = (TTree*)input->Get("TreeR");
156  std::cout << "--- Select signal sample" << std::endl;
157  theTree->SetBranchAddress( "var1", &var1 );
158  theTree->SetBranchAddress( "var2", &var2 );
159 
160  std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
161  TStopwatch sw;
162  sw.Start();
163  for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
164 
165  if (ievt%1000 == 0) {
166  std::cout << "--- ... Processing event: " << ievt << std::endl;
167  }
168 
169  theTree->GetEntry(ievt);
170 
171  // Retrieve the MVA target values (regression outputs) and fill into histograms
172  // NOTE: EvaluateRegression(..) returns a vector for multi-target regression
173 
174  for (Int_t ih=0; ih<nhists; ih++) {
175  TString title = hists[ih]->GetTitle();
176  Float_t val = (reader->EvaluateRegression( title ))[0];
177  hists[ih]->Fill( val );
178  }
179  }
180  sw.Stop();
181  std::cout << "--- End of event loop: "; sw.Print();
182 
183  // --- Write histograms
184 
185  TFile *target = new TFile( "TMVARegApp.root","RECREATE" );
186  for (Int_t ih=0; ih<nhists; ih++) hists[ih]->Write();
187  target->Close();
188 
189  std::cout << "--- Created root file: \"" << target->GetName()
190  << "\" containing the MVA output histograms" << std::endl;
191 
192  delete reader;
193 
194  std::cout << "==> TMVARegressionApplication is done!" << std::endl << std::endl;
195 }
196 
197 int main( int argc, char** argv )
198 {
199  // Select methods (don't look at this code - not of interest)
200  TString methodList;
201  for (int i=1; i<argc; i++) {
202  TString regMethod(argv[i]);
203  if(regMethod=="-b" || regMethod=="--batch") continue;
204  if (!methodList.IsNull()) methodList += TString(",");
205  methodList += regMethod;
206  }
207  TMVARegressionApplication(methodList);
208  return 0;
209 }
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition: TSystem.cxx:1276
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition: TH1.cxx:3244
static Tools & Instance()
Definition: Tools.cxx:75
long long Long64_t
Definition: RtypesCore.h:69
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
Definition: TStopwatch.cxx:58
void Print(Option_t *option="") const
Print the real and cpu time passed between the start and stop events.
Definition: TStopwatch.cxx:219
float Float_t
Definition: RtypesCore.h:53
void AddVariable(const TString &expression, Float_t *)
Add a float variable or expression to the reader.
Definition: Reader.cxx:308
THist< 1, float, THistStatContent, THistStatUncertainty > TH1F
Definition: THist.hxx:285
TH1 * h
Definition: legend2.C:5
const std::vector< Float_t > & EvaluateRegression(const TString &methodTag, Double_t aux=0)
evaluates MVA for given set of input variables
Definition: Reader.cxx:582
static Bool_t SetCacheFileDir(ROOT::Internal::TStringView cacheDir, Bool_t operateDisconnected=kTRUE, Bool_t forceCacheread=kFALSE)
Definition: TFile.h:303
int Int_t
Definition: RtypesCore.h:41
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=1, Int_t netopt=0)
Create / open a file.
Definition: TFile.cxx:3950
void Stop()
Stop the stopwatch.
Definition: TStopwatch.cxx:77
int main(int argc, char **argv)
IMethod * BookMVA(const TString &methodTag, const TString &weightfile)
read method name from weight file
Definition: Reader.cxx:377
R__EXTERN TSystem * gSystem
Definition: TSystem.h:540
unsigned int UInt_t
Definition: RtypesCore.h:42
Tools & gTools()
void AddSpectator(const TString &expression, Float_t *)
Add a float spectator or expression to the reader.
Definition: Reader.cxx:326
The TH1 histogram class.
Definition: TH1.h:56
The Reader class serves to use the MVAs in a specific analysis context.
Definition: Reader.h:63
Abstract ClassifierFactory template that handles arbitrary types.
std::vector< TString > SplitString(const TString &theOpt, const char separator) const
splits the option string at &#39;separator&#39; and fills the list &#39;splitV&#39; with the primitive strings ...
Definition: Tools.cxx:1210
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:48
Stopwatch class.
Definition: TStopwatch.h:28