本文整理汇总了C++中tmva::Factory类的典型用法代码示例。如果您正苦于以下问题:C++ Factory类的具体用法?C++ Factory怎么用?C++ Factory使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Factory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: TMVAClassification
void TMVAClassification()
{
TMVA::Tools::Instance();
std::cout << "==> Start TMVAClassification" << std::endl;
TString outfileName( "TMVA.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
"AnalysisType=Classification" );
factory->AddVariable("LifeTime", 'F');
factory->AddVariable("FlightDistance", 'F');
factory->AddVariable("pt", 'F');
TString fname = "../tau_data/training.root";
TFile *input = TFile::Open( fname );
TTree *tree = (TTree*)input->Get("data");
factory->AddTree(tree, "Signal", 1., "signal == 1", "Training");
factory->AddTree(tree, "Signal", 1., "signal == 1", "Test");
factory->AddTree(tree, "Background", 1., "signal == 0", "Training");
factory->AddTree(tree, "Background", 1., "signal == 0", "Test");
// gradient boosting training
factory->BookMethod(TMVA::Types::kBDT, "GBDT",
"NTrees=40:BoostType=Grad:Shrinkage=0.01:MaxDepth=7:UseNvars=6:nCuts=20:MinNodeSize=10");
factory->TrainAllMethods();
input->Close();
outputFile->Close();
delete factory;
}
示例2: TMVAClassification
void TMVAClassification(char* trainFile, char* tree,
char* mycuts, char* mycutb, char* inputVars[], int size)
{
// this loads the library
TMVA::Tools::Instance();
// Create a new root output file.
TFile* outputFile = TFile::Open( "TMVA.root", "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
for (int ivar = 0; ivar < size; ++ivar) {
factory->AddVariable(inputVars[ivar], 'F');
}
// read training and test data
TFile *input = TFile::Open( trainFile);
TTree *signal = (TTree*)input->Get(tree);
TTree *background = (TTree*)input->Get(tree);
// global event weights per tree
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 );
// tell the factory to use all remaining events in the trees after training for testing:
factory->PrepareTrainingAndTestTree( TCut(mycuts), TCut(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:
// ---- Use BDT: Adaptive Boost
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 << "==> TMVAClassification is done!" << std::endl;
delete factory;
}
示例3: main
int main ()
{
TFile * outputfile = TFile::Open ("outputTMVA.root","RECREATE");
TMVA::Factory * TMVAtest = new TMVA::Factory ("TMVAtest", outputfile, "S") ;
//PG get the signal and deliver it to the TMVA factory
TFile signalFile ("/Users/govoni/data/ntuplesHWW/H160/NTUPLE_H160_output_0.root") ;
TTree * signalTree = (TTree *) signalFile.Get ("ntpla/VBFSimpleTree") ;
std::cout << "READ " << signalTree->GetEntries () << " signal events\n" ;
TMVAtest->AddSignalTree (signalTree,1) ;
//PG get the bkg and deliver it to the TMVA factory
TFile bkg1File ("/Users/govoni/data/ntuplesHWW/WW_incl/NTUPLE_WW_incl_output_0.root") ;
TTree * bkg1Tree = (TTree *) bkg1File.Get ("ntpla/VBFSimpleTree") ;
std::cout << "READ " << bkg1Tree->GetEntries () << " bkg1 events\n" ;
TMVAtest->AddBackgroundTree (bkg1Tree,1) ;
delete TMVAtest ;
delete outputfile ;
}
示例4: Loop
void REG::Loop() {
if (fChain == 0) return;
Long64_t nentries = fChain->GetEntriesFast();
Long64_t nbytes = 0, nb = 0;
TMVA::Tools::Instance();
std::cout << std::endl;
std::cout << "==> Start TMVARegression" << std::endl;
TString outfileName( "TMVAReg.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
TMVA::Factory *factory = new TMVA::Factory( "TMVARegression", outputFile,
"!V:!Silent:Color:DrawProgressBar" );
factory->AddVariable( "l1Pt", "Variable 1", "units", 'F' );
factory->AddVariable( "l1Eta", "Variable 2", "units", 'F' );
factory->AddVariable( "l1Phi", "Variable 1", "units", 'F' );
// factory->AddVariable( "RhoL1", "Variable 2", "units", 'F' );
factory->AddTarget( "ratio" );
factory->AddRegressionTree(fChain, 1.0 );
TCut mycut = "";
factory->PrepareTrainingAndTestTree( mycut,
"nTrain_Regression=10000:nTest_Regression=0:SplitMode=Block:NormMode=NumEvents:!V" );
factory->BookMethod( TMVA::Types::kBDT, "BDT",
"!H:!V:NTrees=100:nEventsMin=5:BoostType=AdaBoostR2:SeparationType=RegressionVariance:nCuts=20:PruneMethod=CostComplexity:PruneStrength=30" );
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 << "==> TMVARegression is done!" << std::endl;
delete factory;
}
示例5: trainBJetIdMVA
void trainBJetIdMVA(TString SELECTION)
{
// the training is done using a dedicated tree format
TFile *src = TFile::Open("bjetId_"+SELECTION+".root");
TTree *tr = (TTree*)src->Get("jets");
TFile *outf = new TFile("bjetId_"+SELECTION+"_MVA.root","RECREATE");
TCut signalCut = "abs(partonId) == 5";
TCut bkgCut = "abs(partonId) != 5";
TCut preselectionCut = "btagIdx<4 && etaIdx<4 && etaIdx>-1 && ptIdx<4";
int N = 100000;
cout<<"NUMBER OF TRAINING EVENTS = "<<N<<endl;
TMVA::Factory* factory = new TMVA::Factory("factory_"+SELECTION+"_",outf,"!V:!Silent:Color:DrawProgressBar:Transformations=I;G:AnalysisType=Classification" );
factory->SetInputTrees(tr,signalCut,bkgCut);
factory->AddVariable("btagIdx",'I');
factory->AddVariable("etaIdx" ,'I');
factory->AddVariable("btag" ,'F');
factory->AddVariable("eta" ,'F');
char name[1000];
sprintf(name,"nTrain_Signal=%d:nTrain_Background=%d:nTest_Signal=%d:nTest_Background=%d",N,N,N,N);
factory->PrepareTrainingAndTestTree(preselectionCut,name);
// specify the training methods
factory->BookMethod(TMVA::Types::kLikelihood,"Likelihood");
//factory->BookMethod(TMVA::Types::kBDT,"BDT_DEF");
//factory->BookMethod(TMVA::Types::kBDT,"BDT_ADA","NTrees=600:AdaBoostBeta=0.1:nCuts=35");
//factory->BookMethod(TMVA::Types::kBDT,"BDT_GRAD1","NTrees=600:nCuts=40:BoostType=Grad:Shrinkage=0.5");
factory->BookMethod(TMVA::Types::kBDT,"BDT_GRAD2","NTrees=600:nCuts=25:BoostType=Grad:Shrinkage=0.2");
factory->TrainAllMethods();
factory->TestAllMethods();
factory->EvaluateAllMethods();
}
示例6: classifyBDT
void classifyBDT(TString inputVariables = "trainingVars.txt",
TString signalName = "/mnt/hscratch/dabercro/skims2/BDT_Signal.root",
TString backName = "/mnt/hscratch/dabercro/skims2/BDT_Background.root") {
TMVA::Tools::Instance();
std::cout << "==> Start TMVAClassification" << std::endl;
// Create a ROOT output file where TMVA will store ntuples, histograms, etc.
TString outfileName( "TMVA/TMVA.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassificationCategory", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;N" );
// A very simple MVA (feel free to uncomment and comment what you like) => as a rule of thumb 10-20 variables is where people start to get worried about total number
ifstream configFile;
configFile.open(inputVariables.Data());
TString tempFormula;
configFile >> tempFormula; // Is the name of the BDT
while(!configFile.eof()){
configFile >> tempFormula;
if(tempFormula != ""){
factory->AddVariable(tempFormula,'F');
}
}
TString lVars;
// TCut lCut = "jet1qg2<2.&&jet1pt>250.&&jet1pullAngle>-5.";// < 10 && jet1mass_m2 > 60 && jet1mass_m2 < 120";
// TCut lCut = "passZ > 3 && fjet1pt > 250 && fjet1MassPruned < 120 && fatjetid < 2";
TCut lCut = "abs(fjet1PartonId)!=24&&abs(fjet1PartonId)!=23";
// std::string lEventCut = "event % 2 == 1";
// lCut += lEventCut.c_str();
// TCut lSCut = "passT > 0 && fjet1pt > 250 && fjet1MassPruned < 120 && abs(fjet1PartonId) == 24&& fatjetid < 2";
TCut lSCut = "abs(fjet1PartonId)==24||abs(fjet1PartonId)==23";
// lSCut += lEventCut.c_str();
TCut cleanCut = "fjet1QGtagSub2 > -10 && fjet1PullAngle > -4 && abs(fjet1pt/fjet1MassTrimmed)<200 && abs(fjet1pt/fjet1MassPruned)<200";
TFile *lSAInput = TFile::Open(signalName);
TTree *lSASignal = (TTree*)lSAInput ->Get("DMSTree");
TFile *lSBInput = TFile::Open(backName);
TTree *lSBSignal = (TTree*)lSBInput ->Get("DMSTree");
Double_t lSWeight = 1.0;
Double_t lBWeight = 1.0;
gROOT->cd( outfileName+TString(":/") );
factory->AddSignalTree ( lSASignal, lSWeight );
gROOT->cd( outfileName+TString(":/") );
factory->AddBackgroundTree( lSBSignal, lBWeight );
factory->SetWeightExpression("weight");
std::stringstream pSignal,pBackground;
pSignal << "nTrain_Signal="<< lSASignal->GetEntries() << ":nTrain_Background=" << lSBSignal->GetEntries();
// factory->PrepareTrainingAndTestTree( lSCut, lCut,(pSignal.str()+":SplitMode=Block:NormMode=NumEvents:!V").c_str() );
factory->PrepareTrainingAndTestTree(lSCut&&cleanCut,lCut&&cleanCut,"nTrain_Signal=0:nTrain_Background=0:SplitMode=Alternate:NormMode=NumEvents:!V");
std::string lName = "alpha_VBF";
TString lBDTDef = "!H:!V:NTrees=400:BoostType=Grad:Shrinkage=0.1:UseBaggedGrad=F:nCuts=2000:NNodesMax=10000:MaxDepth=5:UseYesNoLeaf=F:nEventsMin=200";
// TString lBDTDef = "!H:!V:NTrees=400:BoostType=Grad:Shrinkage=0.1:UseBaggedGrad=F:nCuts=2000:MaxDepth=5:UseYesNoLeaf=F:MinNodeSize=0.086:NegWeightTreatment=IgnoreNegWeightsInTraining";
factory->BookMethod(TMVA::Types::kBDT,"BDT_simple_alpha",lBDTDef);
factory->TrainAllMethods();
factory->TestAllMethods();
factory->EvaluateAllMethods();
outputFile->Close();
std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
std::cout << "==> TMVAClassification is done!" << std::endl;
delete factory;
//if (!gROOT->IsBatch()) TMVAGui( outfileName );
//TString lBDTDef = "!H:!V:NTrees=100:BoostType=Grad:Shrinkage=0.10:UseBaggedGrad=F:nCuts=2000:NNodesMax=10000:MaxDepth=3:SeparationType=GiniIndex";
}
示例7: TMVAClassification
//.........这里部分代码省略.........
else if( index == "2" ) indexTest = "0";
fnameTestS += "_"+indexTest;
fnameTestB += "_"+indexTest;
outputFileName += "_"+index;
weightDirName += index;
}
fnameTrainS = rootDir + fnameTrainS + ".root";
fnameTrainB = rootDir + fnameTrainB + ".root";
fnameTestS = rootDir + fnameTestS + ".root";
fnameTestB = rootDir + fnameTestB + ".root";
outputFileName = rootDir + outputFileName + ".root";
weightDirName = weightsDir + weightDirName + "Weights";
// --------------------------------------------------------------------------------------------------
// --- Here the preparation phase begins
// Create a ROOT output file where TMVA will store ntuples, histograms, etc.
TString outfileName(outputFileName);
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";
// (TMVA::gConfig().GetIONames()).fWeightFileDir = outputFileName;
(TMVA::gConfig().GetIONames()).fWeightFileDir = weightDirName;
// 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" )]
bool useNewMuonID = false;
factory->AddVariable( "fls3d", "fls3d", "", 'F' );
factory->AddVariable( "alpha", "alpha", "", 'F' );
factory->AddVariable( "pvips", "pvips", "", 'F' );
factory->AddVariable( "iso", "iso", "", 'F' );
factory->AddVariable( "m1iso", "m1iso", "", 'F' );
factory->AddVariable( "m2iso", "m2iso", "", 'F' );
factory->AddVariable( "chi2dof", "chi2/dof", "", 'F' );
if( region == "barrel" ) {
factory->AddVariable( "eta", "eta", "", 'F' );
factory->AddVariable( "maxdoca", "maxdoca", "cm", 'F' );
}
else {
factory->AddVariable( "pt", "pt", "GeV/c", 'F' );
factory->AddVariable( "pvip", "pvip", "cm", 'F' );
}
factory->AddVariable( "docatrk", "docatrk", "cm", 'F' );
// factory->AddVariable( "pt", "pt", "GeV/c", 'F' );
示例8: main
int main(int argc, char**argv){
if(argc != 2){
std::cerr << " >>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
return 1;
}
parseConfigFile (argv[1]) ;
// 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();
std::vector<std::string> UseMethodName;
UseMethodName = gConfigParser -> readStringListOption("Input::UseMethodName");
std::cout << " >>>>> Input::UseMethodName size = " << UseMethodName.size() << std::endl;
std::cout << " >>>>> >>>>> ";
for (unsigned int iCat = 0; iCat < UseMethodName.size(); iCat++){
std::cout << " " << UseMethodName.at(iCat) << ", ";
}
std::cout << std::endl;
// ---------------------------------------------------------------
std::cout << std::endl;
std::cout << "==> Start TMVARegression" << std::endl;
std::map<std::string,int> Use;
for(std::vector<std::string>::iterator it=UseMethodName.begin(); it!=UseMethodName.end(); ++it) Use[*it]=0;
std::string UseMethodFlag;
try{ UseMethodFlag = gConfigParser -> readStringOption("Input::UseMethodFlag");
std::cout<< UseMethodFlag<<std::endl;
std::vector<TString> mlist = gTools().SplitString( UseMethodFlag, '/' );
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 -1;
}
Use[regMethod] = 1;
std::cout << "regMethod= " << regMethod<< " 1 "<<std::endl;
}
}
catch (char * exception){
std::cerr << " exception = Use All method " << std::endl;
for(std::vector<std::string>::iterator it=UseMethodName.begin() ;it!=UseMethodName.end(); it++) Use[*it]=1;
}
// --------------------------------------------------------------------------------------------------
// --- Here the preparation phase begins
// Create a new root output file
std::string outputFileName = gConfigParser -> readStringOption("Output::outputFileName");
std::cout<<" Output Data File = "<<outputFileName<<std::endl;
TFile* outputFile = TFile::Open( outputFileName.c_str(), "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/
// All TMVA output can be suppressed by removing the "!" (not) in
// front of the "Silent" argument in the option string
// Read training and test data (see TMVAClassification for reading ASCII files)
// load the signal and background event samples from ROOT trees
std::string inputFileList = gConfigParser -> readStringOption("Input::inputFileList");
std::string treeNameDATA = gConfigParser -> readStringOption("Input::treeNameDATA");
std::cout<<" Input Data List = "<<inputFileList<<std::endl;
TChain* treeDATA = new TChain(treeNameDATA.c_str());
FillChain(*treeDATA,inputFileList.c_str());
TMVA::Factory *factory = new TMVA::Factory( "TMVARegression", outputFile,
"!V:!Silent:Color:DrawProgressBar" );
// If you wish to modify default settings
//.........这里部分代码省略.........
示例9: testBDT
void testBDT(){
//---------------------------------------------------------------
// This loads the library
TMVA::Tools::Instance();
/*
TString outfileName( "TMVA.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
TMVA::Factory *factory = new TMVA::Factory( "testBDT", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
// global event weights per tree (see below for setting event-wise weights)
//Double_t signalWeight = 0.003582;
//Double_t backgroundWeight = 0.0269;
Double_t signalWeight = 1;
Double_t backgroundWeight = 1;
TFile *input_sig = TFile::Open( "signal_exclusif.root" );
TFile *input_wz = TFile::Open( "bruit_w_z.root" );
TTree *signal = (TTree*)input_sig->Get("tree");
TTree *background = (TTree*)input_wz->Get("tree");
// You can add an arbitrary number of signal or background trees
factory->AddSignalTree ( signal, signalWeight );
factory->AddBackgroundTree( background, backgroundWeight );
factory->AddVariable("PT_z" , 'F');
factory->AddVariable("ASYM" , 'F');
factory->AddVariable("PHI_lw_b", 'F');
factory->AddVariable("M_top", 'F');
*/
TString outfileName( "bdtTMVA_FCNC_tZ.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
TMVA::Factory *factory = new TMVA::Factory( "doBDT_FCNC_tZ", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
// global event weights per tree (see below for setting event-wise weights)
//Double_t signalWeight = 0.003582;
//Double_t backgroundWeight = 0.0269;
Double_t signalWeight = 1;
Double_t backgroundWeight = 1;
TFile *input_sig = TFile::Open( "proof.root" );
TFile *input_wz = TFile::Open( "proof.root" );
TTree *signal = (TTree*)input_sig->Get("Ttree_FCNCkut");
TTree *background_WZ = (TTree*)input_wz->Get("Ttree_WZ");
/*TTree *background_ZZ = (TTree*)input_wz->Get("Ttree_ZZ");
TTree *background_WW = (TTree*)input_wz->Get("Ttree_WW");
TTree *background_TTbar = (TTree*)input_wz->Get("Ttree_TTbar");
TTree *background_Zjets = (TTree*)input_wz->Get("Ttree_Zjets");
TTree *background_Wjets = (TTree*)input_wz->Get("Ttree_Wjets");
TTree *background_TtW = (TTree*)input_wz->Get("Ttree_TtW");
TTree *background_TbartW = (TTree*)input_wz->Get("Ttree_TbartW");*/
// You can add an arbitrary number of signal or background trees
factory->AddSignalTree ( signal, signalWeight );
factory->AddBackgroundTree( background_WZ, backgroundWeight );
/*factory->AddBackgroundTree( background_ZZ, backgroundWeight );
factory->AddBackgroundTree( background_WW, backgroundWeight );
factory->AddBackgroundTree( background_TTbar, backgroundWeight );
factory->AddBackgroundTree( background_Zjets, backgroundWeight );
factory->AddBackgroundTree( background_Wjets, backgroundWeight );
factory->AddBackgroundTree( background_TtW, backgroundWeight );
factory->AddBackgroundTree( background_TbartW, backgroundWeight );*/
factory->AddVariable("tree_topMass", 'F');
factory->AddVariable("tree_deltaPhilb", 'F');
factory->AddVariable("tree_asym", 'F');
factory->AddVariable("tree_Zpt", 'F');
// to set weights. The variable must exist in the tree
// for signal : factory->SetSignalWeightExpression ("weight1*weight2");
// for background: factory->SetBackgroundWeightExpression("weight1*weight2");
//.........这里部分代码省略.........
示例10: TMVAClassification_cc1pcoh_bdt_ver6noveract
//.........这里部分代码省略.........
Use["RuleFit"] = 1;
// ---------------------------------------------------------------
// Choose method
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;
}
}
// ---------------------------------------------------------------
// --- 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";
示例11: ZTMVAClassification
void ZTMVAClassification( TString myMethodList = "" )
{
//---------------------------------------------------------------
// This loads the library
TMVA::Tools::Instance();
// Default MVA methods to be trained + tested
std::map<std::string,int> Use;
// --- Cut optimisation
Use["Cuts"] = 0;
Use["CutsD"] = 0;
Use["CutsPCA"] = 0;
Use["CutsGA"] = 0;
Use["CutsSA"] = 0;
//
// --- 1-dimensional likelihood ("naive Bayes estimator")
Use["Likelihood"] = 0;
Use["LikelihoodD"] = 0; // the "D" extension indicates decorrelated input variables (see option strings)
Use["LikelihoodPCA"] = 0; // the "PCA" extension indicates PCA-transformed input variables (see option strings)
Use["LikelihoodKDE"] = 0;
Use["LikelihoodMIX"] = 0;
//
// --- Mutidimensional likelihood and Nearest-Neighbour methods
Use["PDERS"] = 0;
Use["PDERSD"] = 0;
Use["PDERSPCA"] = 0;
Use["PDEFoam"] = 0;
Use["PDEFoamBoost"] = 0; // uses generalised MVA method boosting
Use["KNN"] = 0; // k-nearest neighbour method
//
// --- Linear Discriminant Analysis
Use["LD"] = 0; // Linear Discriminant identical to Fisher
Use["Fisher"] = 0;
Use["FisherG"] = 0;
Use["BoostedFisher"] = 0; // uses generalised MVA method boosting
Use["HMatrix"] = 0;
//
// --- Function Discriminant analysis
Use["FDA_GA"] = 0; // minimisation of user-defined function using Genetics Algorithm
Use["FDA_SA"] = 0;
Use["FDA_MC"] = 0;
Use["FDA_MT"] = 0;
Use["FDA_GAMT"] = 0;
Use["FDA_MCMT"] = 0;
//
// --- Neural Networks (all are feed-forward Multilayer Perceptrons)
Use["MLP"] = 1; // Recommended ANN
Use["MLPBFGS"] = 0; // Recommended ANN with optional training method
Use["MLPBNN"] = 0; // Recommended ANN with BFGS training method and bayesian regulator
Use["CFMlpANN"] = 0; // Depreciated ANN from ALEPH
Use["TMlpANN"] = 0; // ROOT's own ANN
//
// --- Support Vector Machine
Use["SVM"] = 0;
//
// --- Boosted Decision Trees
Use["BDT"] = 1; // uses Adaptive Boost
Use["BDTG"] = 1; // uses Gradient Boost
Use["BDTB"] = 0; // uses Bagging
Use["BDTD"] = 1; // 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;
// --------------------------------------------------------------------------------------------------
// --- 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" );
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
//factory->AddVariable( "maxpioneta", "maxpioneta", "", 'F' );
//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' );
//.........这里部分代码省略.........
示例12: 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();
//.........这里部分代码省略.........
示例13: TMVA_stop
//.........这里部分代码省略.........
std::cout << std::endl;
std::cout << "==> Start TMVAClassification" << std::endl;
// --- Here the preparation phase begins
// Create a ROOT output file where TMVA will store ntuples, histograms, etc.
TString outfileName = "TMVA_" + signal_name + "_" + s_train_region;
if (signal_name == "T2bw") outfileName = outfileName +"_" + s_x_parameter;
outfileName += ".root";
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
TString classification_name = "classification_" + signal_name + "_" + s_train_region;
if (signal_name == "T2bw") classification_name = classification_name +"_" + s_x_parameter;
/*
TString multioutfileName( "TMVA_HWW_multi.root" );
TFile* multioutputFile;
if( doMultipleOutputs )
multioutputFile = TFile::Open( multioutfileName, "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( classification_name, outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
/*
TMVA::Factory *multifactory;
if( doMultipleOutputs )
multifactory= new TMVA::Factory( "TMVAMulticlass", multioutputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=multiclass" );
*/
// 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' );
//--------------------------------------------------------
// choose which variables to include in training
//--------------------------------------------------------
if( mvaVar[ "met" ] == 1 ) factory->AddVariable( "mini_met" , "E_{T}^{miss}" , "GeV", 'F' );
if( mvaVar[ "mt" ] == 1 ) factory->AddVariable( "mini_mt" , "M_{T}" , "GeV", 'F' );
if( mvaVar[ "mt2w" ] == 1 ) factory->AddVariable( "mini_mt2w" , "MT2W" , "GeV", 'F' );
if( mvaVar[ "mt2bl" ] == 1 ) factory->AddVariable( "mini_mt2bl" , "MT2bl" , "GeV", 'F' );
if( mvaVar[ "mt2b" ] == 1 ) factory->AddVariable( "mini_mt2b" , "MT2b" , "GeV", 'F' );
if( mvaVar[ "chi2" ] == 1 ) factory->AddVariable( "mini_chi2" , "chi2" , "" , 'F' );
if( mvaVar[ "lep1pt" ] == 1 ) factory->AddVariable( "mini_lep1pt" , "lepton pt" , "" , 'F' );
示例14: 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' );
//.........这里部分代码省略.........
示例15: TMVAMulticlass
void TMVAMulticlass(){
TString outfileName = "TMVAMulticlass.root";
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=multiclass" );
factory->AddVariable( "var0", 'F' );
factory->AddVariable( "var1", 'F' );
TFile *input(0);
TString fname = "./data.root";
if (!gSystem->AccessPathName( fname )) {
// first we try to find data.root in the local directory
std::cout << "--- TMVAMulticlass : Accessing " << fname << std::endl;
input = TFile::Open( fname );
}
else {
gROOT->LoadMacro( "./createData.C");
create_multiclassdata(20000);
cout << " created data.root for tests of the multiclass features"<<endl;
input = TFile::Open( fname );
}
if (!input) {
std::cout << "ERROR: could not open data file" << std::endl;
exit(1);
}
TTree *tree = (TTree*)input->Get("TreeR");
gROOT->cd( outfileName+TString(":/") );
factory->AddTree ( tree, "Signal1", 1. , "cls==0" );
factory->AddTree ( tree, "Signal2", 1. , "cls==1" );
factory->AddTree ( tree, "Background", 1., "cls==2" );
factory->PrepareTrainingAndTestTree( "", "SplitMode=Random:NormMode=NumEvents:!V" );
factory->BookMethod( TMVA::Types::kBDT, "BDT", "!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:GradBaggingFraction=0.6:SeparationType=GiniIndex:nCuts=20:NNodesMax=5");
factory->BookMethod( TMVA::Types::kMLP, "MLP", "!H:!V:NeuronType=tanh:VarTransform=N:NCycles=100:HiddenLayers=N+5,3:TestRate=5"); // testing vartransforms
factory->BookMethod( TMVA::Types::kMLP, "MLP2", "!H:!V:NeuronType=tanh:NCycles=100:HiddenLayers=N+5,3:TestRate=5");
factory->BookMethod( TMVA::Types::kFDA, "FDA_GA",
"H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x0*x1:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10):FitMethod=GA:PopSize=300:Cycles=3:Steps=20:Trim=True:SaveBestGen=1" );
// 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 );
}