本文整理汇总了C++中tmva::Factory::AddTree方法的典型用法代码示例。如果您正苦于以下问题:C++ Factory::AddTree方法的具体用法?C++ Factory::AddTree怎么用?C++ Factory::AddTree使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tmva::Factory
的用法示例。
在下文中一共展示了Factory::AddTree方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
//.........这里部分代码省略.........
// 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" );
TMVA::Factory* factory = new TMVA::Factory("TMVAMulticlass_2GeV_barrel2",outputFile,
"!V:!Silent:Color:!DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=multiclass" );
TFile* file = TFile::Open("/scratchfs/higgs/yudan/SingleParticle/Reco//all_2GeV/PID_2GeV_E30L_E10mm_H48L_H10mm_2GeV.root");
if (!file->IsOpen()) std::cout << "could not open file" <<std::endl;
TTree* treePi = (TTree*)file->Get("Pion");
if (treePi == 0) std::cout << "could not open tree" <<std::endl;
TTree* treeMu = (TTree*)file->Get("Muon");
if (treeMu == 0) std::cout << "could not open tree" <<std::endl;
TTree* treeE = (TTree*)file->Get("Electron");
if (treeE == 0) std::cout << "could not open tree" <<std::endl;
// 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" )]
// TCut mycuts = "NTrk==1 && MCPP[2]/MCPEn<0.7"; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
factory->AddTree( treePi, TString("Pi"), 1. ,"abs(cosTheta)>0.3&&abs(cosTheta)<0.55");
factory->AddTree( treeMu, TString("Mu"), 1.,"abs(cosTheta)>0.3&&abs(cosTheta)<0.55");
factory->AddTree( treeE, TString("E"), 1.,"abs(cosTheta)>0.3&&abs(cosTheta)<0.55");
factory->AddVariable("EcalNHit","EcalNHit", "units", 'I');
factory->AddVariable("HcalNHit","HcalNHit", "units", 'I');
factory->AddVariable("NLEcal","NLEcal", "units", 'I');
factory->AddVariable("NLHcal","NLHcal", "units", 'I');
factory->AddVariable("maxDisHtoL","maxDisHtoL", "units", 'F');
factory->AddVariable("avDisHtoL","avDisHtoL", "units", 'F');
factory->AddVariable("EE := EcalEn/EClu","EcalEn", "units", 'F');
factory->AddVariable("graDepth","graDepth", "units", 'F');
factory->AddVariable("cluDepth","cluDepth", "units", 'F');
factory->AddVariable("minDepth","minDepth", "units", 'F');
factory->AddVariable("MaxDisHel","MaxDisHel", "units", 'F');
factory->AddVariable("FD_all","FD_all", "units", 'F');
factory->AddVariable("FD_ECAL","FD_ECAL", "units", 'F');
factory->AddVariable("FD_HCAL","FD_HCAL", "units", 'F');
factory->AddVariable("E_10 := EEClu_L10/EcalEn","EEClu_L10", "units", 'F');
factory->AddVariable("E_R := EEClu_R/EcalEn","EEClu_R", "units", 'F');
factory->AddVariable("E_r := EEClu_r/EcalEn","EEClu_r", "units", 'F');
factory->AddVariable("rms_Hcal","rms_Hcal", "units", 'F');
factory->AddVariable("av_NHH","av_NHH", "units", 'F');
factory->AddVariable("AL_Ecal","AL_Ecal", "units", 'I');
factory->AddVariable("FD_ECALF10","FD_ECALF10", "units", 'F');
factory->AddVariable("FD_ECALL20","FD_ECALL20", "units", 'F');
factory->AddVariable("NH_ECALF10","NH_ECALF10", "units", 'I');
factory->AddVariable("dEdx","dEdx", "units", 'F');
std::cout << "--- TMVAClassification : Using input file: " << std::endl;
示例3: main
//.........这里部分代码省略.........
}
}
// --------------------------------------------------------------------------------------------------
// --- Here the preparation phase begins
// Create a new root output file
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
// TMVA::Factory *factory = new TMVA::Factory( "TMVAMulticlass", outputFile, "AnalysisType=multiclass:!V:!Silent:!V:Transformations=I;D" );
TMVA::Factory *factory = new TMVA::Factory( "TMVAMulticlass", outputFile, "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=multiclass" );
factory->AddVariable( "jetpt1" , 'F');
factory->AddVariable( "jetpt2" , 'F');
factory->AddVariable( "mjj" , 'F');
factory->AddVariable( "detajj" , 'F');
factory->AddVariable( "dphilljetjet" , 'F');
factory->AddVariable( "pt1" , 'F');
factory->AddVariable( "pt2" , 'F');
factory->AddVariable( "mll" , 'F');
factory->AddVariable( "dphill" , 'F');
factory->AddVariable( "mth" , 'F');
factory->AddVariable( "dphillmet" , 'F');
factory->AddVariable( "mpmet" , 'F');
factory->AddSpectator( "channel" , 'F');
for (int iSample=0; iSample<numberOfSamples; iSample++) {
int numEnt = treeJetLepVect[iSample]->GetEntries(Cut.c_str());
std::cout << " Sample = " << nameSample[iSample] << " ~ " << nameHumanReadable[iSample] << " --> " << numEnt << std::endl;
if (numEnt != 0) {
if (iSample == 0) factory->AddTree( treeJetLepVect[iSample], "Signal", Normalization[iSample] );
else if (iSample == 1) factory->AddTree( treeJetLepVect[iSample], "Background", Normalization[iSample] );
else factory->AddTree( treeJetLepVect[iSample], TString(nameHumanReadable[iSample]), Normalization[iSample] );
// factory->AddTree( treeJetLepVect[iSample], TString(nameHumanReadable[iSample]), Normalization[iSample] );
// factory->AddTree( treeJetLepVect[iSample], TString(nameHumanReadable[iSample]), Normalization[iSample] , nameWeight.c_str());
// factory->AddTree( treeJetLepVect[iSample], TString(nameHumanReadable[iSample]));
}
}
// for (int iSample=0; iSample<numberOfSamples; iSample++){
// int numEnt = treeJetLepVect[iSample]->GetEntries(Cut.c_str());
// std::cout << " Sample = " << nameSample[iSample] << " ~ " << nameHumanReadable[iSample] << " --> " << numEnt << std::endl;
// if (numEnt != 0) {
// bool isSig = false;
// for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
// if (nameHumanReadable[iSample] == *itSig) isSig = true;
// }
// if (isSig) {
// factory->AddTree( treeJetLepVect[iSample], TString("Signal"), Normalization[iSample] ); //---> ci deve essere uno chiamato Signal!
// }
// else {
// factory->AddTree( treeJetLepVect[iSample], TString(nameHumanReadable[iSample]), Normalization[iSample] );
// }
// }
// }
//
// for (int iSample=0; iSample<numberOfSamples; iSample++){
// int numEnt = treeJetLepVect[iSample]->GetEntries(Cut.c_str());
// std::cout << " Sample = " << nameSample[iSample] << " ~ " << nameHumanReadable[iSample] << " --> " << numEnt << std::endl;
// if (numEnt != 0) {
// bool isSig = false;
// for (std::vector<std::string>::const_iterator itSig = SignalName.begin(); itSig != SignalName.end(); itSig++){
示例4: TMVA_stop
//.........这里部分代码省略.........
// TTree* signalTestTree = (TTree*) chSignalTest;
//
// TTree* bkgTrainingTree = (TTree*) chBkgTrain;
// TTree* bkgTestTree = (TTree*) chBkgTest;
// std::cout << "--- TMVAClassification : Using bkg input files: -------------------" << std::endl;
//
// TObjArray *listOfBkgFiles = chbackground->GetListOfFiles();
// TIter bkgFileIter(listOfBkgFiles);
// TChainElement* currentBkgFile = 0;
//
// while((currentBkgFile = (TChainElement*)bkgFileIter.Next())) {
// std::cout << currentBkgFile->GetTitle() << std::endl;
// }
//
// std::cout << "--- TMVAClassification : Using sig input files: -------------------" << std::endl;
//
// TObjArray *listOfSigFiles = chsignal->GetListOfFiles();
// TIter sigFileIter(listOfSigFiles);
// TChainElement* currentSigFile = 0;
//
// while((currentSigFile = (TChainElement*)sigFileIter.Next())) {
// std::cout << currentSigFile->GetTitle() << 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 ( chSignal, signalWeight );
// factory->AddBackgroundTree( chBackground, backgroundWeight );
factory->AddTree(chSignal, "Signal", signalWeight, sel0+"mini_rand < 0.5", "train");
factory->AddTree(chSignal, "Signal", signalWeight, sel0+"mini_rand >= 0.5", "test");
factory->AddTree(chBackground, "Background", backgroundWeight, sel0+"mini_rand < 0.5", "train");
factory->AddTree(chBackground, "Background", backgroundWeight, sel0+"mini_rand >= 0.5", "test");
// To give different trees for training and testing, do as follows:
//factory->AddSignalTree( signalTrainingTree, signalWeight, "Training" );
//factory->AddSignalTree( signalTestTree, signalWeight, "Test" );
//factory->AddBackgroundTree( bkgTrainingTree, backgroundWeight, "Training" );
//factory->AddBackgroundTree( bkgTestTree, backgroundWeight, "Test" );
// Use the following code instead of the above two or four lines to add signal and background
// training and test events "by hand"
// NOTE that in this case one should not give expressions (such as "var1+var2") in the input
// variable definition, but simply compute the expression before adding the event
//
// // --- begin ----------------------------------------------------------
// std::vector<Double_t> vars( 4 ); // vector has size of number of input variables
// Float_t treevars[4], weight;
//
// // Signal
// for (UInt_t ivar=0; ivar<4; ivar++) signal->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
// for (UInt_t i=0; i<signal->GetEntries(); i++) {
// signal->GetEntry(i);
// for (UInt_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
// // add training and test events; here: first half is training, second is testing
// // note that the weight can also be event-wise
// if (i < signal->GetEntries()/2.0) factory->AddSignalTrainingEvent( vars, signalWeight );
// else factory->AddSignalTestEvent ( vars, signalWeight );
// }
//
// // Background (has event weights)
示例5: 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 );
}
示例6: TMVAKaggleHiggs
//.........这里部分代码省略.........
// [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' );
TString limit ("-900.0");
TString replacementValue ("0.0");
std::vector<std::string> vars = {"DER_mass_MMC","DER_mass_transverse_met_lep","DER_mass_vis","DER_pt_h","DER_deltaeta_jet_jet","DER_mass_jet_jet","DER_prodeta_jet_jet","DER_deltar_tau_lep","DER_pt_tot","DER_sum_pt","DER_pt_ratio_lep_tau","DER_met_phi_centrality","DER_lep_eta_centrality","PRI_tau_pt","PRI_tau_eta","PRI_tau_phi","PRI_lep_pt","PRI_lep_eta","PRI_lep_phi","PRI_met","PRI_met_phi","PRI_met_sumet","PRI_jet_num","PRI_jet_leading_pt","PRI_jet_leading_eta","PRI_jet_leading_phi","PRI_jet_subleading_pt","PRI_jet_subleading_eta","PRI_jet_subleading_phi","PRI_jet_all_pt"};
for (std::vector<std::string>::iterator it = vars.begin (), itEnd = vars.end (); it != itEnd; ++it)
{
std::string s = *it;
TString current;
current.Form ("%s:=(%s<%s?%s:%s)",s.c_str (), s.c_str (), limit.Data (), replacementValue.Data (), s.c_str ());
factory->AddVariable (current, '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' );
// global event weights per tree (see below for setting event-wise weights)
Double_t weight = 1.0;
// Double_t backgroundWeight = 1.0;
// You can add an arbitrary number of signal or background trees
// factory->AddBackgroundTree( background, backgroundWeight );
factory->AddTree(tree, "Signal", 1., "Label == 1");
factory->AddTree(tree, "Background", 1., "Label == 0");
// To give different trees for training and testing, do as follows:
// factory->AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" );
// factory->AddSignalTree( signalTestTree, signalTestWeight, "Test" );
// Use the following code instead of the above two or four lines to add signal and background
// training and test events "by hand"
// NOTE that in this case one should not give expressions (such as "var1+var2") in the input
// variable definition, but simply compute the expression before adding the event
//
// // --- begin ----------------------------------------------------------
// std::vector<Double_t> vars( 4 ); // vector has size of number of input variables
// Float_t treevars[4], weight;
//
// // Signal
// for (UInt_t ivar=0; ivar<4; ivar++) signal->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
// for (UInt_t i=0; i<signal->GetEntries(); i++) {
// signal->GetEntry(i);
// for (UInt_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
// // add training and test events; here: first half is training, second is testing
// // note that the weight can also be event-wise
// if (i < signal->GetEntries()/2.0) factory->AddSignalTrainingEvent( vars, signalWeight );
// else factory->AddSignalTestEvent ( vars, signalWeight );
// }
//
// // Background (has event weights)
// background->SetBranchAddress( "weight", &weight );
// for (UInt_t ivar=0; ivar<4; ivar++) background->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
// for (UInt_t i=0; i<background->GetEntries(); i++) {
// background->GetEntry(i);
// for (UInt_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
示例7: TMVARegression
//.........这里部分代码省略.........
// Read training and test data (see TMVAClassification for reading ASCII files)
// load the signal and background event samples from ROOT trees
/* TFile *input(0);
TString fname = "./tmva_reg_example.root";
if (!gSystem->AccessPathName( fname ))
input = TFile::Open( fname ); // check if file in local directory exists
else
input = TFile::Open( "http://root.cern.ch/files/tmva_reg_example.root" ); // if not: download from ROOT server
if (!input) {
std::cout << "ERROR: could not open data file" << std::endl;
exit(1);
}
std::cout << "--- TMVARegression : Using input file: " << input->GetName() << std::endl;
// --- Register the regression tree
TTree *regTree = (TTree*)input->Get("TreeR");
*/
TChain chainTraining("Events");
chainTraining.Add("TrainingFiles/training.root");
TTree *regTreeTraining = (TTree*) chainTraining;
TChain chainTesting("Events");
chainTesting.Add("TrainingFiles/testing.root");
TTree *regTreeTesting = (TTree*) chainTesting;
// global event weights per tree (see below for setting event-wise weights)
Double_t regWeight = 1.0;
// You can add an arbitrary number of regression trees
factory->AddTree( regTreeTraining, "Regression", regWeight, "", "training" );
factory->AddTree( regTreeTesting, "Regression", regWeight, "", "test" );
// Apply additional cuts on the signal and background samples (can be different)
TCut mycut = "hJet_pt[0]>20. && hJet_pt[1]>20. && fabs(hJet_eta[0])<2.5 && fabs(hJet_eta[1])<2.5 && hJet_csv[0]>0. && hJet_csv[1]>0. && hJet_ptLeadTrack[0]<1500. && hJet_ptLeadTrack[1]<1500. && hJet_genJetPt[0]>0. && hJet_genJetPt[1]>0. && hJet_puJetIdL[0]>0.0 && hJet_puJetIdL[1]>0.0";
TCut testingCut = "hJet_pt[0]>20. && hJet_pt[1]>20. && abs(hJet_eta[0])<2.5 && abs(hJet_eta[1])<2.5";
TCut mjjCut = "sqrt(pow(hJet_pt[0]*cos(hJet_phi[0])+hJet_pt[1]*cos(hJet_phi[1]),2)+pow(hJet_pt[0]*sin(hJet_phi[0])+hJet_pt[1]*sin(hJet_phi[1]),2)) < 110";
if(Cat==1) mjjCut = "sqrt(pow(hJet_pt[0]*cos(hJet_phi[0])+hJet_pt[1]*cos(hJet_phi[1]),2)+pow(hJet_pt[0]*sin(hJet_phi[0])+hJet_pt[1]*sin(hJet_phi[1]),2)) > 110";
TCut jetPtCut="jet_pt>90";
if(Cat==1) jetPtCut="jet_pt>90";
//TCut trainingCut = "hJet_pt[0]>20. && hJet_pt[1]>20. && abs(hJet_eta[0])<2.5 && abs(hJet_eta[1])<2.5 && hJet_genJetPt[0]>0. && hJet_genJetPt[1]>0. && hJet_csv[0]>0.0 && hJet_csv[1]>0.0 && hJet_ptLeadTrack[0]<1500. && hJet_ptLeadTrack[1]<1500.";
TCut trainingCut = "jet_pt>20. && abs(jet_eta)<2.5 && jet_genJetPt>0. && jet_dRJetGenJet < 0.4 && (jet_partonID)==5";
// for example: TCut mycut = "abs(var1)<0.5 && abs(var2-0.5)<1";
// for example: TCut mycut = "abs(var1)<0.5 && abs(var2-0.5)<1";
// tell the factory to use all remaining events in the trees after training for testing:
// factory->PrepareTrainingAndTestTree(mycut, "nTrain_Regression=600000:nTest_Regression=600000:SplitMode=Random:NormMode=NumEvents:!V");
//factory->PrepareTrainingAndTestTree(mycut, "nTrain_Regression=337500:nTest_Regression=337500:SplitMode=Random:NormMode=NumEvents:!V");
// factory->PrepareTrainingAndTestTree(mycut, "nTrain_Regression=158393:nTest_Regression=158393:SplitMode=Random:NormMode=NumEvents:!V");
//factory->PrepareTrainingAndTestTree(mycut, "nTrain_Regression=14197:nTest_Regression=14197:SplitMode=Random:NormMode=NumEvents:!V");
factory->PrepareTrainingAndTestTree(trainingCut+jetPtCut, "!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:
// factory->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
// ---- Book MVA methods
//
// please lookup the various method configuration options in the corresponding cxx files, eg:
// src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/optionRef.html
// it is possible to preset ranges in the option string in which the cut optimisation should be done:
示例8: 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();
}
示例9: TMVAMulticlass
void TMVAMulticlass( TString myMethodList = "" )
{
// This loads the library
TMVA::Tools::Instance();
// to get access to the GUI and all tmva macros
TString tmva_dir(TString(gRootDir) + "/tmva");
if(gSystem->Getenv("TMVASYS"))
tmva_dir = TString(gSystem->Getenv("TMVASYS"));
gROOT->SetMacroPath(tmva_dir + "/test/:" + gROOT->GetMacroPath() );
gROOT->ProcessLine(".L TMVAMultiClassGui.C");
//---------------------------------------------------------------
// default MVA methods to be trained + tested
std::map<std::string,int> Use;
Use["MLP"] = 1;
Use["BDTG"] = 1;
Use["FDA_GA"] = 0;
Use["PDEFoam"] = 0;
//---------------------------------------------------------------
std::cout << std::endl;
std::cout << "==> Start TMVAMulticlass" << 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 = "TMVAMulticlass.root";
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
TMVA::Factory *factory = new TMVA::Factory( "TMVAMulticlass", outputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=multiclass" );
factory->AddVariable( "var1", 'F' );
factory->AddVariable( "var2", "Variable 2", "", 'F' );
factory->AddVariable( "var3", "Variable 3", "units", 'F' );
factory->AddVariable( "var4", "Variable 4", "units", 'F' );
TFile *input(0);
TString fname = "./tmva_example_multiple_background.root";
if (!gSystem->AccessPathName( fname )) {
// first we try to find the file in the local directory
std::cout << "--- TMVAMulticlass : Accessing " << fname << std::endl;
input = TFile::Open( fname );
}
else {
cout << "Creating testdata...." << std::endl;
gROOT->ProcessLine(".L createData.C+");
gROOT->ProcessLine("create_MultipleBackground(2000)");
cout << " created tmva_example_multiple_background.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 *signal = (TTree*)input->Get("TreeS");
TTree *background0 = (TTree*)input->Get("TreeB0");
TTree *background1 = (TTree*)input->Get("TreeB1");
TTree *background2 = (TTree*)input->Get("TreeB2");
gROOT->cd( outfileName+TString(":/") );
factory->AddTree (signal,"Signal");
factory->AddTree (background0,"bg0");
factory->AddTree (background1,"bg1");
factory->AddTree (background2,"bg2");
factory->PrepareTrainingAndTestTree( "", "SplitMode=Random:NormMode=NumEvents:!V" );
if (Use["BDTG"]) // gradient boosted decision trees
factory->BookMethod( TMVA::Types::kBDT, "BDTG", "!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.10:UseBaggedBoost:BaggedSampleFraction=0.50:nCuts=20:MaxDepth=2");
if (Use["MLP"]) // neural network
factory->BookMethod( TMVA::Types::kMLP, "MLP", "!H:!V:NeuronType=tanh:NCycles=1000:HiddenLayers=N+5,5:TestRate=5:EstimatorType=MSE");
if (Use["FDA_GA"]) // functional discriminant with GA minimizer
factory->BookMethod( TMVA::Types::kFDA, "FDA_GA", "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:PopSize=300:Cycles=3:Steps=20:Trim=True:SaveBestGen=1" );
if (Use["PDEFoam"]) // PDE-Foam approach
factory->BookMethod( TMVA::Types::kPDEFoam, "PDEFoam", "!H:!V:TailCut=0.001:VolFrac=0.0666:nActiveCells=500:nSampl=2000:nBin=5:Nmin=100:Kernel=None:Compress=T" );
// Train MVAs using the set of training events
factory->TrainAllMethods();
// ---- Evaluate all MVAs using the set of test events
factory->TestAllMethods();
//.........这里部分代码省略.........
示例10: tmstr
std::pair<TString,TString> TMVAClassification (
TString infilename,
AnalysisType analysisType = AnalysisType::DIRECT,
TString additionalRootFileName = "")
{
TMVA::Tools::Instance();
std::string tmstr (now ());
TString tmstmp (tmstr.c_str ());
std::cout << "==> Start TMVAClassification" << std::endl;
std::cout << "-------------------- open input file ---------------- " << std::endl;
TString fname = infilename; //pathToData + infilename + TString (".root");
if (analysisType != AnalysisType::TRANSFORMED)
fname = pathToData + infilename + TString (".root");
std::cout << "open file " << std::endl << fname.Data () << std::endl;
std::cout << "-------------------- get tree ---------------- " << std::endl;
TString treeName = "data";
if (analysisType == AnalysisType::TRANSFORMED)
treeName = "transformed";
std::cout << "-------------------- create tchain with treeName ---------------- " << std::endl;
std::cout << treeName << std::endl;
TChain* tree = new TChain (treeName);
std::cout << "add file" << std::endl;
std::cout << fname << std::endl;
tree->Add (fname);
TChain* treeFriend (NULL);
if (additionalRootFileName.Length () > 0)
{
std::cout << "-------------------- add additional input file ---------------- " << std::endl;
std::cout << additionalRootFileName << std::endl;
treeFriend = new TChain (treeName);
treeFriend->Add (additionalRootFileName);
tree->AddFriend (treeFriend,"p");
}
// tree->Draw ("mass:prediction");
// return std::make_pair(TString("hallo"),TString ("nix"));
TString outfileName;
if (analysisType == AnalysisType::BACKGROUND)
{
outfileName = TString ("BACK_" + infilename) + tmstmp + TString (".root");
}
else
outfileName += TString ( "TMVA__" ) + tmstmp + TString (".root");
std::cout << "-------------------- open output file ---------------- " << std::endl;
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
std::cout << "-------------------- prepare factory ---------------- " << std::endl;
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
"AnalysisType=Classification:Transformations=I:!V" );
std::cout << "-------------------- add variables ---------------- " << std::endl;
for (auto varname : variableNames)
{
factory->AddVariable (varname.c_str (), 'F');
}
for (auto varname : spectatorNames)
{
factory->AddSpectator (varname.c_str (), 'F');
}
std::cout << "-------------------- add trees ---------------- " << std::endl;
TCut signalCut ("signal==1");
TCut backgroundCut ("signal==0");
if (analysisType == AnalysisType::TRANSFORMED)
{
signalCut = "(signal_original==1 && signal_in==0)";
backgroundCut = "(signal_original==0 && signal_in==0)";
}
if (analysisType == AnalysisType::BACKGROUND)
{
signalCut = TString("(signal==0) * (prediction > 0.7)");
backgroundCut = TString("(signal==0) * (prediction < 0.4)");
}
//tree->Draw ("prediction",signalCut);
//return std::make_pair(TString("hallo"),TString ("nix"));
factory->AddTree(tree, "Signal", 1.0, baseCut + signalCut, "TrainingTesting");
factory->AddTree(tree, "Background", 1.0, baseCut + backgroundCut, "TrainingTesting");
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";
/* // Set individual event weights (the variables must exist in the original TTree) */
if (analysisType == AnalysisType::BACKGROUND)
{
factory->SetSignalWeightExpression ("prediction");
factory->SetBackgroundWeightExpression ("1");
}
//.........这里部分代码省略.........