TMVARegression.C

Go to the documentation of this file.
00001 // @(#)root/tmva $Id: TMVARegression.C 37399 2010-12-08 15:22:07Z evt $
00002 /**********************************************************************************
00003  * Project   : TMVA - a Root-integrated toolkit for multivariate data analysis    *
00004  * Package   : TMVA                                                               *
00005  * Root Macro: TMVARegression                                                     *
00006  *                                                                                *
00007  * This macro provides examples for the training and testing of the               *
00008  * TMVA classifiers.                                                              *
00009  *                                                                                *
00010  * As input data is used a toy-MC sample consisting of four Gaussian-distributed  *
00011  * and linearly correlated input variables.                                       *
00012  *                                                                                *
00013  * The methods to be used can be switched on and off by means of booleans, or     *
00014  * via the prompt command, for example:                                           *
00015  *                                                                                *
00016  *    root -l TMVARegression.C\(\"LD,MLP\"\)                                      *
00017  *                                                                                *
00018  * (note that the backslashes are mandatory)                                      *
00019  * If no method given, a default set is used.                                     *
00020  *                                                                                *
00021  * The output file "TMVAReg.root" can be analysed with the use of dedicated       *
00022  * macros (simply say: root -l <macro.C>), which can be conveniently              *
00023  * invoked through a GUI that will appear at the end of the run of this macro.    *
00024  **********************************************************************************/
00025 
00026 #include <cstdlib>
00027 #include <iostream> 
00028 #include <map>
00029 #include <string>
00030 
00031 #include "TChain.h"
00032 #include "TFile.h"
00033 #include "TTree.h"
00034 #include "TString.h"
00035 #include "TObjString.h"
00036 #include "TSystem.h"
00037 #include "TROOT.h"
00038 
00039 #include "TMVARegGui.C"
00040 
00041 #if not defined(__CINT__) || defined(__MAKECINT__)
00042 #include "TMVA/Tools.h"
00043 #include "TMVA/Factory.h"
00044 #endif
00045 
00046 using namespace TMVA;
00047    
00048 void TMVARegression( TString myMethodList = "" ) 
00049 {
00050    // The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
00051    // if you use your private .rootrc, or run from a different directory, please copy the 
00052    // corresponding lines from .rootrc
00053 
00054    // methods to be processed can be given as an argument; use format:
00055    //
00056    // mylinux~> root -l TMVARegression.C\(\"myMethod1,myMethod2,myMethod3\"\)
00057    //
00058 
00059    //---------------------------------------------------------------
00060    // This loads the library
00061    TMVA::Tools::Instance();
00062 
00063    // Default MVA methods to be trained + tested
00064    std::map<std::string,int> Use;
00065 
00066    // --- Mutidimensional likelihood and Nearest-Neighbour methods
00067    Use["PDERS"]           = 0;
00068    Use["PDEFoam"]         = 1; 
00069    Use["KNN"]             = 1;
00070    // 
00071    // --- Linear Discriminant Analysis
00072    Use["LD"]                    = 1;
00073    // 
00074    // --- Function Discriminant analysis
00075    Use["FDA_GA"]          = 1;
00076    Use["FDA_MC"]          = 0;
00077    Use["FDA_MT"]          = 0;
00078    Use["FDA_GAMT"]        = 0;
00079    // 
00080    // --- Neural Network
00081    Use["MLP"]             = 1; 
00082    // 
00083    // --- Support Vector Machine 
00084    Use["SVM"]             = 0;
00085    // 
00086    // --- Boosted Decision Trees
00087    Use["BDT"]             = 0;
00088    Use["BDTG"]            = 1;
00089    // ---------------------------------------------------------------
00090 
00091    std::cout << std::endl;
00092    std::cout << "==> Start TMVARegression" << std::endl;
00093 
00094    // Select methods (don't look at this code - not of interest)
00095    if (myMethodList != "") {
00096       for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
00097 
00098       std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
00099       for (UInt_t i=0; i<mlist.size(); i++) {
00100          std::string regMethod(mlist[i]);
00101 
00102          if (Use.find(regMethod) == Use.end()) {
00103             std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
00104             for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
00105             std::cout << std::endl;
00106             return;
00107          }
00108          Use[regMethod] = 1;
00109       }
00110    }
00111 
00112    // --------------------------------------------------------------------------------------------------
00113 
00114    // --- Here the preparation phase begins
00115 
00116    // Create a new root output file
00117    TString outfileName( "TMVAReg.root" );
00118    TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
00119 
00120    // Create the factory object. Later you can choose the methods
00121    // whose performance you'd like to investigate. The factory will
00122    // then run the performance analysis for you.
00123    //
00124    // The first argument is the base of the name of all the
00125    // weightfiles in the directory weight/ 
00126    //
00127    // The second argument is the output file for the training results
00128    // All TMVA output can be suppressed by removing the "!" (not) in 
00129    // front of the "Silent" argument in the option string
00130    TMVA::Factory *factory = new TMVA::Factory( "TMVARegression", outputFile, 
00131                                                "!V:!Silent:Color:DrawProgressBar" );
00132 
00133    // If you wish to modify default settings 
00134    // (please check "src/Config.h" to see all available global options)
00135    //    (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
00136    //    (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
00137 
00138    // Define the input variables that shall be used for the MVA training
00139    // note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
00140    // [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
00141    factory->AddVariable( "var1", "Variable 1", "units", 'F' );
00142    factory->AddVariable( "var2", "Variable 2", "units", 'F' );
00143 
00144    // You can add so-called "Spectator variables", which are not used in the MVA training, 
00145    // but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the 
00146    // input variables, the response values of all trained MVAs, and the spectator variables
00147    factory->AddSpectator( "spec1:=var1*2",  "Spectator 1", "units", 'F' );
00148    factory->AddSpectator( "spec2:=var1*3",  "Spectator 2", "units", 'F' );
00149 
00150    // Add the variable carrying the regression target
00151    factory->AddTarget( "fvalue" ); 
00152 
00153    // It is also possible to declare additional targets for multi-dimensional regression, ie:
00154    // -- factory->AddTarget( "fvalue2" );
00155    // BUT: this is currently ONLY implemented for MLP
00156 
00157    // Read training and test data (see TMVAClassification for reading ASCII files)
00158    // load the signal and background event samples from ROOT trees
00159    TFile *input(0);
00160    TString fname = "./tmva_reg_example.root";
00161    if (!gSystem->AccessPathName( fname )) 
00162       input = TFile::Open( fname ); // check if file in local directory exists
00163    else 
00164       input = TFile::Open( "http://root.cern.ch/files/tmva_reg_example.root" ); // if not: download from ROOT server
00165    
00166    if (!input) {
00167       std::cout << "ERROR: could not open data file" << std::endl;
00168       exit(1);
00169    }
00170    std::cout << "--- TMVARegression           : Using input file: " << input->GetName() << std::endl;
00171 
00172    // --- Register the regression tree
00173 
00174    TTree *regTree = (TTree*)input->Get("TreeR");
00175 
00176    // global event weights per tree (see below for setting event-wise weights)
00177    Double_t regWeight  = 1.0;   
00178 
00179    // You can add an arbitrary number of regression trees
00180    factory->AddRegressionTree( regTree, regWeight );
00181 
00182    // This would set individual event weights (the variables defined in the 
00183    // expression need to exist in the original TTree)
00184    factory->SetWeightExpression( "var1", "Regression" );
00185 
00186    // Apply additional cuts on the signal and background samples (can be different)
00187    TCut mycut = ""; // for example: TCut mycut = "abs(var1)<0.5 && abs(var2-0.5)<1";
00188 
00189    // tell the factory to use all remaining events in the trees after training for testing:
00190    factory->PrepareTrainingAndTestTree( mycut, 
00191                                         "nTrain_Regression=0:nTest_Regression=0:SplitMode=Random:NormMode=NumEvents:!V" );
00192 
00193    // If no numbers of events are given, half of the events in the tree are used 
00194    // for training, and the other half for testing:
00195    //    factory->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );  
00196 
00197    // ---- Book MVA methods
00198    //
00199    // please lookup the various method configuration options in the corresponding cxx files, eg:
00200    // src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/optionRef.html
00201    // it is possible to preset ranges in the option string in which the cut optimisation should be done:
00202    // "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable
00203 
00204    // PDE - RS method
00205    if (Use["PDERS"])
00206       factory->BookMethod( TMVA::Types::kPDERS, "PDERS", 
00207                            "!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=40:NEventsMax=60:VarTransform=None" );
00208    // And the options strings for the MinMax and RMS methods, respectively:
00209    //      "!H:!V:VolumeRangeMode=MinMax:DeltaFrac=0.2:KernelEstimator=Gauss:GaussSigma=0.3" );   
00210    //      "!H:!V:VolumeRangeMode=RMS:DeltaFrac=3:KernelEstimator=Gauss:GaussSigma=0.3" );   
00211 
00212    if (Use["PDEFoam"])
00213        factory->BookMethod( TMVA::Types::kPDEFoam, "PDEFoam", 
00214                             "!H:!V:MultiTargetRegression=F:TargetSelection=Mpv:TailCut=0.001:VolFrac=0.0333:nActiveCells=500:nSampl=2000:nBin=5:Compress=T:Kernel=None:Nmin=10:VarTransform=None" );
00215 
00216    // K-Nearest Neighbour classifier (KNN)
00217    if (Use["KNN"])
00218       factory->BookMethod( TMVA::Types::kKNN, "KNN", 
00219                            "nkNN=20:ScaleFrac=0.8:SigmaFact=1.0:Kernel=Gaus:UseKernel=F:UseWeight=T:!Trim" );
00220 
00221    // Linear discriminant
00222    if (Use["LD"])
00223       factory->BookMethod( TMVA::Types::kLD, "LD", 
00224                            "!H:!V:VarTransform=None" );
00225 
00226         // Function discrimination analysis (FDA) -- test of various fitters - the recommended one is Minuit (or GA or SA)
00227    if (Use["FDA_MC"]) 
00228       factory->BookMethod( TMVA::Types::kFDA, "FDA_MC",
00229                           "!H:!V:Formula=(0)+(1)*x0+(2)*x1:ParRanges=(-100,100);(-100,100);(-100,100):FitMethod=MC:SampleSize=100000:Sigma=0.1:VarTransform=D" );
00230    
00231    if (Use["FDA_GA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options) .. the formula of this example is good for parabolas
00232       factory->BookMethod( TMVA::Types::kFDA, "FDA_GA",
00233                            "!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" );
00234 
00235    if (Use["FDA_MT"]) 
00236       factory->BookMethod( TMVA::Types::kFDA, "FDA_MT",
00237                            "!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" );
00238 
00239    if (Use["FDA_GAMT"]) 
00240       factory->BookMethod( TMVA::Types::kFDA, "FDA_GAMT",
00241                            "!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" );
00242 
00243    // Neural network (MLP)
00244    if (Use["MLP"])
00245       factory->BookMethod( 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" );
00246 
00247    // Support Vector Machine
00248    if (Use["SVM"])
00249       factory->BookMethod( TMVA::Types::kSVM, "SVM", "Gamma=0.25:Tol=0.001:VarTransform=Norm" );
00250 
00251    // Boosted Decision Trees
00252    if (Use["BDT"])
00253      factory->BookMethod( TMVA::Types::kBDT, "BDT",
00254                            "!H:!V:NTrees=100:nEventsMin=5:BoostType=AdaBoostR2:SeparationType=RegressionVariance:nCuts=20:PruneMethod=CostComplexity:PruneStrength=30" );
00255 
00256    if (Use["BDTG"])
00257      factory->BookMethod( TMVA::Types::kBDT, "BDTG",
00258                            "!H:!V:NTrees=2000::BoostType=Grad:Shrinkage=0.1:UseBaggedGrad:GradBaggingFraction=0.5:nCuts=20:MaxDepth=3:NNodesMax=15" );
00259    // --------------------------------------------------------------------------------------------------
00260 
00261    // ---- Now you can tell the factory to train, test, and evaluate the MVAs
00262 
00263    // Train MVAs using the set of training events
00264    factory->TrainAllMethods();
00265 
00266    // ---- Evaluate all MVAs using the set of test events
00267    factory->TestAllMethods();
00268 
00269    // ----- Evaluate and compare performance of all configured MVAs
00270    factory->EvaluateAllMethods();    
00271 
00272    // --------------------------------------------------------------
00273    
00274    // Save the output
00275    outputFile->Close();
00276 
00277    std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
00278    std::cout << "==> TMVARegression is done!" << std::endl;      
00279 
00280    delete factory;
00281 
00282    // Launch the GUI for the root macros
00283    if (!gROOT->IsBatch()) TMVARegGui( outfileName );
00284 }

Generated on Tue Jul 5 15:26:37 2011 for ROOT_528-00b_version by  doxygen 1.5.1