31useTMVACNN = opt[0]
if len(opt) > 0
else False
32useKerasCNN = opt[1]
if len(opt) > 1
else False
33useTMVADNN = opt[2]
if len(opt) > 2
else False
34useTMVABDT = opt[3]
if len(opt) > 3
else False
35usePyTorchCNN = opt[4]
if len(opt) > 4
else False
42def MakeImagesTree(n, nh, nw):
45 fileOutName =
"images_data_16x16.root"
52 sX2 = sX1 + delta_sigma
53 sY2 = sY1 - delta_sigma
54 h1 = ROOT.TH2D(
"h1",
"h1", nh, 0, 10, nw, 0, 10)
55 h2 = ROOT.TH2D(
"h2",
"h2", nh, 0, 10, nw, 0, 10)
56 f1 = ROOT.TF2(
"f1",
"xygaus")
57 f2 = ROOT.TF2(
"f2",
"xygaus")
58 sgn = ROOT.TTree(
"sig_tree",
"signal_tree")
59 bkg = ROOT.TTree(
"bkg_tree",
"background_tree")
61 f =
TFile(fileOutName,
"RECREATE")
62 x1 = ROOT.std.vector[
"float"](ntot)
63 x2 = ROOT.std.vector[
"float"](ntot)
67 bkg.Branch(
"vars",
"std::vector<float>", x1)
68 sgn.Branch(
"vars",
"std::vector<float>", x2)
73 f1.SetParameters(1, 5, sX1, 5, sY1)
74 f2.SetParameters(1, 5, sX2, 5, sY2)
75 ROOT.gRandom.SetSeed(0)
76 ROOT.Info(
"TMVA_CNN_Classification",
"Filling ROOT tree \n")
79 print(
"Generating image event ...", i)
84 f1.SetParameter(1, ROOT.gRandom.Uniform(3, 7))
85 f1.SetParameter(3, ROOT.gRandom.Uniform(3, 7))
86 f2.SetParameter(1, ROOT.gRandom.Uniform(3, 7))
87 f2.SetParameter(3, ROOT.gRandom.Uniform(3, 7))
89 h1.FillRandom(f1, nRndmEvts)
90 h2.FillRandom(f2, nRndmEvts)
96 x1[m] = h1.GetBinContent(k + 1, l + 1) + ROOT.gRandom.Gaus(0, pixelNoise)
97 x2[m] = h2.GetBinContent(k + 1, l + 1) + ROOT.gRandom.Gaus(0, pixelNoise)
105 print(
"Signal and background tree with images data written to the file %s", f.GetName())
110hasGPU =
"tmva-gpu" in ROOT.gROOT.GetConfigFeatures()
111hasCPU =
"tmva-cpu" in ROOT.gROOT.GetConfigFeatures()
115if (
not hasCPU
and not hasGPU) :
116 ROOT.Warning(
"TMVA_CNN_Classificaton",
"ROOT is not supporting tmva-cpu and tmva-gpu skip using TMVA-DNN and TMVA-CNN")
120if "tmva-pymva" not in ROOT.gROOT.GetConfigFeatures():
122 usePyTorchCNN =
False
128 "TMVA_CNN_Classificaton",
129 "TMVA is not build with GPU or CPU multi-thread support. Cannot use TMVA Deep Learning for CNN",
132writeOutputFile =
True
139if "imt" in ROOT.gROOT.GetConfigFeatures():
141 ROOT.gSystem.Setenv(
"OMP_NUM_THREADS",
"1")
144 print(
"Running in serial mode since ROOT does not support MT")
151 outputFile =
TFile.Open(
"TMVA_CNN_ClassificationOutput.root",
"RECREATE")
176 "TMVA_CNN_Classification",
182 AnalysisType=
"Classification",
183 Transformations=
None,
206inputFileName =
"images_data_16x16.root"
209if ROOT.gSystem.AccessPathName(inputFileName):
210 MakeImagesTree(nevt, 16, 16)
214 ROOT.Warning(
"TMVA_CNN_Classification",
"Error opening input file %s - exit", inputFileName.Data())
222signalTree = inputFile.Get(
"sig_tree")
223backgroundTree = inputFile.Get(
"bkg_tree")
225nEventsSig = signalTree.GetEntries()
226nEventsBkg = backgroundTree.GetEntries()
230backgroundWeight = 1.0
233loader.AddSignalTree(signalTree, signalWeight)
234loader.AddBackgroundTree(backgroundTree, backgroundWeight)
238loader.AddVariablesArray(
"vars", imgSize)
256nTrainSig = 0.8 * nEventsSig
257nTrainBkg = 0.8 * nEventsBkg
261loader.PrepareTrainingAndTestTree(
264 nTrain_Signal=nTrainSig,
265 nTrain_Background=nTrainBkg,
268 NormMode=
"NumEvents",
270 CalcCorrelations=
False,
296 BoostType=
"AdaBoost",
299 BaggedSampleFraction=0.5,
300 SeparationType=
"GiniIndex",
311 layoutString = ROOT.TString(
312 "DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,DENSE|1|LINEAR"
318 trainingString1 = ROOT.TString(
319 "LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
320 "ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
321 "WeightDecay=1e-4,Regularization=None,"
322 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0."
324 trainingString1 +=
",MaxEpochs=" + str(max_epochs)
327 dnnMethodName =
"TMVA_DNN_CPU"
333 dnnMethodName =
"TMVA_DNN_GPU"
341 ErrorStrategy=
"CROSSENTROPY",
343 WeightInitialization=
"XAVIER",
345 TrainingStrategy=trainingString1,
346 Architecture=dnnOptions
379 trainingString1 = ROOT.TString(
380 "LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
381 "ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
382 "WeightDecay=1e-4,Regularization=None,"
383 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.0"
385 trainingString1 +=
",MaxEpochs=" + str(max_epochs)
388 cnnMethodName =
"TMVA_CNN_CPU"
393 cnnMethodName =
"TMVA_CNN_GPU"
401 ErrorStrategy=
"CROSSENTROPY",
403 WeightInitialization=
"XAVIER",
404 InputLayout=
"1|16|16",
405 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",
406 TrainingStrategy=trainingString1,
407 Architecture=cnnOptions,
415 ROOT.Info(
"TMVA_CNN_Classification",
"Using Convolutional PyTorch Model")
416 pyTorchFileName = str(ROOT.gROOT.GetTutorialDir())
417 pyTorchFileName +=
"/machine_learning/PyTorch_Generate_CNN_Model.py"
419 torch_spec = importlib.util.find_spec(
"torch")
420 if torch_spec
is not None and os.path.exists(pyTorchFileName):
424 ROOT.Info(
"TMVA_CNN_Classification",
"Booking PyTorch CNN model")
432 FilenameModel=
"PyTorchModelCNN.pt",
433 FilenameTrainedModel=
"PyTorchTrainedModelCNN.pt",
434 NumEpochs=max_epochs,
436 UserCode=str(pyTorchFileName)
440 "TMVA_CNN_Classification",
441 "PyTorch is not installed or model building file is not existing - skip using PyTorch",
445 ROOT.Info(
"TMVA_CNN_Classification",
"Building convolutional keras model")
450 from tensorflow.keras.layers
import Conv2D, Dense, Flatten, MaxPooling2D, Reshape
451 from tensorflow.keras.models
import Sequential
452 from tensorflow.keras.optimizers
import Adam
456 model.add(Reshape((16, 16, 1), input_shape=(256,)))
457 model.add(Conv2D(10, kernel_size=(3, 3), kernel_initializer=
"TruncatedNormal", activation=
"relu", padding=
"same"))
458 model.add(Conv2D(10, kernel_size=(3, 3), kernel_initializer=
"TruncatedNormal", activation=
"relu", padding=
"same"))
460 model.add(MaxPooling2D(pool_size=(2, 2)))
462 model.add(Dense(64, activation=
"tanh"))
464 model.add(Dense(2, activation=
"sigmoid"))
465 model.compile(loss=
"binary_crossentropy", optimizer=Adam(learning_rate=0.001), weighted_metrics=[
"accuracy"])
466 model.save(
"model_cnn.keras")
469 if not os.path.exists(
"model_cnn.keras"):
470 raise FileNotFoundError(
"Error creating Keras model file - skip using Keras")
473 ROOT.Info(
"TMVA_CNN_Classification",
"Booking convolutional keras model")
481 FilenameModel=
"model_cnn.keras",
482 FilenameTrainedModel=
"trained_model_cnn.keras",
483 NumEpochs=max_epochs,
485 GpuOptions=
"allow_growth=True",
492factory.TrainAllMethods()
496factory.TestAllMethods()
498factory.EvaluateAllMethods()
502c1 = factory.GetROCCurve(loader)
A file, usually with extension .root, that stores data and code in the form of serialized objects in ...
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.