29ROOT.gSystem.Setenv(
"OMP_NUM_THREADS",
"1")
40def MakeImagesTree(n, nh, nw):
43 fileOutName =
"images_data_16x16.root"
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")
59 f =
TFile(fileOutName,
"RECREATE")
60 x1 = ROOT.std.vector[
"float"](ntot)
61 x2 = ROOT.std.vector[
"float"](ntot)
65 bkg.Branch(
"vars",
"std::vector<float>", x1)
66 sgn.Branch(
"vars",
"std::vector<float>", x2)
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")
77 print(
"Generating image event ...", i)
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))
87 h1.FillRandom(
"f1", nRndmEvts)
88 h2.FillRandom(
"f2", nRndmEvts)
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)
103 print(
"Signal and background tree with images data written to the file %s", f.GetName())
108hasGPU = ROOT.gSystem.GetFromPipe(
"root-config --has-tmva-gpu") ==
"yes"
109hasCPU = ROOT.gSystem.GetFromPipe(
"root-config --has-tmva-cpu") ==
"yes"
113useTMVACNN = opt[0]
if len(opt) > 0
else False
114useKerasCNN = opt[1]
if len(opt) > 1
else False
115useTMVADNN = opt[2]
if len(opt) > 2
else False
116useTMVABDT = opt[3]
if len(opt) > 3
else False
117usePyTorchCNN = opt[4]
if len(opt) > 4
else False
119if (
not hasCPU
and not hasGPU) :
120 ROOT.Warning(
"TMVA_CNN_Classificaton",
"ROOT is not supporting tmva-cpu and tmva-gpu skip using TMVA-DNN and TMVA-CNN")
124if ROOT.gSystem.GetFromPipe(
"root-config --has-tmva-pymva") !=
"yes":
126 usePyTorchCNN =
False
130tf_spec = importlib.util.find_spec(
"tensorflow")
133 ROOT.Warning(
"TMVA_CNN_Classificaton",
"Skip using Keras since tensorflow is not installed")
135torch_spec = importlib.util.find_spec(
"torch")
136if torch_spec
is None:
137 usePyTorchCNN =
False
138 ROOT.Warning(
"TMVA_CNN_Classificaton",
"Skip using PyTorch since torch is not installed")
142 "TMVA_CNN_Classificaton",
143 "TMVA is not build with GPU or CPU multi-thread support. Cannot use TMVA Deep Learning for CNN",
146writeOutputFile =
True
162 outputFile =
TFile.Open(
"TMVA_CNN_ClassificationOutput.root",
"RECREATE")
187 "TMVA_CNN_Classification",
193 AnalysisType=
"Classification",
194 Transformations=
None,
217inputFileName =
"images_data_16x16.root"
220if ROOT.gSystem.AccessPathName(inputFileName):
221 MakeImagesTree(nevt, 16, 16)
225 ROOT.Warning(
"TMVA_CNN_Classification",
"Error opening input file %s - exit", inputFileName.Data())
233signalTree = inputFile.Get(
"sig_tree")
234backgroundTree = inputFile.Get(
"bkg_tree")
236nEventsSig = signalTree.GetEntries()
237nEventsBkg = backgroundTree.GetEntries()
241backgroundWeight = 1.0
244loader.AddSignalTree(signalTree, signalWeight)
245loader.AddBackgroundTree(backgroundTree, backgroundWeight)
249loader.AddVariablesArray(
"vars", imgSize)
267nTrainSig = 0.8 * nEventsSig
268nTrainBkg = 0.8 * nEventsBkg
272loader.PrepareTrainingAndTestTree(
275 nTrain_Signal=nTrainSig,
276 nTrain_Background=nTrainBkg,
279 NormMode=
"NumEvents",
281 CalcCorrelations=
False,
307 BoostType=
"AdaBoost",
310 BaggedSampleFraction=0.5,
311 SeparationType=
"GiniIndex",
322 layoutString = ROOT.TString(
323 "DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,DENSE|1|LINEAR"
329 trainingString1 = ROOT.TString(
330 "LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
331 "ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
332 "WeightDecay=1e-4,Regularization=None,"
333 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0."
335 trainingString1 +=
",MaxEpochs=" + str(max_epochs)
338 dnnMethodName =
"TMVA_DNN_CPU"
344 dnnMethodName =
"TMVA_DNN_GPU"
352 ErrorStrategy=
"CROSSENTROPY",
354 WeightInitialization=
"XAVIER",
356 TrainingStrategy=trainingString1,
357 Architecture=dnnOptions
390 trainingString1 = ROOT.TString(
391 "LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
392 "ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
393 "WeightDecay=1e-4,Regularization=None,"
394 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.0"
396 trainingString1 +=
",MaxEpochs=" + str(max_epochs)
399 cnnMethodName =
"TMVA_CNN_CPU"
404 cnnMethodName =
"TMVA_CNN_GPU"
412 ErrorStrategy=
"CROSSENTROPY",
414 WeightInitialization=
"XAVIER",
415 InputLayout=
"1|16|16",
416 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",
417 TrainingStrategy=trainingString1,
418 Architecture=cnnOptions,
426 ROOT.Info(
"TMVA_CNN_Classification",
"Using Convolutional PyTorch Model")
427 pyTorchFileName = str(ROOT.gROOT.GetTutorialDir())
428 pyTorchFileName +=
"/tmva/PyTorch_Generate_CNN_Model.py"
430 torch_spec = importlib.util.find_spec(
"torch")
431 if torch_spec
is not None and os.path.exists(pyTorchFileName):
435 ROOT.Info(
"TMVA_CNN_Classification",
"Booking PyTorch CNN model")
443 FilenameModel=
"PyTorchModelCNN.pt",
444 FilenameTrainedModel=
"PyTorchTrainedModelCNN.pt",
445 NumEpochs=max_epochs,
447 UserCode=str(pyTorchFileName)
451 "TMVA_CNN_Classification",
452 "PyTorch is not installed or model building file is not existing - skip using PyTorch",
456 ROOT.Info(
"TMVA_CNN_Classification",
"Building convolutional keras model")
460 from tensorflow.keras.models
import Sequential
461 from tensorflow.keras.optimizers
import Adam
465 from tensorflow.keras.layers
import Input, Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Reshape
469 model.add(Reshape((16, 16, 1), input_shape=(256,)))
470 model.add(Conv2D(10, kernel_size=(3, 3), kernel_initializer=
"TruncatedNormal", activation=
"relu", padding=
"same"))
471 model.add(Conv2D(10, kernel_size=(3, 3), kernel_initializer=
"TruncatedNormal", activation=
"relu", padding=
"same"))
473 model.add(MaxPooling2D(pool_size=(2, 2)))
475 model.add(Dense(64, activation=
"tanh"))
477 model.add(Dense(2, activation=
"sigmoid"))
478 model.compile(loss=
"binary_crossentropy", optimizer=Adam(learning_rate=0.001), weighted_metrics=[
"accuracy"])
479 model.save(
"model_cnn.h5")
482 if not os.path.exists(
"model_cnn.h5"):
483 raise FileNotFoundError(
"Error creating Keras model file - skip using Keras")
486 ROOT.Info(
"TMVA_CNN_Classification",
"Booking convolutional keras model")
494 FilenameModel=
"model_cnn.h5",
495 FilenameTrainedModel=
"trained_model_cnn.h5",
496 NumEpochs=max_epochs,
498 GpuOptions=
"allow_growth=True",
505factory.TrainAllMethods()
509factory.TestAllMethods()
511factory.EvaluateAllMethods()
515c1 = factory.GetROCCurve(loader)
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
A ROOT file is composed of a header, followed by consecutive data records (TKey instances) with a wel...
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.
This is the main MVA steering class.
static void PyInitialize()
Initialize Python interpreter.
void EnableImplicitMT(UInt_t numthreads=0)
Enable ROOT's implicit multi-threading for all objects and methods that provide an internal paralleli...
UInt_t GetThreadPoolSize()
Returns the size of ROOT's thread pool.