本文整理汇总了C++中tmva::Factory::AddSpectator方法的典型用法代码示例。如果您正苦于以下问题:C++ Factory::AddSpectator方法的具体用法?C++ Factory::AddSpectator怎么用?C++ Factory::AddSpectator使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tmva::Factory
的用法示例。
在下文中一共展示了Factory::AddSpectator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: TMVAClassification
void TMVAClassification( TString myMethodList = "" )
{
// TString curDynamicPath( gSystem->GetDynamicPath() );
// gSystem->SetDynamicPath( "/usr/local/bin/root/bin:" + curDynamicPath );
// TString curIncludePath(gSystem->GetIncludePath());
// gSystem->SetIncludePath( " -I /usr/local/bin/root/include " + curIncludePath );
// // load TMVA shared library created in local release: for MAC OSX
// if (TString(gSystem->GetBuildArch()).Contains("macosx") ) gSystem->Load( "libTMVA.so" );
// gSystem->Load( "libTMVA" );
// TMVA::Tools::Instance();
// // welcome the user
// TMVA::gTools().TMVAWelcomeMessage();
// TMVAGlob::SetTMVAStyle();
// // this loads the library
// TMVA::Tools::Instance();
//---------------------------------------------------------------
// default MVA methods to be trained + tested
std::map<std::string,int> Use;
Use["Cuts"] = 1;
// Use["Likelihood"] = 1;
// ---------------------------------------------------------------
std::cout << std::endl;
std::cout << "==> Start TMVAClassification" << std::endl;
if (myMethodList != "") {
for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
std::vector<TString> mlist = TMVA::gTools().SplitString( myMethodList, ',' );
for (UInt_t i=0; i<mlist.size(); i++) {
std::string regMethod(mlist[i]);
if (Use.find(regMethod) == Use.end()) {
std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
std::cout << std::endl;
return;
}
Use[regMethod] = 1;
}
}
// Create a new root output file.
TString outfileName( "TMVA.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
// Create the factory object. Later you can choose the methods
// whose performance you'd like to investigate. The factory will
// then run the performance analysis for you.
//
// The first argument is the base of the name of all the
// weightfiles in the directory weight/
//
// The second argument is the output file for the training results
// All TMVA output can be suppressed by removing the "!" (not) in
// front of the "Silent" argument in the option string
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D" );
// If you wish to modify default settings
// (please check "src/Config.h" to see all available global options)
// (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
// (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
// Define the input variables that shall be used for the MVA training
// note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
// [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
// factory->AddVariable( "myvar1 := var1+var2", 'F' );
// factory->AddVariable( "myvar2 := var1-var2", "Expression 2", "", 'F' );
// factory->AddVariable( "var3", "Variable 3", "units", 'F' );
// factory->AddVariable( "var4", "Variable 4", "units", 'F' );
factory->AddVariable("deltaEta := deta", 'F');
factory->AddVariable("deltaPhi := dphi", 'F');
factory->AddVariable("sigmaIetaIeta := sieie", 'F');
factory->AddVariable("HoverE := hoe", 'F');
factory->AddVariable("trackIso := trackiso", 'F');
factory->AddVariable("ecalIso := ecaliso", 'F');
factory->AddVariable("hcalIso := hcaliso", 'F');
//factory->AddVariable("nMissingHits := misshits", 'I');
// You can add so-called "Spectator variables", which are not used in the MVA training,
// but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
// input variables, the response values of all trained MVAs, and the spectator variables
factory->AddSpectator( "et", 'F' );
factory->AddSpectator( "eta", 'F' );
factory->AddSpectator( "phi", 'F' );
//.........这里部分代码省略.........
示例2: TMVAClassificationCategory
void TMVAClassificationCategory()
{
//---------------------------------------------------------------
// Example for usage of different event categories with classifiers
std::cout << std::endl << "==> Start TMVAClassificationCategory" << std::endl;
bool batchMode = false;
// Create a new root output file.
TString outfileName( "TMVA.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
// Create the factory object (see TMVAClassification.C for more information)
std::string factoryOptions( "!V:!Silent:Transformations=I;D;P;G,D" );
if (batchMode) factoryOptions += ":!Color:!DrawProgressBar";
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassificationCategory", outputFile, factoryOptions );
// Define the input variables used for the MVA training
factory->AddVariable( "var1", 'F' );
factory->AddVariable( "var2", 'F' );
factory->AddVariable( "var3", 'F' );
factory->AddVariable( "var4", 'F' );
// You can add so-called "Spectator variables", which are not used in the MVA training,
// but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
// input variables, the response values of all trained MVAs, and the spectator variables
factory->AddSpectator( "eta" );
// Load the signal and background event samples from ROOT trees
TFile *input(0);
TString fname( "" );
if (UseOffsetMethod) fname = "data/toy_sigbkg_categ_offset.root";
else fname = "data/toy_sigbkg_categ_varoff.root";
if (!gSystem->AccessPathName( fname )) {
// first we try to find tmva_example.root in the local directory
std::cout << "--- TMVAClassificationCategory: Accessing " << fname << std::endl;
input = TFile::Open( fname );
}
if (!input) {
std::cout << "ERROR: could not open data file: " << fname << std::endl;
exit(1);
}
TTree *signal = (TTree*)input->Get("TreeS");
TTree *background = (TTree*)input->Get("TreeB");
/// Global event weights per tree (see below for setting event-wise weights)
Double_t signalWeight = 1.0;
Double_t backgroundWeight = 1.0;
/// You can add an arbitrary number of signal or background trees
factory->AddSignalTree ( signal, signalWeight );
factory->AddBackgroundTree( background, backgroundWeight );
// Apply additional cuts on the signal and background samples (can be different)
TCut mycuts = ""; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
TCut mycutb = ""; // for example: TCut mycutb = "abs(var1)<0.5";
// Tell the factory how to use the training and testing events
factory->PrepareTrainingAndTestTree( mycuts, mycutb,
"nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );
// ---- Book MVA methods
// Fisher discriminant
factory->BookMethod( TMVA::Types::kFisher, "Fisher", "!H:!V:Fisher" );
// Likelihood
factory->BookMethod( TMVA::Types::kLikelihood, "Likelihood",
"!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" );
// --- Categorised classifier
TMVA::MethodCategory* mcat = 0;
// The variable sets
TString theCat1Vars = "var1:var2:var3:var4";
TString theCat2Vars = (UseOffsetMethod ? "var1:var2:var3:var4" : "var1:var2:var3");
// Fisher with categories
TMVA::MethodBase* fiCat = factory->BookMethod( TMVA::Types::kCategory, "FisherCat","" );
mcat = dynamic_cast<TMVA::MethodCategory*>(fiCat);
mcat->AddMethod( "abs(eta)<=1.3", theCat1Vars, TMVA::Types::kFisher, "Category_Fisher_1","!H:!V:Fisher" );
mcat->AddMethod( "abs(eta)>1.3", theCat2Vars, TMVA::Types::kFisher, "Category_Fisher_2","!H:!V:Fisher" );
// Likelihood with categories
TMVA::MethodBase* liCat = factory->BookMethod( TMVA::Types::kCategory, "LikelihoodCat","" );
mcat = dynamic_cast<TMVA::MethodCategory*>(liCat);
mcat->AddMethod( "abs(eta)<=1.3",theCat1Vars, TMVA::Types::kLikelihood,
"Category_Likelihood_1","!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" );
mcat->AddMethod( "abs(eta)>1.3", theCat2Vars, TMVA::Types::kLikelihood,
"Category_Likelihood_2","!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" );
// ---- Now you can tell the factory to train, test, and evaluate the MVAs
// Train MVAs using the set of training events
factory->TrainAllMethods();
//.........这里部分代码省略.........
示例3: TMVARegression
void TMVARegression( TString myMethodList = "" )
{
// The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
// if you use your private .rootrc, or run from a different directory, please copy the
// corresponding lines from .rootrc
// methods to be processed can be given as an argument; use format:
//
// mylinux~> root -l TMVARegression.C\(\"myMethod1,myMethod2,myMethod3\"\)
//
//---------------------------------------------------------------
// This loads the library
TMVA::Tools::Instance();
// Default MVA methods to be trained + tested
std::map<std::string,int> Use;
// --- Mutidimensional likelihood and Nearest-Neighbour methods
Use["PDERS"] = 0;
Use["PDEFoam"] = 1;
Use["KNN"] = 1;
//
// --- Linear Discriminant Analysis
Use["LD"] = 1;
//
// --- Function Discriminant analysis
Use["FDA_GA"] = 1;
Use["FDA_MC"] = 0;
Use["FDA_MT"] = 0;
Use["FDA_GAMT"] = 0;
//
// --- Neural Network
Use["MLP"] = 1;
//
// --- Support Vector Machine
Use["SVM"] = 0;
//
// --- Boosted Decision Trees
Use["BDT"] = 0;
Use["BDTG"] = 1;
// ---------------------------------------------------------------
std::cout << std::endl;
std::cout << "==> Start TMVARegression" << std::endl;
// Select methods (don't look at this code - not of interest)
if (myMethodList != "") {
for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
for (UInt_t i=0; i<mlist.size(); i++) {
std::string regMethod(mlist[i]);
if (Use.find(regMethod) == Use.end()) {
std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
std::cout << std::endl;
return;
}
Use[regMethod] = 1;
}
}
// --------------------------------------------------------------------------------------------------
// --- Here the preparation phase begins
// Create a new root output file
TString outfileName( "TMVAReg.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
// Create the factory object. Later you can choose the methods
// whose performance you'd like to investigate. The factory will
// then run the performance analysis for you.
//
// The first argument is the base of the name of all the
// weightfiles in the directory weight/
//
// The second argument is the output file for the training results
// All TMVA output can be suppressed by removing the "!" (not) in
// front of the "Silent" argument in the option string
TMVA::Factory *factory = new TMVA::Factory( "TMVARegression", outputFile,
"!V:!Silent:Color:DrawProgressBar" );
// If you wish to modify default settings
// (please check "src/Config.h" to see all available global options)
// (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
// (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
// Define the input variables that shall be used for the MVA training
// note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
// [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
factory->AddVariable( "var1", "Variable 1", "units", 'F' );
factory->AddVariable( "var2", "Variable 2", "units", 'F' );
// You can add so-called "Spectator variables", which are not used in the MVA training,
// but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
// input variables, the response values of all trained MVAs, and the spectator variables
factory->AddSpectator( "spec1:=var1*2", "Spectator 1", "units", 'F' );
//.........这里部分代码省略.........
示例4: main
//.........这里部分代码省略.........
bkgfiles.push_back("MC_GJets-HT-400ToInf-madgraph");
bkgfiles.push_back("MC_WGamma");
bkgfiles.push_back("MC_EWK-Z2j");
bkgfiles.push_back("MC_EWK-Z2jiglep");
bkgfiles.push_back("MC_EWK-W2jminus_enu");
bkgfiles.push_back("MC_EWK-W2jplus_enu");
bkgfiles.push_back("MC_EWK-W2jminus_munu");
bkgfiles.push_back("MC_EWK-W2jplus_munu");
bkgfiles.push_back("MC_EWK-W2jminus_taunu");
bkgfiles.push_back("MC_EWK-W2jplus_taunu");
}
// Create a ROOT output file where TMVA will store ntuples, histograms, etc.
TFile *output_tmva = TFile::Open((folder+"/TMVA_QCDrej.root").c_str(),"RECREATE");
// Create the factory object. Later you can choose the methods
// whose performance you'd like to investigate. The factory is
// the only TMVA object you have to interact with
//
// The first argument is the base of the name of all the
// weightfiles in the directory weight/
//
// The second argument is the output file for the training results
// All TMVA output can be suppressed by removing the "!" (not) in
// front of the "Silent" argument in the option string
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", output_tmva,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
//fill the variables with event weight from the trees
//const unsigned nVars = 4;
factory->AddSpectator("jet1_pt","Jet 1 p_{T}", "GeV", 'F');
factory->AddSpectator("jet2_pt","Jet 2 p_{T}", "GeV", 'F');
factory->AddSpectator("jet1_eta","Jet 1 #eta", "", 'F');
factory->AddVariable("jet2_eta","Jet 2 #eta", "", 'F');// **
factory->AddSpectator("jet1_phi","Jet 1 #phi", "", 'F');
factory->AddSpectator("jet2_phi","Jet 2 #phi", "", 'F');
factory->AddSpectator("dijet_M","M_{jj}", " GeV", 'F');
factory->AddSpectator("dijet_deta","#Delta#eta_{jj}", "", 'F');
factory->AddSpectator("dijet_sumeta","#eta_{j1}+#eta_{j2}", "", 'F');
factory->AddSpectator("dijet_dphi","#Delta#phi_{jj}", "", 'F');
factory->AddSpectator("met","MET", "GeV", 'F');// **
factory->AddSpectator("met_phi","MET #phi", "", 'F');
factory->AddVariable("met_significance","MET significance", "", 'F');// **
factory->AddSpectator("sumet","#Sum E_{T}", "GeV", 'F');
factory->AddSpectator("ht","H_{T}", "GeV", 'F');
factory->AddVariable("mht","MH_{T}", "GeV", 'F');// **
factory->AddSpectator("sqrt_ht","#sqrt{H_{T}}", "GeV^{0.5}", 'F');
factory->AddSpectator("unclustered_et","Unclustered E_{T}", "GeV", 'F');
factory->AddSpectator("unclustered_phi","Unclustered #phi", "GeV", 'F');
factory->AddSpectator("jet1met_dphi","#Delta#phi(MET,jet1)", "", 'F');
factory->AddVariable("jet2met_dphi","#Delta#phi(MET,jet2)", "", 'F');// **
factory->AddVariable("jetmet_mindphi","minimum #Delta#phi(MET,jet)", "", 'F');// **
factory->AddVariable("jetunclet_mindphi","minimum #Delta#phi(unclustered,jet)", "", 'F');// **
factory->AddVariable("metunclet_dphi","#Delta#phi(MET,unclustered)", "", 'F');// **
factory->AddVariable("dijetmet_scalarSum_pt", "p_{T}^{jet1}+p_{T}^{jet2}+MET", "GeV", 'F');// **
factory->AddSpectator("dijetmet_vectorialSum_pt","p_{T}(#vec{j1}+#vec{j2}+#vec{MET})", "GeV", 'F');
factory->AddVariable("dijetmet_ptfraction","p_{T}^{dijet}/(p_{T}^{dijet}+MET)", "", 'F');// **
//factory->AddVariable("jet1met_scalarprod := (jet1_pt*cos(jet1_phi)*met_x+jet1_pt*sin(jet1_phi)*met_y)/met", "#vec{p_{T}^{jet1}}.#vec{MET}/MET", "GeV" , 'F');
//factory->AddVariable("jet2met_scalarprod := (jet2_pt*cos(jet2_phi)*met_x+jet2_pt*sin(jet2_phi)*met_y)/met", "#vec{p_{T}^{jet2}}.#vec{MET}/MET", "GeV" , 'F');
factory->AddVariable("jet1met_scalarprod", "#vec{p_{T}^{jet1}}.#vec{MET}/MET", "GeV" , 'F');// **
factory->AddVariable("jet2met_scalarprod", "#vec{p_{T}^{jet2}}.#vec{MET}/MET", "GeV" , 'F');// **
factory->AddVariable("jet1met_scalarprod_frac := jet1met_scalarprod/met", "#vec{p_{T}^{jet1}}.#vec{MET}/MET^{2}", "" , 'F');// **
factory->AddVariable("jet2met_scalarprod_frac := jet2met_scalarprod/met", "#vec{p_{T}^{jet2}}.#vec{MET}/MET^{2}", "" , 'F');// **
示例5: TMVAClassification_cc1pcoh_bdt_ver6noveract
//.........这里部分代码省略.........
return;
}
Use[regMethod] = 1;
}
}
// ---------------------------------------------------------------
// --- Here the preparation phase begins
// Create a ROOT output file where TMVA will store ntuples, histograms, etc.
TString outfileName( "TMVA_cc1pcoh_bdt_ver6noveract.root" );//newchange
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
// Create the factory object.
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification_ver6noveract", outputFile,//newchange
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
// Add variable
//sprintf(select, "Ntrack==2&&mumucl>0.6&&pmucl>0.25&&pang<90&&muang_t<15 && veract*7.66339869e-2<34");
//factory->AddVariable( "Ntrack", 'F' );
factory->AddVariable( "mumucl", 'F' );
factory->AddVariable( "pmucl", 'F' );
factory->AddVariable( "pang_t", 'F' );//use pang instead of pang_t
factory->AddVariable( "muang_t", 'F' );
//factory->AddVariable( "veract", 'F' );
factory->AddVariable( "ppe", 'F');
factory->AddVariable( "mupe", 'F');
factory->AddVariable( "range", 'F');
factory->AddVariable( "coplanarity", 'F');
factory->AddVariable( "opening", 'F');//newadd
// Add spectator
factory->AddSpectator( "fileIndex", 'I' );
factory->AddSpectator( "nuE", 'F' );
factory->AddSpectator( "inttype", 'I' );
factory->AddSpectator( "norm", 'F' );
factory->AddSpectator( "totcrsne", 'F' );
factory->AddSpectator( "veract", 'F' );
factory->AddSpectator( "pang", 'F' );
factory->AddSpectator( "mupdg", 'I' );
factory->AddSpectator( "ppdg", 'I' );
// ---------------------------------------------------------------
// --- Get weight
TString fratioStr="/home/kikawa/macros/nd34_tuned_11bv3.1_250ka.root";
// ---------------------------------------------------------------
// --- Add sample
TString fsignalStr="/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/pm_merged_ccqe_tot.root";
TString fbarStr="/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/pmbar_merged_ccqe.root";
TString fbkgStr="/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/wall_merged_ccqe_tot.root";
TString fbkg2Str="/home/cvson/cc1picoh/frkikawa/meAna/ip4tmva/ingrid_merged_nd3_ccqe_tot.root";
/*TString fsignalStr="/home/cvson/cc1picoh/frkikawa/meAna/ip4tmvafix/pm_merged_ccqe_tot.root";
TString fbarStr="/home/cvson/cc1picoh/frkikawa/meAna/ip4tmvafix/pmbar_merged_ccqe.root";
TString fbkgStr="/home/cvson/cc1picoh/frkikawa/meAna/ip4tmvafix/wall_merged_ccqe_tot.root";
TString fbkg2Str="/home/cvson/cc1picoh/frkikawa/meAna/ip4tmvafix/ingrid_merged_nd3_ccqe_tot.root";*/
TFile *pfileSignal = new TFile(fsignalStr);
TFile *pfileBar = new TFile(fbarStr);
TFile *pfileBkg = new TFile(fbkgStr);
TFile *pfileBkg2 = new TFile(fbkg2Str);
TFile *pfileRatio = new TFile(fratioStr);
示例6: TMVAClassification
void TMVAClassification( )
{
// this loads the library
TMVA::Tools::Instance();
std::cout << std::endl;
std::cout << "==> Start TMVAClassification" << std::endl;
// Create a new root output file.
TString outfileName( "TMVA.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
// Create the factory object.
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D" );
// ---------- input variables
factory->AddVariable("iso12x12", 'F');
factory->AddVariable("iso4x4", 'F');
factory->AddVariable("isoLshaped", 'F');
factory->AddVariable("PUM0", 'F');
// ---------- spectators ----------------
factory->AddSpectator("pt", "F");
factory->AddSpectator("eta", "F");
factory->AddSpectator("phi", "F");
factory->AddSpectator("e", "F");
// read training and test data
TString fSig = "DrellYan_Zee.root";
TString fBkg = "MinBias.root";
TFile *fileSig = TFile::Open( fSig );
TFile *fileBkg = TFile::Open( fBkg );
TTree *signal = (TTree*)fileSig->Get("tree");
TTree *background = (TTree*)fileBkg->Get("tree");
// global event weights per tree (see below for setting event-wise weights)
Double_t signalWeight = 1.0;
Double_t backgroundWeight = 1.0;
// ====== register trees ====================================================
// you can add an arbitrary number of signal or background trees
factory->AddSignalTree ( signal, signalWeight );
factory->AddBackgroundTree( background, backgroundWeight );
TCut mycuts = "pt > 10";
TCut mycutb = "pt > 10";
// tell the factory to use all remaining events in the trees after training for testing:
factory->PrepareTrainingAndTestTree( mycuts, mycutb,
"nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );
// If no numbers of events are given, half of the events in the tree are used for training, and
// the other half for testing:
// ---- Book MVA methods
// Boosted Decision Trees
factory->BookMethod( TMVA::Types::kBDT, "BDT",
"!H:!V:NTrees=400:nEventsMin=400:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );
// ---- Train MVAs using the set of training events
factory->TrainAllMethods();
// ---- Evaluate all MVAs using the set of test events
factory->TestAllMethods();
// ----- Evaluate and compare performance of all configured MVAs
factory->EvaluateAllMethods();
// Save the output
outputFile->Close();
std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
std::cout << "==> TMVAClassification is done!" << std::endl;
delete factory;
// Launch the GUI for the root macros
if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
示例7: TMVAClassificationElecTau
void TMVAClassificationElecTau(std::string ordering_ = "Pt", std::string bkg_ = "qqH115vsWZttQCD") {
TMVA::Tools::Instance();
TString outfileName( "TMVAElecTau"+ordering_+"Ord_"+bkg_+".root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassificationElecTau"+ordering_+"Ord_"+bkg_, outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D" );
factory->AddVariable( "pt1", "pT-tag1", "GeV/c" , 'F' );
factory->AddVariable( "pt2", "pT-tag2", "GeV/c" , 'F' );
factory->AddVariable( "Deta","|y-tag1 - y-tag2|","" , 'F' );
//factory->AddVariable( "opposite:=abs(eta1*eta2)/eta1/eta2","sign1*sign2","" , 'F' );
//factory->AddVariable( "Dphi", "#Delta#phi" ,"" , 'F' );
factory->AddVariable( "Mjj", "M(tag1,tag2)", "GeV/c^{2}" , 'F' );
factory->AddSpectator( "eta1", "#eta_{tag1}" , 'F' );
factory->AddSpectator( "eta2", "#eta_{tag2}" , 'F' );
factory->SetWeightExpression( "sampleWeight" );
TString fSignalName = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleVBFH115-powheg-PUS1_Open_ElecTauStream.root";
TString fBackgroundNameDYJets = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleZjets-alpgen-PUS1_Open_ElecTauStream.root";
TString fBackgroundNameWJets = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleWJets-madgraph-PUS1_Open_ElecTauStream.root";
TString fBackgroundNameQCD = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleQCD_Open_ElecTauStream.root";
TString fBackgroundNameTTbar = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/ElecTauStream2011/nTupleTTJets-madgraph-PUS1_Open_ElecTauStream.root";
TFile *fSignal(0);
TFile *fBackgroundDYJets(0);
TFile *fBackgroundWJets(0);
TFile *fBackgroundQCD(0);
TFile *fBackgroundTTbar(0);
fSignal = TFile::Open( fSignalName );
fBackgroundDYJets = TFile::Open( fBackgroundNameDYJets );
fBackgroundWJets = TFile::Open( fBackgroundNameWJets );
fBackgroundQCD = TFile::Open( fBackgroundNameQCD );
fBackgroundTTbar = TFile::Open( fBackgroundNameTTbar );
if(!fSignal || !fBackgroundDYJets || !fBackgroundWJets || !fBackgroundQCD || !fBackgroundTTbar) {
std::cout << "ERROR: could not open files" << std::endl;
exit(1);
}
TString tree = "outTree"+ordering_+"Ord";
TCut mycuts = "";
TCut mycutb = "";
TCut cutA = "pt1>0 && tightestHPSWP>0";
TCut cutB = "pt1>0 && combRelIsoLeg1<0.1";
TCut cutBl = "pt1>0 && combRelIsoLeg1<0.3";
TCut cutC = "pt1>0 && diTauCharge==0";
TCut cutD = "pt1>0 && MtLeg1<40";
// select events for training
TFile* dummy = new TFile("dummy.root","RECREATE");
TH1F* allEvents = new TH1F("allEvents","",1,-10,10);
float totalEvents, cutEvents;
// signal: all
TTree *signal = ((TTree*)(fSignal->Get(tree)))->CopyTree(cutA&&cutB&&cutC&&cutD);
cout << "Copied signal tree with full selection: " << ((TTree*)(fSignal->Get(tree)))->GetEntries() << " --> " << signal->GetEntries() << endl;
allEvents->Reset();
signal->Draw("eta1>>allEvents","sampleWeight");
cutEvents = allEvents->Integral();
Double_t signalWeight = 1.0;
cout << "Signal: expected yield " << cutEvents << " -- weight " << signalWeight << endl;
// Z+jets: all
TTree *backgroundDYJets = ((TTree*)(fBackgroundDYJets->Get(tree)))->CopyTree(cutA&&cutB&&cutC&&cutD);
cout << "Copied DYJets tree with full selection: " << ((TTree*)(fBackgroundDYJets->Get(tree)))->GetEntries() << " --> " << backgroundDYJets->GetEntries() << endl;
allEvents->Reset();
backgroundDYJets->Draw("eta1>>allEvents","sampleWeight");
cutEvents = allEvents->Integral();
Double_t backgroundDYJetsWeight = 1.0;
cout << "ZJets: expected yield " << cutEvents << " -- weight " << backgroundDYJetsWeight << endl;
// W+jets: iso+Mt
TTree *backgroundWJets = ((TTree*)(fBackgroundWJets->Get(tree)))->CopyTree(cutB&&cutD);
cout << "Copied WJets tree with iso+Mt selection: " << ((TTree*)(fBackgroundWJets->Get(tree)))->GetEntries() << " --> " << backgroundWJets->GetEntries() << endl;
allEvents->Reset();
backgroundWJets->Draw("eta1>>allEvents","sampleWeight");
totalEvents = allEvents->Integral();
allEvents->Reset();
backgroundWJets->Draw("eta1>>allEvents","sampleWeight*(tightestHPSWP>0 && diTauCharge==0)");
cutEvents = allEvents->Integral();
Double_t backgroundWJetsWeight = cutEvents / totalEvents;
cout << "WJets: expected yield " << cutEvents << " -- weight " << backgroundWJetsWeight << endl;
// QCD: Mt+loose iso
TTree *backgroundQCD = ((TTree*)(fBackgroundQCD->Get(tree)))->CopyTree(cutD&&cutBl);
cout << "Copied QCD tree with Mt selection: " << ((TTree*)(fBackgroundQCD->Get(tree)))->GetEntries() << " --> " << backgroundQCD->GetEntries() << endl;
allEvents->Reset();
backgroundQCD->Draw("eta1>>allEvents","sampleWeight");
totalEvents = allEvents->Integral();
allEvents->Reset();
backgroundQCD->Draw("eta1>>allEvents","sampleWeight*(tightestHPSWP>0 && diTauCharge==0 && combRelIsoLeg1<0.1)");
cutEvents = allEvents->Integral();
//.........这里部分代码省略.........
示例8: ZTMVAClassification
//.........这里部分代码省略.........
//factory->AddVariable( "minpioneta", "minpioneta", "", 'F' );
factory->AddVariable( "nTT", "nTT", "", 'F' );
// factory->AddVariable( "pidpimin", "pidpimin", "", 'F' );
// factory->AddVariable( "pidpimax", "pidpimax", "", 'F' );
factory->AddVariable( "normxpt", "normxpt", "", 'F' );
factory->AddVariable( "eta", "eta", "", 'F' );
//factory->AddVariable( "phi", "phi", "", 'F' );
// factory->AddVariable( "normptsum", "normptsum", "", 'F' );
//factory->AddVariable( "ptAsym", "ptAsym", "", 'F' );
//factory->AddVariable( "dphimax", "dphimax", "", 'F' );
//factory->AddVariable( "dphimin", "dphimin", "", 'F' );
//factory->AddVariable( "drmax", "drmax", "", 'F' );
// factory->AddVariable( "drmin", "drmin", "", 'F' );
// factory->AddVariable( "normpionp", "normpionp", "", 'F' );
factory->AddVariable( "normminpionpt", "normminpionpt", "", 'F' );
//factory->AddVariable( "normminpionp", "normminpionp", "", 'F' );
factory->AddVariable( "normmaxpionpt", "normmaxpionpt", "", 'F' );
// factory->AddVariable( "normptj", "normptj", "", 'F' );
//factory->AddVariable( "jmasspull", "jmasspull", "", 'F' );
//factory->AddVariable( "vchi2dof", "vchi2dof", "", 'F' );
// factory->AddVariable("maxchi2","maxchi2","", 'F');
// factory->AddVariable("normr","normr","", 'F');
// factory->AddVariable("normq","normq","", 'F');
//factory->AddVariable("normminm","normminm","", 'F');
factory->AddVariable("logipmax","logipmax","", 'F');
factory->AddVariable("logipmin","logipmin","", 'F');
factory->AddVariable("logfd","logfd",'F');
factory->AddVariable("logvd","logvd",'F');
//factory->AddVariable("pointAngle","pointingAngle",'F');
factory->AddVariable("logvpi","",'F');
//factory->AddVariable("logmaxprob","",'F');
//factory->AddVariable("logminprob","",'F');
factory->AddSpectator( "mReFit", "mReFit", "", 'D' );
// factory->AddSpectator( "Qdecay", "Qdecay", "",'F' );
// factory->AddSpectator( "m23", "m23", "",'F' );
// TFile * input_Background = new TFile("../back.root");
TFile * input_Signal = new TFile("../cmx12.root");
TFile * input_Background = new TFile("../background12.root");
std::cout << "--- TMVAClassification : Using input file for signal : " << input_Signal->GetName() << std::endl;
std::cout << "--- TMVAClassification : Using input file for backgound : " << input_Background->GetName() << std::endl;
// --- Register the training and test trees
TTree *signal = (TTree*)input_Signal->Get("psiCand");
TTree *background = (TTree*)input_Background->Get("psiCand");
// global event weights per tree (see below for setting event-wise weights)
Double_t signalWeight = 1.0;
Double_t backgroundWeight = 1.0;
// You can add an arbitrary number of signal or background trees
factory->AddSignalTree ( signal, signalWeight );
factory->AddBackgroundTree( background, backgroundWeight );
// Apply additional cuts on the signal and background samples (can be different)
TCut mycuts = "QDecay < 300&&fdchi2 > 300"; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
TCut mycutb = "QDecay < 300&&fdchi2> 300"; // for example: TCut mycutb = "abs(var1)<0.5";
factory->PrepareTrainingAndTestTree( mycuts, mycutb,
"nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );
// ---- Book MVA methods
示例9: TMVAClassification
//.........这里部分代码省略.........
// Create a ROOT output file where TMVA will store ntuples, histograms, etc.
TString outfileName( "TMVA.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
// Create the factory object. Later you can choose the methods
// whose performance you'd like to investigate. The factory is
// the only TMVA object you have to interact with
//
// The first argument is the base of the name of all the
// weightfiles in the directory weight/
//
// The second argument is the output file for the training results
// All TMVA output can be suppressed by removing the "!" (not) in
// front of the "Silent" argument in the option string
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
// If you wish to modify default settings
// (please check "src/Config.h" to see all available global options)
// (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
// (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
// Define the input variables that shall be used for the MVA training
// note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
// [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
//factory->AddVariable( "myvar1 := var1+var2", 'F' );
//factory->AddVariable( "myvar2 := var1-var2", "Expression 2", "", 'F' );
factory->AddVariable( "Lambdab_ETA", "Lambdab_ETA", "", 'F' );
factory->AddVariable( "Lambdab_P", "Lambdab_P", "", 'F' );
// You can add so-called "Spectator variables", which are not used in the MVA training,
// but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
// input variables, the response values of all trained MVAs, and the spectator variables
factory->AddSpectator( "Lambdab_PT", "Lambdab_PT", "units", 'F' );
// Read training and test data
// (it is also possible to use ASCII format as input -> see TMVA Users Guide)
TString fname_signal = "/exp/LHCb/amhis/LeptonU/tuples/montecarlo/spring16/mc-15154001-leptonU.root";
TString fname_background = "/exp/LHCb/amhis/LeptonU/tuples/data/LeptonU-total-electrons-11122015.root";
TFile *input_signal = TFile::Open( fname_signal );
TFile *input_background = TFile::Open( fname_background );
std::cout << "--- TMVAClassification : Using input file for signal: " << input_signal->GetName() << std::endl;
std::cout << "--- TMVAClassification : Using input file for background: " << input_background->GetName() << std::endl;
// --- Register the training and test trees
TTree *signal = (TTree*)input_signal->Get("Tuple_Bu2LLK_eeLine2/DecayTree");
TTree *background = (TTree*)input_background->Get("TupleFromData_Bu2LLK_eeLine2/DecayTree");
std::cout << signal << std::endl;
std::cout << background << std::endl;
// global event weights per tree (see below for setting event-wise weights)
Double_t signalWeight = 1.0;
Double_t backgroundWeight = 1.0;
// You can add an arbitrary number of signal or background trees
factory->AddSignalTree ( signal, signalWeight );
factory->AddBackgroundTree( background, backgroundWeight );
// To give different trees for training and testing, do as follows:
// factory->AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" );
// factory->AddSignalTree( signalTestTree, signalTestWeight, "Test" );
示例10: TMVAClassificationHwwNtuple
void TMVAClassificationHwwNtuple( TString myMethodList = "" )
{
// This loads the library
TMVA::Tools::Instance();
gROOT->ProcessLine(".L TMVAGui.C");
// Default MVA methods to be trained + tested
std::map<std::string,int> Use;
// --- Cut optimisation
Use["Cuts"] = 1;
Use["CutsD"] = 0;
Use["CutsPCA"] = 0;
Use["CutsGA"] = 0;
Use["CutsSA"] = 0;
//
Use["BDT"] = 1; // uses Adaptive Boost
Use["BDTG"] = 0; // uses Gradient Boost
Use["BDTB"] = 0; // uses Bagging
Use["BDTD"] = 0; // decorrelation + Adaptive Boost
Use["BDTF"] = 0; // allow usage of fisher discriminant for node splitting
//
// --- Friedman's RuleFit method, ie, an optimised series of cuts ("rules")
Use["RuleFit"] = 0;
// ---------------------------------------------------------------
std::cout << std::endl;
std::cout << "==> Start TMVAClassification" << std::endl;
// Select methods (don't look at this code - not of interest)
if (myMethodList != "") {
for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;
std::vector<TString> mlist = TMVA::gTools().SplitString( myMethodList, ',' );
for (UInt_t i=0; i<mlist.size(); i++) {
std::string regMethod(mlist[i]);
if (Use.find(regMethod) == Use.end()) {
std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
std::cout << std::endl;
return;
}
Use[regMethod] = 1;
cout<<regMethod<<" is on"<<endl;
}
}
// -------------------------------------------------------------------------
// --- Here the preparation phase begins
// Create a ROOT output file where TMVA will store ntuples, histograms, etc.
TString outfileName( "TMVA.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
// For one variable
//TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
// "!V:!Silent:Color:DrawProgressBar:Transformations=I:AnalysisType=Classification" );
// For Multiple Variables
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
//factory->AddVariable( "pt1", "LeadLepton pt", "", 'F' );
//factory->AddVariable( "pt2", "TailLepton pt", "", 'F' );
factory->AddVariable( "pfmet", "MissingEt", "", 'F' );
factory->AddVariable( "mpmet", "Minimum Proj. Met", "", 'F' );
factory->AddVariable( "dphill", "DeltPhiOfLepLep", "", 'F' );
//factory->AddVariable( "mll", "DiLepton Mass", "", 'F' );
factory->AddVariable( "ptll", "DiLepton pt", "", 'F' );
//
// You can add so-called "Spectator variables", which are not used in the MVA training,
// but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
// input variables, the response values of all trained MVAs, and the spectator variables
//factory->AddSpectator( "spec1 := var1*2", "Spectator 1", "units", 'F' );
//factory->AddSpectator( "spec2 := var1*3", "Spectator 2", "units", 'F' );
//
//factory->AddSpectator( "mWW", "Higgs Mass", "", 'F' );
factory->AddSpectator( "pt1", "LeadLepton pt", "", 'F' );
factory->AddSpectator( "pt2", "TailLepton pt", "", 'F' );
factory->AddSpectator( "pfmet", "MissingEt", "", 'F' );
factory->AddSpectator( "mpmet", "Minimum Proj. Met", "", 'F' );
factory->AddSpectator( "dphill", "DeltPhiOfLepLep", "", 'F' );
factory->AddSpectator( "mll", "DiLepton Mass", "", 'F' );
factory->AddSpectator( "ptll", "DiLepton pt", "", 'F' );
// Read training and test data
// (it is also possible to use ASCII format as input -> see TMVA Users Guide)
//TString fname = "./tmva_class_example.root";
//TString fname = "/afs/cern.ch/work/s/salee/private/HWWwidth/HWW/GGVvAnalyzer/MkNtuple/Hw1Int8TeV/MkNtuple.root";
//TString fname = "/terranova_0/HWWwidth/HWW/GGVvAnalyzer/MkNtuple/Hw1Int8TeV/MkNtuple.root";
//if (gSystem->AccessPathName( fname )) // file does not exist in local directory
// exit(-1);
//gSystem->Exec("wget http://root.cern.ch/files/tmva_class_example.root");
//TFile *input = TFile::Open( fname );
//TFile *SB_OnPeak = TFile::Open("root://eoscms.cern.ch//eos/cms/store/group/phys_higgs/cmshww/amassiro/HiggsWidth/gg2vv/latinogg2vv_Hw1_IntOnPeak_8TeV.root");
//TTree *SB_OnPeak_Tree = (TTree*)SB_OnPeak->Get("latino");
TChain *S_Chain = new TChain("latino");
TChain *C_Chain = new TChain("latino");
//.........这里部分代码省略.........
示例11: main
//.........这里部分代码省略.........
std::vector<TFile*> SignalSamples;
for(unsigned int sigIter=0;sigIter<signallist.size();++sigIter){
SignalSamples.push_back(TFile::Open((folder+signallist.at(sigIter)+"_mt_2012.root").c_str()));
}
std::vector<TTree*> backgroundTrees;
for(unsigned int iter2=0;iter2<BackgroundSamples.size();++iter2){
backgroundTrees.push_back(dynamic_cast<TTree*>(BackgroundSamples.at(iter2)->Get("ntuple")));
}
std::vector<TTree*> signalTrees;
for(unsigned int sigIter2=0;sigIter2<SignalSamples.size();++sigIter2){
signalTrees.push_back(dynamic_cast<TTree*>(SignalSamples.at(sigIter2)->Get("ntuple")));
}
TFile *outfile = new TFile((output_folder+output_name).c_str(),"RECREATE");
TMVA::Factory *factory = new TMVA::Factory(classname,outfile,"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification");
std::vector<std::string> vars;
std::ifstream parafile(paramfile2.c_str());
std::cout<<paramfile2.c_str()<<std::endl;
string line;
while(getline(parafile,line)){
vars.push_back(line);
}
parafile.close();
std::cout<<(vars.at(0)).c_str()<<std::endl;
std::vector<float> var2;
for(unsigned int variter=0;variter<vars.size();++variter){
var2.push_back(::atof((vars.at(variter)).c_str()));
}
for(unsigned int variter=0;variter<vars.size();++variter){
factory->AddVariable((vars.at(variter)).c_str(),(vars.at(variter)).c_str(),"",'F');
}
factory->AddSpectator("mt_1","mt_1","",'F');
factory->AddSpectator("n_prebjets","n_prebjets","",'I');
factory->AddSpectator("prebjetbcsv_1","prebjetbcsv_1","",'F');
factory->AddSpectator("prebjetbcsv_2","prebjetbcsv_2","",'F');
double weightval_=0;
ParseParamFile(paramfile);
for(unsigned int bckgit=0;bckgit<backgroundTrees.size();++bckgit){
auto it = sample_info_.find(bckglist.at(bckgit).c_str());
if(it!=sample_info_.end()){
double evt = it->second.first;
double xs = it->second.second;
weightval_=(double) xs/evt;
std::cout<<weightval_<<std::endl;
}
factory->AddBackgroundTree(backgroundTrees.at(bckgit),weightval_);
}
for(unsigned int sgit=0;sgit<signalTrees.size();++sgit){
auto it = sample_info_.find(signallist.at(sgit).c_str());
if(it!=sample_info_.end()){
double evt = it->second.first;
double xs=it->second.second;
weightval_=(Double_t) xs/evt;
}
std::cout<<weightval_<<std::endl;
factory->AddSignalTree(signalTrees.at(sgit),weightval_);
}
factory->SetBackgroundWeightExpression("wt");
factory->SetSignalWeightExpression("wt");
TCut mycutb, mycuts;
if(twotag){
mycutb="n_prebjets>1&&mt_1<30&&prebjetbcsv_1>0.679&&prebjetbcsv_2>0.679";
mycuts="n_prebjets>1&&mt_1<30&&prebjetbcsv_1>0.679&&prebjetbcsv_2>0.679";
}
else if(onetag){
mycutb="n_prebjets>1&&mt_1<30&&prebjetbcsv_1>0.679&&prebjetbcsv_2<0.679";
mycuts="n_prebjets>1&&mt_1<30&&prebjetbcsv_1>0.679&&prebjetbcsv_2<0.679";
}
else{
mycutb="n_prebjets>1&&mt_1<30";
mycuts="n_prebjets>1&&mt_1<30";
}
//TCut mycutb="";
//TCut mycuts="";
factory->PrepareTrainingAndTestTree( mycuts, mycutb,"SplitMode=Random:!V");
factory->BookMethod( TMVA::Types::kBDT, "BDT","!H:!V:NTrees=850:nEventsMin=150:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );
factory->TrainAllMethods();
factory->TestAllMethods();
factory->EvaluateAllMethods();
outfile->Close();
delete factory;
return 0;
}
示例12: main
int main(int argc, char * argv[])
{
//Processing input options
int c;
std::string outFname;
outFname = std::string("QualityNaF.root");
// Open input files, get the trees
TChain *mc = InputFileReader("FileListNtuples_ext.txt","parametri_geo");
// Preparing options for the TMVA::Factory
std::string options(
"!V:"
"!Silent:"
"Color:"
"DrawProgressBar:"
"Transformations=I;D;P;G,D:"
"AnalysisType=Classification"
);
//Creating the factory
TFile * ldFile = new TFile(outFname.c_str(),"RECREATE");
TMVA::Factory * factory = new TMVA::Factory("QualityNaF", ldFile, options.c_str());
//Preparing variables
//general
/*factory->AddVariable("Chisquare", 'F');
factory->AddVariable("Layernonusati", 'I');
factory->AddVariable("NTofUsed", 'I');
factory->AddVariable("diffR", 'F');
factory->AddVariable("TOF_Up_Down", 'F');*/
//Tof
//factory->AddVariable("TOFchisq_s", 'F');
//factory->AddVariable("TOFchisq_t", 'F');
//RICH
factory->AddVariable("Richtotused", 'F');
factory->AddVariable("RichPhEl", 'F');
factory->AddVariable("RICHprob", 'F');
factory->AddVariable("RICHcollovertotal");
factory->AddVariable("RICHLipBetaConsistency");
factory->AddVariable("RICHTOFBetaConsistency");
factory->AddVariable("RICHChargeConsistency");
factory->AddVariable("RICHPmts");
factory->AddVariable("RICHgetExpected");
factory->AddVariable("tot_hyp_p_uncorr");
factory->AddVariable("Bad_ClusteringRICH");
factory->AddVariable("NSecondariesRICHrich");
//factory->AddVariable("HitHValldir");
//factory->AddVariable("HitHVallrefl");
//factory->AddVariable("HVBranchCheck:= (HitHValldir - HitHVoutdir) - (HitHVallrefl - HitHVoutrefl)");
factory->AddVariable("HitHVoutdir");
factory->AddVariable("HitHVoutrefl");
//Spectator Variables
factory->AddSpectator("R", 'F');
factory->AddSpectator("BetaRICH_new", 'F');
//Preselection cuts
std::string PreSelection = "qL1>0&&(joinCutmask&187)==187&&qL1<1.75&&R>0";
std::string ChargeCut = "qUtof>0.8&&qUtof<1.3&&qLtof>0.8&&qLtof<1.3";
std::string VelocityCut = /*"Beta<0.8";*/"((joinCutmask>>11))==1024&&BetaRICH_new>0&&BetaRICH_new<0.975";
std::string signalCut = /*"(R/Beta)*(1-Beta^2)^0.5>1.65&&GenMass>1&&GenMass<2";*/"(R/BetaRICH_new)*(1-BetaRICH_new^2)^0.5>0.5&&(R/BetaRICH_new)*(1-BetaRICH_new^2)^0.5<1.5";
std::string bkgndCut = /*"(R/Beta)*(1-Beta^2)^0.5>1.65&&GenMass>0&&GenMass<1";*/"(R/BetaRICH_new)*(1-BetaRICH_new^2)^0.5>3";
factory->AddTree(mc,"Signal" ,1,(PreSelection +"&&"+ ChargeCut + "&&" + VelocityCut + "&&"+ signalCut).c_str());
factory->AddTree(mc,"Background",1,(PreSelection +"&&"+ ChargeCut + "&&" + VelocityCut + "&&"+ bkgndCut).c_str());
// Preparing
std::string preselection = "";
std::string inputparams(
"SplitMode=Random:"
"NormMode=NumEvents:"
"!V"
);
factory->PrepareTrainingAndTestTree(preselection.c_str(),inputparams.c_str());
// Training
std::string trainparams ="!H:!V:MaxDepth=3";
factory->BookMethod(TMVA::Types::kBDT, "BDT", trainparams.c_str());
trainparams ="!H:!V";
factory->BookMethod(TMVA::Types::kLikelihood, "Likelihood", trainparams.c_str());
trainparams ="!H:!V:VarTransform=Decorrelate";
//factory->BookMethod(TMVA::Types::kLikelihood, "LikelihoodD", trainparams.c_str());
trainparams ="!H:!V";
//factory->BookMethod(TMVA::Types::kCuts, "Cuts", trainparams.c_str());
factory->TrainAllMethods();
factory->TestAllMethods();
factory->EvaluateAllMethods();
}
示例13: WWTMVAClassification
//.........这里部分代码省略.........
// (please check "src/Config.h" to see all available global options)
// (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
// (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
// Define the input variables that shall be used for the MVA training
// leptonic W
factory->AddVariable("WWpt := ptlvjj", 'F');
factory->AddVariable("WWy := ylvjj", 'F');
//factory->AddVariable("Wpt := W_pt", 'F');
//factory->AddVariable("MET := event_met_pfmet", 'F');
if (chan = "mu"){
factory->AddVariable("LepCharge := W_muon_charge", 'F');
}
else if (chan = "el"){
factory->AddVariable("LepCharge := W_electron_charge", 'F');
}
else{
std::cout << "Invalid channel!" << std::endl;
return;
}
// factory->AddVariable("J1QGL := JetPFCor_QGLikelihood[0]", 'F');
// factory->AddVariable("J2QGL := JetPFCor_QGLikelihood[1]", 'F');
factory->AddVariable("costheta1 := ang_ha", 'F');
factory->AddVariable("costheta2 := ang_hb", 'F');
factory->AddVariable("costhetaS := ang_hs", 'F');
factory->AddVariable("Phi := ang_phi", 'F');
factory->AddVariable("Phi2 := ang_phib", 'F');
// You can add so-called "Spectator variables", which are not used in the MVA training,
// but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
// input variables, the response values of all trained MVAs, and the spectator variables
factory->AddSpectator("run := event_runNo", "I");
factory->AddSpectator("lumi := event_lumi", "I");
factory->AddSpectator("event := event_evtNo", "I");
factory->AddSpectator("mjj := Mass2j_PFCor", "F");
factory->AddSpectator("mlvjj := MassV2j_PFCor", "F");
factory->AddSpectator("masslvjj := masslvjj", "F");
//factory->AddSpectator("ggdevt := ggdevt", "F");
//factory->AddSpectator("fit_mlvjj := fit_mlvjj", "F");
// read training and test data
char signalOutputName[192];
sprintf(signalOutputName,"/uscms_data/d2/kalanand/WjjTrees/Full2011DataFall11MC/ReducedTree/RD_%s_HWWMH%3.0f_CMSSW428.root",chan.Data(),mH);
TFile *input1 = TFile::Open( signalOutputName );
//TFile *input1 = TFile::Open( "/uscms_data/d2/kalanand/WjjTrees/Full2011DataFall11MC/ReducedTree/RD_mu_HWWMH400_CMSSW428.root");
char backgroundOutputName[192];
sprintf(backgroundOutputName,"/uscms_data/d2/kalanand/WjjTrees/Full2011DataFall11MC/ReducedTree/RD_%s_WpJ_CMSSW428.root",chan.Data());
TFile *input2 = TFile::Open( backgroundOutputName );
std::cout << "--- TMVAClassification : Using input file: " << input1->GetName() << std::endl;
TTree *signal = (TTree*)input1->Get("WJet");
TTree *background = (TTree*)input2->Get("WJet");
// global event weights per tree (see below for setting event-wise weights)
Double_t signalWeight = 1.0;
Double_t backgroundWeight = 1.0;
// ====== register trees ====================================================
//
// the following method is the prefered one:
示例14: TMVAClassification
//.........这里部分代码省略.........
// factory->AddVariable( "mu1_nMuSegsCln", "mu1_nMuSegsCln", "", 'F' );
// factory->AddVariable( "mu1_nPixHits", "mu1_nPixHits", "", 'F' );
// factory->AddVariable( "mu1_nTrHits", "mu1_nTrHits", "", 'F' );
// factory->AddVariable( "mu1_segComp", "mu1_segComp", "", 'F' );
// factory->AddVariable( "mu1_trkEHitsOut", "mu1_trkEHitsOut", "", 'F' );
// factory->AddVariable( "mu1_trkVHits", "mu1_trkVHits", "", 'F' );
// factory->AddVariable( "mu1_validFrac", "mu1_validFrac", "", 'F' );
// factory->AddVariable( "mu1_chi2LocMom", "mu1_chi2LocMom", "", 'F' );
// factory->AddVariable( "mu1_chi2LocPos", "mu1_chi2LocPos", "", 'F' );
// factory->AddVariable( "mu2_glbTrackProb", "mu2_glbTrackProb", "", 'F' );
// factory->AddVariable( "mu2_nChi2", "mu2_nChi2", "", 'F' );
// factory->AddVariable( "mu2_nMuSegs", "mu2_nMuSegs", "", 'F' );
// factory->AddVariable( "mu2_nMuSegsCln", "mu2_nMuSegsCln", "", 'F' );
// factory->AddVariable( "mu2_nPixHits", "mu2_nPixHits", "", 'F' );
// factory->AddVariable( "mu2_nTrHits", "mu2_nTrHits", "", 'F' );
// factory->AddVariable( "mu2_segComp", "mu2_segComp", "", 'F' );
// factory->AddVariable( "mu2_trkEHitsOut", "mu2_trkEHitsOut", "", 'F' );
// factory->AddVariable( "mu2_trkVHits", "mu2_trkVHits", "", 'F' );
// factory->AddVariable( "mu2_validFrac", "mu2_validFrac", "", 'F' );
// factory->AddVariable( "mu2_chi2LocMom", "mu2_chi2LocMom", "", 'F' );
// factory->AddVariable( "mu2_chi2LocPos", "mu2_chi2LocPos", "", 'F' );
// factory->AddVariable( "l3d := ctauPV*pt/mass", "l3d", "cm", 'F' );
// factory->AddVariable( "l3dSig := ctauPV/ctauErrPV", "l3dSig", "", 'F' );
// You can add so-called "Spectator variables", which are not used in the MVA training,
// but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
// input variables, the response values of all trained MVAs, and the spectator variables
// factory->AddSpectator( "spec1 := mass*2", "Spectator 1", "units", 'F' );
// factory->AddSpectator( "spec2 := mass*3", "Spectator 2", "units", 'F' );
factory->AddSpectator( "mass", "mass", "GeV/c^{2}", 'F' );
// Read training and test data
// (it is also possible to use ASCII format as input -> see TMVA Users Guide)
if (gSystem->AccessPathName( fnameTrainS )) { // file does not exist in local directory
std::cout << "Did not access " << fnameTrainS << " exiting." << std::endl;
std::exit(4);
}
//gSystem->Exec("wget http://root.cern.ch/files/tmva_class_example.root");
TFile *inputTrainS = TFile::Open( fnameTrainS );
TFile *inputTrainB = TFile::Open( fnameTrainB );
TFile *inputTestS = TFile::Open( fnameTestS );
TFile *inputTestB = TFile::Open( fnameTestB );
// --- Register the training and test trees
TTree *signalTrainTree = (TTree*)inputTrainS->Get("probe_tree");
TTree *backgroundTrainTree = (TTree*)inputTrainB->Get("probe_tree");
TTree *signalTestTree = (TTree*)inputTestS->Get("probe_tree");
TTree *backgroundTestTree = (TTree*)inputTestB->Get("probe_tree");
// global event weights per tree (see below for setting event-wise weights)
Double_t signalTrainWeight = 1.0;
Double_t backgroundTrainWeight = 1.0;
Double_t signalTestWeight = 1.0;
Double_t backgroundTestWeight = 1.0;
// Decide if using the split and mixing or the full trees
if( fnameTrainS == fnameTestS ) {
if( fnameTrainB != fnameTestB ) {
std::cout << "This macro cannot handle cases where the same signal sample is used for training and testing, but different background samples are used.";
exit(1);
}
示例15: TMVATrainer
void TMVATrainer(){
// This loads the library
TMVA::Tools::Instance();
// --- Here the preparation phase begins
// Create a ROOT output file where TMVA will store ntuples, histograms, etc.
TString outfileName = "TMVATrainingResults_fat_BBvsGSP.root";
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
// Create the factory object. Later you can choose the methods
// whose performance you'd like to investigate. The factory is
// the only TMVA object you have to interact with
//
// The first argument is the base of the name of all the
// weightfiles in the directory weight/
//
// The second argument is the output file for the training results
// All TMVA output can be suppressed by removing the "!" (not) in
// front of the "Silent" argument in the option string
TMVA::Factory *factory = new TMVA::Factory( "TMVATrainer", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
// If you wish to modify default settings
// (please check "src/Config.h" to see all available global options)
// (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
// (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
// Define the input variables that shall be used for the MVA training
// note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
// [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
factory->AddVariable("TagVarCSV_vertexCategory","TagVarCSV_vertexCategory","units",'F');
factory->AddVariable("TagVarCSV_jetNTracks","TagVarCSV_jetNTracks","units",'F');
//factory->AddVariable("TagVarCSV_trackSip2dSig_0","TagVarCSV_trackSip2dSig_0","units",'F');
//factory->AddVariable("TagVarCSV_trackSip2dSig_1","TagVarCSV_trackSip2dSig_1","units",'F');
//factory->AddVariable("TagVarCSV_trackSip2dSig_2","TagVarCSV_trackSip2dSig_2","units",'F');
//factory->AddVariable("TagVarCSV_trackSip2dSig_3","TagVarCSV_trackSip2dSig_3","units",'F');
factory->AddVariable("TagVarCSV_trackSip3dSig_0","TagVarCSV_trackSip3dSig_0","units",'F');
factory->AddVariable("TagVarCSV_trackSip3dSig_1","TagVarCSV_trackSip3dSig_1","units",'F');
factory->AddVariable("TagVarCSV_trackSip3dSig_2","TagVarCSV_trackSip3dSig_2","units",'F');
factory->AddVariable("TagVarCSV_trackSip3dSig_3","TagVarCSV_trackSip3dSig_3","units",'F');
//factory->AddVariable("TagVarCSV_trackPtRel_0","TagVarCSV_trackPtRel_0","units",'F');
//factory->AddVariable("TagVarCSV_trackPtRel_1","TagVarCSV_trackPtRel_1","units",'F');
//factory->AddVariable("TagVarCSV_trackPtRel_2","TagVarCSV_trackPtRel_2","units",'F');
//factory->AddVariable("TagVarCSV_trackPtRel_3","TagVarCSV_trackPtRel_3","units",'F');
factory->AddVariable("TagVarCSV_trackSip2dSigAboveCharm","TagVarCSV_trackSip2dSigAboveCharm","units",'F');
//factory->AddVariable("TagVarCSV_trackSip3dSigAboveCharm","TagVarCSV_trackSip3dSigAboveCharm","units",'F');
//factory->AddVariable("TagVarCSV_trackSumJetEtRatio","TagVarCSV_trackSumJetEtRatio","units",'F');
//factory->AddVariable("TagVarCSV_trackSumJetDeltaR","TagVarCSV_trackSumJetDeltaR","units",'F');
factory->AddVariable("TagVarCSV_jetNTracksEtaRel","TagVarCSV_jetNTracksEtaRel","units",'F');
factory->AddVariable("TagVarCSV_trackEtaRel_0","TagVarCSV_trackEtaRel_0","units",'F');
factory->AddVariable("TagVarCSV_trackEtaRel_1","TagVarCSV_trackEtaRel_1","units",'F');
factory->AddVariable("TagVarCSV_trackEtaRel_2","TagVarCSV_trackEtaRel_2","units",'F');
factory->AddVariable("TagVarCSV_jetNSecondaryVertices","TagVarCSV_jetNSecondaryVertices","units",'F');
factory->AddVariable("TagVarCSV_vertexMass","TagVarCSV_vertexMass","units",'F');
factory->AddVariable("TagVarCSV_vertexNTracks","TagVarCSV_vertexNTracks","units",'F');
factory->AddVariable("TagVarCSV_vertexEnergyRatio","TagVarCSV_vertexEnergyRatio","units",'F');
factory->AddVariable("TagVarCSV_vertexJetDeltaR","TagVarCSV_vertexJetDeltaR","units",'F');
factory->AddVariable("TagVarCSV_flightDistance2dSig","TagVarCSV_flightDistance2dSig","units",'F');
//factory->AddVariable("TagVarCSV_flightDistance3dSig","TagVarCSV_flightDistance3dSig","units",'F');
// You can add so-called "Spectator variables", which are not used in the MVA training,
// but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
// input variables, the response values of all trained MVAs, and the spectator variables
factory->AddSpectator("Jet_pt","Jet_pt","units",'F');
factory->AddSpectator("Jet_eta","Jet_eta","units",'F');
factory->AddSpectator("Jet_phi","Jet_phi","units",'F');
factory->AddSpectator("Jet_mass","Jet_mass","units",'F');
factory->AddSpectator("Jet_massGroomed","Jet_massGroomed","units",'F');
factory->AddSpectator("Jet_flavour","Jet_flavour","units",'F');
factory->AddSpectator("Jet_nbHadrons","Jet_nbHadrons","units",'F');
factory->AddSpectator("Jet_JP","Jet_JP","units",'F');
factory->AddSpectator("Jet_JBP","Jet_JBP","units",'F');
factory->AddSpectator("Jet_CSV","Jet_CSV","units",'F');
factory->AddSpectator("Jet_CSVIVF","Jet_CSVIVF","units",'F');
factory->AddSpectator("Jet_tau1","Jet_tau1","units",'F');
factory->AddSpectator("Jet_tau2","Jet_tau2","units",'F');
factory->AddSpectator("SubJet1_CSVIVF","SubJet1_CSVIVF","units",'F');
factory->AddSpectator("SubJet2_CSVIVF","SubJet2_CSVIVF","units",'F');
// Read training and test data
// (it is also possible to use ASCII format as input -> see TMVA Users Guide)
TString fnameSig = "RadionToHH_4b_M-800_TuneZ2star_8TeV-Madgraph_pythia6_JetTaggingVariables_training.root";
TString fnameBkg = "QCD_Pt-300to470_TuneZ2star_8TeV_pythia6_JetTaggingVariables_training.root";
TFile *inputSig = TFile::Open( fnameSig );
TFile *inputBkg = TFile::Open( fnameBkg );
std::cout << "--- TMVAClassification : Using input files: " << inputSig->GetName() << std::endl
<< inputBkg->GetName() << std::endl;
// --- Register the training and test trees
TTree *sigTree = (TTree*)inputSig->Get("tagVars/ttree");
TTree *bkgTree = (TTree*)inputBkg->Get("tagVars/ttree");
// // global event weights per tree (see below for setting event-wise weights)
Double_t signalWeight = 1.0;
Double_t backgroundWeight = 1.0;
// factory->SetInputTrees( tree,signalCut,backgroundCut );
//.........这里部分代码省略.........