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)
48useKeras = True # Use Keras Deep Learning via PyMVA
49
50if ROOT.gSystem.GetFromPipe("root-config --has-tmva-pymva") == "yes":
52else:
53 useKeras = False # cannot use Keras if PYMVA is not available
54
55if useKeras:
56 try:
57 pass
58 except:
59 ROOT.Warning("TMVA_Higgs_Classification", "Skip using Keras since tensorflow is not available")
60 useKeras = False
61
62outputFile = TFile.Open("Higgs_ClassificationOutput.root", "RECREATE")
63factory = TMVA.Factory(
64 "TMVA_Higgs_Classification", outputFile, V=False, ROC=True, Silent=False, Color=True, AnalysisType="Classification"
65)
66
67
68## Setup Dataset(s)
69
70# Define now input data file and signal and background trees
71
72inputFileName = str(ROOT.gROOT.GetTutorialDir()) + "/machine_learning/data/Higgs_data.root"
73
74inputFile = TFile.Open(inputFileName)
75if inputFile is None:
76 raise FileNotFoundError("Input file is not found - exit")
77
78
79# --- Register the training and test trees
80signalTree = inputFile.Get("sig_tree")
81backgroundTree = inputFile.Get("bkg_tree")
83
84## Declare DataLoader(s)
85
86# The next step is to declare the DataLoader class that deals with input variables
87# Define the input variables that shall be used for the MVA training
88# note that you may also use variable expressions, which can be parsed by TTree::Draw( "expression" )]
89loader = TMVA.DataLoader("dataset")
90
92loader.AddVariable("m_jjj")
94loader.AddVariable("m_jlv")
96loader.AddVariable("m_wbb")
97loader.AddVariable("m_wwbb")
98
99# We set now the input data trees in the TMVA DataLoader class
100# global event weights per tree (see below for setting event-wise weights)
101signalWeight = 1.0
102backgroundWeight = 1.0
103# You can add an arbitrary number of signal or background trees
104loader.AddSignalTree(signalTree, signalWeight)
105loader.AddBackgroundTree(backgroundTree, backgroundWeight)
106
107# Set individual event weights (the variables must exist in the original TTree)
108# for signal : factory->SetSignalWeightExpression ("weight1*weight2");
109# for background: factory->SetBackgroundWeightExpression("weight1*weight2");
110# loader->SetBackgroundWeightExpression( "weight" );
111
112
113# Apply additional cuts on the signal and background samples (can be different)
114mycuts = ROOT.TCut("") # for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
115mycutb = ROOT.TCut("") # for example: TCut mycutb = "abs(var1)<0.5";
116
117# Tell the factory how to use the training and testing events
118#
119# If no numbers of events are given, half of the events in the tree are used
120# for training, and the other half for testing:
121# loader->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
122# To also specify the number of testing events, use:
123
125 mycuts, mycutb, nTrain_Signal=7000, nTrain_Background=7000, SplitMode="Random", NormMode="NumEvents", V=False
126)
127
128## Booking Methods
129
130# Here we book the TMVA methods. We book first a Likelihood based on KDE (Kernel Density Estimation), a Fischer discriminant, a BDT
131# and a shallow neural network
132# Likelihood ("naive Bayes estimator")
133if useLikelihood:
135 loader,
137 "Likelihood",
138 H=True,
139 V=False,
140 TransformOutput=True,
141 PDFInterpol="Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10",
142 NSmooth=1,
143 NAvEvtPerBin=50,
144 )
145
146# Use a kernel density estimator to approximate the PDFs
147if useLikelihoodKDE:
149 loader,
151 "LikelihoodKDE",
152 H=False,
153 V=False,
154 TransformOutput=False,
155 PDFInterpol="KDE",
156 KDEtype="Gauss",
157 KDEiter="Adaptive",
158 KDEFineFactor=0.3,
159 KDEborder=None,
160 NAvEvtPerBin=50,
161 )
162
163# Fisher discriminant (same as LD)
164if useFischer:
166 loader,
168 "Fisher",
169 H=True,
170 V=False,
171 Fisher=True,
172 VarTransform=None,
173 CreateMVAPdfs=True,
174 PDFInterpolMVAPdf="Spline2",
175 NbinsMVAPdf=50,
176 NsmoothMVAPdf=10,
177 )
178
179# Boosted Decision Trees
180if useBDT:
182 loader,
184 "BDT",
185 V=False,
186 NTrees=200,
187 MinNodeSize="2.5%",
188 MaxDepth=2,
189 BoostType="AdaBoost",
190 AdaBoostBeta=0.5,
191 UseBaggedBoost=True,
192 BaggedSampleFraction=0.5,
193 SeparationType="GiniIndex",
194 nCuts=20,
195 )
196
197# Multi-Layer Perceptron (Neural Network)
198if useMLP:
200 loader,
202 "MLP",
203 H=False,
204 V=False,
205 NeuronType="tanh",
206 VarTransform="N",
207 NCycles=100,
208 HiddenLayers="N+5",
209 TestRate=5,
210 UseRegulator=False,
211 )
212
213## 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
214
215
216## Booking Deep Neural Network
217
218# Here we define the option string for building the Deep Neural network model.
219
220#### 1. Define DNN layout
221
222# The DNN configuration is defined using a string. Note that whitespaces between characters are not allowed.
223
224# We define first the DNN layout:
225
226# - **input layout** : this defines the input data format for the DNN as ``input depth | height | width``.
227# In case of a dense layer as first layer the input layout should be ``1 | 1 | number of input variables`` (features)
228# - **batch layout** : this defines how are the input batch. It is related to input layout but not the same.
229# If the first layer is dense it should be ``1 | batch size ! number of variables`` (features)
230
231# *(note the use of the character `|` as separator of input parameters for DNN layout)*
232
233# note that in case of only dense layer the input layout could be omitted but it is required when defining more
234# complex architectures
235
236# - **layer layout** string defining the layer architecture. The syntax is
237# - layer type (e.g. DENSE, CONV, RNN)
238# - layer parameters (e.g. number of units)
239# - activation function (e.g TANH, RELU,...)
240
241# *the different layers are separated by the ``","`` *
242
243#### 2. Define Training Strategy
244
245# We define here the training strategy parameters for the DNN. The parameters are separated by the ``","`` separator.
246# One can then concatenate different training strategy with different parameters. The training strategy are separated by
247# the ``"|"`` separator.
248
249# - Optimizer
250# - Learning rate
251# - Momentum (valid for SGD and RMSPROP)
252# - Regularization and Weight Decay
253# - Dropout
254# - Max number of epochs
255# - Convergence steps. if the test error will not decrease after that value the training will stop
256# - Batch size (This value must be the same specified in the input layout)
257# - Test Repetitions (the interval when the test error will be computed)
258
259
260#### 3. Define general DNN options
261
262# We define the general DNN options concatenating in the final string the previously defined layout and training strategy.
263# Note we use the ``":"`` separator to separate the different higher level options, as in the other TMVA methods.
264# In addition to input layout, batch layout and training strategy we add now:
265
266# - Type of Loss function (e.g. CROSSENTROPY)
267# - Weight Initizalization (e.g XAVIER, XAVIERUNIFORM, NORMAL )
268# - Variable Transformation
269# - Type of Architecture (e.g. CPU, GPU, Standard)
270
271# We can then book the DL method using the built option string
272if useDL:
273 useDLGPU = ROOT.gSystem.GetFromPipe("root-config --has-tmva-gpu") == "yes"
274
275 # Define DNN layout
276 # Define Training strategies
277 # one can catenate several training strategies
278 training1 = ROOT.TString(
279 "LearningRate=1e-3,Momentum=0.9,"
280 "ConvergenceSteps=10,BatchSize=128,TestRepetitions=1,"
281 "MaxEpochs=20,WeightDecay=1e-4,Regularization=None,"
282 "Optimizer=ADAM,ADAM_beta1=0.9,ADAM_beta2=0.999,ADAM_eps=1.E-7," # ADAM default parameters
283 "DropConfig=0.0+0.0+0.0+0."
284 )
285 # training2 = ROOT.TString("LearningRate=1e-3,Momentum=0.9"
286 # "ConvergenceSteps=10,BatchSize=128,TestRepetitions=1,"
287 # "MaxEpochs=20,WeightDecay=1e-4,Regularization=None,"
288 # "Optimizer=SGD,DropConfig=0.0+0.0+0.0+0.")
289
290 # General Options.
291 dnnMethodName = ROOT.TString("DNN_CPU")
292
293 if useDLGPU:
294 arch = "GPU"
295 dnnMethodName = "DNN_GPU"
296 else:
297 arch = "CPU"
298
300 loader,
302 dnnMethodName,
303 H=False,
304 V=True,
305 ErrorStrategy="CROSSENTROPY",
306 VarTransform="G",
307 WeightInitialization="XAVIER",
308 InputLayout="1|1|7",
309 BatchLayout="1|128|7",
310 Layout="DENSE|64|TANH,DENSE|64|TANH,DENSE|64|TANH,DENSE|64|TANH,DENSE|1|LINEAR",
311 TrainingStrategy=training1,
312 Architecture=arch,
313 )
314
315# Keras DL
316if useKeras:
317 ROOT.Info("TMVA_Higgs_Classification", "Building Deep Learning keras model")
318 # create Keras model with 4 layers of 64 units and relu activations
319 from tensorflow.keras.layers import Dense
320 from tensorflow.keras.models import Sequential
321 from tensorflow.keras.optimizers import Adam
322
323 model = Sequential()
324 model.add(Dense(64, activation="relu", input_dim=7))
325 model.add(Dense(64, activation="relu"))
326 model.add(Dense(64, activation="relu"))
327 model.add(Dense(64, activation="relu"))
328 model.add(Dense(2, activation="sigmoid"))
329 model.compile(loss="binary_crossentropy", optimizer=Adam(learning_rate=0.001), weighted_metrics=["accuracy"])
330 model.save("model_higgs.keras")
332
333 if not os.path.exists("model_higgs.keras"):
334 raise FileNotFoundError("Error creating Keras model file - skip using Keras")
335 else:
336 # book PyKeras method only if Keras model could be created
337 ROOT.Info("TMVA_Higgs_Classification", "Booking Deep Learning keras model")
339 loader,
341 "PyKeras",
342 H=True,
343 V=False,
344 VarTransform=None,
345 FilenameModel="model_higgs.keras",
346 FilenameTrainedModel="trained_model_higgs.keras",
347 NumEpochs=20,
348 BatchSize=100,
349 )
350# GpuOptions="allow_growth=True",
351# ) # needed for RTX NVidia card and to avoid TF allocates all GPU memory
352
353
354## Train Methods
355
356# Here we train all the previously booked methods.
357
359## Test all methods
360
361# Now we test and evaluate all methods using the test data set
363
365
366# after we get the ROC curve and we display
367
368c1 = factory.GetROCCurve(loader)
369c1.Draw()
370# at the end we close the output file which contains the evaluation result of all methods and it can be used by TMVAGUI
371# to display additional plots
372
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
This is the main MVA steering class.
Definition Factory.h:80