29useTMVACNN = opt[0]
if len(opt) > 0
else False
30useKerasCNN = opt[1]
if len(opt) > 1
else False
31useTMVADNN = opt[2]
if len(opt) > 2
else False
32useTMVABDT = opt[3]
if len(opt) > 3
else False
33usePyTorchCNN = opt[4]
if len(opt) > 4
else False
35tf_spec = importlib.util.find_spec(
"tensorflow")
38 print(
"TMVA_CNN_Classificaton",
"Skip using Keras since tensorflow is not installed")
45torch_spec = importlib.util.find_spec(
"torch")
48 print(
"TMVA_CNN_Classificaton",
"Skip using PyTorch since torch is not installed")
61def MakeImagesTree(n, nh, nw):
64 fileOutName =
"images_data_16x16.root"
71 sX2 = sX1 + delta_sigma
72 sY2 = sY1 - delta_sigma
73 h1 = ROOT.TH2D(
"h1",
"h1", nh, 0, 10, nw, 0, 10)
74 h2 = ROOT.TH2D(
"h2",
"h2", nh, 0, 10, nw, 0, 10)
75 f1 = ROOT.TF2(
"f1",
"xygaus")
76 f2 = ROOT.TF2(
"f2",
"xygaus")
77 sgn = ROOT.TTree(
"sig_tree",
"signal_tree")
78 bkg = ROOT.TTree(
"bkg_tree",
"background_tree")
80 f =
TFile(fileOutName,
"RECREATE")
81 x1 = ROOT.std.vector[
"float"](ntot)
82 x2 = ROOT.std.vector[
"float"](ntot)
86 bkg.Branch(
"vars",
"std::vector<float>", x1)
87 sgn.Branch(
"vars",
"std::vector<float>", x2)
92 f1.SetParameters(1, 5, sX1, 5, sY1)
93 f2.SetParameters(1, 5, sX2, 5, sY2)
94 ROOT.gRandom.SetSeed(0)
95 ROOT.Info(
"TMVA_CNN_Classification",
"Filling ROOT tree \n")
98 print(
"Generating image event ...", i)
103 f1.SetParameter(1, ROOT.gRandom.Uniform(3, 7))
104 f1.SetParameter(3, ROOT.gRandom.Uniform(3, 7))
105 f2.SetParameter(1, ROOT.gRandom.Uniform(3, 7))
106 f2.SetParameter(3, ROOT.gRandom.Uniform(3, 7))
108 h1.FillRandom(
"f1", nRndmEvts)
109 h2.FillRandom(
"f2", nRndmEvts)
115 x1[m] = h1.GetBinContent(k + 1, l + 1) + ROOT.gRandom.Gaus(0, pixelNoise)
116 x2[m] = h2.GetBinContent(k + 1, l + 1) + ROOT.gRandom.Gaus(0, pixelNoise)
124 print(
"Signal and background tree with images data written to the file %s", f.GetName())
129hasGPU =
"tmva-gpu" in ROOT.gROOT.GetConfigFeatures()
130hasCPU =
"tmva-cpu" in ROOT.gROOT.GetConfigFeatures()
134if (
not hasCPU
and not hasGPU) :
135 ROOT.Warning(
"TMVA_CNN_Classificaton",
"ROOT is not supporting tmva-cpu and tmva-gpu skip using TMVA-DNN and TMVA-CNN")
139if not "tmva-pymva" in ROOT.gROOT.GetConfigFeatures():
141 usePyTorchCNN =
False
147 "TMVA_CNN_Classificaton",
148 "TMVA is not build with GPU or CPU multi-thread support. Cannot use TMVA Deep Learning for CNN",
151writeOutputFile =
True
158if "imt" in ROOT.gROOT.GetConfigFeatures():
160 ROOT.gSystem.Setenv(
"OMP_NUM_THREADS",
"1")
163 print(
"Running in serial mode since ROOT does not support MT")
170 outputFile =
TFile.Open(
"TMVA_CNN_ClassificationOutput.root",
"RECREATE")
195 "TMVA_CNN_Classification",
201 AnalysisType=
"Classification",
202 Transformations=
None,
225inputFileName =
"images_data_16x16.root"
228if ROOT.gSystem.AccessPathName(inputFileName):
229 MakeImagesTree(nevt, 16, 16)
233 ROOT.Warning(
"TMVA_CNN_Classification",
"Error opening input file %s - exit", inputFileName.Data())
241signalTree = inputFile.Get(
"sig_tree")
242backgroundTree = inputFile.Get(
"bkg_tree")
244nEventsSig = signalTree.GetEntries()
245nEventsBkg = backgroundTree.GetEntries()
249backgroundWeight = 1.0
252loader.AddSignalTree(signalTree, signalWeight)
253loader.AddBackgroundTree(backgroundTree, backgroundWeight)
257loader.AddVariablesArray(
"vars", imgSize)
275nTrainSig = 0.8 * nEventsSig
276nTrainBkg = 0.8 * nEventsBkg
280loader.PrepareTrainingAndTestTree(
283 nTrain_Signal=nTrainSig,
284 nTrain_Background=nTrainBkg,
287 NormMode=
"NumEvents",
289 CalcCorrelations=
False,
315 BoostType=
"AdaBoost",
318 BaggedSampleFraction=0.5,
319 SeparationType=
"GiniIndex",
330 layoutString = ROOT.TString(
331 "DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,DENSE|1|LINEAR"
337 trainingString1 = ROOT.TString(
338 "LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
339 "ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
340 "WeightDecay=1e-4,Regularization=None,"
341 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0."
343 trainingString1 +=
",MaxEpochs=" + str(max_epochs)
346 dnnMethodName =
"TMVA_DNN_CPU"
352 dnnMethodName =
"TMVA_DNN_GPU"
360 ErrorStrategy=
"CROSSENTROPY",
362 WeightInitialization=
"XAVIER",
364 TrainingStrategy=trainingString1,
365 Architecture=dnnOptions
398 trainingString1 = ROOT.TString(
399 "LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
400 "ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
401 "WeightDecay=1e-4,Regularization=None,"
402 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.0"
404 trainingString1 +=
",MaxEpochs=" + str(max_epochs)
407 cnnMethodName =
"TMVA_CNN_CPU"
412 cnnMethodName =
"TMVA_CNN_GPU"
420 ErrorStrategy=
"CROSSENTROPY",
422 WeightInitialization=
"XAVIER",
423 InputLayout=
"1|16|16",
424 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",
425 TrainingStrategy=trainingString1,
426 Architecture=cnnOptions,
434 ROOT.Info(
"TMVA_CNN_Classification",
"Using Convolutional PyTorch Model")
435 pyTorchFileName = str(ROOT.gROOT.GetTutorialDir())
436 pyTorchFileName +=
"/tmva/PyTorch_Generate_CNN_Model.py"
438 torch_spec = importlib.util.find_spec(
"torch")
439 if torch_spec
is not None and os.path.exists(pyTorchFileName):
443 ROOT.Info(
"TMVA_CNN_Classification",
"Booking PyTorch CNN model")
451 FilenameModel=
"PyTorchModelCNN.pt",
452 FilenameTrainedModel=
"PyTorchTrainedModelCNN.pt",
453 NumEpochs=max_epochs,
455 UserCode=str(pyTorchFileName)
459 "TMVA_CNN_Classification",
460 "PyTorch is not installed or model building file is not existing - skip using PyTorch",
464 ROOT.Info(
"TMVA_CNN_Classification",
"Building convolutional keras model")
468 from tensorflow.keras.models
import Sequential
469 from tensorflow.keras.optimizers
import Adam
473 from tensorflow.keras.layers
import Input, Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Reshape
477 model.add(Reshape((16, 16, 1), input_shape=(256,)))
478 model.add(Conv2D(10, kernel_size=(3, 3), kernel_initializer=
"TruncatedNormal", activation=
"relu", padding=
"same"))
479 model.add(Conv2D(10, kernel_size=(3, 3), kernel_initializer=
"TruncatedNormal", activation=
"relu", padding=
"same"))
481 model.add(MaxPooling2D(pool_size=(2, 2)))
483 model.add(Dense(64, activation=
"tanh"))
485 model.add(Dense(2, activation=
"sigmoid"))
486 model.compile(loss=
"binary_crossentropy", optimizer=Adam(learning_rate=0.001), weighted_metrics=[
"accuracy"])
487 model.save(
"model_cnn.h5")
490 if not os.path.exists(
"model_cnn.h5"):
491 raise FileNotFoundError(
"Error creating Keras model file - skip using Keras")
494 ROOT.Info(
"TMVA_CNN_Classification",
"Booking convolutional keras model")
502 FilenameModel=
"model_cnn.h5",
503 FilenameTrainedModel=
"trained_model_cnn.h5",
504 NumEpochs=max_epochs,
506 GpuOptions=
"allow_growth=True",
513factory.TrainAllMethods()
517factory.TestAllMethods()
519factory.EvaluateAllMethods()
523c1 = 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
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 ROOT file is an on-disk file, usually with extension .root, that stores objects in a file-system-li...
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.