Logo ROOT  
Reference Guide
TMVA_Higgs_Classification.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_tmva
3/// \notebook
4/// Classification example of TMVA based on public Higgs UCI dataset
5///
6/// The UCI data set is a public HIGGS data set , see http://archive.ics.uci.edu/ml/datasets/HIGGS
7/// used in this paper: Baldi, P., P. Sadowski, and D. Whiteson. “Searching for Exotic Particles in High-energy Physics
8/// with Deep Learning.” Nature Communications 5 (July 2, 2014).
9///
10/// \macro_image
11/// \macro_output
12/// \macro_code
13///
14/// \author Lorenzo Moneta
15
16/***
17## Declare Factory
18
19Create the Factory class. Later you can choose the methods
20whose performance you'd like to investigate.
21
22The factory is the major TMVA object you have to interact with. Here is the list of parameters you need to pass
23
24 - The first argument is the base of the name of all the output
25weightfiles in the directory weight/ that will be created with the
26method parameters
27
28 - The second argument is the output file for the training results
29
30 - The third argument is a string option defining some general configuration for the TMVA session. For example all TMVA output can be suppressed by removing the "!" (not) in front of the "Silent" argument in the option string
31
32**/
33
34void TMVA_Higgs_Classification() {
35
36 // options to control used methods
37
38 bool useLikelihood = true; // likelihood based discriminant
39 bool useLikelihoodKDE = false; // likelihood based discriminant
40 bool useFischer = true; // Fischer discriminant
41 bool useMLP = false; // Multi Layer Perceptron (old TMVA NN implementation)
42 bool useBDT = true; // BOosted Decision Tree
43 bool useDL = true; // TMVA Deep learning ( CPU or GPU)
44
45
46
48
49 auto outputFile = TFile::Open("Higgs_ClassificationOutput.root", "RECREATE");
50
51 TMVA::Factory factory("TMVA_Higgs_Classification", outputFile,
52 "!V:ROC:!Silent:Color:AnalysisType=Classification" );
53
54/**
55
56## Setup Dataset(s)
57
58Define now input data file and signal and background trees
59
60 **/
61
62 TString inputFileName = "Higgs_data.root";
63 TString inputFileLink = "http://root.cern.ch/files/" + inputFileName;
64
65 TFile *inputFile = nullptr;
66
67 if (!gSystem->AccessPathName(inputFileName)) {
68 // file exists
69 inputFile = TFile::Open( inputFileName );
70 }
71
72 if (!inputFile) {
73 // download file from Cernbox location
74 Info("TMVA_Higgs_Classification","Download Higgs_data.root file");
75 inputFile = TFile::Open(inputFileLink, "CACHEREAD");
76 //gSystem->Exec( TString::Format("wget -O %s %s",inputFileName.Data(), downloadLinkFile.Data() ) );
77 //inputFile = TFile::Open( inputFileName);
78 if (!inputFile) {
79 Error("TMVA_Higgs_Classification","Input file cannot be downloaded - exit");
80 return;
81 }
82 }
83
84// --- Register the training and test trees
85
86 TTree *signalTree = (TTree*)inputFile->Get("sig_tree");
87 TTree *backgroundTree = (TTree*)inputFile->Get("bkg_tree");
88
89 signalTree->Print();
90
91/***
92## Declare DataLoader(s)
93
94The next step is to declare the DataLoader class that deals with input variables
95
96Define the input variables that shall be used for the MVA training
97note that you may also use variable expressions, which can be parsed by TTree::Draw( "expression" )]
98
99***/
100
101 TMVA::DataLoader * loader = new TMVA::DataLoader("dataset");
102
103 loader->AddVariable("m_jj");
104 loader->AddVariable("m_jjj");
105 loader->AddVariable("m_lv");
106 loader->AddVariable("m_jlv");
107 loader->AddVariable("m_bb");
108 loader->AddVariable("m_wbb");
109 loader->AddVariable("m_wwbb");
110
111/// We set now the input data trees in the TMVA DataLoader class
112
113// global event weights per tree (see below for setting event-wise weights)
114 Double_t signalWeight = 1.0;
115 Double_t backgroundWeight = 1.0;
116
117// You can add an arbitrary number of signal or background trees
118 loader->AddSignalTree ( signalTree, signalWeight );
119 loader->AddBackgroundTree( backgroundTree, backgroundWeight );
120
121
122// Set individual event weights (the variables must exist in the original TTree)
123// for signal : factory->SetSignalWeightExpression ("weight1*weight2");
124// for background: factory->SetBackgroundWeightExpression("weight1*weight2");
125//loader->SetBackgroundWeightExpression( "weight" );
126
127// Apply additional cuts on the signal and background samples (can be different)
128 TCut mycuts = ""; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
129 TCut mycutb = ""; // for example: TCut mycutb = "abs(var1)<0.5";
130
131// Tell the factory how to use the training and testing events
132//
133// If no numbers of events are given, half of the events in the tree are used
134// for training, and the other half for testing:
135// loader->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
136// To also specify the number of testing events, use:
137
138 loader->PrepareTrainingAndTestTree( mycuts, mycutb,
139 "nTrain_Signal=7000:nTrain_Background=7000:SplitMode=Random:NormMode=NumEvents:!V" );
140
141/***
142## Booking Methods
143
144Here we book the TMVA methods. We book first a Likelihood based on KDE (Kernel Density Estimation), a Fischer discriminant, a BDT
145and a shallow neural network
146
147 */
148
149
150// Likelihood ("naive Bayes estimator")
151if (useLikelihood) {
152 factory.BookMethod(loader, TMVA::Types::kLikelihood, "Likelihood",
153 "H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" );
154}
155// Use a kernel density estimator to approximate the PDFs
156if (useLikelihoodKDE) {
157 factory.BookMethod(loader, TMVA::Types::kLikelihood, "LikelihoodKDE",
158 "!H:!V:!TransformOutput:PDFInterpol=KDE:KDEtype=Gauss:KDEiter=Adaptive:KDEFineFactor=0.3:KDEborder=None:NAvEvtPerBin=50" );
159
160}
161
162// Fisher discriminant (same as LD)
163if (useFischer) {
164 factory.BookMethod(loader, TMVA::Types::kFisher, "Fisher", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
165}
166
167//Boosted Decision Trees
168if (useBDT) {
169 factory.BookMethod(loader,TMVA::Types::kBDT, "BDT",
170 "!V:NTrees=200:MinNodeSize=2.5%:MaxDepth=2:BoostType=AdaBoost:AdaBoostBeta=0.5:UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex:nCuts=20" );
171}
172
173//Multi-Layer Perceptron (Neural Network)
174if (useMLP) {
175 factory.BookMethod(loader, TMVA::Types::kMLP, "MLP",
176 "!H:!V:NeuronType=tanh:VarTransform=N:NCycles=100:HiddenLayers=N+5:TestRate=5:!UseRegulator" );
177}
178
179
180/// Here we book the new DNN of TMVA if we have support in ROOT. We will use GPU version if ROOT is enabled with GPU
181
182
183 /***
184
185## Booking Deep Neural Network
186
187Here we define the option string for building the Deep Neural network model.
188
189#### 1. Define DNN layout
190
191The DNN configuration is defined using a string. Note that whitespaces between characters are not allowed.
192
193We define first the DNN layout:
194
195- **input layout** : this defines the input data format for the DNN as ``input depth | height | width``.
196 In case of a dense layer as first layer the input layout should be ``1 | 1 | number of input variables`` (features)
197- **batch layout** : this defines how are the input batch. It is related to input layout but not the same.
198 If the first layer is dense it should be ``1 | batch size ! number of variables`` (fetures)
199
200 *(note the use of the character `|` as separator of input parameters for DNN layout)*
201
202note that in case of only dense layer the input layout could be omitted but it is required when defining more
203complex architectures
204
205- **layer layout** string defining the layer architecture. The syntax is
206 - layer type (e.g. DENSE, CONV, RNN)
207 - layer parameters (e.g. number of units)
208 - activation function (e.g TANH, RELU,...)
209
210 *the different layers are separated by the ``","`` *
211
212#### 2. Define Trainining Strategy
213
214We define here the training strategy parameters for the DNN. The parameters are separated by the ``","`` separator.
215One can then concatenate different training strategy with different parameters. The training strategy are separated by
216the ``"|"`` separator.
217
218 - Optimizer
219 - Learning rate
220 - Momentum (valid for SGD and RMSPROP)
221 - Regularization and Weight Decay
222 - Dropout
223 - Max number of epochs
224 - Convergence steps. if the test error will not decrease after that value the training will stop
225 - Batch size (This value must be the same specified in the input layout)
226 - Test Repetitions (the interval when the test error will be computed)
227
228
229#### 3. Define general DNN options
230
231We define the general DNN options concateneting in the final string the previously defined layout and training strategy.
232Note we use the ``":"`` separator to separate the different higher level options, as in the other TMVA methods.
233In addition to input layout, batch layout and training strategy we add now:
234
235- Type of Loss function (e.g. CROSSENTROPY)
236- Weight Initizalization (e.g XAVIER, XAVIERUNIFORM, NORMAL )
237- Variable Transformation
238- Type of Architecture (e.g. CPU, GPU, Standard)
239
240We can then book the DL method using the built option string
241
242 ***/
243
244 if (useDL) {
245
246 bool useDLGPU = false;
247#ifdef R__HAS_TMVAGPU
248 useDLGPU = true;
249#endif
250
251 // Define DNN layout
252 TString inputLayoutString = "InputLayout=1|1|7";
253 TString batchLayoutString= "BatchLayout=1|128|7";
254 TString layoutString ("Layout=DENSE|64|TANH,DENSE|64|TANH,DENSE|64|TANH,DENSE|64|TANH,DENSE|1|LINEAR");
255 // Define Training strategies
256 // one can catenate several training strategies
257 TString training1("LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
258 "ConvergenceSteps=10,BatchSize=128,TestRepetitions=1,"
259 "MaxEpochs=30,WeightDecay=1e-4,Regularization=None,"
260 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.");
261 // TString training2("LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
262 // "ConvergenceSteps=10,BatchSize=128,TestRepetitions=1,"
263 // "MaxEpochs=20,WeightDecay=1e-4,Regularization=None,"
264 // "Optimizer=SGD,DropConfig=0.0+0.0+0.0+0.");
265
266 TString trainingStrategyString ("TrainingStrategy=");
267 trainingStrategyString += training1; // + "|" + training2;
268
269 // General Options.
270
271 TString dnnOptions ("!H:V:ErrorStrategy=CROSSENTROPY:VarTransform=G:"
272 "WeightInitialization=XAVIER");
273 dnnOptions.Append (":"); dnnOptions.Append (inputLayoutString);
274 dnnOptions.Append (":"); dnnOptions.Append (batchLayoutString);
275 dnnOptions.Append (":"); dnnOptions.Append (layoutString);
276 dnnOptions.Append (":"); dnnOptions.Append (trainingStrategyString);
277
278 TString dnnMethodName = "DNN_CPU";
279 if (useDLGPU) {
280 dnnOptions += ":Architecture=GPU";
281 dnnMethodName = "DNN_GPU";
282 } else {
283 dnnOptions += ":Architecture=CPU";
284 }
285
286 factory.BookMethod(loader, TMVA::Types::kDL, dnnMethodName, dnnOptions);
287
288 }
289
290 /**
291## Train Methods
292
293Here we train all the previously booked methods.
294
295 */
296
297 factory.TrainAllMethods();
298
299/**
300 ## Test all methods
301
302 Now we test and evaluate all methods using the test data set
303*/
304
305 factory.TestAllMethods();
306
307 factory.EvaluateAllMethods();
308
309/// after we get the ROC curve and we display
310
311 auto c1 = factory.GetROCCurve(loader);
312 c1->Draw();
313
314/// at the end we close the output file which contains the evaluation result of all methods and it can be used by TMVAGUI
315/// to display additional plots
316
317 outputFile->Close();
318
319
320}
double Double_t
Definition: RtypesCore.h:57
void Info(const char *location, const char *msgfmt,...)
void Error(const char *location, const char *msgfmt,...)
R__EXTERN TSystem * gSystem
Definition: TSystem.h:556
A specialized string object used for TTree selections.
Definition: TCut.h:25
TObject * Get(const char *namecycle) override
Return pointer to object identified by namecycle.
A ROOT file is a suite of consecutive data records (TKey instances) with a well defined format.
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:3942
void AddSignalTree(TTree *signal, Double_t weight=1.0, Types::ETreeType treetype=Types::kMaxTreeType)
number of signal events (used to compute significance)
Definition: DataLoader.cxx:372
void PrepareTrainingAndTestTree(const TCut &cut, const TString &splitOpt)
prepare the training and test trees -> same cuts for signal and background
Definition: DataLoader.cxx:633
void AddBackgroundTree(TTree *background, Double_t weight=1.0, Types::ETreeType treetype=Types::kMaxTreeType)
number of signal events (used to compute significance)
Definition: DataLoader.cxx:403
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
Definition: DataLoader.cxx:486
This is the main MVA steering class.
Definition: Factory.h:81
static Tools & Instance()
Definition: Tools.cxx:74
@ kFisher
Definition: Types.h:84
@ kBDT
Definition: Types.h:88
@ kLikelihood
Definition: Types.h:81
@ kMLP
Definition: Types.h:92
Basic string class.
Definition: TString.h:131
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:1291
A TTree represents a columnar dataset.
Definition: TTree.h:78
virtual void Print(Option_t *option="") const
Print a summary of the tree contents.
Definition: TTree.cxx:7122
return c1
Definition: legend1.C:41