Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TMVAMulticlass.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_ml
3/// \notebook -nodraw
4/// This macro provides a simple example for the training and testing of the TMVA
5/// multiclass classification
6/// - Project : TMVA - a Root-integrated toolkit for multivariate data analysis
7/// - Package : TMVA
8/// - Root Macro: TMVAMulticlass
9///
10/// \macro_code
11/// \macro_output
12/// \author Andreas Hoecker
13
14#include <cstdlib>
15#include <iostream>
16#include <map>
17#include <string>
18
19#include "TFile.h"
20#include "TTree.h"
21#include "TString.h"
22#include "TSystem.h"
23#include "TROOT.h"
24
25
26#include "TMVA/Tools.h"
27#include "TMVA/Factory.h"
28#include "TMVA/DataLoader.h"
30
31
32using namespace TMVA;
33
34void TMVAMulticlass( TString myMethodList = "" )
35{
36
37 // This loads the library
39
40 // to get access to the GUI and all tmva macros
41 //
42 // gROOT->ProcessLine("TMVA::TMVAMultiClassGui()");
43
44
45 //---------------------------------------------------------------
46 // Default MVA methods to be trained + tested
47 std::map<std::string,int> Use;
48 Use["MLP"] = 1;
49 Use["BDTG"] = 1;
50 Use["FDA_GA"] = 0;
51 Use["PDEFoam"] = 1;
52
53 //---------------------------------------------------------------
54
55 std::cout << std::endl;
56 std::cout << "==> Start TMVAMulticlass" << std::endl;
57
58 if (myMethodList != "") {
59 for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
60
61 std::vector<TString> mlist = TMVA::gTools().SplitString( myMethodList, ',' );
62 for (UInt_t i=0; i<mlist.size(); i++) {
63 std::string regMethod(mlist[i]);
64
65 if (Use.find(regMethod) == Use.end()) {
66 std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
67 for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
68 std::cout << std::endl;
69 return;
70 }
71 Use[regMethod] = 1;
72 }
73 }
74
75 // Create a new root output file.
76 TString outfileName = "TMVAMulticlass.root";
77 TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
78
79 TMVA::Factory *factory = new TMVA::Factory( "TMVAMulticlass", outputFile,
80 "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=multiclass" );
81 TMVA::DataLoader *dataloader=new TMVA::DataLoader("dataset");
82
83 dataloader->AddVariable( "var1", 'F' );
84 dataloader->AddVariable( "var2", "Variable 2", "", 'F' );
85 dataloader->AddVariable( "var3", "Variable 3", "units", 'F' );
86 dataloader->AddVariable( "var4", "Variable 4", "units", 'F' );
87
88 TFile *input(nullptr);
89 TString fname = gROOT->GetTutorialDir() + "/machine_learning/data/tmva_multiclass_example.root";
90 if (!gSystem->AccessPathName( fname )) {
91 input = TFile::Open( fname ); // check if file in local directory exists
92 }
93 if (!input) {
94 std::cout << "ERROR: could not open data file" << std::endl;
95 exit(1);
96 }
97 std::cout << "--- TMVAMulticlass: Using input file: " << input->GetName() << std::endl;
98
99 TTree *signalTree = (TTree*)input->Get("TreeS");
100 TTree *background0 = (TTree*)input->Get("TreeB0");
101 TTree *background1 = (TTree*)input->Get("TreeB1");
102 TTree *background2 = (TTree*)input->Get("TreeB2");
103
104 gROOT->cd( outfileName+TString(":/") );
105 dataloader->AddTree (signalTree,"Signal");
106 dataloader->AddTree (background0,"bg0");
107 dataloader->AddTree (background1,"bg1");
108 dataloader->AddTree (background2,"bg2");
109
110 dataloader->PrepareTrainingAndTestTree( "", "SplitMode=Random:NormMode=NumEvents:!V" );
111
112 if (Use["BDTG"]) // gradient boosted decision trees
113 factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTG", "!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.10:UseBaggedBoost:BaggedSampleFraction=0.50:nCuts=20:MaxDepth=2");
114 if (Use["MLP"]) // neural network
115 factory->BookMethod( dataloader, TMVA::Types::kMLP, "MLP", "!H:!V:NeuronType=tanh:NCycles=1000:HiddenLayers=N+5,5:TestRate=5:EstimatorType=MSE");
116 if (Use["FDA_GA"]) // functional discriminant with GA minimizer
117 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_GA", "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:PopSize=300:Cycles=3:Steps=20:Trim=True:SaveBestGen=1" );
118 if (Use["PDEFoam"]) // PDE-Foam approach
119 factory->BookMethod( dataloader, TMVA::Types::kPDEFoam, "PDEFoam", "!H:!V:TailCut=0.001:VolFrac=0.0666:nActiveCells=500:nSampl=2000:nBin=5:Nmin=100:Kernel=None:Compress=T" );
120
121
122 // Train MVAs using the set of training events
123 factory->TrainAllMethods();
124
125 // Evaluate all MVAs using the set of test events
126 factory->TestAllMethods();
127
128 // Evaluate and compare performance of all configured MVAs
129 factory->EvaluateAllMethods();
130
131 // --------------------------------------------------------------
132
133 // Save the output
134 outputFile->Close();
135
136 std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
137 std::cout << "==> TMVAMulticlass is done!" << std::endl;
138
139 delete factory;
140 delete dataloader;
141
142 // Launch the GUI for the root macros
143 if (!gROOT->IsBatch()) TMVAMultiClassGui( outfileName );
144
145
146}
147
148int main( int argc, char** argv )
149{
150 // Select methods (don't look at this code - not of interest)
151 TString methodList;
152 for (int i=1; i<argc; i++) {
153 TString regMethod(argv[i]);
154 if(regMethod=="-b" || regMethod=="--batch") continue;
155 if (!methodList.IsNull()) methodList += TString(",");
156 methodList += regMethod;
157 }
158 TMVAMulticlass(methodList);
159 return 0;
160}
161
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
Definition RtypesCore.h:61
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
#define gROOT
Definition TROOT.h:417
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
A file, usually with extension .root, that stores data and code in the form of serialized objects in ...
Definition TFile.h:130
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:3804
void Close(Option_t *option="") override
Close a file.
Definition TFile.cxx:992
void PrepareTrainingAndTestTree(const TCut &cut, const TString &splitOpt)
prepare the training and test trees -> same cuts for signal and background
void AddTree(TTree *tree, const TString &className, Double_t weight=1.0, const TCut &cut="", Types::ETreeType tt=Types::kMaxTreeType)
void AddVariable(const TString &expression, const TString &title, const TString &unit, char type='F', Double_t min=0, Double_t max=0)
user inserts discriminating variable in data set info
This is the main MVA steering class.
Definition Factory.h:80
void TrainAllMethods()
Iterates through all booked methods and calls training.
Definition Factory.cxx:1105
void TestAllMethods()
Evaluates all booked methods on the testing data and adds the output to the Results in the corresponi...
Definition Factory.cxx:1262
void EvaluateAllMethods(void)
Iterates over all MVAs that have been booked, and calls their evaluation methods.
Definition Factory.cxx:1367
MethodBase * BookMethod(DataLoader *loader, MethodName theMethodName, TString methodTitle, TString theOption="")
Books an MVA classifier or regression method.
Definition Factory.cxx:354
static Tools & Instance()
Definition Tools.cxx:72
std::vector< TString > SplitString(const TString &theOpt, const char separator) const
splits the option string at 'separator' and fills the list 'splitV' with the primitive strings
Definition Tools.cxx:1174
@ kPDEFoam
Definition Types.h:94
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
Basic string class.
Definition TString.h:137
Bool_t IsNull() const
Definition TString.h:423
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:1319
A TTree represents a columnar dataset.
Definition TTree.h:95
int main()
Definition main.cpp:18
create variable transformations
Tools & gTools()
void TMVAMultiClassGui(const char *fName="TMVAMulticlass.root", TString dataset="")