Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TMVA_RNN_Classification.py
Go to the documentation of this file.
1## \file
2## \ingroup tutorial_ml
3## \notebook
4## TMVA Classification Example Using a Recurrent Neural Network
5##
6## This is an example of using a RNN in TMVA. We do classification using a toy time dependent data set
7## that is generated when running this example macro
8##
9## \macro_code
10##
11## \author Harshal Shende
12
13
14# TMVA Classification Example Using a Recurrent Neural Network
15
16# This is an example of using a RNN in TMVA.
17# We do the classification using a toy data set containing a time series of data sample ntimes
18# and with dimension ndim that is generated when running the provided function `MakeTimeData (nevents, ntime, ndim)`
19
20
21import ROOT
22
23num_threads = 4 # use max 4 threads
24# do enable MT running
25if "imt" in ROOT.gROOT.GetConfigFeatures():
26 ROOT.EnableImplicitMT(num_threads)
27 # switch off MT in OpenBLAS to avoid conflict with tbb
28 ROOT.gSystem.Setenv("OMP_NUM_THREADS", "1")
29 print("Running with nthreads = {}".format(ROOT.GetThreadPoolSize()))
30else:
31 print("Running in serial mode since ROOT does not support MT")
32
33
34TMVA = ROOT.TMVA
35TFile = ROOT.TFile
36
37import os
38
41
42
43## Helper function to generate the time data set
44## make some time data but not of fixed length.
45## use a poisson with mu = 5 and truncated at 10
46
47
48def MakeTimeData(n, ntime, ndim):
49 # ntime = 10;
50 # ndim = 30; // number of dim/time
51
52 fname = "time_data_t" + str(ntime) + "_d" + str(ndim) + ".root"
53 v1 = []
54 v2 = []
55
56 for i in range(ntime):
57 v1.append(ROOT.TH1D("h1_" + str(i), "h1", ndim, 0, 10))
58 v2.append(ROOT.TH1D("h2_" + str(i), "h2", ndim, 0, 10))
59
60 f1 = ROOT.TF1("f1", "gaus")
61 f2 = ROOT.TF1("f2", "gaus")
62
63 sgn = ROOT.TTree("sgn", "sgn")
64 bkg = ROOT.TTree("bkg", "bkg")
65 f = TFile(fname, "RECREATE")
66
67 x1 = []
68 x2 = []
69
70 for i in range(ntime):
71 x1.append(ROOT.std.vector["float"](ndim))
72 x2.append(ROOT.std.vector["float"](ndim))
73
74 for i in range(ntime):
75 bkg.Branch("vars_time" + str(i), "std::vector<float>", x1[i])
76 sgn.Branch("vars_time" + str(i), "std::vector<float>", x2[i])
77
78 sgn.SetDirectory(f)
79 bkg.SetDirectory(f)
80 ROOT.gRandom.SetSeed(0)
81
82 mean1 = ROOT.std.vector["double"](ntime)
83 mean2 = ROOT.std.vector["double"](ntime)
84 sigma1 = ROOT.std.vector["double"](ntime)
85 sigma2 = ROOT.std.vector["double"](ntime)
86
87 for j in range(ntime):
88 mean1[j] = 5.0 + 0.2 * ROOT.TMath.Sin(ROOT.TMath.Pi() * j / float(ntime))
89 mean2[j] = 5.0 + 0.2 * ROOT.TMath.Cos(ROOT.TMath.Pi() * j / float(ntime))
90 sigma1[j] = 4 + 0.3 * ROOT.TMath.Sin(ROOT.TMath.Pi() * j / float(ntime))
91 sigma2[j] = 4 + 0.3 * ROOT.TMath.Cos(ROOT.TMath.Pi() * j / float(ntime))
92
93 for i in range(n):
94 if i % 1000 == 0:
95 print("Generating event ... %d", i)
96
97 for j in range(ntime):
98 h1 = v1[j]
99 h2 = v2[j]
100 h1.Reset()
101 h2.Reset()
102
103 f1.SetParameters(1, mean1[j], sigma1[j])
104 f2.SetParameters(1, mean2[j], sigma2[j])
105
106 h1.FillRandom(f1, 1000)
107 h2.FillRandom(f2, 1000)
108
109 for k in range(ntime):
110 # std::cout << j*10+k << " ";
111 x1[j][k] = h1.GetBinContent(k + 1) + ROOT.gRandom.Gaus(0, 10)
112 x2[j][k] = h2.GetBinContent(k + 1) + ROOT.gRandom.Gaus(0, 10)
113
114 sgn.Fill()
115 bkg.Fill()
116
117 if n == 1:
118 c1 = ROOT.TCanvas()
119 c1.Divide(ntime, 2)
120 for j in range(ntime):
121 c1.cd(j + 1)
122 v1[j].Draw()
123 for j in range(ntime):
124 c1.cd(ntime + j + 1)
125 v2[j].Draw()
126
127 ROOT.gPad.Update()
128
129 if n > 1:
130 sgn.Write()
131 bkg.Write()
132 sgn.Print()
133 bkg.Print()
134 f.Close()
135
136
137## macro for performing a classification using a Recurrent Neural Network
138## @param use_type
139## use_type = 0 use Simple RNN network
140## use_type = 1 use LSTM network
141## use_type = 2 use GRU
142## use_type = 3 build 3 different networks with RNN, LSTM and GRU
143
144
145use_type = 1
146ninput = 30
147ntime = 10
148batchSize = 100
149maxepochs = 10
150
151nTotEvts = 2000 # total events to be generated for signal or background
152
153useTMVA_RNN = True
154useTMVA_DNN = True
155useTMVA_BDT = False
156
157
158rnn_types = ["RNN", "LSTM", "GRU"]
159use_rnn_type = [1, 1, 1]
160
161if 0 <= use_type < 3:
162 use_rnn_type = [0, 0, 0]
163 use_rnn_type[use_type] = 1
164
165useGPU = True # use GPU for TMVA if available
166
167useGPU = "tmva-gpu" in ROOT.gROOT.GetConfigFeatures()
168useTMVA_RNN = ("tmva-cpu" in ROOT.gROOT.GetConfigFeatures()) or useGPU
169
170if useTMVA_RNN:
171 ROOT.Warning(
172 "TMVA_RNN_Classification",
173 "TMVA is not build with GPU or CPU multi-thread support. Cannot use TMVA Deep Learning for RNN",
174 )
175
176archString = "GPU" if useGPU else "CPU"
177
178writeOutputFile = True
179
180rnn_type = "RNN"
181
182
183
184inputFileName = "time_data_t10_d30.root"
185
186fileDoesNotExist = ROOT.gSystem.AccessPathName(inputFileName)
187
188# if file does not exists create it
189if fileDoesNotExist:
190 MakeTimeData(nTotEvts, ntime, ninput)
191
192
193inputFile = TFile.Open(inputFileName)
194if inputFile is None:
195 raise ROOT.Error("Error opening input file %s - exit", inputFileName.Data())
196
197
198print("--- RNNClassification : Using input file: {}".format(inputFile.GetName()))
199
200# Create a ROOT output file where TMVA will store ntuples, histograms, etc.
201outfileName = "data_RNN_" + archString + ".root"
202outputFile = None
203
204
205if writeOutputFile:
206 outputFile = TFile.Open(outfileName, "RECREATE")
207
208
209## Declare Factory
210
211# Create the Factory class. Later you can choose the methods
212# whose performance you'd like to investigate.
213
214# The factory is the major TMVA object you have to interact with. Here is the list of parameters you need to
215# pass
216
217# - The first argument is the base of the name of all the output
218# weightfiles in the directory weight/ that will be created with the
219# method parameters
220
221# - The second argument is the output file for the training results
222#
223# - The third argument is a string option defining some general configuration for the TMVA session.
224# For example all TMVA output can be suppressed by removing the "!" (not) in front of the "Silent" argument in
225# the option string
226
227
228# // Creating the factory object
229factory = TMVA.Factory(
230 "TMVAClassification",
231 outputFile,
232 V=False,
233 Silent=False,
234 Color=True,
235 DrawProgressBar=True,
236 Transformations=None,
237 Correlations=False,
238 AnalysisType="Classification",
239 ModelPersistence=True,
240)
241dataloader = TMVA.DataLoader("dataset")
242
243signalTree = inputFile.Get("sgn")
244background = inputFile.Get("bkg")
245
246nvar = ninput * ntime
247
248## add variables - use new AddVariablesArray function
249for i in range(ntime):
250 dataloader.AddVariablesArray("vars_time" + str(i), ninput)
251
252
253dataloader.AddSignalTree(signalTree, 1.0)
254dataloader.AddBackgroundTree(background, 1.0)
255
256# check given input
257datainfo = dataloader.GetDataSetInfo()
258vars = datainfo.GetListOfVariables()
259print("number of variables is {}".format(vars.size()))
260
261
262for v in vars:
263 print(v)
264
265nTrainSig = 0.8 * nTotEvts
266nTrainBkg = 0.8 * nTotEvts
267
268# Apply additional cuts on the signal and background samples (can be different)
269mycuts = "" # for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
270mycutb = ""
271
272# build the string options for DataLoader::PrepareTrainingAndTestTree
273dataloader.PrepareTrainingAndTestTree(
274 mycuts,
275 mycutb,
276 nTrain_Signal=nTrainSig,
277 nTrain_Background=nTrainBkg,
278 SplitMode="Random",
279 SplitSeed=100,
280 NormMode="NumEvents",
281 V=False,
282 CalcCorrelations=False,
283)
284
285print("prepared DATA LOADER ")
286
287
288## Book TMVA recurrent models
289
290# Book the different types of recurrent models in TMVA (SimpleRNN, LSTM or GRU)
291
292
293if useTMVA_RNN:
294 for i in range(3):
295 if not use_rnn_type[i]:
296 continue
297
298 rnn_type = rnn_types[i]
299
300 ## Define RNN layer layout
301 ## it should be LayerType (RNN or LSTM or GRU) | number of units | number of inputs | time steps | remember output (typically no=0 | return full sequence
302 rnnLayout = str(rnn_type) + "|10|" + str(ninput) + "|" + str(ntime) + "|0|1,RESHAPE|FLAT,DENSE|64|TANH,LINEAR"
303
304 ## Defining Training strategies. Different training strings can be concatenate. Use however only one
305 trainingString1 = "LearningRate=1e-3,Momentum=0.0,Repetitions=1,ConvergenceSteps=5,BatchSize=" + str(batchSize)
306 trainingString1 += ",TestRepetitions=1,WeightDecay=1e-2,Regularization=None,MaxEpochs=" + str(maxepochs)
307 trainingString1 += "Optimizer=ADAM,DropConfig=0.0+0.+0.+0."
308
309 ## define the inputlayout string for RNN
310 ## the input data should be organize as following:
311 ##/ input layout for RNN: time x ndim
312 ## add after RNN a reshape layer (needed top flatten the output) and a dense layer with 64 units and a last one
313 ## Note the last layer is linear because when using Crossentropy a Sigmoid is applied already
314 ## Define the full RNN Noption string adding the final options for all network
315 rnnName = "TMVA_" + str(rnn_type)
316 factory.BookMethod(
317 dataloader,
318 TMVA.Types.kDL,
319 rnnName,
320 H=False,
321 V=True,
322 ErrorStrategy="CROSSENTROPY",
323 VarTransform=None,
324 WeightInitialization="XAVIERUNIFORM",
325 ValidationSize=0.2,
326 RandomSeed=1234,
327 InputLayout=str(ntime) + "|" + str(ninput),
328 Layout=rnnLayout,
329 TrainingStrategy=trainingString1,
330 Architecture=archString
331 )
332
333
334## Book TMVA fully connected dense layer models
335if useTMVA_DNN:
336 # Method DL with Dense Layer
337 # Training strategies.
338 trainingString1 = ROOT.TString(
339 "LearningRate=1e-3,Momentum=0.0,Repetitions=1,"
340 "ConvergenceSteps=10,BatchSize=256,TestRepetitions=1,"
341 "WeightDecay=1e-4,Regularization=None,MaxEpochs=20"
342 "DropConfig=0.0+0.+0.+0.,Optimizer=ADAM:"
343 ) # + "|" + trainingString2
344 # General Options.
345 trainingString1.Append(archString)
346 dnnName = "TMVA_DNN"
347 factory.BookMethod(
348 dataloader,
349 TMVA.Types.kDL,
350 dnnName,
351 H=False,
352 V=True,
353 ErrorStrategy="CROSSENTROPY",
354 VarTransform=None,
355 WeightInitialization="XAVIER",
356 RandomSeed=0,
357 InputLayout="1|1|" + str(ntime * ninput),
358 Layout="DENSE|64|TANH,DENSE|TANH|64,DENSE|TANH|64,LINEAR",
359 TrainingStrategy=trainingString1
360 )
361
362
363useTMVA_BDT = True
364
365
366## Book TMVA BDT
367
368
369if useTMVA_BDT:
370 factory.BookMethod(
371 dataloader,
372 TMVA.Types.kBDT,
373 "BDTG",
374 H=True,
375 V=False,
376 NTrees=100,
377 MinNodeSize="2.5%",
378 BoostType="Grad",
379 Shrinkage=0.10,
380 UseBaggedBoost=True,
381 BaggedSampleFraction=0.5,
382 nCuts=20,
383 MaxDepth=2,
384 )
385
386
387## Train all methods
388factory.TrainAllMethods()
389
390print("nthreads = {}".format(ROOT.GetThreadPoolSize()))
391
392# ---- Evaluate all MVAs using the set of test events
393factory.TestAllMethods()
394
395# ----- Evaluate and compare performance of all configured MVAs
396factory.EvaluateAllMethods()
397
398# check method
399
400# plot ROC curve
401c1 = factory.GetROCCurve(dataloader)
402c1.Draw()
403
404if outputFile:
405 outputFile.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 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
static Config & Instance()
static function: returns TMVA instance
Definition Config.cxx:97
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
th1 Draw()