Logo ROOT   6.12/07
Reference Guide
TMVAClassification.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_tmva
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 "TMVA.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 
62 int 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  Use["DNN_GPU"] = 0; // CUDA-accelerated DNN training.
123  Use["DNN_CPU"] = 0; // Multi-core accelerated DNN.
124  //
125  // Support Vector Machine
126  Use["SVM"] = 1;
127  //
128  // Boosted Decision Trees
129  Use["BDT"] = 1; // uses Adaptive Boost
130  Use["BDTG"] = 0; // uses Gradient Boost
131  Use["BDTB"] = 0; // uses Bagging
132  Use["BDTD"] = 0; // decorrelation + Adaptive Boost
133  Use["BDTF"] = 0; // allow usage of fisher discriminant for node splitting
134  //
135  // Friedman's RuleFit method, ie, an optimised series of cuts ("rules")
136  Use["RuleFit"] = 1;
137  // ---------------------------------------------------------------
138 
139  std::cout << std::endl;
140  std::cout << "==> Start TMVAClassification" << std::endl;
141 
142  // Select methods (don't look at this code - not of interest)
143  if (myMethodList != "") {
144  for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
145 
146  std::vector<TString> mlist = TMVA::gTools().SplitString( myMethodList, ',' );
147  for (UInt_t i=0; i<mlist.size(); i++) {
148  std::string regMethod(mlist[i]);
149 
150  if (Use.find(regMethod) == Use.end()) {
151  std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
152  for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
153  std::cout << std::endl;
154  return 1;
155  }
156  Use[regMethod] = 1;
157  }
158  }
159 
160  // --------------------------------------------------------------------------------------------------
161 
162  // Here the preparation phase begins
163 
164  // Read training and test data
165  // (it is also possible to use ASCII format as input -> see TMVA Users Guide)
166  TFile *input(0);
167  TString fname = "./tmva_class_example.root";
168  if (!gSystem->AccessPathName( fname )) {
169  input = TFile::Open( fname ); // check if file in local directory exists
170  }
171  else {
173  input = TFile::Open("http://root.cern.ch/files/tmva_class_example.root", "CACHEREAD");
174  }
175  if (!input) {
176  std::cout << "ERROR: could not open data file" << std::endl;
177  exit(1);
178  }
179  std::cout << "--- TMVAClassification : Using input file: " << input->GetName() << std::endl;
180 
181  // Register the training and test trees
182 
183  TTree *signalTree = (TTree*)input->Get("TreeS");
184  TTree *background = (TTree*)input->Get("TreeB");
185 
186  // Create a ROOT output file where TMVA will store ntuples, histograms, etc.
187  TString outfileName( "TMVA.root" );
188  TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
189 
190  // Create the factory object. Later you can choose the methods
191  // whose performance you'd like to investigate. The factory is
192  // the only TMVA object you have to interact with
193  //
194  // The first argument is the base of the name of all the
195  // weightfiles in the directory weight/
196  //
197  // The second argument is the output file for the training results
198  // All TMVA output can be suppressed by removing the "!" (not) in
199  // front of the "Silent" argument in the option string
200  TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
201  "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
202 
204  // If you wish to modify default settings
205  // (please check "src/Config.h" to see all available global options)
206  //
207  // (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
208  // (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
209 
210  // Define the input variables that shall be used for the MVA training
211  // note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
212  // [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
213  dataloader->AddVariable( "myvar1 := var1+var2", 'F' );
214  dataloader->AddVariable( "myvar2 := var1-var2", "Expression 2", "", 'F' );
215  dataloader->AddVariable( "var3", "Variable 3", "units", 'F' );
216  dataloader->AddVariable( "var4", "Variable 4", "units", 'F' );
217 
218  // You can add so-called "Spectator variables", which are not used in the MVA training,
219  // but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
220  // input variables, the response values of all trained MVAs, and the spectator variables
221 
222  dataloader->AddSpectator( "spec1 := var1*2", "Spectator 1", "units", 'F' );
223  dataloader->AddSpectator( "spec2 := var1*3", "Spectator 2", "units", 'F' );
224 
225 
226  // global event weights per tree (see below for setting event-wise weights)
227  Double_t signalWeight = 1.0;
228  Double_t backgroundWeight = 1.0;
229 
230  // You can add an arbitrary number of signal or background trees
231  dataloader->AddSignalTree ( signalTree, signalWeight );
232  dataloader->AddBackgroundTree( background, backgroundWeight );
233 
234  // To give different trees for training and testing, do as follows:
235  //
236  // dataloader->AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" );
237  // dataloader->AddSignalTree( signalTestTree, signalTestWeight, "Test" );
238 
239  // Use the following code instead of the above two or four lines to add signal and background
240  // training and test events "by hand"
241  // NOTE that in this case one should not give expressions (such as "var1+var2") in the input
242  // variable definition, but simply compute the expression before adding the event
243  // ```cpp
244  // // --- begin ----------------------------------------------------------
245  // std::vector<Double_t> vars( 4 ); // vector has size of number of input variables
246  // Float_t treevars[4], weight;
247  //
248  // // Signal
249  // for (UInt_t ivar=0; ivar<4; ivar++) signalTree->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
250  // for (UInt_t i=0; i<signalTree->GetEntries(); i++) {
251  // signalTree->GetEntry(i);
252  // for (UInt_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
253  // // add training and test events; here: first half is training, second is testing
254  // // note that the weight can also be event-wise
255  // if (i < signalTree->GetEntries()/2.0) dataloader->AddSignalTrainingEvent( vars, signalWeight );
256  // else dataloader->AddSignalTestEvent ( vars, signalWeight );
257  // }
258  //
259  // // Background (has event weights)
260  // background->SetBranchAddress( "weight", &weight );
261  // for (UInt_t ivar=0; ivar<4; ivar++) background->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
262  // for (UInt_t i=0; i<background->GetEntries(); i++) {
263  // background->GetEntry(i);
264  // for (UInt_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
265  // // add training and test events; here: first half is training, second is testing
266  // // note that the weight can also be event-wise
267  // if (i < background->GetEntries()/2) dataloader->AddBackgroundTrainingEvent( vars, backgroundWeight*weight );
268  // else dataloader->AddBackgroundTestEvent ( vars, backgroundWeight*weight );
269  // }
270  // // --- end ------------------------------------------------------------
271  // ```
272  // End of tree registration
273 
274  // Set individual event weights (the variables must exist in the original TTree)
275  // - for signal : `dataloader->SetSignalWeightExpression ("weight1*weight2");`
276  // - for background: `dataloader->SetBackgroundWeightExpression("weight1*weight2");`
277  dataloader->SetBackgroundWeightExpression( "weight" );
278 
279  // Apply additional cuts on the signal and background samples (can be different)
280  TCut mycuts = ""; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
281  TCut mycutb = ""; // for example: TCut mycutb = "abs(var1)<0.5";
282 
283  // Tell the dataloader how to use the training and testing events
284  //
285  // If no numbers of events are given, half of the events in the tree are used
286  // for training, and the other half for testing:
287  //
288  // dataloader->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
289  //
290  // To also specify the number of testing events, use:
291  //
292  // dataloader->PrepareTrainingAndTestTree( mycut,
293  // "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" );
294  dataloader->PrepareTrainingAndTestTree( mycuts, mycutb,
295  "nTrain_Signal=1000:nTrain_Background=1000:SplitMode=Random:NormMode=NumEvents:!V" );
296 
297  // ### Book MVA methods
298  //
299  // Please lookup the various method configuration options in the corresponding cxx files, eg:
300  // src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/optionRef.html
301  // it is possible to preset ranges in the option string in which the cut optimisation should be done:
302  // "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable
303 
304  // Cut optimisation
305  if (Use["Cuts"])
306  factory->BookMethod( dataloader, TMVA::Types::kCuts, "Cuts",
307  "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" );
308 
309  if (Use["CutsD"])
310  factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsD",
311  "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" );
312 
313  if (Use["CutsPCA"])
314  factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsPCA",
315  "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=PCA" );
316 
317  if (Use["CutsGA"])
318  factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsGA",
319  "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" );
320 
321  if (Use["CutsSA"])
322  factory->BookMethod( dataloader, TMVA::Types::kCuts, "CutsSA",
323  "!H:!V:FitMethod=SA:EffSel:MaxCalls=150000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );
324 
325  // Likelihood ("naive Bayes estimator")
326  if (Use["Likelihood"])
327  factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "Likelihood",
328  "H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" );
329 
330  // Decorrelated likelihood
331  if (Use["LikelihoodD"])
332  factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodD",
333  "!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=Decorrelate" );
334 
335  // PCA-transformed likelihood
336  if (Use["LikelihoodPCA"])
337  factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodPCA",
338  "!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=PCA" );
339 
340  // Use a kernel density estimator to approximate the PDFs
341  if (Use["LikelihoodKDE"])
342  factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodKDE",
343  "!H:!V:!TransformOutput:PDFInterpol=KDE:KDEtype=Gauss:KDEiter=Adaptive:KDEFineFactor=0.3:KDEborder=None:NAvEvtPerBin=50" );
344 
345  // Use a variable-dependent mix of splines and kernel density estimator
346  if (Use["LikelihoodMIX"])
347  factory->BookMethod( dataloader, TMVA::Types::kLikelihood, "LikelihoodMIX",
348  "!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" );
349 
350  // Test the multi-dimensional probability density estimator
351  // here are the options strings for the MinMax and RMS methods, respectively:
352  //
353  // "!H:!V:VolumeRangeMode=MinMax:DeltaFrac=0.2:KernelEstimator=Gauss:GaussSigma=0.3" );
354  // "!H:!V:VolumeRangeMode=RMS:DeltaFrac=3:KernelEstimator=Gauss:GaussSigma=0.3" );
355  if (Use["PDERS"])
356  factory->BookMethod( dataloader, TMVA::Types::kPDERS, "PDERS",
357  "!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" );
358 
359  if (Use["PDERSD"])
360  factory->BookMethod( dataloader, TMVA::Types::kPDERS, "PDERSD",
361  "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=Decorrelate" );
362 
363  if (Use["PDERSPCA"])
364  factory->BookMethod( dataloader, TMVA::Types::kPDERS, "PDERSPCA",
365  "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=PCA" );
366 
367  // Multi-dimensional likelihood estimator using self-adapting phase-space binning
368  if (Use["PDEFoam"])
369  factory->BookMethod( dataloader, TMVA::Types::kPDEFoam, "PDEFoam",
370  "!H:!V:SigBgSeparate=F:TailCut=0.001:VolFrac=0.0666:nActiveCells=500:nSampl=2000:nBin=5:Nmin=100:Kernel=None:Compress=T" );
371 
372  if (Use["PDEFoamBoost"])
373  factory->BookMethod( dataloader, TMVA::Types::kPDEFoam, "PDEFoamBoost",
374  "!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" );
375 
376  // K-Nearest Neighbour classifier (KNN)
377  if (Use["KNN"])
378  factory->BookMethod( dataloader, TMVA::Types::kKNN, "KNN",
379  "H:nkNN=20:ScaleFrac=0.8:SigmaFact=1.0:Kernel=Gaus:UseKernel=F:UseWeight=T:!Trim" );
380 
381  // H-Matrix (chi2-squared) method
382  if (Use["HMatrix"])
383  factory->BookMethod( dataloader, TMVA::Types::kHMatrix, "HMatrix", "!H:!V:VarTransform=None" );
384 
385  // Linear discriminant (same as Fisher discriminant)
386  if (Use["LD"])
387  factory->BookMethod( dataloader, TMVA::Types::kLD, "LD", "H:!V:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
388 
389  // Fisher discriminant (same as LD)
390  if (Use["Fisher"])
391  factory->BookMethod( dataloader, TMVA::Types::kFisher, "Fisher", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
392 
393  // Fisher with Gauss-transformed input variables
394  if (Use["FisherG"])
395  factory->BookMethod( dataloader, TMVA::Types::kFisher, "FisherG", "H:!V:VarTransform=Gauss" );
396 
397  // Composite classifier: ensemble (tree) of boosted Fisher classifiers
398  if (Use["BoostedFisher"])
399  factory->BookMethod( dataloader, TMVA::Types::kFisher, "BoostedFisher",
400  "H:!V:Boost_Num=20:Boost_Transform=log:Boost_Type=AdaBoost:Boost_AdaBoostBeta=0.2:!Boost_DetailedMonitoring" );
401 
402  // Function discrimination analysis (FDA) -- test of various fitters - the recommended one is Minuit (or GA or SA)
403  if (Use["FDA_MC"])
404  factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MC",
405  "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" );
406 
407  if (Use["FDA_GA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
408  factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_GA",
409  "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" );
410 
411  if (Use["FDA_SA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
412  factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_SA",
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=SA:MaxCalls=15000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );
414 
415  if (Use["FDA_MT"])
416  factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MT",
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=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=2:UseImprove:UseMinos:SetBatch" );
418 
419  if (Use["FDA_GAMT"])
420  factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_GAMT",
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=GA:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:Cycles=1:PopSize=5:Steps=5:Trim" );
422 
423  if (Use["FDA_MCMT"])
424  factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MCMT",
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=MC:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:SampleSize=20" );
426 
427  // TMVA ANN: MLP (recommended ANN) -- all ANNs in TMVA are Multilayer Perceptrons
428  if (Use["MLP"])
429  factory->BookMethod( dataloader, TMVA::Types::kMLP, "MLP", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:!UseRegulator" );
430 
431  if (Use["MLPBFGS"])
432  factory->BookMethod( dataloader, TMVA::Types::kMLP, "MLPBFGS", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:!UseRegulator" );
433 
434  if (Use["MLPBNN"])
435  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
436 
437 
438  // Multi-architecture DNN implementation.
439  if (Use["DNN_CPU"] or Use["DNN_GPU"]) {
440  // General layout.
441  TString layoutString ("Layout=TANH|128,TANH|128,TANH|128,LINEAR");
442 
443  // Training strategies.
444  TString training0("LearningRate=1e-1,Momentum=0.9,Repetitions=1,"
445  "ConvergenceSteps=20,BatchSize=256,TestRepetitions=10,"
446  "WeightDecay=1e-4,Regularization=L2,"
447  "DropConfig=0.0+0.5+0.5+0.5, Multithreading=True");
448  TString training1("LearningRate=1e-2,Momentum=0.9,Repetitions=1,"
449  "ConvergenceSteps=20,BatchSize=256,TestRepetitions=10,"
450  "WeightDecay=1e-4,Regularization=L2,"
451  "DropConfig=0.0+0.0+0.0+0.0, Multithreading=True");
452  TString training2("LearningRate=1e-3,Momentum=0.0,Repetitions=1,"
453  "ConvergenceSteps=20,BatchSize=256,TestRepetitions=10,"
454  "WeightDecay=1e-4,Regularization=L2,"
455  "DropConfig=0.0+0.0+0.0+0.0, Multithreading=True");
456  TString trainingStrategyString ("TrainingStrategy=");
457  trainingStrategyString += training0 + "|" + training1 + "|" + training2;
458 
459  // General Options.
460  TString dnnOptions ("!H:V:ErrorStrategy=CROSSENTROPY:VarTransform=N:"
461  "WeightInitialization=XAVIERUNIFORM");
462  dnnOptions.Append (":"); dnnOptions.Append (layoutString);
463  dnnOptions.Append (":"); dnnOptions.Append (trainingStrategyString);
464 
465  // Cuda implementation.
466  if (Use["DNN_GPU"]) {
467  TString gpuOptions = dnnOptions + ":Architecture=GPU";
468  factory->BookMethod(dataloader, TMVA::Types::kDNN, "DNN_GPU", gpuOptions);
469  }
470  // Multi-core CPU implementation.
471  if (Use["DNN_CPU"]) {
472  TString cpuOptions = dnnOptions + ":Architecture=CPU";
473  factory->BookMethod(dataloader, TMVA::Types::kDNN, "DNN_CPU", cpuOptions);
474  }
475  }
476 
477  // CF(Clermont-Ferrand)ANN
478  if (Use["CFMlpANN"])
479  factory->BookMethod( dataloader, TMVA::Types::kCFMlpANN, "CFMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N" ); // n_cycles:#nodes:#nodes:...
480 
481  // Tmlp(Root)ANN
482  if (Use["TMlpANN"])
483  factory->BookMethod( dataloader, TMVA::Types::kTMlpANN, "TMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N:LearningMethod=BFGS:ValidationFraction=0.3" ); // n_cycles:#nodes:#nodes:...
484 
485  // Support Vector Machine
486  if (Use["SVM"])
487  factory->BookMethod( dataloader, TMVA::Types::kSVM, "SVM", "Gamma=0.25:Tol=0.001:VarTransform=Norm" );
488 
489  // Boosted Decision Trees
490  if (Use["BDTG"]) // Gradient Boost
491  factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTG",
492  "!H:!V:NTrees=1000:MinNodeSize=2.5%:BoostType=Grad:Shrinkage=0.10:UseBaggedBoost:BaggedSampleFraction=0.5:nCuts=20:MaxDepth=2" );
493 
494  if (Use["BDT"]) // Adaptive Boost
495  factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDT",
496  "!H:!V:NTrees=850:MinNodeSize=2.5%:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex:nCuts=20" );
497 
498  if (Use["BDTB"]) // Bagging
499  factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTB",
500  "!H:!V:NTrees=400:BoostType=Bagging:SeparationType=GiniIndex:nCuts=20" );
501 
502  if (Use["BDTD"]) // Decorrelation + Adaptive Boost
503  factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTD",
504  "!H:!V:NTrees=400:MinNodeSize=5%:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:VarTransform=Decorrelate" );
505 
506  if (Use["BDTF"]) // Allow Using Fisher discriminant in node splitting for (strong) linearly correlated variables
507  factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTF",
508  "!H:!V:NTrees=50:MinNodeSize=2.5%:UseFisherCuts:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=20" );
509 
510  // RuleFit -- TMVA implementation of Friedman's method
511  if (Use["RuleFit"])
512  factory->BookMethod( dataloader, TMVA::Types::kRuleFit, "RuleFit",
513  "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" );
514 
515  // For an example of the category classifier usage, see: TMVAClassificationCategory
516  //
517  // --------------------------------------------------------------------------------------------------
518  // Now you can optimize the setting (configuration) of the MVAs using the set of training events
519  // STILL EXPERIMENTAL and only implemented for BDT's !
520  //
521  // factory->OptimizeAllMethods("SigEffAt001","Scan");
522  // factory->OptimizeAllMethods("ROCIntegral","FitGA");
523  //
524  // --------------------------------------------------------------------------------------------------
525 
526  // Now you can tell the factory to train, test, and evaluate the MVAs
527  //
528  // Train MVAs using the set of training events
529  factory->TrainAllMethods();
530 
531  // Evaluate all MVAs using the set of test events
532  factory->TestAllMethods();
533 
534  // Evaluate and compare performance of all configured MVAs
535  factory->EvaluateAllMethods();
536 
537  // --------------------------------------------------------------
538 
539  // Save the output
540  outputFile->Close();
541 
542  std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
543  std::cout << "==> TMVAClassification is done!" << std::endl;
544 
545  delete factory;
546  delete dataloader;
547  // Launch the GUI for the root macros
548  if (!gROOT->IsBatch()) TMVA::TMVAGui( outfileName );
549 
550  return 0;
551 }
552 
553 int main( int argc, char** argv )
554 {
555  // Select methods (don't look at this code - not of interest)
556  TString methodList;
557  for (int i=1; i<argc; i++) {
558  TString regMethod(argv[i]);
559  if(regMethod=="-b" || regMethod=="--batch") continue;
560  if (!methodList.IsNull()) methodList += TString(",");
561  methodList += regMethod;
562  }
563  return TMVAClassification(methodList);
564 }
void AddBackgroundTree(TTree *background, Double_t weight=1.0, Types::ETreeType treetype=Types::kMaxTreeType)
number of signal events (used to compute significance)
Definition: DataLoader.cxx:408
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition: TSystem.cxx:1276
static Tools & Instance()
Definition: Tools.cxx:75
MethodBase * BookMethod(DataLoader *loader, TString theMethodName, TString methodTitle, TString theOption="")
Book a classifier or regression method.
Definition: Factory.cxx:343
void TMVAGui(const char *fName="TMVA.root", TString dataset="")
A ROOT file is a suite of consecutive data records (TKey instances) with a well defined format...
Definition: TFile.h:46
static Bool_t SetCacheFileDir(ROOT::Internal::TStringView cacheDir, Bool_t operateDisconnected=kTRUE, Bool_t forceCacheread=kFALSE)
Definition: TFile.h:303
#define gROOT
Definition: TROOT.h:402
Basic string class.
Definition: TString.h:125
void TrainAllMethods()
Iterates through all booked methods and calls training.
Definition: Factory.cxx:1015
void AddVariable(const TString &expression, const TString &title, const TString &unit, char type='F', Double_t min=0, Double_t max=0)
user inserts discriminating variable in data set info
Definition: DataLoader.cxx:491
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=1, Int_t netopt=0)
Create / open a file.
Definition: TFile.cxx:3950
int main(int argc, char **argv)
A specialized string object used for TTree selections.
Definition: TCut.h:25
R__EXTERN TSystem * gSystem
Definition: TSystem.h:540
void EvaluateAllMethods(void)
Iterates over all MVAs that have been booked, and calls their evaluation methods. ...
Definition: Factory.cxx:1252
void TestAllMethods()
Definition: Factory.cxx:1150
unsigned int UInt_t
Definition: RtypesCore.h:42
This is the main MVA steering class.
Definition: Factory.h:81
Tools & gTools()
void PrepareTrainingAndTestTree(const TCut &cut, const TString &splitOpt)
prepare the training and test trees -> same cuts for signal and background
Definition: DataLoader.cxx:629
double Double_t
Definition: RtypesCore.h:55
void SetBackgroundWeightExpression(const TString &variable)
Definition: DataLoader.cxx:553
Bool_t IsNull() const
Definition: TString.h:383
std::vector< TString > SplitString(const TString &theOpt, const char separator) const
splits the option string at &#39;separator&#39; and fills the list &#39;splitV&#39; with the primitive strings ...
Definition: Tools.cxx:1210
A TTree object has a header with a name and a title.
Definition: TTree.h:70
void AddSignalTree(TTree *signal, Double_t weight=1.0, Types::ETreeType treetype=Types::kMaxTreeType)
number of signal events (used to compute significance)
Definition: DataLoader.cxx:377
void AddSpectator(const TString &expression, const TString &title="", const TString &unit="", Double_t min=0, Double_t max=0)
user inserts target in data set info
Definition: DataLoader.cxx:521
virtual void Close(Option_t *option="")
Close a file.
Definition: TFile.cxx:916