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