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