Skip to content

Commit 3fc39bc

Browse files
committed
[tmva][pymva] Fix and improve Python tutorials and set tf.keras=1 by default
- protect usage of pymva when it is available - set tf.keras by default in MethodPyKeras since this is now the standard for Keras.
1 parent df0136a commit 3fc39bc

File tree

4 files changed

+58
-13
lines changed

4 files changed

+58
-13
lines changed

tmva/pymva/inc/TMVA/MethodPyKeras.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ namespace TMVA {
8686
UInt_t fNumEpochs {0}; // Number of training epochs
8787
Int_t fNumThreads {0}; // Number of CPU threads (if 0 uses default values)
8888
Int_t fVerbose; // Keras verbosity during training
89-
Bool_t fUseTFKeras { kFALSE}; // use Keras from Tensorflow (-1, default, 0 false, 1, true)
89+
Bool_t fUseTFKeras { true}; // use Keras from Tensorflow default is true
9090
Bool_t fContinueTraining; // Load weights from previous training
9191
Bool_t fSaveBestOnly; // Store only weights with smallest validation loss
9292
Int_t fTriesEarlyStopping; // Stop training if validation loss is not decreasing for several epochs

tmva/pymva/src/MethodPyKeras.cxx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ void MethodPyKeras::DeclareOptions() {
8282
DeclareOptionRef(fNumThreads, "NumThreads", "Number of CPU threads (only for Tensorflow backend)");
8383
DeclareOptionRef(fGpuOptions, "GpuOptions", "GPU options for tensorflow, such as allow_growth");
8484
DeclareOptionRef(fUseTFKeras, "tf.keras", "Use tensorflow from Keras");
85+
DeclareOptionRef(fUseTFKeras, "tfkeras", "Use tensorflow from Keras");
8586
DeclareOptionRef(fVerbose, "Verbose", "Keras verbosity during training");
8687
DeclareOptionRef(fContinueTraining, "ContinueTraining", "Load weights from previous training");
8788
DeclareOptionRef(fSaveBestOnly, "SaveBestOnly", "Store only weights with smallest validation loss");

tutorials/tmva/TMVA_CNN_Classification.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,6 @@
3333
import importlib
3434

3535
TMVA.Tools.Instance()
36-
TMVA.PyMethodBase.PyInitialize()
37-
3836

3937
def MakeImagesTree(n, nh, nw):
4038
# image size (nh x nw)
@@ -122,6 +120,8 @@ def MakeImagesTree(n, nh, nw):
122120
if ROOT.gSystem.GetFromPipe("root-config --has-tmva-pymva") != "yes":
123121
useKerasCNN = False
124122
usePyTorchCNN = False
123+
else:
124+
TMVA.PyMethodBase.PyInitialize()
125125

126126
tf_spec = importlib.util.find_spec("tensorflow")
127127
if tf_spec is None:
@@ -139,10 +139,6 @@ def MakeImagesTree(n, nh, nw):
139139
"TMVA is not build with GPU or CPU multi-thread support. Cannot use TMVA Deep Learning for CNN",
140140
)
141141

142-
#there is an issue using TF and PyTorch - so use only one of the two
143-
if (usePyTorchCNN):
144-
useKerasCNN = False
145-
146142
writeOutputFile = True
147143

148144
num_threads = 0 # use default threads

tutorials/tmva/TMVA_Higgs_Classification.py

Lines changed: 54 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,15 +30,12 @@
3030
## - 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
3131

3232
import ROOT
33+
import os
3334

3435
TMVA = ROOT.TMVA
3536
TFile = ROOT.TFile
3637

37-
3838
TMVA.Tools.Instance()
39-
## For PYMVA methods
40-
TMVA.PyMethodBase.PyInitialize()
41-
4239

4340
# options to control used methods
4441
useLikelihood = True # likelihood based discriminant
@@ -47,8 +44,20 @@
4744
useMLP = False # Multi Layer Perceptron (old TMVA NN implementation)
4845
useBDT = True # Boosted Decision Tree
4946
useDL = True # TMVA Deep learning ( CPU or GPU)
47+
useKeras = True # Use Keras Deep Learning via PyMVA
48+
49+
if ROOT.gSystem.GetFromPipe("root-config --has-tmva-pymva") == "yes":
50+
TMVA.PyMethodBase.PyInitialize()
51+
else:
52+
useKeras = False # cannot use Keras if PYMVA is not available
53+
54+
if useKeras:
55+
try:
56+
import tensorflow
57+
except:
58+
ROOT.Warning("TMVA_Higgs_Classification", "Skip using Keras since tensorflow is not available")
59+
useKeras = False
5060

51-
TMVA.Tools.Instance()
5261
outputFile = TFile.Open("Higgs_ClassificationOutput.root", "RECREATE")
5362
factory = TMVA.Factory(
5463
"TMVA_Higgs_Classification", outputFile, V=False, ROC=True, Silent=False, Color=True, AnalysisType="Classification"
@@ -276,7 +285,7 @@
276285
training1 = ROOT.TString(
277286
"LearningRate=1e-3,Momentum=0.9,"
278287
"ConvergenceSteps=10,BatchSize=128,TestRepetitions=1,"
279-
"MaxEpochs=30,WeightDecay=1e-4,Regularization=None,"
288+
"MaxEpochs=20,WeightDecay=1e-4,Regularization=None,"
280289
"Optimizer=ADAM,ADAM_beta1=0.9,ADAM_beta2=0.999,ADAM_eps=1.E-7," # ADAM default parameters
281290
"DropConfig=0.0+0.0+0.0+0."
282291
)
@@ -310,6 +319,45 @@
310319
Architecture=arch,
311320
)
312321

322+
#Keras DL
323+
if useKeras:
324+
ROOT.Info("TMVA_Higgs_Classification", "Building Deep Learning keras model")
325+
# create Keras model with 4 layers of 64 units and relu activations
326+
import tensorflow
327+
from tensorflow.keras.models import Sequential
328+
from tensorflow.keras.optimizers import Adam
329+
from tensorflow.keras.layers import Input, Dense
330+
331+
model = Sequential()
332+
model.add(Dense(64, activation='relu',input_dim=7))
333+
model.add(Dense(64, activation='relu'))
334+
model.add(Dense(64, activation='relu'))
335+
model.add(Dense(64, activation='relu'))
336+
model.add(Dense(2, activation='sigmoid'))
337+
model.compile(loss = 'binary_crossentropy', optimizer = Adam(learning_rate = 0.001), metrics = ['accuracy'])
338+
model.save('model_higgs.h5')
339+
model.summary()
340+
341+
if not os.path.exists("model_higgs.h5"):
342+
raise FileNotFoundError("Error creating Keras model file - skip using Keras")
343+
else:
344+
# book PyKeras method only if Keras model could be created
345+
ROOT.Info("TMVA_Higgs_Classification", "Booking Deep Learning keras model")
346+
factory.BookMethod(
347+
loader,
348+
TMVA.Types.kPyKeras,
349+
"PyKeras",
350+
H=True,
351+
V=False,
352+
VarTransform=None,
353+
FilenameModel="model_higgs.h5",
354+
FilenameTrainedModel="trained_model_higgs.h5",
355+
NumEpochs=20,
356+
BatchSize=100 )
357+
# GpuOptions="allow_growth=True",
358+
# ) # needed for RTX NVidia card and to avoid TF allocates all GPU memory
359+
360+
313361
## Train Methods
314362

315363
# Here we train all the previously booked methods.

0 commit comments

Comments
 (0)