29void MakeImagesTree(
int n,
int nh,
int nw)
33 const int ntot = nh * nw;
35 TFile f(fileOutName,
"RECREATE");
37 const int nRndmEvts = 10000;
38 double delta_sigma = 0.1;
39 double pixelNoise = 5;
43 double sX2 = sX1 + delta_sigma;
44 double sY2 = sY1 - delta_sigma;
46 TH2D h1(
"h1",
"h1", nh, 0, 10, nw, 0, 10);
47 TH2D h2(
"h2",
"h2", nh, 0, 10, nw, 0, 10);
49 TF2 f1(
"f1",
"xygaus");
50 TF2 f2(
"f2",
"xygaus");
52 TTree sgn(
"sig_tree",
"signal_tree");
53 TTree bkg(
"bkg_tree",
"background_tree");
56 std::vector<float>
x1(ntot);
57 std::vector<float>
x2(ntot);
62 std::vector<float> *px1 = &
x1;
63 std::vector<float> *px2 = &
x2;
65 bkg.Branch(
"vars",
"std::vector<float>", &px1);
66 sgn.Branch(
"vars",
"std::vector<float>", &px2);
74 f2.SetParameters(1, 5, sX2, 5, sY2);
76 std::cout <<
"Filling ROOT tree " << std::endl;
77 for (
int i = 0; i <
n; ++i) {
79 std::cout <<
"Generating image event ... " << i << std::endl;
89 h2.FillRandom(
"f2", nRndmEvts);
91 for (
int k = 0; k < nh; ++k) {
92 for (
int l = 0;
l < nw; ++
l) {
105 Info(
"MakeImagesTree",
"Signal and background tree with images data written to the file %s",
f.GetName());
123 int imgSize = 16 * 16;
124 TString inputFileName =
"images_data_16x16.root";
130 MakeImagesTree(nevts, 16, 16);
133 bool useTMVACNN = (opt.size() > 0) ? opt[0] : false;
134 bool useKerasCNN = (opt.size() > 1) ? opt[1] : false;
135 bool useTMVADNN = (opt.size() > 2) ? opt[2] : false;
136 bool useTMVABDT = (opt.size() > 3) ? opt[3] : false;
137 bool usePyTorchCNN = (opt.size() > 4) ? opt[4] : false;
138#ifndef R__HAS_TMVACPU
139#ifndef R__HAS_TMVAGPU
140 Warning(
"TMVA_CNN_Classification",
141 "TMVA is not build with GPU or CPU multi-thread support. Cannot use TMVA Deep Learning for CNN");
146 bool writeOutputFile =
true;
154 if (num_threads >= 0) {
170 usePyTorchCNN =
false;
173 TFile *outputFile =
nullptr;
175 outputFile =
TFile::Open(
"TMVA_CNN_ClassificationOutput.root",
"RECREATE");
200 "TMVA_CNN_Classification", outputFile,
201 "!V:ROC:!Silent:Color:AnalysisType=Classification:Transformations=None:!Correlations");
226 std::unique_ptr<TFile> inputFile{
TFile::Open(inputFileName)};
228 Error(
"TMVA_CNN_Classification",
"Error opening input file %s - exit", inputFileName.
Data());
234 auto signalTree = inputFile->Get<
TTree>(
"sig_tree");
235 auto backgroundTree = inputFile->Get<
TTree>(
"bkg_tree");
238 Error(
"TMVA_CNN_Classification",
"Could not find signal tree in file '%s'", inputFileName.
Data());
241 if (!backgroundTree) {
242 Error(
"TMVA_CNN_Classification",
"Could not find background tree in file '%s'", inputFileName.
Data());
246 int nEventsSig = signalTree->GetEntries();
247 int nEventsBkg = backgroundTree->
GetEntries();
254 loader.AddSignalTree(signalTree, signalWeight);
255 loader.AddBackgroundTree(backgroundTree, backgroundWeight);
259 loader.AddVariablesArray(
"vars", imgSize);
278 int nTrainSig = 0.8 * nEventsSig;
279 int nTrainBkg = 0.8 * nEventsBkg;
283 "nTrain_Signal=%d:nTrain_Background=%d:SplitMode=Random:SplitSeed=100:NormMode=NumEvents:!V:!CalcCorrelations",
284 nTrainSig, nTrainBkg);
286 loader.PrepareTrainingAndTestTree(mycuts, mycutb, prepareOptions);
309 "!V:NTrees=200:MinNodeSize=2.5%:MaxDepth=2:BoostType=AdaBoost:AdaBoostBeta=0.5:"
310 "UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex:nCuts=20");
324 "Layout=DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,BNORM,DENSE|100|RELU,DENSE|1|LINEAR");
329 TString trainingString1(
"LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
330 "ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
331 "MaxEpochs=10,WeightDecay=1e-4,Regularization=None,"
332 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.");
334 TString trainingStrategyString(
"TrainingStrategy=");
335 trainingStrategyString += trainingString1;
339 TString dnnOptions(
"!H:V:ErrorStrategy=CROSSENTROPY:VarTransform=None:"
340 "WeightInitialization=XAVIER");
341 dnnOptions.Append(
":");
342 dnnOptions.Append(layoutString);
343 dnnOptions.Append(
":");
344 dnnOptions.Append(trainingStrategyString);
346 TString dnnMethodName =
"TMVA_DNN_CPU";
349 dnnOptions +=
":Architecture=GPU";
350 dnnMethodName =
"TMVA_DNN_GPU";
351#elif defined(R__HAS_TMVACPU)
352 dnnOptions +=
":Architecture=CPU";
390 TString inputLayoutString(
"InputLayout=1|16|16");
393 TString layoutString(
"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,"
394 "RESHAPE|FLAT,DENSE|100|RELU,DENSE|1|LINEAR");
397 TString trainingString1(
"LearningRate=1e-3,Momentum=0.9,Repetitions=1,"
398 "ConvergenceSteps=5,BatchSize=100,TestRepetitions=1,"
399 "MaxEpochs=10,WeightDecay=1e-4,Regularization=None,"
400 "Optimizer=ADAM,DropConfig=0.0+0.0+0.0+0.0");
402 TString trainingStrategyString(
"TrainingStrategy=");
403 trainingStrategyString +=
407 TString cnnOptions(
"!H:V:ErrorStrategy=CROSSENTROPY:VarTransform=None:"
408 "WeightInitialization=XAVIER");
410 cnnOptions.Append(
":");
411 cnnOptions.Append(inputLayoutString);
412 cnnOptions.Append(
":");
413 cnnOptions.Append(layoutString);
414 cnnOptions.Append(
":");
415 cnnOptions.Append(trainingStrategyString);
418 TString cnnMethodName =
"TMVA_CNN_CPU";
421 cnnOptions +=
":Architecture=GPU";
422 cnnMethodName =
"TMVA_CNN_GPU";
424 cnnOptions +=
":Architecture=CPU";
425 cnnMethodName =
"TMVA_CNN_CPU";
439 TString python_exe = tmva_python_exe.
IsNull() ?
"python" : tmva_python_exe;
443 Info(
"TMVA_CNN_Classification",
"Building convolutional keras model");
447 m.AddLine(
"import tensorflow");
448 m.AddLine(
"from tensorflow.keras.models import Sequential");
449 m.AddLine(
"from tensorflow.keras.optimizers import Adam");
451 "from tensorflow.keras.layers import Input, Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Reshape, BatchNormalization");
453 m.AddLine(
"model = Sequential() ");
454 m.AddLine(
"model.add(Reshape((16, 16, 1), input_shape = (256, )))");
455 m.AddLine(
"model.add(Conv2D(10, kernel_size = (3, 3), kernel_initializer = 'glorot_normal',activation = "
456 "'relu', padding = 'same'))");
457 m.AddLine(
"model.add(BatchNormalization())");
458 m.AddLine(
"model.add(Conv2D(10, kernel_size = (3, 3), kernel_initializer = 'glorot_normal',activation = "
459 "'relu', padding = 'same'))");
461 m.AddLine(
"model.add(MaxPooling2D(pool_size = (2, 2), strides = (1,1))) ");
462 m.AddLine(
"model.add(Flatten())");
463 m.AddLine(
"model.add(Dense(256, activation = 'relu')) ");
464 m.AddLine(
"model.add(Dense(2, activation = 'sigmoid')) ");
465 m.AddLine(
"model.compile(loss = 'binary_crossentropy', optimizer = Adam(learning_rate = 0.001), weighted_metrics = ['accuracy'])");
466 m.AddLine(
"model.save('model_cnn.h5')");
467 m.AddLine(
"model.summary()");
469 m.SaveSource(
"make_cnn_model.py");
474 Warning(
"TMVA_CNN_Classification",
"Error creating Keras model file - skip using Keras");
477 Info(
"TMVA_CNN_Classification",
"Booking tf.Keras CNN model");
480 "H:!V:VarTransform=None:FilenameModel=model_cnn.h5:tf.keras:"
481 "FilenameTrainedModel=trained_model_cnn.h5:NumEpochs=10:BatchSize=100:"
482 "GpuOptions=allow_growth=True");
488 Info(
"TMVA_CNN_Classification",
"Using Convolutional PyTorch Model");
489 TString pyTorchFileName =
gROOT->GetTutorialDir() +
TString(
"/tmva/PyTorch_Generate_CNN_Model.py");
493 Warning(
"TMVA_CNN_Classification",
"PyTorch is not installed or model building file is not existing - skip using PyTorch");
496 Info(
"TMVA_CNN_Classification",
"Booking PyTorch CNN model");
497 TString methodOpt =
"H:!V:VarTransform=None:FilenameModel=PyTorchModelCNN.pt:"
498 "FilenameTrainedModel=PyTorchTrainedModelCNN.pt:NumEpochs=10:BatchSize=100";
499 methodOpt +=
TString(
":UserCode=") + pyTorchFileName;
507 factory.TrainAllMethods();
511 factory.TestAllMethods();
513 factory.EvaluateAllMethods();
517 auto c1 = factory.GetROCCurve(&loader);
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Option_t Option_t TPoint TPoint const char x2
Option_t Option_t TPoint TPoint const char x1
R__EXTERN TRandom * gRandom
R__EXTERN TSystem * gSystem
A specialized string object used for TTree selections.
virtual void SetParameters(const Double_t *params)
virtual void SetParameter(Int_t param, Double_t value)
A 2-Dim function with parameters.
A ROOT file is a suite of consecutive data records (TKey instances) with a well defined format.
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.
void Close(Option_t *option="") override
Close a file.
void Reset(Option_t *option="") override
Reset.
virtual void FillRandom(const char *fname, Int_t ntimes=5000, TRandom *rng=nullptr)
Fill histogram following distribution in function fname.
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
2-D histogram with a double per channel (see TH1 documentation)}
This is the main MVA steering class.
static void PyInitialize()
Initialize Python interpreter.
Class supporting a collection of lines with C++ code.
virtual Double_t Gaus(Double_t mean=0, Double_t sigma=1)
Samples a random number from the standard Normal (Gaussian) Distribution with the given mean and sigm...
virtual void SetSeed(ULong_t seed=0)
Set the random generator seed.
virtual Double_t Uniform(Double_t x1=1)
Returns a uniform deviate on the interval (0, x1).
const char * Data() const
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
virtual Int_t Exec(const char *shellcmd)
Execute a command.
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
virtual void Setenv(const char *name, const char *value)
Set environment variable.
A TTree represents a columnar dataset.
virtual Long64_t GetEntries() const
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.
TString Python_Executable()
Function to find current Python executable used by ROOT If Python2 is installed return "python" Inste...