Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TMVAClassificationCategoryApplication.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 classifiers
5/// (with categories) within an analysis module
6/// - Project : TMVA - a Root-integrated toolkit for multivariate data analysis
7/// - Package : TMVA
8/// - Executable: TMVAClassificationCategoryApplication
9///
10/// \macro_output
11/// \macro_code
12/// \author Andreas Hoecker
13
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 "TH1F.h"
27#include "TStopwatch.h"
28
29#include "TMVA/Tools.h"
30#include "TMVA/Reader.h"
31#include "TMVA/MethodCuts.h"
32
33// two types of category methods are implemented
34Bool_t UseOffsetMethod = kTRUE;
35
36void TMVAClassificationCategoryApplication()
37{
38 // ---------------------------------------------------------------
39 // default MVA methods to be trained + tested
40 std::map<std::string,int> Use;
41 //
42 Use["LikelihoodCat"] = 1;
43 Use["FisherCat"] = 1;
44 // ---------------------------------------------------------------
45
46 std::cout << std::endl
47 << "==> Start TMVAClassificationCategoryApplication" << std::endl;
48
49 // Create the Reader object
50
51 TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );
52
53 // Create a set of variables and spectators and declare them to the reader
54 // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
55 Float_t var1, var2, var3, var4, eta;
56 reader->AddVariable( "var1", &var1 );
57 reader->AddVariable( "var2", &var2 );
58 reader->AddVariable( "var3", &var3 );
59 reader->AddVariable( "var4", &var4 );
60
61 reader->AddSpectator( "eta", &eta );
62
63 // Book the MVA methods
64
65 for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
66 if (it->second) {
67 TString methodName = it->first + " method";
68 TString weightfile = "dataset/weights/TMVAClassificationCategory_" + TString(it->first) + ".weights.xml";
69 reader->BookMVA( methodName, weightfile );
70 }
71 }
72
73 // Book output histograms
74 UInt_t nbin = 100;
75 std::map<std::string,TH1*> hist;
76 hist["LikelihoodCat"] = new TH1F( "MVA_LikelihoodCat", "MVA_LikelihoodCat", nbin, -1, 0.9999 );
77 hist["FisherCat"] = new TH1F( "MVA_FisherCat", "MVA_FisherCat", nbin, -4, 4 );
78
79 // Prepare input tree (this must be replaced by your data source)
80 // in this example, there is a toy tree with signal and one with background events
81 // we'll later on use only the "signal" events for the test in this example.
82 //
83 TString fname = gSystem->GetDirName(__FILE__) + "/data/";
84 // if directory data not found try using tutorials dir
85 if (gSystem->AccessPathName( fname + "toy_sigbkg_categ_offset.root" )) {
86 fname = gROOT->GetTutorialDir() + "/tmva/data/";
87 }
88 if (UseOffsetMethod) fname += "toy_sigbkg_categ_offset.root";
89 else fname += "toy_sigbkg_categ_varoff.root";
90 std::cout << "--- TMVAClassificationApp : Accessing " << fname << "!" << std::endl;
91 TFile *input = TFile::Open(fname);
92 if (!input) {
93 std::cout << "ERROR: could not open data file: " << fname << std::endl;
94 exit(1);
95 }
96
97 // Event loop
98
99 // Prepare the tree
100 // - here the variable names have to corresponds to your tree
101 // - you can use the same variables as above which is slightly faster,
102 // but of course you can use different ones and copy the values inside the event loop
103 //
104 TTree* theTree = (TTree*)input->Get("TreeS");
105 std::cout << "--- Use signal sample for evaluation" << std::endl;
106 theTree->SetBranchAddress( "var1", &var1 );
107 theTree->SetBranchAddress( "var2", &var2 );
108 theTree->SetBranchAddress( "var3", &var3 );
109 theTree->SetBranchAddress( "var4", &var4 );
110
111 theTree->SetBranchAddress( "eta", &eta ); // spectator
112
113 std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
114 TStopwatch sw;
115 sw.Start();
116 for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
117
118 if (ievt%1000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl;
119
120 theTree->GetEntry(ievt);
121
122 // Return the MVA outputs and fill into histograms
123
124 for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
125 if (!it->second) continue;
126 TString methodName = it->first + " method";
127 hist[it->first]->Fill( reader->EvaluateMVA( methodName ) );
128 }
129
130 }
131 sw.Stop();
132 std::cout << "--- End of event loop: "; sw.Print();
133
134 // Write histograms
135
136 TFile *target = new TFile( "TMVApp.root","RECREATE" );
137 for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++)
138 if (it->second) hist[it->first]->Write();
139
140 target->Close();
141 std::cout << "--- Created root file: \"TMVApp.root\" containing the MVA output histograms" << std::endl;
142
143 delete reader;
144 std::cout << "==> TMVAClassificationApplication is done!" << std::endl << std::endl;
145}
146
147int main( int argc, char** argv )
148{
149 TMVAClassificationCategoryApplication();
150 return 0;
151}
int main()
Definition Prototype.cxx:12
bool Bool_t
Definition RtypesCore.h:63
unsigned int UInt_t
Definition RtypesCore.h:46
float Float_t
Definition RtypesCore.h:57
long long Long64_t
Definition RtypesCore.h:80
constexpr Bool_t kTRUE
Definition RtypesCore.h:100
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t target
#define gROOT
Definition TROOT.h:406
R__EXTERN TSystem * gSystem
Definition TSystem.h:555
A ROOT file is an on-disk file, usually with extension .root, that stores objects in a file-system-li...
Definition TFile.h:53
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
Create / open a file.
Definition TFile.cxx:4082
1-D histogram with a float per channel (see TH1 documentation)
Definition TH1.h:621
The Reader class serves to use the MVAs in a specific analysis context.
Definition Reader.h:64
Double_t EvaluateMVA(const std::vector< Float_t > &, const TString &methodTag, Double_t aux=0)
Evaluate a std::vector<float> of input data for a given method The parameter aux is obligatory for th...
Definition Reader.cxx:468
IMethod * BookMVA(const TString &methodTag, const TString &weightfile)
read method name from weight file
Definition Reader.cxx:368
void AddSpectator(const TString &expression, Float_t *)
Add a float spectator or expression to the reader.
Definition Reader.cxx:321
void AddVariable(const TString &expression, Float_t *)
Add a float variable or expression to the reader.
Definition Reader.cxx:303
Stopwatch class.
Definition TStopwatch.h:28
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
void Stop()
Stop the stopwatch.
void Print(Option_t *option="") const override
Print the real and cpu time passed between the start and stop events.
Basic string class.
Definition TString.h:139
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:1296
virtual TString GetDirName(const char *pathname)
Return the directory name in pathname.
Definition TSystem.cxx:1032
A TTree represents a columnar dataset.
Definition TTree.h:79
virtual Int_t GetEntry(Long64_t entry, Int_t getall=0)
Read all branches of entry and return total number of bytes read.
Definition TTree.cxx:5638
virtual Int_t SetBranchAddress(const char *bname, void *add, TBranch **ptr=nullptr)
Change branch address, dealing with clone trees properly.
Definition TTree.cxx:8385
virtual Long64_t GetEntries() const
Definition TTree.h:463