Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TMVAClassification.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_ml
3/// \notebook -nodraw
4/// This macro provides examples for the training and testing of the
5/// TMVA classifiers.
6///
7/// As input data is used a toy-MC sample consisting of four Gaussian-distributed
8/// and linearly correlated input variables.
9/// The methods to be used can be switched on and off by means of booleans, or
10/// via the prompt command, for example:
11///
12/// root -l ./TMVAClassification.C\‍(\"Fisher,Likelihood\"\‍)
13///
14/// (note that the backslashes are mandatory)
15/// If no method given, a default set of classifiers is used.
16/// The output file "TMVAC.root" can be analysed with the use of dedicated
17/// macros (simply say: root -l <macro.C>), which can be conveniently
18/// invoked through a GUI that will appear at the end of the run of this macro.
19/// Launch the GUI via the command:
20///
21/// root -l ./TMVAGui.C
22///
23/// You can also compile and run the example with the following commands
24///
25/// make
26/// ./TMVAClassification <Methods>
27///
28/// where: `<Methods> = "method1 method2"` are the TMVA classifier names
29/// example:
30///
31/// ./TMVAClassification Fisher LikelihoodPCA BDT
32///
33/// If no method given, a default set is of classifiers is used
34///
35/// - Project : TMVA - a ROOT-integrated toolkit for multivariate data analysis
36/// - Package : TMVA
37/// - Root Macro: TMVAClassification
38///
39/// \macro_output
40/// \macro_code
41/// \author Andreas Hoecker
42
43
44#include <cstdlib>
45#include <iostream>
46#include <map>
47#include <string>
48
49#include "TChain.h"
50#include "TFile.h"
51#include "TTree.h"
52#include "TString.h"
53#include "TObjString.h"
54#include "TSystem.h"
55#include "TROOT.h"
56
57#include "TMVA/Factory.h"
58#include "TMVA/DataLoader.h"
59#include "TMVA/Tools.h"
60#include "TMVA/TMVAGui.h"
61
62int TMVAClassification( TString myMethodList = "" )
63{
64 // The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
65 // if you use your private .rootrc, or run from a different directory, please copy the
66 // corresponding lines from .rootrc
67
68 // Methods to be processed can be given as an argument; use format:
69 //
70 // mylinux~> root -l TMVAClassification.C\‍(\"myMethod1,myMethod2,myMethod3\"\‍)
71
72 //---------------------------------------------------------------
73 // This loads the library
75
76 // Default MVA methods to be trained + tested
77 std::map<std::string,int> Use;
78
79 // Cut optimisation
80 Use["Cuts"] = 1;
81 Use["CutsD"] = 1;
82 Use["CutsPCA"] = 0;
83 Use["CutsGA"] = 0;
84 Use["CutsSA"] = 0;
85 //
86 // 1-dimensional likelihood ("naive Bayes estimator")
87 Use["Likelihood"] = 1;
88 Use["LikelihoodD"] = 0; // the "D" extension indicates decorrelated input variables (see option strings)
89 Use["LikelihoodPCA"] = 1; // the "PCA" extension indicates PCA-transformed input variables (see option strings)
90 Use["LikelihoodKDE"] = 0;
91 Use["LikelihoodMIX"] = 0;
92 //
93 // Mutidimensional likelihood and Nearest-Neighbour methods
94 Use["PDERS"] = 1;
95 Use["PDERSD"] = 0;
96 Use["PDERSPCA"] = 0;
97 Use["PDEFoam"] = 1;
98 Use["PDEFoamBoost"] = 0; // uses generalised MVA method boosting
99 Use["KNN"] = 1; // k-nearest neighbour method
100 //
101 // Linear Discriminant Analysis
102 Use["LD"] = 1; // Linear Discriminant identical to Fisher
103 Use["Fisher"] = 0;
104 Use["FisherG"] = 0;
105 Use["BoostedFisher"] = 0; // uses generalised MVA method boosting
106 Use["HMatrix"] = 0;
107 //
108 // Function Discriminant analysis
109 Use["FDA_GA"] = 1; // minimisation of user-defined function using Genetics Algorithm
110 Use["FDA_SA"] = 0;
111 Use["FDA_MC"] = 0;
112 Use["FDA_MT"] = 0;
113 Use["FDA_GAMT"] = 0;
114 Use["FDA_MCMT"] = 0;
115 //
116 // Neural Networks (all are feed-forward Multilayer Perceptrons)
117 Use["MLP"] = 0; // Recommended ANN
118 Use["MLPBFGS"] = 0; // Recommended ANN with optional training method
119 Use["MLPBNN"] = 1; // Recommended ANN with BFGS training method and bayesian regulator
120 Use["CFMlpANN"] = 0; // Depreciated ANN from ALEPH
121 Use["TMlpANN"] = 0; // ROOT's own ANN
122#ifdef R__HAS_TMVAGPU
123 Use["DNN_GPU"] = 1; // CUDA-accelerated DNN training.
124#else
125 Use["DNN_GPU"] = 0;
126#endif
127
128#ifdef R__HAS_TMVACPU
129 Use["DNN_CPU"] = 1; // Multi-core accelerated DNN.
130#else
131 Use["DNN_CPU"] = 0;
132#endif
133 //
134 // Support Vector Machine
135 Use["SVM"] = 1;
136 //
137 // Boosted Decision Trees
138 Use["BDT"] = 1; // uses Adaptive Boost
139 Use["BDTG"] = 0; // uses Gradient Boost
140 Use["BDTB"] = 0; // uses Bagging
141 Use["BDTD"] = 0; // decorrelation + Adaptive Boost
142 Use["BDTF"] = 0; // allow usage of fisher discriminant for node splitting
143 //
144 // Friedman's RuleFit method, ie, an optimised series of cuts ("rules")
145 Use["RuleFit"] = 1;
146 // ---------------------------------------------------------------
147
148 std::cout << std::endl;
149 std::cout << "==> Start TMVAClassification" << std::endl;
150
151 // Select methods (don't look at this code - not of interest)
152 if (myMethodList != "") {
153 for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
154
155 std::vector<TString> mlist = TMVA::gTools().SplitString( myMethodList, ',' );
156 for (UInt_t i=0; i<mlist.size(); i++) {
157 std::string regMethod(mlist[i]);
158
159 if (Use.find(regMethod) == Use.end()) {
160 std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
161 for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
162 std::cout << std::endl;
163 return 1;
164 }
165 Use[regMethod] = 1;
166 }
167 }
168
169 // --------------------------------------------------------------------------------------------------
170
171 // Here the preparation phase begins
172
173 // Read training and test data
174 // (it is also possible to use ASCII format as input -> see TMVA Users Guide)
175 // Set the cache directory for the TFile to the current directory. The input
176 // data file will be downloaded here if not present yet, then it will be read
177 // from the cache path directly.
179 std::unique_ptr<TFile> input{TFile::Open("http://root.cern/files/tmva_class_example.root", "CACHEREAD")};
180 if (!input || input->IsZombie()) {
181 throw std::runtime_error("ERROR: could not open data file");
182 }
183 std::cout << "--- TMVAClassification : Using input file: " << input->GetName() << std::endl;
184
185 // Register the training and test trees
186
187 TTree *signalTree = (TTree*)input->Get("TreeS");
188 TTree *background = (TTree*)input->Get("TreeB");
189
190 // Create a ROOT output file where TMVA will store ntuples, histograms, etc.
191 TString outfileName("TMVAC.root");
192 std::unique_ptr<TFile> outputFile{TFile::Open(outfileName, "RECREATE")};
193 if (!outputFile || outputFile->IsZombie()) {
194 throw std::runtime_error("ERROR: could not open output file");
195 }
196
197 // Create the factory object. Later you can choose the methods
198 // whose performance you'd like to investigate. The factory is
199 // the only TMVA object you have to interact with
200 //
201 // The first argument is the base of the name of all the
202 // weightfiles in the directory weight/
203 //
204 // The second argument is the output file for the training results
205 // All TMVA output can be suppressed by removing the "!" (not) in
206 // front of the "Silent" argument in the option string
207 auto factory = std::make_unique<TMVA::Factory>(
208 "TMVAClassification", outputFile.get(),
209 "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification");
210 auto dataloader_raii = std::make_unique<TMVA::DataLoader>("dataset");
211 auto *dataloader = dataloader_raii.get();
212 // If you wish to modify default settings
213 // (please check "src/Config.h" to see all available global options)
214 //
215 // (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
216 // (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
217
218 // Define the input variables that shall be used for the MVA training
219 // note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
220 // [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
221 dataloader->AddVariable( "myvar1 := var1+var2", 'F' );
222 dataloader->AddVariable( "myvar2 := var1-var2", "Expression 2", "", 'F' );
223 dataloader->AddVariable( "var3", "Variable 3", "units", 'F' );
224 dataloader->AddVariable( "var4", "Variable 4", "units", 'F' );
225
226 // You can add so-called "Spectator variables", which are not used in the MVA training,
227 // but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
228 // input variables, the response values of all trained MVAs, and the spectator variables
229
230 dataloader->AddSpectator( "spec1 := var1*2", "Spectator 1", "units", 'F' );
231 dataloader->AddSpectator( "spec2 := var1*3", "Spectator 2", "units", 'F' );
232
233
234 // global event weights per tree (see below for setting event-wise weights)
235 Double_t signalWeight = 1.0;
236 Double_t backgroundWeight = 1.0;
237
238 // You can add an arbitrary number of signal or background trees
239 dataloader->AddSignalTree ( signalTree, signalWeight );
240 dataloader->AddBackgroundTree( background, backgroundWeight );
241
242 // To give different trees for training and testing, do as follows:
243 //
244 // dataloader->AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" );
245 // dataloader->AddSignalTree( signalTestTree, signalTestWeight, "Test" );
246
247 // Use the following code instead of the above two or four lines to add signal and background
248 // training and test events "by hand"
249 // NOTE that in this case one should not give expressions (such as "var1+var2") in the input
250 // variable definition, but simply compute the expression before adding the event
251 // ```cpp
252 // // --- begin ----------------------------------------------------------
253 // std::vector<Double_t> vars( 4 ); // vector has size of number of input variables
254 // Float_t treevars[4], weight;
255 //
256 // // Signal
257 // for (UInt_t ivar=0; ivar<4; ivar++) signalTree->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
258 // for (UInt_t i=0; i<signalTree->GetEntries(); i++) {
259 // signalTree->GetEntry(i);
260 // for (UInt_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
261 // // add training and test events; here: first half is training, second is testing
262 // // note that the weight can also be event-wise
263 // if (i < signalTree->GetEntries()/2.0) dataloader->AddSignalTrainingEvent( vars, signalWeight );
264 // else dataloader->AddSignalTestEvent ( vars, signalWeight );
265 // }
266 //
267 // // Background (has event weights)
268 // background->SetBranchAddress( "weight", &weight );
269 // for (UInt_t ivar=0; ivar<4; ivar++) background->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
270 // for (UInt_t i=0; i<background->GetEntries(); i++) {
271 // background->GetEntry(i);
272 // for (UInt_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
273 // // add training and test events; here: first half is training, second is testing
274 // // note that the weight can also be event-wise
275 // if (i < background->GetEntries()/2) dataloader->AddBackgroundTrainingEvent( vars, backgroundWeight*weight );
276 // else dataloader->AddBackgroundTestEvent ( vars, backgroundWeight*weight );
277 // }
278 // // --- end ------------------------------------------------------------
279 // ```
280 // End of tree registration
281
282 // Set individual event weights (the variables must exist in the original TTree)
283 // - for signal : `dataloader->SetSignalWeightExpression ("weight1*weight2");`
284 // - for background: `dataloader->SetBackgroundWeightExpression("weight1*weight2");`
285 dataloader->SetBackgroundWeightExpression( "weight" );
286
287 // Apply additional cuts on the signal and background samples (can be different)
288 TCut mycuts = ""; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
289 TCut mycutb = ""; // for example: TCut mycutb = "abs(var1)<0.5";
290
291 // Tell the dataloader how to use the training and testing events
292 //
293 // If no numbers of events are given, half of the events in the tree are used
294 // for training, and the other half for testing:
295 //
296 // dataloader->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
297 //
298 // To also specify the number of testing events, use:
299 //
300 // dataloader->PrepareTrainingAndTestTree( mycut,
301 // "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" );
302 dataloader->PrepareTrainingAndTestTree( mycuts, mycutb,
303 "nTrain_Signal=1000:nTrain_Background=1000:SplitMode=Random:NormMode=NumEvents:!V" );
304
305 // ### Book MVA methods
306 //
307 // Please lookup the various method configuration options in the corresponding cxx files, eg:
308 // src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/old_site/optionRef.html
309 // it is possible to preset ranges in the option string in which the cut optimisation should be done:
310 // "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable
311
312 // Cut optimisation
313 if (Use["Cuts"])
314 factory->BookMethod( dataloader, TMVA::Types::kCuts, "Cuts",
315 "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" );
316
317 if (Use["CutsD"])
318 factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsD",
319 "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" );
320
321 if (Use["CutsPCA"])
322 factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsPCA",
323 "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=PCA" );
324
325 if (Use["CutsGA"])
326 factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsGA",
327 "H:!V:FitMethod=GA:CutRangeMin[0]=-10:CutRangeMax[0]=10:VarProp[1]=FMax:EffSel:Steps=30:Cycles=3:PopSize=400:SC_steps=10:SC_rate=5:SC_factor=0.95" );
328
329 if (Use["CutsSA"])
330 factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsSA",
331 "!H:!V:FitMethod=SA:EffSel:MaxCalls=150000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );
332
333 // Likelihood ("naive Bayes estimator")
334 if (Use["Likelihood"])
335 factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "Likelihood",
336 "H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" );
337
338 // Decorrelated likelihood
339 if (Use["LikelihoodD"])
340 factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodD",
341 "!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=Decorrelate" );
342
343 // PCA-transformed likelihood
344 if (Use["LikelihoodPCA"])
345 factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodPCA",
346 "!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=PCA" );
347
348 // Use a kernel density estimator to approximate the PDFs
349 if (Use["LikelihoodKDE"])
350 factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodKDE",
351 "!H:!V:!TransformOutput:PDFInterpol=KDE:KDEtype=Gauss:KDEiter=Adaptive:KDEFineFactor=0.3:KDEborder=None:NAvEvtPerBin=50" );
352
353 // Use a variable-dependent mix of splines and kernel density estimator
354 if (Use["LikelihoodMIX"])
355 factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodMIX",
356 "!H:!V:!TransformOutput:PDFInterpolSig[0]=KDE:PDFInterpolBkg[0]=KDE:PDFInterpolSig[1]=KDE:PDFInterpolBkg[1]=KDE:PDFInterpolSig[2]=Spline2:PDFInterpolBkg[2]=Spline2:PDFInterpolSig[3]=Spline2:PDFInterpolBkg[3]=Spline2:KDEtype=Gauss:KDEiter=Nonadaptive:KDEborder=None:NAvEvtPerBin=50" );
357
358 // Test the multi-dimensional probability density estimator
359 // here are the options strings for the MinMax and RMS methods, respectively:
360 //
361 // "!H:!V:VolumeRangeMode=MinMax:DeltaFrac=0.2:KernelEstimator=Gauss:GaussSigma=0.3" );
362 // "!H:!V:VolumeRangeMode=RMS:DeltaFrac=3:KernelEstimator=Gauss:GaussSigma=0.3" );
363 if (Use["PDERS"])
364 factory->BookMethod( dataloader, TMVA::Types::kPDERS, "PDERS",
365 "!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" );
366
367 if (Use["PDERSD"])
368 factory->BookMethod( dataloader, TMVA::Types::kPDERS, "PDERSD",
369 "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=Decorrelate" );
370
371 if (Use["PDERSPCA"])
372 factory->BookMethod( dataloader, TMVA::Types::kPDERS, "PDERSPCA",
373 "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=PCA" );
374
375 // Multi-dimensional likelihood estimator using self-adapting phase-space binning
376 if (Use["PDEFoam"])
377 factory->BookMethod( dataloader, TMVA::Types::kPDEFoam, "PDEFoam",
378 "!H:!V:SigBgSeparate=F:TailCut=0.001:VolFrac=0.0666:nActiveCells=500:nSampl=2000:nBin=5:Nmin=100:Kernel=None:Compress=T" );
379
380 if (Use["PDEFoamBoost"])
381 factory->BookMethod( dataloader, TMVA::Types::kPDEFoam, "PDEFoamBoost",
382 "!H:!V:Boost_Num=30:Boost_Transform=linear:SigBgSeparate=F:MaxDepth=4:UseYesNoCell=T:DTLogic=MisClassificationError:FillFoamWithOrigWeights=F:TailCut=0:nActiveCells=500:nBin=20:Nmin=400:Kernel=None:Compress=T" );
383
384 // K-Nearest Neighbour classifier (KNN)
385 if (Use["KNN"])
386 factory->BookMethod( dataloader, TMVA::Types::kKNN, "KNN",
387 "H:nkNN=20:ScaleFrac=0.8:SigmaFact=1.0:Kernel=Gaus:UseKernel=F:UseWeight=T:!Trim" );
388
389 // H-Matrix (chi2-squared) method
390 if (Use["HMatrix"])
391 factory->BookMethod( dataloader, TMVA::Types::kHMatrix, "HMatrix", "!H:!V:VarTransform=None" );
392
393 // Linear discriminant (same as Fisher discriminant)
394 if (Use["LD"])
395 factory->BookMethod( dataloader, TMVA::Types::kLD, "LD", "H:!V:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
396
397 // Fisher discriminant (same as LD)
398 if (Use["Fisher"])
399 factory->BookMethod( dataloader, TMVA::Types::kFisher, "Fisher", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
400
401 // Fisher with Gauss-transformed input variables
402 if (Use["FisherG"])
403 factory->BookMethod( dataloader, TMVA::Types::kFisher, "FisherG", "H:!V:VarTransform=Gauss" );
404
405 // Composite classifier: ensemble (tree) of boosted Fisher classifiers
406 if (Use["BoostedFisher"])
407 factory->BookMethod( dataloader, TMVA::Types::kFisher, "BoostedFisher",
408 "H:!V:Boost_Num=20:Boost_Transform=log:Boost_Type=AdaBoost:Boost_AdaBoostBeta=0.2:!Boost_DetailedMonitoring" );
409
410 // Function discrimination analysis (FDA) -- test of various fitters - the recommended one is Minuit (or GA or SA)
411 if (Use["FDA_MC"])
412 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MC",
413 "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:SampleSize=100000:Sigma=0.1" );
414
415 if (Use["FDA_GA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
416 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_GA",
417 "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:PopSize=100:Cycles=2:Steps=5:Trim=True:SaveBestGen=1" );
418
419 if (Use["FDA_SA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
420 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_SA",
421 "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=SA:MaxCalls=15000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );
422
423 if (Use["FDA_MT"])
424 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MT",
425 "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=2:UseImprove:UseMinos:SetBatch" );
426
427 if (Use["FDA_GAMT"])
428 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_GAMT",
429 "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:Cycles=1:PopSize=5:Steps=5:Trim" );
430
431 if (Use["FDA_MCMT"])
432 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MCMT",
433 "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:SampleSize=20" );
434
435 // TMVA ANN: MLP (recommended ANN) -- all ANNs in TMVA are Multilayer Perceptrons
436 if (Use["MLP"])
437 factory->BookMethod( dataloader, TMVA::Types::kMLP, "MLP", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:!UseRegulator" );
438
439 if (Use["MLPBFGS"])
440 factory->BookMethod( dataloader, TMVA::Types::kMLP, "MLPBFGS", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:!UseRegulator" );
441
442 if (Use["MLPBNN"])
443 factory->BookMethod( dataloader, TMVA::Types::kMLP, "MLPBNN", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=60:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:UseRegulator" ); // BFGS training with bayesian regulators
444
445
446 // Multi-architecture DNN implementation.
447 if (Use["DNN_CPU"] or Use["DNN_GPU"]) {
448 // General layout.
449 TString layoutString ("Layout=TANH|128,TANH|128,TANH|128,LINEAR");
450
451 // Define Training strategy. One could define multiple strategy string separated by the "|" delimiter
452
453 TString trainingStrategyString = ("TrainingStrategy=LearningRate=1e-2,Momentum=0.9,"
454 "ConvergenceSteps=20,BatchSize=100,TestRepetitions=1,"
455 "WeightDecay=1e-4,Regularization=None,"
456 "DropConfig=0.0+0.5+0.5+0.5");
457
458 // General Options.
459 TString dnnOptions ("!H:V:ErrorStrategy=CROSSENTROPY:VarTransform=N:"
460 "WeightInitialization=XAVIERUNIFORM");
461 dnnOptions.Append (":"); dnnOptions.Append (layoutString);
462 dnnOptions.Append (":"); dnnOptions.Append (trainingStrategyString);
463
464 // Cuda implementation.
465 if (Use["DNN_GPU"]) {
466 TString gpuOptions = dnnOptions + ":Architecture=GPU";
467 factory->BookMethod(dataloader, TMVA::Types::kDL, "DNN_GPU", gpuOptions);
468 }
469 // Multi-core CPU implementation.
470 if (Use["DNN_CPU"]) {
471 TString cpuOptions = dnnOptions + ":Architecture=CPU";
472 factory->BookMethod(dataloader, TMVA::Types::kDL, "DNN_CPU", cpuOptions);
473 }
474 }
475
476 // CF(Clermont-Ferrand)ANN
477 if (Use["CFMlpANN"])
478 factory->BookMethod( dataloader, TMVA::Types::kCFMlpANN, "CFMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N" ); // n_cycles:#nodes:#nodes:...
479
480 // Tmlp(Root)ANN
481 if (Use["TMlpANN"])
482 factory->BookMethod( dataloader, TMVA::Types::kTMlpANN, "TMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N:LearningMethod=BFGS:ValidationFraction=0.3" ); // n_cycles:#nodes:#nodes:...
483
484 // Support Vector Machine
485 if (Use["SVM"])
486 factory->BookMethod( dataloader, TMVA::Types::kSVM, "SVM", "Gamma=0.25:Tol=0.001:VarTransform=Norm" );
487
488 // Boosted Decision Trees
489 if (Use["BDTG"]) // Gradient Boost
490 factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTG",
491 "!H:!V:NTrees=1000:MinNodeSize=2.5%:BoostType=Grad:Shrinkage=0.10:UseBaggedBoost:BaggedSampleFraction=0.5:nCuts=20:MaxDepth=2" );
492
493 if (Use["BDT"]) // Adaptive Boost
494 factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDT",
495 "!H:!V:NTrees=850:MinNodeSize=2.5%:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex:nCuts=20" );
496
497 if (Use["BDTB"]) // Bagging
498 factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTB",
499 "!H:!V:NTrees=400:BoostType=Bagging:SeparationType=GiniIndex:nCuts=20" );
500
501 if (Use["BDTD"]) // Decorrelation + Adaptive Boost
502 factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTD",
503 "!H:!V:NTrees=400:MinNodeSize=5%:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:VarTransform=Decorrelate" );
504
505 if (Use["BDTF"]) // Allow Using Fisher discriminant in node splitting for (strong) linearly correlated variables
506 factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTF",
507 "!H:!V:NTrees=50:MinNodeSize=2.5%:UseFisherCuts:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=20" );
508
509 // RuleFit -- TMVA implementation of Friedman's method
510 if (Use["RuleFit"])
511 factory->BookMethod( dataloader, TMVA::Types::kRuleFit, "RuleFit",
512 "H:!V:RuleFitModule=RFTMVA:Model=ModRuleLinear:MinImp=0.001:RuleMinDist=0.001:NTrees=20:fEventsMin=0.01:fEventsMax=0.5:GDTau=-1.0:GDTauPrec=0.01:GDStep=0.01:GDNSteps=10000:GDErrScale=1.02" );
513
514 // For an example of the category classifier usage, see: TMVAClassificationCategory
515 //
516 // --------------------------------------------------------------------------------------------------
517 // Now you can optimize the setting (configuration) of the MVAs using the set of training events
518 // STILL EXPERIMENTAL and only implemented for BDT's !
519 //
520 // factory->OptimizeAllMethods("SigEffAtBkg0.01","Scan");
521 // factory->OptimizeAllMethods("ROCIntegral","FitGA");
522 //
523 // --------------------------------------------------------------------------------------------------
524
525 // Now you can tell the factory to train, test, and evaluate the MVAs
526 //
527 // Train MVAs using the set of training events
528 factory->TrainAllMethods();
529
530 // Evaluate all MVAs using the set of test events
531 factory->TestAllMethods();
532
533 // Evaluate and compare performance of all configured MVAs
534 factory->EvaluateAllMethods();
535
536 // --------------------------------------------------------------
537
538 // Save the output
539 outputFile->Write();
540
541 std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
542 std::cout << "==> TMVAClassification is done!" << std::endl;
543
544 // Launch the GUI for the root macros
545 if (!gROOT->IsBatch()) TMVA::TMVAGui( outfileName );
546
547 return 0;
548}
549
550int main( int argc, char** argv )
551{
552 // Select methods (don't look at this code - not of interest)
553 TString methodList;
554 for (int i=1; i<argc; i++) {
555 TString regMethod(argv[i]);
556 if(regMethod=="-b" || regMethod=="--batch") continue;
557 if (!methodList.IsNull()) methodList += TString(",");
558 methodList += regMethod;
559 }
560 return TMVAClassification(methodList);
561}
int main()
Definition Prototype.cxx:12
unsigned int UInt_t
Definition RtypesCore.h:46
double Double_t
Definition RtypesCore.h:59
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
#define gROOT
Definition TROOT.h:406
A specialized string object used for TTree selections.
Definition TCut.h:25
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.
Definition TFile.cxx:4086
static Bool_t SetCacheFileDir(std::string_view cacheDir, Bool_t operateDisconnected=kTRUE, Bool_t forceCacheread=kFALSE)
Sets the directory where to locally stage/cache remote files.
Definition TFile.cxx:4623
static Tools & Instance()
Definition Tools.cxx:71
std::vector< TString > SplitString(const TString &theOpt, const char separator) const
splits the option string at 'separator' and fills the list 'splitV' with the primitive strings
Definition Tools.cxx:1199
@ kFisher
Definition Types.h:82
@ kTMlpANN
Definition Types.h:85
@ kPDEFoam
Definition Types.h:94
@ kLikelihood
Definition Types.h:79
@ kHMatrix
Definition Types.h:81
@ kRuleFit
Definition Types.h:88
@ kCFMlpANN
Definition Types.h:84
Basic string class.
Definition TString.h:139
Bool_t IsNull() const
Definition TString.h:414
A TTree represents a columnar dataset.
Definition TTree.h:79
Tools & gTools()
void TMVAGui(const char *fName="TMVA.root", TString dataset="")