DataSetInfo : [dataset] : Added class "Signal"
: Add Tree sig_tree of type Signal with 1000 events
DataSetInfo : [dataset] : Added class "Background"
: Add Tree bkg_tree of type Background with 1000 events
Factory : Booking method: ␛[1mBDT␛[0m
:
: Rebuilding Dataset dataset
: Building event vectors for type 2 Signal
: Dataset[dataset] : create input formulas for tree sig_tree
: Using variable vars[0] from array expression vars of size 256
: Building event vectors for type 2 Background
: Dataset[dataset] : create input formulas for tree bkg_tree
: Using variable vars[0] from array expression vars of size 256
DataSetFactory : [dataset] : Number of events in input trees
:
:
: Number of training and testing events
: ---------------------------------------------------------------------------
: Signal -- training events : 800
: Signal -- testing events : 200
: Signal -- training and testing events: 1000
: Background -- training events : 800
: Background -- testing events : 200
: Background -- training and testing events: 1000
:
Factory : Booking method: ␛[1mTMVA_DNN_CPU␛[0m
:
: Parsing option string:
: ... "!H:V:ErrorStrategy=CROSSENTROPY:VarTransform=None:WeightInitialization=XAVIER:Layout=DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,DENSE|1|LINEAR:TrainingStrategy=LearningRate=1e-3,Momentum=0.9,Repetitions=1,ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,WeightDecay=1e-4,Regularization=None,Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.,MaxEpochs=10:Architecture=CPU"
: The following options are set:
: - By User:
: <none>
: - Default:
: Boost_num: "0" [Number of times the classifier will be boosted]
: Parsing option string:
: ... "!H:V:ErrorStrategy=CROSSENTROPY:VarTransform=None:WeightInitialization=XAVIER:Layout=DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,DENSE|1|LINEAR:TrainingStrategy=LearningRate=1e-3,Momentum=0.9,Repetitions=1,ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,WeightDecay=1e-4,Regularization=None,Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.,MaxEpochs=10:Architecture=CPU"
: The following options are set:
: - By User:
: V: "True" [Verbose output (short form of "VerbosityLevel" below - overrides the latter one)]
: VarTransform: "None" [List of variable transformations performed before training, e.g., "D_Background,P_Signal,G,N_AllClasses" for: "Decorrelation, PCA-transformation, Gaussianisation, Normalisation, each for the given class of events ('AllClasses' denotes all events of all classes, if no class indication is given, 'All' is assumed)"]
: H: "False" [Print method-specific help message]
: Layout: "DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,DENSE|1|LINEAR" [Layout of the network.]
: ErrorStrategy: "CROSSENTROPY" [Loss function: Mean squared error (regression) or cross entropy (binary classification).]
: WeightInitialization: "XAVIER" [Weight initialization strategy]
: Architecture: "CPU" [Which architecture to perform the training on.]
: TrainingStrategy: "LearningRate=1e-3,Momentum=0.9,Repetitions=1,ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,WeightDecay=1e-4,Regularization=None,Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.,MaxEpochs=10" [Defines the training strategies.]
: - Default:
: VerbosityLevel: "Default" [Verbosity level]
: CreateMVAPdfs: "False" [Create PDFs for classifier outputs (signal and background)]
: IgnoreNegWeightsInTraining: "False" [Events with negative weights are ignored in the training (but are included for testing and performance evaluation)]
: InputLayout: "0|0|0" [The Layout of the input]
: BatchLayout: "0|0|0" [The Layout of the batch]
: RandomSeed: "0" [Random seed used for weight initialization and batch shuffling]
: ValidationSize: "20%" [Part of the training data to use for validation. Specify as 0.2 or 20% to use a fifth of the data set as validation set. Specify as 100 to use exactly 100 events. (Default: 20%)]
: Will now use the CPU architecture with BLAS and IMT support !
Factory : Booking method: ␛[1mTMVA_CNN_CPU␛[0m
:
: Parsing option string:
: ... "!H:V:ErrorStrategy=CROSSENTROPY:VarTransform=None:WeightInitialization=XAVIER:InputLayout=1|16|16: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:TrainingStrategy=LearningRate=1e-3,Momentum=0.9,Repetitions=1,ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,WeightDecay=1e-4,Regularization=None,Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.0,MaxEpochs=10:Architecture=CPU"
: The following options are set:
: - By User:
: <none>
: - Default:
: Boost_num: "0" [Number of times the classifier will be boosted]
: Parsing option string:
: ... "!H:V:ErrorStrategy=CROSSENTROPY:VarTransform=None:WeightInitialization=XAVIER:InputLayout=1|16|16: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:TrainingStrategy=LearningRate=1e-3,Momentum=0.9,Repetitions=1,ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,WeightDecay=1e-4,Regularization=None,Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.0,MaxEpochs=10:Architecture=CPU"
: The following options are set:
: - By User:
: V: "True" [Verbose output (short form of "VerbosityLevel" below - overrides the latter one)]
: VarTransform: "None" [List of variable transformations performed before training, e.g., "D_Background,P_Signal,G,N_AllClasses" for: "Decorrelation, PCA-transformation, Gaussianisation, Normalisation, each for the given class of events ('AllClasses' denotes all events of all classes, if no class indication is given, 'All' is assumed)"]
: H: "False" [Print method-specific help message]
: InputLayout: "1|16|16" [The Layout of the input]
: 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" [Layout of the network.]
: ErrorStrategy: "CROSSENTROPY" [Loss function: Mean squared error (regression) or cross entropy (binary classification).]
: WeightInitialization: "XAVIER" [Weight initialization strategy]
: Architecture: "CPU" [Which architecture to perform the training on.]
: TrainingStrategy: "LearningRate=1e-3,Momentum=0.9,Repetitions=1,ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,WeightDecay=1e-4,Regularization=None,Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.0,MaxEpochs=10" [Defines the training strategies.]
: - Default:
: VerbosityLevel: "Default" [Verbosity level]
: CreateMVAPdfs: "False" [Create PDFs for classifier outputs (signal and background)]
: IgnoreNegWeightsInTraining: "False" [Events with negative weights are ignored in the training (but are included for testing and performance evaluation)]
: BatchLayout: "0|0|0" [The Layout of the batch]
: RandomSeed: "0" [Random seed used for weight initialization and batch shuffling]
: ValidationSize: "20%" [Part of the training data to use for validation. Specify as 0.2 or 20% to use a fifth of the data set as validation set. Specify as 100 to use exactly 100 events. (Default: 20%)]
: Will now use the CPU architecture with BLAS and IMT support !
Factory : Booking method: ␛[1mPyTorch␛[0m
:
: Using PyTorch - setting special configuration options
: Using PyTorch version 2
: Setup PyTorch Model for training
: Executing user initialization code from /home/sftnight/build/workspace/root-makedoc-master/rootspi/rdoc/src/master.build/tutorials/tmva/PyTorch_Generate_CNN_Model.py
Running with nthreads = 4
running Torch code defining the model....
The PyTorch CNN model is created and saved as PyTorchModelCNN.pt
: Loaded pytorch train function:
: Loaded pytorch optimizer:
: Loaded pytorch loss function:
: Loaded pytorch predict function:
import ROOT
TMVA = ROOT.TMVA
TFile = ROOT.TFile
import os
import importlib
def MakeImagesTree(n, nh, nw):
ntot = nh * nw
fileOutName = "images_data_16x16.root"
nRndmEvts = 10000
delta_sigma = 0.1
pixelNoise = 5
sX1 = 3
sY1 = 3
sX2 = sX1 + delta_sigma
sY2 = sY1 - delta_sigma
h1 = ROOT.TH2D("h1", "h1", nh, 0, 10, nw, 0, 10)
h2 = ROOT.TH2D("h2", "h2", nh, 0, 10, nw, 0, 10)
f1 = ROOT.TF2("f1", "xygaus")
f2 = ROOT.TF2("f2", "xygaus")
sgn = ROOT.TTree("sig_tree", "signal_tree")
bkg = ROOT.TTree("bkg_tree", "background_tree")
f =
TFile(fileOutName,
"RECREATE")
x1 = ROOT.std.vector["float"](ntot)
x2 = ROOT.std.vector["float"](ntot)
bkg.Branch("vars", "std::vector<float>", x1)
sgn.Branch("vars", "std::vector<float>", x2)
sgn.SetDirectory(f)
bkg.SetDirectory(f)
f1.SetParameters(1, 5, sX1, 5, sY1)
f2.SetParameters(1, 5, sX2, 5, sY2)
ROOT.gRandom.SetSeed(0)
ROOT.Info("TMVA_CNN_Classification", "Filling ROOT tree \n")
for i in range(n):
if i % 1000 == 0:
print("Generating image event ...", i)
h1.Reset()
h2.Reset()
f1.SetParameter(1, ROOT.gRandom.Uniform(3, 7))
f1.SetParameter(3, ROOT.gRandom.Uniform(3, 7))
f2.SetParameter(1, ROOT.gRandom.Uniform(3, 7))
f2.SetParameter(3, ROOT.gRandom.Uniform(3, 7))
h1.FillRandom("f1", nRndmEvts)
h2.FillRandom("f2", nRndmEvts)
for k in range(nh):
for l in range(nw):
m = k * nw + l
x1[m] = h1.GetBinContent(k + 1, l + 1) + ROOT.gRandom.Gaus(0, pixelNoise)
x2[m] = h2.GetBinContent(k + 1, l + 1) + ROOT.gRandom.Gaus(0, pixelNoise)
sgn.Fill()
bkg.Fill()
sgn.Write()
bkg.Write()
print("Signal and background tree with images data written to the file %s", f.GetName())
sgn.Print()
bkg.Print()
f.Close()
hasGPU = "tmva-gpu" in ROOT.gROOT.GetConfigFeatures()
hasCPU = "tmva-cpu" in ROOT.gROOT.GetConfigFeatures()
nevt = 1000
opt = [1, 1, 1, 1, 1]
useTMVACNN = opt[0]
if len(opt) > 0
else False
useKerasCNN = opt[1]
if len(opt) > 1
else False
useTMVADNN = opt[2]
if len(opt) > 2
else False
useTMVABDT = opt[3]
if len(opt) > 3
else False
usePyTorchCNN = opt[4]
if len(opt) > 4
else False
if (not hasCPU and not hasGPU) :
ROOT.Warning("TMVA_CNN_Classificaton","ROOT is not supporting tmva-cpu and tmva-gpu skip using TMVA-DNN and TMVA-CNN")
useTMVACNN = False
useTMVADNN = False
if not "tmva-pymva" in ROOT.gROOT.GetConfigFeatures():
useKerasCNN = False
usePyTorchCNN = False
else:
tf_spec = importlib.util.find_spec("tensorflow")
if tf_spec is None:
useKerasCNN = False
ROOT.Warning("TMVA_CNN_Classificaton","Skip using Keras since tensorflow is not installed")
torch_spec = importlib.util.find_spec("torch")
if torch_spec is None:
usePyTorchCNN = False
ROOT.Warning("TMVA_CNN_Classificaton","Skip using PyTorch since torch is not installed")
if not useTMVACNN:
ROOT.Warning(
"TMVA_CNN_Classificaton",
"TMVA is not build with GPU or CPU multi-thread support. Cannot use TMVA Deep Learning for CNN",
)
writeOutputFile = True
num_threads = 4
max_epochs = 10
if "imt" in ROOT.gROOT.GetConfigFeatures():
ROOT.gSystem.Setenv("OMP_NUM_THREADS", "1")
else:
print("Running in serial mode since ROOT does not support MT")
outputFile = None
if writeOutputFile:
outputFile =
TFile.Open(
"TMVA_CNN_ClassificationOutput.root",
"RECREATE")
"TMVA_CNN_Classification",
outputFile,
V=False,
ROC=True,
Silent=False,
Color=True,
AnalysisType="Classification",
Transformations=None,
Correlations=False,
)
imgSize = 16 * 16
inputFileName = "images_data_16x16.root"
if ROOT.gSystem.AccessPathName(inputFileName):
MakeImagesTree(nevt, 16, 16)
if inputFile is None:
ROOT.Warning("TMVA_CNN_Classification", "Error opening input file %s - exit", inputFileName.Data())
signalTree = inputFile.Get("sig_tree")
backgroundTree = inputFile.Get("bkg_tree")
nEventsSig = signalTree.GetEntries()
nEventsBkg = backgroundTree.GetEntries()
signalWeight = 1.0
backgroundWeight = 1.0
loader.AddSignalTree(signalTree, signalWeight)
loader.AddBackgroundTree(backgroundTree, backgroundWeight)
loader.AddVariablesArray("vars", imgSize)
mycuts = ""
mycutb = ""
nTrainSig = 0.8 * nEventsSig
nTrainBkg = 0.8 * nEventsBkg
loader.PrepareTrainingAndTestTree(
mycuts,
mycutb,
nTrain_Signal=nTrainSig,
nTrain_Background=nTrainBkg,
SplitMode="Random",
SplitSeed=100,
NormMode="NumEvents",
V=False,
CalcCorrelations=False,
)
if useTMVABDT:
factory.BookMethod(
loader,
TMVA.Types.kBDT,
"BDT",
V=False,
NTrees=400,
MinNodeSize="2.5%",
MaxDepth=2,
BoostType="AdaBoost",
AdaBoostBeta=0.5,
UseBaggedBoost=True,
BaggedSampleFraction=0.5,
SeparationType="GiniIndex",
nCuts=20,
)
if useTMVADNN:
layoutString = ROOT.TString(
"DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,DENSE|1|LINEAR"
)
trainingString1 = ROOT.TString(
"LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
"ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
"WeightDecay=1e-4,Regularization=None,"
"Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0."
)
trainingString1 += ",MaxEpochs=" + str(max_epochs)
dnnMethodName = "TMVA_DNN_CPU"
dnnOptions = "CPU"
if hasGPU :
dnnOptions = "GPU"
dnnMethodName = "TMVA_DNN_GPU"
factory.BookMethod(
loader,
TMVA.Types.kDL,
dnnMethodName,
H=False,
V=True,
ErrorStrategy="CROSSENTROPY",
VarTransform=None,
WeightInitialization="XAVIER",
Layout=layoutString,
TrainingStrategy=trainingString1,
Architecture=dnnOptions
)
if useTMVACNN:
trainingString1 = ROOT.TString(
"LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
"ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
"WeightDecay=1e-4,Regularization=None,"
"Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.0"
)
trainingString1 += ",MaxEpochs=" + str(max_epochs)
cnnMethodName = "TMVA_CNN_CPU"
cnnOptions = "CPU"
if hasGPU:
cnnOptions = "GPU"
cnnMethodName = "TMVA_CNN_GPU"
factory.BookMethod(
loader,
TMVA.Types.kDL,
cnnMethodName,
H=False,
V=True,
ErrorStrategy="CROSSENTROPY",
VarTransform=None,
WeightInitialization="XAVIER",
InputLayout="1|16|16",
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",
TrainingStrategy=trainingString1,
Architecture=cnnOptions,
)
if usePyTorchCNN:
ROOT.Info("TMVA_CNN_Classification", "Using Convolutional PyTorch Model")
pyTorchFileName = str(ROOT.gROOT.GetTutorialDir())
pyTorchFileName += "/tmva/PyTorch_Generate_CNN_Model.py"
torch_spec = importlib.util.find_spec("torch")
if torch_spec is not None and os.path.exists(pyTorchFileName):
ROOT.Info("TMVA_CNN_Classification", "Booking PyTorch CNN model")
factory.BookMethod(
loader,
TMVA.Types.kPyTorch,
"PyTorch",
H=True,
V=False,
VarTransform=None,
FilenameModel="PyTorchModelCNN.pt",
FilenameTrainedModel="PyTorchTrainedModelCNN.pt",
NumEpochs=max_epochs,
BatchSize=100,
UserCode=str(pyTorchFileName)
)
else:
ROOT.Warning(
"TMVA_CNN_Classification",
"PyTorch is not installed or model building file is not existing - skip using PyTorch",
)
if useKerasCNN:
ROOT.Info("TMVA_CNN_Classification", "Building convolutional keras model")
import tensorflow
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Input, Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Reshape
model = Sequential()
model.add(Reshape((16, 16, 1), input_shape=(256,)))
model.add(Conv2D(10, kernel_size=(3, 3), kernel_initializer="TruncatedNormal", activation="relu", padding="same"))
model.add(Conv2D(10, kernel_size=(3, 3), kernel_initializer="TruncatedNormal", activation="relu", padding="same"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64, activation="tanh"))
model.add(Dense(2, activation="sigmoid"))
model.compile(loss="binary_crossentropy", optimizer=Adam(learning_rate=0.001), weighted_metrics=["accuracy"])
model.save("model_cnn.h5")
model.summary()
if not os.path.exists("model_cnn.h5"):
raise FileNotFoundError("Error creating Keras model file - skip using Keras")
else:
ROOT.Info("TMVA_CNN_Classification", "Booking convolutional keras model")
factory.BookMethod(
loader,
TMVA.Types.kPyKeras,
"PyKeras",
H=True,
V=False,
VarTransform=None,
FilenameModel="model_cnn.h5",
FilenameTrainedModel="trained_model_cnn.h5",
NumEpochs=max_epochs,
BatchSize=100,
GpuOptions="allow_growth=True",
)
factory.TrainAllMethods()
factory.TestAllMethods()
factory.EvaluateAllMethods()
c1 = factory.GetROCCurve(loader)
c1.Draw()
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 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.