Logo ROOT   6.08/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  //
59  // --- Support Vector Machine
60  Use["SVM"] = 0;
61  //
62  // --- Boosted Decision Trees
63  Use["BDT"] = 0;
64  Use["BDTG"] = 1;
65  // ---------------------------------------------------------------
66 
67  std::cout << std::endl;
68  std::cout << "==> Start TMVARegressionApplication" << std::endl;
69 
70  // Select methods (don't look at this code - not of interest)
71  if (myMethodList != "") {
72  for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
73 
74  std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
75  for (UInt_t i=0; i<mlist.size(); i++) {
76  std::string regMethod(mlist[i]);
77 
78  if (Use.find(regMethod) == Use.end()) {
79  std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
80  for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
81  std::cout << std::endl;
82  return;
83  }
84  Use[regMethod] = 1;
85  }
86  }
87 
88  // --------------------------------------------------------------------------------------------------
89 
90  // --- Create the Reader object
91 
92  TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );
93 
94  // Create a set of variables and declare them to the reader
95  // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
96  Float_t var1, var2;
97  reader->AddVariable( "var1", &var1 );
98  reader->AddVariable( "var2", &var2 );
99 
100  // Spectator variables declared in the training have to be added to the reader, too
101  Float_t spec1,spec2;
102  reader->AddSpectator( "spec1:=var1*2", &spec1 );
103  reader->AddSpectator( "spec2:=var1*3", &spec2 );
104 
105  // --- Book the MVA methods
106 
107  TString dir = "dataset/weights/";
108  TString prefix = "TMVARegression";
109 
110  // Book method(s)
111  for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
112  if (it->second) {
113  TString methodName = it->first + " method";
114  TString weightfile = dir + prefix + "_" + TString(it->first) + ".weights.xml";
115  reader->BookMVA( methodName, weightfile );
116  }
117  }
118 
119  // Book output histograms
120  TH1* hists[100];
121  Int_t nhists = -1;
122  for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
123  TH1* h = new TH1F( it->first.c_str(), TString(it->first) + " method", 100, -100, 600 );
124  if (it->second) hists[++nhists] = h;
125  }
126  nhists++;
127 
128  // Prepare input tree (this must be replaced by your data source)
129  // in this example, there is a toy tree with signal and one with background events
130  // we'll later on use only the "signal" events for the test in this example.
131  //
132  TFile *input(0);
133  TString fname = "./tmva_reg_example.root";
134  if (!gSystem->AccessPathName( fname )) {
135  input = TFile::Open( fname ); // check if file in local directory exists
136  }
137  else {
138  input = TFile::Open( "http://root.cern.ch/files/tmva_reg_example.root" ); // if not: download from ROOT server
139  }
140 
141  if (!input) {
142  std::cout << "ERROR: could not open data file" << std::endl;
143  exit(1);
144  }
145  std::cout << "--- TMVARegressionApp : Using input file: " << input->GetName() << std::endl;
146 
147  // --- Event loop
148 
149  // Prepare the tree
150  // - here the variable names have to corresponds to your tree
151  // - you can use the same variables as above which is slightly faster,
152  // but of course you can use different ones and copy the values inside the event loop
153  //
154  TTree* theTree = (TTree*)input->Get("TreeR");
155  std::cout << "--- Select signal sample" << std::endl;
156  theTree->SetBranchAddress( "var1", &var1 );
157  theTree->SetBranchAddress( "var2", &var2 );
158 
159  std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
160  TStopwatch sw;
161  sw.Start();
162  for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
163 
164  if (ievt%1000 == 0) {
165  std::cout << "--- ... Processing event: " << ievt << std::endl;
166  }
167 
168  theTree->GetEntry(ievt);
169 
170  // Retrieve the MVA target values (regression outputs) and fill into histograms
171  // NOTE: EvaluateRegression(..) returns a vector for multi-target regression
172 
173  for (Int_t ih=0; ih<nhists; ih++) {
174  TString title = hists[ih]->GetTitle();
175  Float_t val = (reader->EvaluateRegression( title ))[0];
176  hists[ih]->Fill( val );
177  }
178  }
179  sw.Stop();
180  std::cout << "--- End of event loop: "; sw.Print();
181 
182  // --- Write histograms
183 
184  TFile *target = new TFile( "TMVARegApp.root","RECREATE" );
185  for (Int_t ih=0; ih<nhists; ih++) hists[ih]->Write();
186  target->Close();
187 
188  std::cout << "--- Created root file: \"" << target->GetName()
189  << "\" containing the MVA output histograms" << std::endl;
190 
191  delete reader;
192 
193  std::cout << "==> TMVARegressionApplication is done!" << std::endl << std::endl;
194 }
195 
196 int main( int argc, char** argv )
197 {
198  // Select methods (don't look at this code - not of interest)
199  TString methodList;
200  for (int i=1; i<argc; i++) {
201  TString regMethod(argv[i]);
202  if(regMethod=="-b" || regMethod=="--batch") continue;
203  if (!methodList.IsNull()) methodList += TString(",");
204  methodList += regMethod;
205  }
206  TMVARegressionApplication(methodList);
207  return 0;
208 }
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:51
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:1266
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition: TH1.cxx:3125
static Tools & Instance()
Definition: Tools.cxx:80
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:309
THist< 1, float, THistStatContent, THistStatUncertainty > TH1F
Definition: THist.hxx:302
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:583
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:3907
Tools & gTools()
Definition: Tools.cxx:79
void Stop()
Stop the stopwatch.
Definition: TStopwatch.cxx:77
IMethod * BookMVA(const TString &methodTag, const TString &weightfile)
read method name from weight file
Definition: Reader.cxx:378
R__EXTERN TSystem * gSystem
Definition: TSystem.h:549
unsigned int UInt_t
Definition: RtypesCore.h:42
void AddSpectator(const TString &expression, Float_t *)
Add a float spectator or expression to the reader.
Definition: Reader.cxx:327
The TH1 histogram class.
Definition: TH1.h:80
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:1207
int main(int argc, char **argv)
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:52
Stopwatch class.
Definition: TStopwatch.h:30