Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TMVA_CNN_Classification.py File Reference

Detailed Description

View in nbviewer Open in SWAN
TMVA Classification Example Using a Convolutional Neural Network

This is an example of using a CNN in TMVA. We do classification using a toy image data set that is generated when running the example macro

Running with nthreads = 4
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 : ␛[1mTrain all methods␛[0m
Factory : Train method: BDT for Classification
:
BDT : #events: (reweighted) sig: 800 bkg: 800
: #events: (unweighted) sig: 800 bkg: 800
: Training 400 Decision Trees ... patience please
: Elapsed time for training with 1600 events: 1.3 sec
BDT : [dataset] : Evaluation of BDT on training sample (1600 events)
: Elapsed time for evaluation of 1600 events: 0.0138 sec
: Creating xml weight file: ␛[0;36mdataset/weights/TMVA_CNN_Classification_BDT.weights.xml␛[0m
: Creating standalone class: ␛[0;36mdataset/weights/TMVA_CNN_Classification_BDT.class.C␛[0m
: TMVA_CNN_ClassificationOutput.root:/dataset/Method_BDT/BDT
Factory : Training finished
:
: Ranking input variables (method specific)...
BDT : Ranking result (top variable is best ranked)
: --------------------------------------
: Rank : Variable : Variable Importance
: --------------------------------------
: 1 : vars : 1.065e-02
: 2 : vars : 9.549e-03
: 3 : vars : 8.529e-03
: 4 : vars : 8.310e-03
: 5 : vars : 8.242e-03
: 6 : vars : 7.781e-03
: 7 : vars : 7.640e-03
: 8 : vars : 7.627e-03
: 9 : vars : 7.552e-03
: 10 : vars : 7.330e-03
: 11 : vars : 7.252e-03
: 12 : vars : 7.243e-03
: 13 : vars : 7.225e-03
: 14 : vars : 7.163e-03
: 15 : vars : 7.103e-03
: 16 : vars : 7.091e-03
: 17 : vars : 7.010e-03
: 18 : vars : 6.955e-03
: 19 : vars : 6.946e-03
: 20 : vars : 6.935e-03
: 21 : vars : 6.925e-03
: 22 : vars : 6.899e-03
: 23 : vars : 6.797e-03
: 24 : vars : 6.764e-03
: 25 : vars : 6.749e-03
: 26 : vars : 6.708e-03
: 27 : vars : 6.686e-03
: 28 : vars : 6.580e-03
: 29 : vars : 6.552e-03
: 30 : vars : 6.339e-03
: 31 : vars : 6.311e-03
: 32 : vars : 6.299e-03
: 33 : vars : 6.144e-03
: 34 : vars : 6.123e-03
: 35 : vars : 6.089e-03
: 36 : vars : 6.048e-03
: 37 : vars : 6.028e-03
: 38 : vars : 5.985e-03
: 39 : vars : 5.929e-03
: 40 : vars : 5.926e-03
: 41 : vars : 5.916e-03
: 42 : vars : 5.899e-03
: 43 : vars : 5.896e-03
: 44 : vars : 5.802e-03
: 45 : vars : 5.772e-03
: 46 : vars : 5.753e-03
: 47 : vars : 5.746e-03
: 48 : vars : 5.672e-03
: 49 : vars : 5.592e-03
: 50 : vars : 5.577e-03
: 51 : vars : 5.543e-03
: 52 : vars : 5.486e-03
: 53 : vars : 5.481e-03
: 54 : vars : 5.454e-03
: 55 : vars : 5.452e-03
: 56 : vars : 5.412e-03
: 57 : vars : 5.362e-03
: 58 : vars : 5.303e-03
: 59 : vars : 5.284e-03
: 60 : vars : 5.249e-03
: 61 : vars : 5.246e-03
: 62 : vars : 5.202e-03
: 63 : vars : 5.201e-03
: 64 : vars : 5.191e-03
: 65 : vars : 5.186e-03
: 66 : vars : 5.180e-03
: 67 : vars : 5.176e-03
: 68 : vars : 5.154e-03
: 69 : vars : 5.092e-03
: 70 : vars : 5.089e-03
: 71 : vars : 5.087e-03
: 72 : vars : 5.086e-03
: 73 : vars : 5.044e-03
: 74 : vars : 4.987e-03
: 75 : vars : 4.841e-03
: 76 : vars : 4.808e-03
: 77 : vars : 4.778e-03
: 78 : vars : 4.742e-03
: 79 : vars : 4.731e-03
: 80 : vars : 4.697e-03
: 81 : vars : 4.671e-03
: 82 : vars : 4.667e-03
: 83 : vars : 4.637e-03
: 84 : vars : 4.624e-03
: 85 : vars : 4.621e-03
: 86 : vars : 4.621e-03
: 87 : vars : 4.535e-03
: 88 : vars : 4.518e-03
: 89 : vars : 4.449e-03
: 90 : vars : 4.444e-03
: 91 : vars : 4.437e-03
: 92 : vars : 4.392e-03
: 93 : vars : 4.378e-03
: 94 : vars : 4.353e-03
: 95 : vars : 4.327e-03
: 96 : vars : 4.324e-03
: 97 : vars : 4.300e-03
: 98 : vars : 4.294e-03
: 99 : vars : 4.261e-03
: 100 : vars : 4.253e-03
: 101 : vars : 4.227e-03
: 102 : vars : 4.197e-03
: 103 : vars : 4.170e-03
: 104 : vars : 4.134e-03
: 105 : vars : 4.109e-03
: 106 : vars : 4.083e-03
: 107 : vars : 4.059e-03
: 108 : vars : 4.055e-03
: 109 : vars : 4.017e-03
: 110 : vars : 4.014e-03
: 111 : vars : 4.013e-03
: 112 : vars : 4.009e-03
: 113 : vars : 4.006e-03
: 114 : vars : 3.996e-03
: 115 : vars : 3.980e-03
: 116 : vars : 3.941e-03
: 117 : vars : 3.913e-03
: 118 : vars : 3.884e-03
: 119 : vars : 3.882e-03
: 120 : vars : 3.879e-03
: 121 : vars : 3.869e-03
: 122 : vars : 3.868e-03
: 123 : vars : 3.863e-03
: 124 : vars : 3.862e-03
: 125 : vars : 3.854e-03
: 126 : vars : 3.852e-03
: 127 : vars : 3.837e-03
: 128 : vars : 3.824e-03
: 129 : vars : 3.752e-03
: 130 : vars : 3.720e-03
: 131 : vars : 3.700e-03
: 132 : vars : 3.689e-03
: 133 : vars : 3.687e-03
: 134 : vars : 3.682e-03
: 135 : vars : 3.665e-03
: 136 : vars : 3.645e-03
: 137 : vars : 3.637e-03
: 138 : vars : 3.629e-03
: 139 : vars : 3.622e-03
: 140 : vars : 3.615e-03
: 141 : vars : 3.594e-03
: 142 : vars : 3.570e-03
: 143 : vars : 3.549e-03
: 144 : vars : 3.536e-03
: 145 : vars : 3.522e-03
: 146 : vars : 3.521e-03
: 147 : vars : 3.493e-03
: 148 : vars : 3.488e-03
: 149 : vars : 3.475e-03
: 150 : vars : 3.444e-03
: 151 : vars : 3.428e-03
: 152 : vars : 3.428e-03
: 153 : vars : 3.426e-03
: 154 : vars : 3.408e-03
: 155 : vars : 3.392e-03
: 156 : vars : 3.380e-03
: 157 : vars : 3.377e-03
: 158 : vars : 3.331e-03
: 159 : vars : 3.310e-03
: 160 : vars : 3.310e-03
: 161 : vars : 3.302e-03
: 162 : vars : 3.298e-03
: 163 : vars : 3.288e-03
: 164 : vars : 3.258e-03
: 165 : vars : 3.249e-03
: 166 : vars : 3.233e-03
: 167 : vars : 3.195e-03
: 168 : vars : 3.162e-03
: 169 : vars : 3.147e-03
: 170 : vars : 3.090e-03
: 171 : vars : 3.073e-03
: 172 : vars : 3.055e-03
: 173 : vars : 3.012e-03
: 174 : vars : 3.012e-03
: 175 : vars : 3.003e-03
: 176 : vars : 3.002e-03
: 177 : vars : 2.999e-03
: 178 : vars : 2.997e-03
: 179 : vars : 2.995e-03
: 180 : vars : 2.974e-03
: 181 : vars : 2.925e-03
: 182 : vars : 2.897e-03
: 183 : vars : 2.896e-03
: 184 : vars : 2.888e-03
: 185 : vars : 2.878e-03
: 186 : vars : 2.859e-03
: 187 : vars : 2.822e-03
: 188 : vars : 2.812e-03
: 189 : vars : 2.801e-03
: 190 : vars : 2.799e-03
: 191 : vars : 2.770e-03
: 192 : vars : 2.716e-03
: 193 : vars : 2.701e-03
: 194 : vars : 2.660e-03
: 195 : vars : 2.651e-03
: 196 : vars : 2.648e-03
: 197 : vars : 2.637e-03
: 198 : vars : 2.593e-03
: 199 : vars : 2.589e-03
: 200 : vars : 2.581e-03
: 201 : vars : 2.546e-03
: 202 : vars : 2.542e-03
: 203 : vars : 2.468e-03
: 204 : vars : 2.459e-03
: 205 : vars : 2.457e-03
: 206 : vars : 2.446e-03
: 207 : vars : 2.439e-03
: 208 : vars : 2.435e-03
: 209 : vars : 2.421e-03
: 210 : vars : 2.412e-03
: 211 : vars : 2.394e-03
: 212 : vars : 2.306e-03
: 213 : vars : 2.296e-03
: 214 : vars : 2.296e-03
: 215 : vars : 2.264e-03
: 216 : vars : 2.243e-03
: 217 : vars : 2.238e-03
: 218 : vars : 2.174e-03
: 219 : vars : 2.166e-03
: 220 : vars : 2.136e-03
: 221 : vars : 2.084e-03
: 222 : vars : 2.041e-03
: 223 : vars : 1.999e-03
: 224 : vars : 1.989e-03
: 225 : vars : 1.974e-03
: 226 : vars : 1.900e-03
: 227 : vars : 1.746e-03
: 228 : vars : 1.676e-03
: 229 : vars : 1.600e-03
: 230 : vars : 1.526e-03
: 231 : vars : 1.400e-03
: 232 : vars : 1.360e-03
: 233 : vars : 1.319e-03
: 234 : vars : 1.293e-03
: 235 : vars : 1.203e-03
: 236 : vars : 1.185e-03
: 237 : vars : 6.177e-04
: 238 : vars : 4.318e-04
: 239 : vars : 3.337e-04
: 240 : vars : 0.000e+00
: 241 : vars : 0.000e+00
: 242 : vars : 0.000e+00
: 243 : vars : 0.000e+00
: 244 : vars : 0.000e+00
: 245 : vars : 0.000e+00
: 246 : vars : 0.000e+00
: 247 : vars : 0.000e+00
: 248 : vars : 0.000e+00
: 249 : vars : 0.000e+00
: 250 : vars : 0.000e+00
: 251 : vars : 0.000e+00
: 252 : vars : 0.000e+00
: 253 : vars : 0.000e+00
: 254 : vars : 0.000e+00
: 255 : vars : 0.000e+00
: 256 : vars : 0.000e+00
: --------------------------------------
Factory : === Destroy and recreate all methods via weight files for testing ===
:
: Reading weight file: ␛[0;36mdataset/weights/TMVA_CNN_Classification_BDT.weights.xml␛[0m
Factory : ␛[1mTest all methods␛[0m
Factory : Test method: BDT for Classification performance
:
BDT : [dataset] : Evaluation of BDT on testing sample (400 events)
: Elapsed time for evaluation of 400 events: 0.00346 sec
Factory : ␛[1mEvaluate all methods␛[0m
Factory : Evaluate classifier: BDT
:
BDT : [dataset] : Loop over test events and fill histograms with classifier response...
:
: Dataset[dataset] : variable plots are not produces ! The number of variables is 256 , it is larger than 200
:
: Evaluation results ranked by best signal efficiency and purity (area)
: -------------------------------------------------------------------------------------------------------------------
: DataSet MVA
: Name: Method: ROC-integ
: dataset BDT : 0.773
: -------------------------------------------------------------------------------------------------------------------
:
: Testing efficiency compared to training efficiency (overtraining check)
: -------------------------------------------------------------------------------------------------------------------
: DataSet MVA Signal efficiency: from test sample (from training sample)
: Name: Method: @B=0.01 @B=0.10 @B=0.30
: -------------------------------------------------------------------------------------------------------------------
: dataset BDT : 0.070 (0.308) 0.375 (0.706) 0.703 (0.879)
: -------------------------------------------------------------------------------------------------------------------
:
Dataset:dataset : Created tree 'TestTree' with 400 events
:
Dataset:dataset : Created tree 'TrainTree' with 1600 events
:
Factory : ␛[1mThank you for using TMVA!␛[0m
: ␛[1mFor citation information, please visit: http://tmva.sf.net/citeTMVA.html␛[0m
# TMVA Classification Example Using a Convolutional Neural Network
## Helper function to create input images data
## we create a signal and background 2D histograms from 2d gaussians
## with a location (means in X and Y) different for each event
## The difference between signal and background is in the gaussian width.
## The width for the background gaussian is slightly larger than the signal width by few % values
import ROOT
import os
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
TMVA = ROOT.TMVA
TFile = ROOT.TFile
def MakeImagesTree(n, nh, nw):
# image size (nh x nw)
ntot = nh * nw
fileOutName = "images_data_16x16.root"
nRndmEvts = 10000 # number of events we use to fill each image
delta_sigma = 0.1 # 5% difference in the sigma
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)
# create signal and background trees with a single branch
# an std::vector<float> of size nh x nw containing the image data
bkg.Branch("vars", "std::vector<float>", x1)
sgn.Branch("vars", "std::vector<float>", x2)
f1.SetParameters(1, 5, sX1, 5, sY1)
f2.SetParameters(1, 5, sX2, 5, sY2)
ROOT.Info("TMVA_CNN_Classification", "Filling ROOT tree \n")
for i in range(n):
if i % 1000 == 0:
print("Generating image event ...", i)
# generate random means in range [3,7] to be not too much on the border
h1.FillRandom("f1", nRndmEvts)
h2.FillRandom("f2", nRndmEvts)
for k in range(nh):
for l in range(nw):
m = k * nw + l
# add some noise in each bin
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)
print("Signal and background tree with images data written to the file %s", f.GetName())
hasGPU = "tmva-gpu" in ROOT.gROOT.GetConfigFeatures()
hasCPU = "tmva-cpu" in ROOT.gROOT.GetConfigFeatures()
nevt = 1000 # use a larger value to get better results
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:
if not useTMVACNN:
"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 # use max 4 threads
max_epochs = 10 # maximum number of epochs used for training
# do enable MT running
ROOT.EnableImplicitMT(num_threads)
ROOT.gSystem.Setenv("OMP_NUM_THREADS", "1") # switch OFF MT in OpenBLAS
print("Running with nthreads = {}".format(ROOT.GetThreadPoolSize()))
else:
print("Running in serial mode since ROOT does not support MT")
outputFile = None
if writeOutputFile:
outputFile = TFile.Open("TMVA_CNN_ClassificationOutput.root", "RECREATE")
## Create TMVA Factory
# Create the Factory class. Later you can choose the methods
# whose performance you'd like to investigate.
# The factory is the major TMVA object you have to interact with. Here is the list of parameters you need to pass
# - The first argument is the base of the name of all the output
# weight files in the directory weight/ that will be created with the
# method parameters
# - The second argument is the output file for the training results
# - The third argument is a string option defining some general configuration for the TMVA session.
# For example all TMVA output can be suppressed by removing the "!" (not) in front of the "Silent" argument in the
# option string
# - note that we disable any pre-transformation of the input variables and we avoid computing correlations between
# input variables
factory = TMVA.Factory(
"TMVA_CNN_Classification",
outputFile,
V=False,
ROC=True,
Silent=False,
Color=True,
AnalysisType="Classification",
Transformations=None,
Correlations=False,
)
## Declare DataLoader(s)
# The next step is to declare the DataLoader class that deals with input variables
# Define the input variables that shall be used for the MVA training
# note that you may also use variable expressions, which can be parsed by TTree::Draw( "expression" )]
# In this case the input data consists of an image of 16x16 pixels. Each single pixel is a branch in a ROOT TTree
loader = TMVA.DataLoader("dataset")
## Setup Dataset(s)
# Define input data file and signal and background trees
imgSize = 16 * 16
inputFileName = "images_data_16x16.root"
# if the input file does not exist create it
if ROOT.gSystem.AccessPathName(inputFileName):
MakeImagesTree(nevt, 16, 16)
inputFile = TFile.Open(inputFileName)
if inputFile is None:
ROOT.Warning("TMVA_CNN_Classification", "Error opening input file %s - exit", inputFileName.Data())
# inputFileName = "tmva_class_example.root"
# --- Register the training and test trees
signalTree = inputFile.Get("sig_tree")
backgroundTree = inputFile.Get("bkg_tree")
nEventsSig = signalTree.GetEntries()
# global event weights per tree (see below for setting event-wise weights)
signalWeight = 1.0
backgroundWeight = 1.0
# You can add an arbitrary number of signal or background trees
loader.AddSignalTree(signalTree, signalWeight)
loader.AddBackgroundTree(backgroundTree, backgroundWeight)
## add event variables (image)
## use new method (from ROOT 6.20 to add a variable array for all image data)
loader.AddVariablesArray("vars", imgSize)
# Set individual event weights (the variables must exist in the original TTree)
# for signal : factory->SetSignalWeightExpression ("weight1*weight2");
# for background: factory->SetBackgroundWeightExpression("weight1*weight2");
# loader->SetBackgroundWeightExpression( "weight" );
# Apply additional cuts on the signal and background samples (can be different)
mycuts = "" # for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
mycutb = "" # for example: TCut mycutb = "abs(var1)<0.5";
# Tell the factory how to use the training and testing events
# If no numbers of events are given, half of the events in the tree are used
# for training, and the other half for testing:
# loader.PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
# It is possible also to specify the number of training and testing events,
# note we disable the computation of the correlation matrix of the input variables
nTrainSig = 0.8 * nEventsSig
nTrainBkg = 0.8 * nEventsBkg
# build the string options for DataLoader::PrepareTrainingAndTestTree
mycuts,
mycutb,
nTrain_Signal=nTrainSig,
nTrain_Background=nTrainBkg,
SplitMode="Random",
SplitSeed=100,
NormMode="NumEvents",
V=False,
CalcCorrelations=False,
)
# DataSetInfo : [dataset] : Added class "Signal"
# : Add Tree sig_tree of type Signal with 10000 events
# DataSetInfo : [dataset] : Added class "Background"
# : Add Tree bkg_tree of type Background with 10000 events
# signalTree.Print();
# Booking Methods
# Here we book the TMVA methods. We book a Boosted Decision Tree method (BDT)
# Boosted Decision Trees
if useTMVABDT:
loader,
"BDT",
V=False,
NTrees=400,
MinNodeSize="2.5%",
MaxDepth=2,
BoostType="AdaBoost",
AdaBoostBeta=0.5,
UseBaggedBoost=True,
BaggedSampleFraction=0.5,
SeparationType="GiniIndex",
nCuts=20,
)
#### Booking Deep Neural Network
# Here we book the DNN of TMVA. See the example TMVA_Higgs_Classification.C for a detailed description of the
# options
if useTMVADNN:
layoutString = ROOT.TString(
"DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,DENSE|1|LINEAR"
)
# Training strategies
# one can catenate several training strings with different parameters (e.g. learning rates or regularizations
# parameters) The training string must be concatenated with the `|` delimiter
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."
) # + "|" + trainingString2 + ...
trainingString1 += ",MaxEpochs=" + str(max_epochs)
# Build now the full DNN Option string
dnnMethodName = "TMVA_DNN_CPU"
# use GPU if available
dnnOptions = "CPU"
if hasGPU :
dnnOptions = "GPU"
dnnMethodName = "TMVA_DNN_GPU"
loader,
dnnMethodName,
H=False,
V=True,
ErrorStrategy="CROSSENTROPY",
VarTransform=None,
WeightInitialization="XAVIER",
Layout=layoutString,
TrainingStrategy=trainingString1,
Architecture=dnnOptions
)
### Book Convolutional Neural Network in TMVA
# For building a CNN one needs to define
# - Input Layout : number of channels (in this case = 1) | image height | image width
# - Batch Layout : batch size | number of channels | image size = (height*width)
# Then one add Convolutional layers and MaxPool layers.
# - For Convolutional layer the option string has to be:
# - CONV | number of units | filter height | filter width | stride height | stride width | padding height | paddig
# width | activation function
# - note in this case we are using a filer 3x3 and padding=1 and stride=1 so we get the output dimension of the
# conv layer equal to the input
# - note we use after the first convolutional layer a batch normalization layer. This seems to help significantly the
# convergence
# - For the MaxPool layer:
# - MAXPOOL | pool height | pool width | stride height | stride width
# The RESHAPE layer is needed to flatten the output before the Dense layer
# Note that to run the CNN is required to have CPU or GPU support
if useTMVACNN:
# Training strategies.
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)
## New DL (CNN)
cnnMethodName = "TMVA_CNN_CPU"
cnnOptions = "CPU"
# use GPU if available
if hasGPU:
cnnOptions = "GPU"
cnnMethodName = "TMVA_CNN_GPU"
loader,
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,
)
### Book Convolutional Neural Network in Keras using a generated model
if usePyTorchCNN:
ROOT.Info("TMVA_CNN_Classification", "Using Convolutional PyTorch Model")
pyTorchFileName = str(ROOT.gROOT.GetTutorialDir())
pyTorchFileName += "/tmva/PyTorch_Generate_CNN_Model.py"
# check that pytorch can be imported and file defining the model exists
torch_spec = importlib.util.find_spec("torch")
if torch_spec is not None and os.path.exists(pyTorchFileName):
#cmd = str(ROOT.TMVA.Python_Executable()) + " " + pyTorchFileName
#os.system(cmd)
#import PyTorch_Generate_CNN_Model
ROOT.Info("TMVA_CNN_Classification", "Booking PyTorch CNN model")
loader,
"PyTorch",
H=True,
V=False,
VarTransform=None,
FilenameModel="PyTorchModelCNN.pt",
FilenameTrainedModel="PyTorchTrainedModelCNN.pt",
NumEpochs=max_epochs,
BatchSize=100,
UserCode=str(pyTorchFileName)
)
else:
"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")
# create python script which can be executed
# create 2 conv2d layer + maxpool + dense
import tensorflow
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
# from keras.initializers import TruncatedNormal
# from keras import initializations
from tensorflow.keras.layers import Input, Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Reshape
# from keras.callbacks import ReduceLROnPlateau
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"))
# stride for maxpool is equal to pool size
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64, activation="tanh"))
# model.add(Dropout(0.2))
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")
if not os.path.exists("model_cnn.h5"):
raise FileNotFoundError("Error creating Keras model file - skip using Keras")
else:
# book PyKeras method only if Keras model could be created
ROOT.Info("TMVA_CNN_Classification", "Booking convolutional keras model")
loader,
"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",
) # needed for RTX NVidia card and to avoid TF allocates all GPU memory
## Train Methods
## Test and Evaluate Methods
## Plot ROC Curve
c1 = factory.GetROCCurve(loader)
# close outputfile to save output file
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
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...
Definition TFile.h:53
This is the main MVA steering class.
Definition Factory.h:80
Author
Harshal Shende

Definition in file TMVA_CNN_Classification.py.