Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TMVA_CNN_Classification.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_ml
3## \notebook
4## TMVA Classification Example Using a Convolutional Neural Network
5##
6## This is an example of using a CNN in TMVA. We do classification using a toy image data set
7## that is generated when running the example macro
8##
9## \macro_image
10## \macro_output
11## \macro_code
12##
13## \author Harshal Shende
14
15
16# TMVA Classification Example Using a Convolutional Neural Network
17
18
19## Helper function to create input images data
20## we create a signal and background 2D histograms from 2d gaussians
21## with a location (means in X and Y) different for each event
22## The difference between signal and background is in the gaussian width.
23## The width for the background gaussian is slightly larger than the signal width by few % values
24
25import importlib.util
26import os
27
28import ROOT
29
30opt = [1, 1, 1, 1, 1]
31useTMVACNN = opt[0] if len(opt) > 0 else False
32useTMVADNN = opt[2] if len(opt) > 2 else False
33useTMVABDT = opt[3] if len(opt) > 3 else False
34
35TMVA = ROOT.TMVA
36TFile = ROOT.TFile
37
39
40def MakeImagesTree(n, nh, nw):
41 # image size (nh x nw)
42 ntot = nh * nw
43 fileOutName = "images_data_16x16.root"
44 nRndmEvts = 10000 # number of events we use to fill each image
45 delta_sigma = 0.1 # 5% difference in the sigma
46 pixelNoise = 5
47
48 sX1 = 3
49 sY1 = 3
50 sX2 = sX1 + delta_sigma
51 sY2 = sY1 - delta_sigma
52 h1 = ROOT.TH2D("h1", "h1", nh, 0, 10, nw, 0, 10)
53 h2 = ROOT.TH2D("h2", "h2", nh, 0, 10, nw, 0, 10)
54 f1 = ROOT.TF2("f1", "xygaus")
55 f2 = ROOT.TF2("f2", "xygaus")
56 sgn = ROOT.TTree("sig_tree", "signal_tree")
57 bkg = ROOT.TTree("bkg_tree", "background_tree")
58
59 f = TFile(fileOutName, "RECREATE")
60 x1 = ROOT.std.vector["float"](ntot)
61 x2 = ROOT.std.vector["float"](ntot)
62
63 # create signal and background trees with a single branch
64 # an std::vector<float> of size nh x nw containing the image data
65 bkg.Branch("vars", "std::vector<float>", x1)
66 sgn.Branch("vars", "std::vector<float>", x2)
67
68 sgn.SetDirectory(f)
69 bkg.SetDirectory(f)
70
71 f1.SetParameters(1, 5, sX1, 5, sY1)
72 f2.SetParameters(1, 5, sX2, 5, sY2)
73 ROOT.gRandom.SetSeed(0)
74 ROOT.Info("TMVA_CNN_Classification", "Filling ROOT tree \n")
75 for i in range(n):
76 if i % 1000 == 0:
77 print("Generating image event ...", i)
78
79 h1.Reset()
80 h2.Reset()
81 # generate random means in range [3,7] to be not too much on the border
82 f1.SetParameter(1, ROOT.gRandom.Uniform(3, 7))
83 f1.SetParameter(3, ROOT.gRandom.Uniform(3, 7))
84 f2.SetParameter(1, ROOT.gRandom.Uniform(3, 7))
85 f2.SetParameter(3, ROOT.gRandom.Uniform(3, 7))
86
87 h1.FillRandom(f1, nRndmEvts)
88 h2.FillRandom(f2, nRndmEvts)
89
90 for k in range(nh):
91 for l in range(nw):
92 m = k * nw + l
93 # add some noise in each bin
94 x1[m] = h1.GetBinContent(k + 1, l + 1) + ROOT.gRandom.Gaus(0, pixelNoise)
95 x2[m] = h2.GetBinContent(k + 1, l + 1) + ROOT.gRandom.Gaus(0, pixelNoise)
96
97 sgn.Fill()
98 bkg.Fill()
99
100 sgn.Write()
101 bkg.Write()
102
103 print("Signal and background tree with images data written to the file %s", f.GetName())
104 sgn.Print()
105 bkg.Print()
106 f.Close()
107
108hasGPU = "tmva-gpu" in ROOT.gROOT.GetConfigFeatures()
109hasCPU = "tmva-cpu" in ROOT.gROOT.GetConfigFeatures()
110
111nevt = 1000 # use a larger value to get better results
112
113if (not hasCPU and not hasGPU) :
114 ROOT.Warning("TMVA_CNN_Classificaton","ROOT is not supporting tmva-cpu and tmva-gpu skip using TMVA-DNN and TMVA-CNN")
115 useTMVACNN = False
116 useTMVADNN = False
117
118if not useTMVACNN:
119 ROOT.Warning(
120 "TMVA_CNN_Classificaton",
121 "TMVA is not build with GPU or CPU multi-thread support. Cannot use TMVA Deep Learning for CNN",
122 )
123
124writeOutputFile = True
125
126num_threads = 4 # use max 4 threads
127max_epochs = 10 # maximum number of epochs used for training
128
129
130# do enable MT running
131if "imt" in ROOT.gROOT.GetConfigFeatures():
132 ROOT.EnableImplicitMT(num_threads)
133 ROOT.gSystem.Setenv("OMP_NUM_THREADS", "1") # switch OFF MT in OpenBLAS
134 print("Running with nthreads = {}".format(ROOT.GetThreadPoolSize()))
135else:
136 print("Running in serial mode since ROOT does not support MT")
137
138
139
140
141outputFile = None
142if writeOutputFile:
143 outputFile = TFile.Open("TMVA_CNN_ClassificationOutput.root", "RECREATE")
144
145
146## Create TMVA Factory
147
148# Create the Factory class. Later you can choose the methods
149# whose performance you'd like to investigate.
150
151# The factory is the major TMVA object you have to interact with. Here is the list of parameters you need to pass
152
153# - The first argument is the base of the name of all the output
154# weight files in the directory weight/ that will be created with the
155# method parameters
156
157# - The second argument is the output file for the training results
158
159# - The third argument is a string option defining some general configuration for the TMVA session.
160# For example all TMVA output can be suppressed by removing the "!" (not) in front of the "Silent" argument in the
161# option string
162
163# - note that we disable any pre-transformation of the input variables and we avoid computing correlations between
164# input variables
165
166
167factory = TMVA.Factory(
168 "TMVA_CNN_Classification",
169 outputFile,
170 V=False,
171 ROC=True,
172 Silent=False,
173 Color=True,
174 AnalysisType="Classification",
175 Transformations=None,
176 Correlations=False,
177)
178
179
180## Declare DataLoader(s)
181
182# The next step is to declare the DataLoader class that deals with input variables
183
184# Define the input variables that shall be used for the MVA training
185# note that you may also use variable expressions, which can be parsed by TTree::Draw( "expression" )]
186
187# In this case the input data consists of an image of 16x16 pixels. Each single pixel is a branch in a ROOT TTree
188
189loader = TMVA.DataLoader("dataset")
190
191
192## Setup Dataset(s)
193
194# Define input data file and signal and background trees
195
196
197imgSize = 16 * 16
198inputFileName = "images_data_16x16.root"
199
200# if the input file does not exist create it
201if ROOT.gSystem.AccessPathName(inputFileName):
202 MakeImagesTree(nevt, 16, 16)
203
204inputFile = TFile.Open(inputFileName)
205if inputFile is None:
206 ROOT.Warning("TMVA_CNN_Classification", "Error opening input file %s - exit", inputFileName.Data())
207
208
209# inputFileName = "tmva_class_example.root"
210
211
212# --- Register the training and test trees
213
214signalTree = inputFile.Get("sig_tree")
215backgroundTree = inputFile.Get("bkg_tree")
216
217nEventsSig = signalTree.GetEntries()
218nEventsBkg = backgroundTree.GetEntries()
219
220# global event weights per tree (see below for setting event-wise weights)
221signalWeight = 1.0
222backgroundWeight = 1.0
223
224# You can add an arbitrary number of signal or background trees
225loader.AddSignalTree(signalTree, signalWeight)
226loader.AddBackgroundTree(backgroundTree, backgroundWeight)
227
228## add event variables (image)
229## use new method (from ROOT 6.20 to add a variable array for all image data)
230loader.AddVariablesArray("vars", imgSize)
231
232# Set individual event weights (the variables must exist in the original TTree)
233# for signal : factory->SetSignalWeightExpression ("weight1*weight2");
234# for background: factory->SetBackgroundWeightExpression("weight1*weight2");
235# loader->SetBackgroundWeightExpression( "weight" );
236
237# Apply additional cuts on the signal and background samples (can be different)
238mycuts = "" # for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
239mycutb = "" # for example: TCut mycutb = "abs(var1)<0.5";
240
241# Tell the factory how to use the training and testing events
242# If no numbers of events are given, half of the events in the tree are used
243# for training, and the other half for testing:
244# loader.PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
245# It is possible also to specify the number of training and testing events,
246# note we disable the computation of the correlation matrix of the input variables
247
248nTrainSig = 0.8 * nEventsSig
249nTrainBkg = 0.8 * nEventsBkg
250
251# build the string options for DataLoader::PrepareTrainingAndTestTree
252
253loader.PrepareTrainingAndTestTree(
254 mycuts,
255 mycutb,
256 nTrain_Signal=nTrainSig,
257 nTrain_Background=nTrainBkg,
258 SplitMode="Random",
259 SplitSeed=100,
260 NormMode="NumEvents",
261 V=False,
262 CalcCorrelations=False,
263)
264
265
266# DataSetInfo : [dataset] : Added class "Signal"
267# : Add Tree sig_tree of type Signal with 10000 events
268# DataSetInfo : [dataset] : Added class "Background"
269# : Add Tree bkg_tree of type Background with 10000 events
270
271# signalTree.Print();
272
273# Booking Methods
274
275# Here we book the TMVA methods. We book a Boosted Decision Tree method (BDT)
276
277
278# Boosted Decision Trees
279if useTMVABDT:
280 factory.BookMethod(
281 loader,
282 TMVA.Types.kBDT,
283 "BDT",
284 V=False,
285 NTrees=400,
286 MinNodeSize="2.5%",
287 MaxDepth=2,
288 BoostType="AdaBoost",
289 AdaBoostBeta=0.5,
290 UseBaggedBoost=True,
291 BaggedSampleFraction=0.5,
292 SeparationType="GiniIndex",
293 nCuts=20,
294 )
295
296
297#### Booking Deep Neural Network
298
299# Here we book the DNN of TMVA. See the example TMVA_Higgs_Classification.C for a detailed description of the
300# options
301
302if useTMVADNN:
303 layoutString = ROOT.TString(
304 "DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,DENSE|1|LINEAR"
305 )
306
307 # Training strategies
308 # one can catenate several training strings with different parameters (e.g. learning rates or regularizations
309 # parameters) The training string must be concatenated with the `|` delimiter
310 trainingString1 = ROOT.TString(
311 "LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
312 "ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
313 "WeightDecay=1e-4,Regularization=None,"
314 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0."
315 ) # + "|" + trainingString2 + ...
316 trainingString1 += ",MaxEpochs=" + str(max_epochs)
317
318 # Build now the full DNN Option string
319 dnnMethodName = "TMVA_DNN_CPU"
320
321 # use GPU if available
322 dnnOptions = "CPU"
323 if hasGPU :
324 dnnOptions = "GPU"
325 dnnMethodName = "TMVA_DNN_GPU"
326
327 factory.BookMethod(
328 loader,
329 TMVA.Types.kDL,
330 dnnMethodName,
331 H=False,
332 V=True,
333 ErrorStrategy="CROSSENTROPY",
334 VarTransform=None,
335 WeightInitialization="XAVIER",
336 Layout=layoutString,
337 TrainingStrategy=trainingString1,
338 Architecture=dnnOptions
339 )
340
341
342### Book Convolutional Neural Network in TMVA
343
344# For building a CNN one needs to define
345
346# - Input Layout : number of channels (in this case = 1) | image height | image width
347# - Batch Layout : batch size | number of channels | image size = (height*width)
348
349# Then one add Convolutional layers and MaxPool layers.
350
351# - For Convolutional layer the option string has to be:
352# - CONV | number of units | filter height | filter width | stride height | stride width | padding height | paddig
353# width | activation function
354
355# - note in this case we are using a filer 3x3 and padding=1 and stride=1 so we get the output dimension of the
356# conv layer equal to the input
357
358# - note we use after the first convolutional layer a batch normalization layer. This seems to help significantly the
359# convergence
360
361# - For the MaxPool layer:
362# - MAXPOOL | pool height | pool width | stride height | stride width
363
364# The RESHAPE layer is needed to flatten the output before the Dense layer
365
366# Note that to run the CNN is required to have CPU or GPU support
367
368
369if useTMVACNN:
370 # Training strategies.
371 trainingString1 = ROOT.TString(
372 "LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
373 "ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
374 "WeightDecay=1e-4,Regularization=None,"
375 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.0"
376 )
377 trainingString1 += ",MaxEpochs=" + str(max_epochs)
378
379 ## New DL (CNN)
380 cnnMethodName = "TMVA_CNN_CPU"
381 cnnOptions = "CPU"
382 # use GPU if available
383 if hasGPU:
384 cnnOptions = "GPU"
385 cnnMethodName = "TMVA_CNN_GPU"
386
387 factory.BookMethod(
388 loader,
389 TMVA.Types.kDL,
390 cnnMethodName,
391 H=False,
392 V=True,
393 ErrorStrategy="CROSSENTROPY",
394 VarTransform=None,
395 WeightInitialization="XAVIER",
396 InputLayout="1|16|16",
397 Layout="CONV|10|3|3|1|1|1|1|RELU,BNORM,CONV|10|3|3|1|1|1|1|RELU,MAXPOOL|2|2|1|1,RESHAPE|FLAT,DENSE|100|RELU,DENSE|1|LINEAR",
398 TrainingStrategy=trainingString1,
399 Architecture=cnnOptions,
400 )
401
402## Train Methods
403
404factory.TrainAllMethods()
405
406## Test and Evaluate Methods
407
408factory.TestAllMethods()
409
410factory.EvaluateAllMethods()
411
412## Plot ROC Curve
413
414c1 = factory.GetROCCurve(loader)
415c1.Draw()
416
417# close outputfile to save output file
418outputFile.Close()
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t format
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
This is the main MVA steering class.
Definition Factory.h:80
static Tools & Instance()
Definition Tools.cxx:72
void EnableImplicitMT(UInt_t numthreads=0)
Enable ROOT's implicit multi-threading for all objects and methods that provide an internal paralleli...
Definition TROOT.cxx:617
UInt_t GetThreadPoolSize()
Returns the size of ROOT's thread pool.
Definition TROOT.cxx:680