Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TMVARegression.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///
10/// The methods to be used can be switched on and off by means of booleans, or
11/// via the prompt command, for example:
12///
13/// root -l TMVARegression.C\‍(\"LD,MLP\"\‍)
14///
15/// (note that the backslashes are mandatory)
16/// If no method given, a default set is used.
17///
18/// The output file "TMVAReg.root" can be analysed with the use of dedicated
19/// macros (simply say: root -l <macro.C>), which can be conveniently
20/// invoked through a GUI that will appear at the end of the run of this macro.
21/// - Project : TMVA - a Root-integrated toolkit for multivariate data analysis
22/// - Package : TMVA
23/// - Root Macro: TMVARegression
24///
25/// \macro_code
26/// \macro_output
27/// \author Andreas Hoecker
28
29#include <cstdlib>
30#include <iostream>
31#include <map>
32#include <string>
33
34#include "TChain.h"
35#include "TFile.h"
36#include "TTree.h"
37#include "TString.h"
38#include "TObjString.h"
39#include "TSystem.h"
40#include "TROOT.h"
41
42#include "TMVA/Tools.h"
43#include "TMVA/Factory.h"
44#include "TMVA/DataLoader.h"
45#include "TMVA/TMVARegGui.h"
46
47
48using namespace TMVA;
49
50void TMVARegression( TString myMethodList = "" )
51{
52 // The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
53 // if you use your private .rootrc, or run from a different directory, please copy the
54 // corresponding lines from .rootrc
55
56 // methods to be processed can be given as an argument; use format:
57 //
58 // mylinux~> root -l TMVARegression.C\‍(\"myMethod1,myMethod2,myMethod3\"\‍)
59 //
60
61 //---------------------------------------------------------------
62 // This loads the library
64
65
66
67 // Default MVA methods to be trained + tested
68 std::map<std::string,int> Use;
69
70 // Mutidimensional likelihood and Nearest-Neighbour methods
71 Use["PDERS"] = 0;
72 Use["PDEFoam"] = 1;
73 Use["KNN"] = 1;
74 //
75 // Linear Discriminant Analysis
76 Use["LD"] = 1;
77 //
78 // Function Discriminant analysis
79 Use["FDA_GA"] = 0;
80 Use["FDA_MC"] = 0;
81 Use["FDA_MT"] = 0;
82 Use["FDA_GAMT"] = 0;
83 //
84 // Neural Network
85 Use["MLP"] = 0;
86 //
87 // Support Vector Machine
88 Use["SVM"] = 0;
89 //
90 // Boosted Decision Trees
91 Use["BDT"] = 0;
92 Use["BDTG"] = 1;
93 // ---------------------------------------------------------------
94
95 std::cout << std::endl;
96 std::cout << "==> Start TMVARegression" << std::endl;
97
98 // Select methods (don't look at this code - not of interest)
99 if (myMethodList != "") {
100 for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
101
102 std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
103 for (UInt_t i=0; i<mlist.size(); i++) {
104 std::string regMethod(mlist[i].Data());
105
106 if (Use.find(regMethod) == Use.end()) {
107 std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
108 for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
109 std::cout << std::endl;
110 return;
111 }
112 Use[regMethod] = 1;
113 }
114 }
115
116 // --------------------------------------------------------------------------------------------------
117
118 // Here the preparation phase begins
119
120 // Create a new root output file
121 TString outfileName( "TMVAReg.root" );
122 TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
123
124 // Create the factory object. Later you can choose the methods
125 // whose performance you'd like to investigate. The factory will
126 // then run the performance analysis for you.
127 //
128 // The first argument is the base of the name of all the
129 // weightfiles in the directory weight/
130 //
131 // The second argument is the output file for the training results
132 // All TMVA output can be suppressed by removing the "!" (not) in
133 // front of the "Silent" argument in the option string
134 TMVA::Factory *factory = new TMVA::Factory( "TMVARegression", outputFile,
135 "!V:!Silent:Color:DrawProgressBar:AnalysisType=Regression" );
136
137
138 TMVA::DataLoader *dataloader=new TMVA::DataLoader("datasetreg");
139 // If you wish to modify default settings
140 // (please check "src/Config.h" to see all available global options)
141 //
142 // (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
143 // (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
144
145 // Define the input variables that shall be used for the MVA training
146 // note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
147 // [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
148 dataloader->AddVariable( "var1", "Variable 1", "units", 'F' );
149 dataloader->AddVariable( "var2", "Variable 2", "units", 'F' );
150
151 // You can add so-called "Spectator variables", which are not used in the MVA training,
152 // but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
153 // input variables, the response values of all trained MVAs, and the spectator variables
154 dataloader->AddSpectator( "spec1:=var1*2", "Spectator 1", "units", 'F' );
155 dataloader->AddSpectator( "spec2:=var1*3", "Spectator 2", "units", 'F' );
156
157 // Add the variable carrying the regression target
158 dataloader->AddTarget( "fvalue" );
159
160 // It is also possible to declare additional targets for multi-dimensional regression, ie:
161 // factory->AddTarget( "fvalue2" );
162 // BUT: this is currently ONLY implemented for MLP
163
164 // Read training and test data (see TMVAClassification for reading ASCII files)
165 // load the signal and background event samples from ROOT trees
166 TFile *input(nullptr);
167 TString fname = gROOT->GetTutorialDir() + "/machine_learning/data/tmva_reg_example.root";
168 if (!gSystem->AccessPathName( fname )) {
169 input = TFile::Open( fname ); // check if file in local directory exists
170 }
171 if (!input) {
172 std::cout << "ERROR: could not open data file" << std::endl;
173 exit(1);
174 }
175 std::cout << "--- TMVARegression : Using input file: " << input->GetName() << std::endl;
176
177 // Register the regression tree
178
179 TTree *regTree = (TTree*)input->Get("TreeR");
180
181 // global event weights per tree (see below for setting event-wise weights)
182 Double_t regWeight = 1.0;
183
184 // You can add an arbitrary number of regression trees
185 dataloader->AddRegressionTree( regTree, regWeight );
186
187 // This would set individual event weights (the variables defined in the
188 // expression need to exist in the original TTree)
189 dataloader->SetWeightExpression( "var1", "Regression" );
190
191 // Apply additional cuts on the signal and background samples (can be different)
192 TCut mycut = ""; // for example: TCut mycut = "abs(var1)<0.5 && abs(var2-0.5)<1";
193
194 // tell the DataLoader to use all remaining events in the trees after training for testing:
195 dataloader->PrepareTrainingAndTestTree( mycut,
196 "nTrain_Regression=1000:nTest_Regression=0:SplitMode=Random:NormMode=NumEvents:!V" );
197 //
198 // dataloader->PrepareTrainingAndTestTree( mycut,
199 // "nTrain_Regression=0:nTest_Regression=0:SplitMode=Random:NormMode=NumEvents:!V" );
200
201 // If no numbers of events are given, half of the events in the tree are used
202 // for training, and the other half for testing:
203 //
204 // dataloader->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
205
206 // Book MVA methods
207 //
208 // Please lookup the various method configuration options in the corresponding cxx files, eg:
209 // src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/old_site/optionRef.html
210 // it is possible to preset ranges in the option string in which the cut optimisation should be done:
211 // "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable
212
213 // PDE - RS method
214 if (Use["PDERS"])
215 factory->BookMethod( dataloader, TMVA::Types::kPDERS, "PDERS",
216 "!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=40:NEventsMax=60:VarTransform=None" );
217 // And the options strings for the MinMax and RMS methods, respectively:
218 //
219 // "!H:!V:VolumeRangeMode=MinMax:DeltaFrac=0.2:KernelEstimator=Gauss:GaussSigma=0.3" );
220 // "!H:!V:VolumeRangeMode=RMS:DeltaFrac=3:KernelEstimator=Gauss:GaussSigma=0.3" );
221
222 if (Use["PDEFoam"])
223 factory->BookMethod( dataloader, TMVA::Types::kPDEFoam, "PDEFoam",
224 "!H:!V:MultiTargetRegression=F:TargetSelection=Mpv:TailCut=0.001:VolFrac=0.0666:nActiveCells=500:nSampl=2000:nBin=5:Compress=T:Kernel=None:Nmin=10:VarTransform=None" );
225
226 // K-Nearest Neighbour classifier (KNN)
227 if (Use["KNN"])
228 factory->BookMethod( dataloader, TMVA::Types::kKNN, "KNN",
229 "nkNN=20:ScaleFrac=0.8:SigmaFact=1.0:Kernel=Gaus:UseKernel=F:UseWeight=T:!Trim" );
230
231 // Linear discriminant
232 if (Use["LD"])
233 factory->BookMethod( dataloader, TMVA::Types::kLD, "LD",
234 "!H:!V:VarTransform=None" );
235
236 // Function discrimination analysis (FDA) -- test of various fitters - the recommended one is Minuit (or GA or SA)
237 if (Use["FDA_MC"])
238 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MC",
239 "!H:!V:Formula=(0)+(1)*x0+(2)*x1:ParRanges=(-100,100);(-100,100);(-100,100):FitMethod=MC:SampleSize=100000:Sigma=0.1:VarTransform=D" );
240
241 if (Use["FDA_GA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options) .. the formula of this example is good for parabolas
242 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_GA",
243 "!H:!V:Formula=(0)+(1)*x0+(2)*x1:ParRanges=(-100,100);(-100,100);(-100,100):FitMethod=GA:PopSize=100:Cycles=3:Steps=30:Trim=True:SaveBestGen=1:VarTransform=Norm" );
244
245 if (Use["FDA_MT"])
246 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_MT",
247 "!H:!V:Formula=(0)+(1)*x0+(2)*x1:ParRanges=(-100,100);(-100,100);(-100,100);(-10,10):FitMethod=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=2:UseImprove:UseMinos:SetBatch" );
248
249 if (Use["FDA_GAMT"])
250 factory->BookMethod( dataloader, TMVA::Types::kFDA, "FDA_GAMT",
251 "!H:!V:Formula=(0)+(1)*x0+(2)*x1:ParRanges=(-100,100);(-100,100);(-100,100):FitMethod=GA:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:Cycles=1:PopSize=5:Steps=5:Trim" );
252
253 // Neural network (MLP)
254 if (Use["MLP"])
255 factory->BookMethod( dataloader, TMVA::Types::kMLP, "MLP", "!H:!V:VarTransform=Norm:NeuronType=tanh:NCycles=20000:HiddenLayers=N+20:TestRate=6:TrainingMethod=BFGS:Sampling=0.3:SamplingEpoch=0.8:ConvergenceImprove=1e-6:ConvergenceTests=15:!UseRegulator" );
256
257 // Support Vector Machine
258 if (Use["SVM"])
259 factory->BookMethod( dataloader, TMVA::Types::kSVM, "SVM", "Gamma=0.25:Tol=0.001:VarTransform=Norm" );
260
261 // Boosted Decision Trees
262 if (Use["BDT"])
263 factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDT",
264 "!H:!V:NTrees=100:MinNodeSize=1.0%:BoostType=AdaBoostR2:SeparationType=RegressionVariance:nCuts=20:PruneMethod=CostComplexity:PruneStrength=30" );
265
266 if (Use["BDTG"])
267 factory->BookMethod( dataloader, TMVA::Types::kBDT, "BDTG",
268 "!H:!V:NTrees=2000::BoostType=Grad:Shrinkage=0.1:UseBaggedBoost:BaggedSampleFraction=0.5:nCuts=20:MaxDepth=3:MaxDepth=4" );
269 // --------------------------------------------------------------------------------------------------
270
271 // Now you can tell the factory to train, test, and evaluate the MVAs
272
273 // Train MVAs using the set of training events
274 factory->TrainAllMethods();
275
276 // Evaluate all MVAs using the set of test events
277 factory->TestAllMethods();
278
279 // Evaluate and compare performance of all configured MVAs
280 factory->EvaluateAllMethods();
281
282 // --------------------------------------------------------------
283
284 // Save the output
285 outputFile->Close();
286
287 std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
288 std::cout << "==> TMVARegression is done!" << std::endl;
289
290 delete factory;
291 delete dataloader;
292
293 // Launch the GUI for the root macros
294 if (!gROOT->IsBatch()) TMVA::TMVARegGui( outfileName );
295}
296
297int main( int argc, char** argv )
298{
299 // Select methods (don't look at this code - not of interest)
300 TString methodList;
301 for (int i=1; i<argc; i++) {
302 TString regMethod(argv[i]);
303 if(regMethod=="-b" || regMethod=="--batch") continue;
304 if (!methodList.IsNull()) methodList += TString(",");
305 methodList += regMethod;
306 }
307 TMVARegression(methodList);
308 return 0;
309}
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
Definition RtypesCore.h:61
double Double_t
Double 8 bytes.
Definition RtypesCore.h:74
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
#define gROOT
Definition TROOT.h:417
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
A specialized string object used for TTree selections.
Definition TCut.h:25
A file, usually with extension .root, that stores data and code in the form of serialized objects in ...
Definition TFile.h:130
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:3804
void Close(Option_t *option="") override
Close a file.
Definition TFile.cxx:992
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
void AddRegressionTree(TTree *tree, Double_t weight=1.0, Types::ETreeType treetype=Types::kMaxTreeType)
Definition DataLoader.h:103
void SetWeightExpression(const TString &variable, const TString &className="")
void PrepareTrainingAndTestTree(const TCut &cut, const TString &splitOpt)
prepare the training and test trees -> same cuts for signal and background
void AddTarget(const TString &expression, const TString &title="", const TString &unit="", Double_t min=0, Double_t max=0)
user inserts target in data set info
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
This is the main MVA steering class.
Definition Factory.h:80
void TrainAllMethods()
Iterates through all booked methods and calls training.
Definition Factory.cxx:1105
void TestAllMethods()
Evaluates all booked methods on the testing data and adds the output to the Results in the corresponi...
Definition Factory.cxx:1262
void EvaluateAllMethods(void)
Iterates over all MVAs that have been booked, and calls their evaluation methods.
Definition Factory.cxx:1367
MethodBase * BookMethod(DataLoader *loader, MethodName theMethodName, TString methodTitle, TString theOption="")
Books an MVA classifier or regression method.
Definition Factory.cxx:354
static Tools & Instance()
Definition Tools.cxx:72
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:1174
@ kPDEFoam
Definition Types.h:94
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
Basic string class.
Definition TString.h:137
Bool_t IsNull() const
Definition TString.h:423
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:1319
A TTree represents a columnar dataset.
Definition TTree.h:95
int main()
Definition main.cpp:18
create variable transformations
void TMVARegGui(const char *fName="TMVAReg.root", TString dataset="")
Tools & gTools()