本文整理汇总了C++中tmva::Factory::SetBackgroundWeightExpression方法的典型用法代码示例。如果您正苦于以下问题:C++ Factory::SetBackgroundWeightExpression方法的具体用法?C++ Factory::SetBackgroundWeightExpression怎么用?C++ Factory::SetBackgroundWeightExpression使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tmva::Factory
的用法示例。
在下文中一共展示了Factory::SetBackgroundWeightExpression方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: TMVAtest
void TMVAtest(){
//gSystem->Load("../lib/slc5_amd64_gcc462/libTAMUWWMEPATNtuple.so");
gSystem->Load("libPhysics");
//gSystem->Load("EvtTreeForAlexx_h.so");
gSystem->Load("libTMVA.1");
gSystem->Load("AutoDict_vector_TLorentzVector__cxx.so");
TMVA::Tools::Instance();
TFile* outputFile = TFile::Open("TMVA1.root", "RECREATE");
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification",outputFile,"V=true:Color:DrawProgressBar");// ":Transformations=I;D;P;G,D" );
TFile* signal = TFile::Open("/uscms_data/d2/aperloff/Spring12ME7TeV/MEResults/microNtuples_oldStructure/microWW_EPDv01.root");
TFile* bkg = TFile::Open("/uscms_data/d2/aperloff/Spring12ME7TeV/MEResults/microNtuples_oldStructure/microWJets_EPDv01.root");
TTree* stree = (TTree*)signal->Get("METree");
TTree* btree = (TTree*)bkg->Get("METree");
factory->AddSignalTree(stree,1.0);
factory->AddBackgroundTree(btree,1.0);
factory->SetSignalWeightExpression("1.0");
factory->SetBackgroundWeightExpression("1.0");
factory->AddVariable("tEventProb[0]");
factory->AddVariable("tEventProb[1]");
factory->AddVariable("tEventProb[2]");
//factory->AddVariable("tEventProb0 := tEventProb[0]",'F');
//factory->AddVariable("tEventProb1 := tEventProb[1]",'F');
//factory->AddVariable("tEventProb2 := tEventProb[2]",'F');
TCut test("Entry$>-2 && jLV[1].Pt()>30");
TCut mycuts (test);
factory->PrepareTrainingAndTestTree(mycuts,mycuts,"nTrain_Signal=0:nTrain_Background=0:nTest_Signal=0:nTest_Background=0:SplitMode=Random:NormMode=None:V=true:VerboseLevel=DEBUG");
factory->BookMethod( TMVA::Types::kBDT, "BDT","!H:!V:NTrees=400:nEventsMin=400:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );
factory->TrainAllMethods();
factory->TestAllMethods();
factory->EvaluateAllMethods();
outputFile->Close();
}
示例2: Classification
void Classification()
{
TMVA::Tools::Instance();
TMVA::PyMethodBase::PyInitialize();
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("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->AddSpectator("spec1 := var1*2", "Spectator 1", "units", 'F');
factory->AddSpectator("spec2 := var1*3", "Spectator 2", "units", 'F');
TString fname = "./tmva_class_example.root";
if (gSystem->AccessPathName(fname)) // file does not exist in local directory
gSystem->Exec("curl -O http://root.cern.ch/files/tmva_class_example.root");
TFile *input = TFile::Open(fname);
std::cout << "--- TMVAClassification : Using input file: " << input->GetName() << std::endl;
// --- Register the training and test trees
TTree *tsignal = (TTree *)input->Get("TreeS");
TTree *tbackground = (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(tsignal, signalWeight);
factory->AddBackgroundTree(tbackground, backgroundWeight);
// Set individual event weights (the variables must exist in the original TTree)
factory->SetBackgroundWeightExpression("weight");
// 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:nTest_Signal=0:nTest_Background=0:SplitMode=Random:NormMode=NumEvents:!V");
///////////////////
//Booking //
///////////////////
// Boosted Decision Trees
//PyMVA methods
factory->BookMethod(TMVA::Types::kPyRandomForest, "PyRandomForest",
"!V:NEstimators=150:Criterion=gini:MaxFeatures=auto:MaxDepth=3:MinSamplesLeaf=1:MinWeightFractionLeaf=0:Bootstrap=kTRUE");
factory->BookMethod(TMVA::Types::kPyAdaBoost, "PyAdaBoost",
"!V:BaseEstimator=None:NEstimators=100:LearningRate=1:Algorithm=SAMME.R:RandomState=None");
factory->BookMethod(TMVA::Types::kPyGTB, "PyGTB",
"!V:NEstimators=150:Loss=deviance:LearningRate=0.1:Subsample=1:MaxDepth=6:MaxFeatures='auto'");
// 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;
}
示例3: TMVAClassification
//.........这里部分代码省略.........
TTree * Cd116_K40_tree = (TTree*) input->Get("Cd116_K40_tree" ) ; Double_t Cd116_K40_weight = 8.9841+25.8272 ; if( Cd116_K40_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( Cd116_K40_tree , Cd116_K40_weight ); };
TTree * Cd116_Pa234m_tree = (TTree*) input->Get("Cd116_Pa234m_tree" ) ; Double_t Cd116_Pa234m_weight = 27.9307+72.4667 ; if( Cd116_Pa234m_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( Cd116_Pa234m_tree , Cd116_Pa234m_weight ); };
TTree * SFoil_Bi210_tree = (TTree*) input->Get("SFoil_Bi210_tree" ) ; Double_t SFoil_Bi210_weight = 0+23.2438 ; if( SFoil_Bi210_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( SFoil_Bi210_tree , SFoil_Bi210_weight ); };
TTree * SWire_Bi210_tree = (TTree*) input->Get("SWire_Bi210_tree" ) ; Double_t SWire_Bi210_weight = 0.136147+0.624187 ; if( SWire_Bi210_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( SWire_Bi210_tree , SWire_Bi210_weight ); };
TTree * SScin_Bi210_tree = (TTree*) input->Get("SScin_Bi210_tree" ) ; Double_t SScin_Bi210_weight = 1.75641 ; if( SScin_Bi210_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( SScin_Bi210_tree , SScin_Bi210_weight ); };
TTree * SScin_Bi214_tree = (TTree*) input->Get("SScin_Bi214_tree" ) ; Double_t SScin_Bi214_weight = 0.0510754 ; if( SScin_Bi214_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( SScin_Bi214_tree , SScin_Bi214_weight ); };
TTree * SScin_Pb214_tree = (TTree*) input->Get("SScin_Pb214_tree" ) ; Double_t SScin_Pb214_weight = 0 ; if( SScin_Pb214_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( SScin_Pb214_tree , SScin_Pb214_weight ); };
TTree * SWire_Tl208_tree = (TTree*) input->Get("SWire_Tl208_tree" ) ; Double_t SWire_Tl208_weight = 0.217623+1.07641 ; if( SWire_Tl208_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( SWire_Tl208_tree , SWire_Tl208_weight ); };
TTree * SWire_Bi214_P1_tree = (TTree*) input->Get("SWire_Bi214_tree" ) ; Double_t SWire_Bi214_weight = 21.4188+17.8236 ; if( SWire_Bi214_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( SWire_Bi214_tree , SWire_Bi214_weight ); };
TTree * SFoil_Bi214_tree = (TTree*) input->Get("SFoil_Bi214_tree" ) ; Double_t SFoil_Bi214_weight = 5.83533+2.80427 ; if( SFoil_Bi214_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( SFoil_Bi214_tree , SFoil_Bi214_weight ); };
TTree * SWire_Pb214_tree = (TTree*) input->Get("SWire_Pb214_tree" ) ; Double_t SWire_Pb214_weight = 0.458486+0.649167 ; if( SWire_Pb214_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( SWire_Pb214_tree , SWire_Pb214_weight ); };
TTree * SFoil_Pb214_tree = (TTree*) input->Get("SFoil_Pb214_tree" ) ; Double_t SFoil_Pb214_weight = 0.218761+0.195287 ; if( SFoil_Pb214_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( SFoil_Pb214_tree , SFoil_Pb214_weight ); };
TTree * FeShield_Bi214_tree = (TTree*) input->Get("FeShield_Bi214_tree" ) ; Double_t FeShield_Bi214_weight = 50.7021 ; if( FeShield_Bi214_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( FeShield_Bi214_tree , FeShield_Bi214_weight ); };
TTree * FeShield_Tl208_tree = (TTree*) input->Get("FeShield_Tl208_tree" ) ; Double_t FeShield_Tl208_weight = 0.859465 ; if( FeShield_Tl208_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( FeShield_Tl208_tree , FeShield_Tl208_weight ); };
TTree * FeShield_Ac228_tree = (TTree*) input->Get("FeShield_Ac228_tree" ) ; Double_t FeShield_Ac228_weight = 0.126868 ; if( FeShield_Ac228_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( FeShield_Ac228_tree , FeShield_Ac228_weight ); };
TTree * CuTower_Co60_tree = (TTree*) input->Get("CuTower_Co60_tree" ) ; Double_t CuTower_Co60_weight = 3.9407 ; if( CuTower_Co60_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( CuTower_Co60_tree , CuTower_Co60_weight ); };
TTree * Air_Bi214_P1_tree = (TTree*) input->Get("Air_Bi214_tree" ) ; Double_t Air_Bi214_P1_weight = 4.19744 ; if( Air_Bi214_P1_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( Air_Bi214_P1_tree , Air_Bi214_P1_weight ); };
TTree * Air_Tl208_P1_tree = (TTree*) input->Get("Air_Tl208_tree" ) ; Double_t Air_Tl208_P1_weight = 0 ; if( Air_Tl208_P1_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( Air_Tl208_P1_tree , Air_Tl208_P1_weight ); };
TTree * PMT_Bi214_tree = (TTree*) input->Get("PMT_Bi214_tree" ) ; Double_t PMT_Bi214_weight = 27.9661 ; if( PMT_Bi214_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( PMT_Bi214_tree , PMT_Bi214_weight ); };
TTree * PMT_Tl208_tree = (TTree*) input->Get("PMT_Tl208_tree" ) ; Double_t PMT_Tl208_weight = 22.923 ; if( PMT_Tl208_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( PMT_Tl208_tree , PMT_Tl208_weight ); };
TTree * PMT_Ac228_tree = (TTree*) input->Get("PMT_Ac228_tree" ) ; Double_t PMT_Ac228_weight = 3.60712 ; if( PMT_Ac228_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( PMT_Ac228_tree , PMT_Ac228_weight ); };
TTree * PMT_K40_tree = (TTree*) input->Get("PMT_K40_tree" ) ; Double_t PMT_K40_weight = 16.813 ; if( PMT_K40_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( PMT_K40_tree , PMT_K40_weight ); };
TTree * ScintInn_K40_tree = (TTree*) input->Get("ScintInn_K40_tree" ) ; Double_t ScintInn_K40_weight = 0.333988 ; if( ScintInn_K40_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( ScintInn_K40_tree , ScintInn_K40_weight ); };
TTree * ScintOut_K40_tree = (TTree*) input->Get("ScintOut_K40_tree" ) ; Double_t ScintOut_K40_weight = 0.601178 ; if( ScintOut_K40_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( ScintOut_K40_tree , ScintOut_K40_weight ); };
TTree * ScintPet_K40_tree = (TTree*) input->Get("ScintPet_K40_tree" ) ; Double_t ScintPet_K40_weight = 1.00195 ; if( ScintPet_K40_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( ScintPet_K40_tree , ScintPet_K40_weight ); };
TTree * MuMetal_Pa234m_tree = (TTree*) input->Get("MuMetal_Pa234m_tree" ) ; Double_t MuMetal_Pa234m_weight = 0.739038 ; if( MuMetal_Pa234m_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( MuMetal_Pa234m_tree , MuMetal_Pa234m_weight ); };
TTree * Cd116_2b2n_m14_tree = (TTree*) input->Get("Cd116_2b2n_m14_tree" ) ; Double_t Cd116_2b2n_m14_weight = 4977.55 ; if( Cd116_2b2n_m14_tree -> GetEntriesFast() > 0. ) {factory->AddBackgroundTree( Cd116_2b2n_m14_tree , Cd116_2b2n_m14_weight ); };
// --- end of tree registration
// Set individual event weights (the variables must exist in the original TTree)
// for signal : factory->SetSignalWeightExpression ("weight1*weight2");
// for background: factory->SetBackgroundWeightExpression("weight1*weight2");
factory->SetBackgroundWeightExpression( "weight" );
// Apply additional cuts on the signal and background samples (can be different)
// Apply cut on charge
//TCut mycuts = "min_el_sign < 0 && max_el_sign < 0.";
//TCut mycutb = "min_el_sign < 0 && max_el_sign < 0.";
// Apply cut on vertex
//TCut mycuts = "((max_vertex_x - min_vertex_x)**2 + (max_vertex_y - min_vertex_y)**2 <= 4**2)&&((max_vertex_z-min_vertex_z)**2<8**2)";
//TCut mycutb = "((max_vertex_x - min_vertex_x)**2 + (max_vertex_y - min_vertex_y)**2 <= 4**2)&&((max_vertex_z-min_vertex_z)**2<8**2)";
TCut mycuts = "";
TCut mycutb = "";
// Tell the factory how to use the training and testing events
//
// 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" );
// To also specify the number of testing events, use:
// factory->PrepareTrainingAndTestTree( mycut,
// "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" );
factory->PrepareTrainingAndTestTree( mycuts, mycutb,
"nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!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:
// "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable
示例4: main
int main(){
TMVA::Tools::Instance();
std::cout<<"Hello world"<<std::endl;
TFile* OutputFile = TFile::Open("Outputfile.root","RECREATE");
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", OutputFile,
"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
std::vector<VMVariable*> Variables;
MVariable* Var3= new MVariable("var3",F,none);
MVariable* Var4 = new MVariable("var4",F,none);
Variables.push_back(Var3);
Variables.push_back(Var4);
MVariable* Var1 = new MVariable("var1",F,none);
MVariable* Var2 = new MVariable("var2",F,none);
MultiVariable* MyVar1 = new MultiVariable("Var1+Var2",sum);
MyVar1->AddVariable(Var1);
MyVar1->AddVariable(Var2);
Variables.push_back(MyVar1);
MultiVariable* MyVar2 = new MultiVariable("Minus",subtract);
MyVar2->AddVariable(Var1);
MyVar2->AddVariable(Var2);
Variables.push_back(MyVar2);
std::string InputName= "./tmva_class_exampleD.root";
TFile *input = TFile::Open("./tmva_class_exampleD.root" );
TTree *signal = (TTree*)input->Get("TreeS");
TTree *background=(TTree*)input->Get("TreeB");
Double_t signalWeight = 1.0;
Double_t backgroundWeight = 1.0;
factory->AddSignalTree ( signal, signalWeight );
factory->AddBackgroundTree( background, backgroundWeight );
for(auto v:Variables){
factory->AddVariable(v->GetFactoryName(),v->GetType());
}
factory->SetBackgroundWeightExpression( "weight" );
TCut mycuts = "";
TCut mycutb = "";
factory->PrepareTrainingAndTestTree( mycuts, mycutb,
"nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );
std::vector<MClassifier*> Classifiers;
Classifiers.push_back(new MClassifier(TMVA::Types::kBDT, "BDT",
"!H:!V:NTrees=850:MinNodeSize=2.5%:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:UseBaggedBoost:BaggedSampleFraction=0.5:SeparationType=GiniIndex:nCuts=20"));
for(auto C:Classifiers){
if(!(C->AddMethodToFactory(factory))){
std::cout<<"Booking classifier failed"<<std::endl;
return 1;
}
}
factory->TrainAllMethods();
factory->TestAllMethods();
factory->EvaluateAllMethods();
OutputFile->Close();
delete factory;
TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );
for(auto v: Variables){
reader->AddVariable(v->GetFactoryName(),v->GetReaderAddress());
}
for(auto C:Classifiers){
if(!(C->AddMethodToReader(reader,"./weights/","TMVAClassification"))){
std::cout<<"Failed adding classifer to reader"<<std::endl;
return 1;
}
}
TFile* Input = TFile::Open("./tmva_class_exampleD.root");
TTree* TreeToEvaluate= (TTree*)Input->Get("TreeS");
TFile* AppliedFile = new TFile("AppliedFile.root","RECREATE");
TTree* AppliedTree=TreeToEvaluate->CloneTree(0);
for(auto C:Classifiers){
if(!(C->MakeBranch(AppliedTree)))return 1;
}
for(auto Var:Variables){
if(!(Var->SetBA(TreeToEvaluate))){
std::cout<<"Problem Setting Branch addresses"<<std::endl;
return 1;
//.........这里部分代码省略.........
示例5: TMVA_stop
//.........这里部分代码省略.........
//
// // --- 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];
// // add training and test events; here: first half is training, second is testing
// // note that the weight can also be event-wise
// if (i < background->GetEntries()/2) factory->AddBackgroundTrainingEvent( vars, backgroundWeight*weight );
// else factory->AddBackgroundTestEvent ( vars, backgroundWeight*weight );
// }
// // --- end ------------------------------------------------------------
//
// --- end of tree registration
// Set individual event weights (the variables must exist in the original TTree)
factory->SetSignalWeightExpression ("mini_weight");
factory->SetBackgroundWeightExpression("mini_weight");
/*
if( doMultipleOutputs ){
multifactory->AddTree(signal,"Signal");
multifactory->SetSignalWeightExpression ("event_scale1fb");
multifactory->SetBackgroundWeightExpression("event_scale1fb");
multifactory->SetWeightExpression("event_scale1fb");
if( includeBkg["ww"] ){
TTree* ww = (TTree*) chww;
multifactory->AddTree(ww,"WW");
cout << "Added WW to multi-MVA" << endl;
}
if( includeBkg["wjets"] ){
TTree* wjets = (TTree*) chwjets;
multifactory->AddTree(wjets,"WJets");
cout << "Added W+jets to multi-MVA" << endl;
}
if( includeBkg["tt"] ){
TTree* tt = (TTree*) chtt;
multifactory->AddTree(tt,"tt");
cout << "Added ttbar multi-MVA" << endl;
}
}
*/
// Apply additional cuts on the signal and background samples (can be different)
TCut mycuts = sel0; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
TCut mycutb = sel0; // for example: TCut mycutb = "abs(var1)<0.5";
// Tell the factory how to use the training and testing events
//
示例6: main
//.........这里部分代码省略.........
for (unsigned i = 0; i < bkgfiles.size(); ++i) {
std::string filename = (bkgfiles[i]+".root");
TFile * tmp = new TFile((folder+"/"+filename).c_str());
if (!tmp) {
std::cerr << "Warning, file " << filename << " could not be opened." << std::endl;
} else {
tfiles[bkgfiles[i]] = tmp;
}
}
TTree *background[bkgfiles.size()];
//signal
std::map<std::string, TFile *> sfiles;
for (unsigned i = 0; i < sigfiles.size(); ++i) {
std::string filename = (sigfiles[i]+".root");
TFile * tmp = new TFile((folder+"/"+filename).c_str());
if (!tmp) {
std::cerr << "Warning, file " << filename << " could not be opened." << std::endl;
} else {
sfiles[sigfiles[i]] = tmp;
}
}
TTree *signal[sigfiles.size()];
for (unsigned i = 0; i < bkgfiles.size(); ++i) {
std::string f = bkgfiles[i];
if (tfiles[f]){
background[i] = (TTree*)tfiles[f]->Get("TmvaInputTree");
//if (f.find("QCD-Pt")!=f.npos){
//}
Double_t backgroundWeight = 1.0;
factory->AddBackgroundTree(background[i],backgroundWeight);
factory->SetBackgroundWeightExpression("total_weight");
}//if file exist
else {
std::cout << " Cannot find background file " << f << std::endl;
}
}//loop on files
for (unsigned i = 0; i < sigfiles.size(); ++i) {
std::string f = sigfiles[i];
if (sfiles[f]){
signal[i] = (TTree*)sfiles[f]->Get("TmvaInputTree");
//if (f.find("QCD-Pt")!=f.npos){
//}
Double_t signalWeight = 1.0;
factory->AddSignalTree(signal[i],signalWeight);
factory->SetSignalWeightExpression("total_weight");
}//if file exist
else {
std::cout << " Cannot find signal file " << f << std::endl;
}
}//loop on files
// Apply additional cuts on the signal and background samples (can be different)
TCut mycuts = "";//dijet_deta>3.8 && dijet_M > 1100 && met > 100 && met_significance>5";
TCut mycutb = "";//dijet_deta>3.8 && dijet_M > 1100 && met > 100 && met_significance>5";
factory->PrepareTrainingAndTestTree( mycuts, mycutb,
"nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );
示例7: tmvaClassifier
//.........这里部分代码省略.........
// // --- 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];
// // add training and test events; here: first half is training, second is testing
// // note that the weight can also be event-wise
// if (i < background->GetEntries()/2) factory->AddBackgroundTrainingEvent( vars, backgroundWeight*weight );
// else factory->AddBackgroundTestEvent ( vars, backgroundWeight*weight );
// }
// --- end ------------------------------------------------------------
//
// --- end of tree registration
// Set individual event weights (the variables must exist in the original TTree)
// for signal : factory->SetSignalWeightExpression ("weight1*weight2");
// for background: factory->SetBackgroundWeightExpression("weight1*weight2");
factory->SetBackgroundWeightExpression( "weight" );
// 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
//
// 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" );
// To also specify the number of testing events, use:
// factory->PrepareTrainingAndTestTree( mycut,
// "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" );
factory->PrepareTrainingAndTestTree( mycuts, mycutb,
"nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!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:
// "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable
// Cut optimisation
if (Use["Cuts"])
factory->BookMethod( TMVA::Types::kCuts, "Cuts",
"!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" );
if (Use["CutsD"])
factory->BookMethod( TMVA::Types::kCuts, "CutsD",
"!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" );
示例8: TMVAClassification
//.........这里部分代码省略.........
// 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];
// for (Int_t ivar=0; ivar<4; ivar++) signal->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
// for (Int_t i=0; i<signal->GetEntries(); i++) {
// signal->GetEntry(i);
// for (Int_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) factory->AddSignalTrainingEvent( vars, signalWeight );
// else factory->AddSignalTestEvent ( vars, signalWeight );
// }
//
// for (Int_t ivar=0; ivar<4; ivar++) background->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
// for (Int_t i=0; i<background->GetEntries(); i++) {
// background->GetEntry(i);
// for (Int_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 < background->GetEntries()/2) factory->AddBackgroundTrainingEvent( vars, backgroundWeight );
// else factory->AddBackgroundTestEvent ( vars, backgroundWeight );
// }
// // --- end ------------------------------------------------------------
//
// ====== end of register trees ==============================================
}
// This would set individual event weights (the variables defined in the
// expression need to exist in the original TTree)
// for signal : factory->SetSignalWeightExpression("weight1*weight2");
// for background: factory->SetBackgroundWeightExpression("weight1*weight2");
factory->SetBackgroundWeightExpression("Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*CUT");
factory->SetSignalWeightExpression("Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*CUT");
// Apply additional cuts on the signal and background samples (can be different)
TCut mycuts = "(CUT>2)";
TCut mycutb = "(CUT>2)";
// tell the factory to use all remaining events in the trees after training for testing:
factory->PrepareTrainingAndTestTree( mycuts, "SplitMode=random:!V" );
// "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:
// factory->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
// To also specify the number of testing events, use:
// factory->PrepareTrainingAndTestTree( mycut,
// "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000: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:
// "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable
// Cut optimisation
if (Use["Cuts"])
factory->BookMethod( TMVA::Types::kCuts, "Cuts",
"!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" );
if (Use["CutsD"])
factory->BookMethod( TMVA::Types::kCuts, "CutsD",
示例9: Reg
void Reg(){
TMVA::Tools::Instance();
std::cout << "==> Start TMVARegression" << std::endl;
ifstream myfile;
myfile.open("99per.txt");
ostringstream xcS,xcH,xcP,xcC,xcN;
double xS,xH,xC,xN,xP;
if(myfile.is_open()){
while(!myfile.eof()){
myfile>>xS>>xH>>xC>>xN>>xP;
}
}
xcS<<xS;
xcH<<xH;
xcC<<xC;
xcN<<xN;
xcP<<xP;
//Output file
TString outfileName( "Ex1out_FullW_def.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
//Declaring the factory
TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
"!V:!Silent:Color:DrawProgressBar" );
//Declaring Input Varibles
factory->AddVariable( "Sieie",'F');
factory->AddVariable( "ToE", 'F' );
factory->AddVariable( "isoC",'F' );
factory->AddVariable( "isoN",'F' );
factory->AddVariable( "isoP",'F' );
TString fname = "../../CutTMVATrees_Barrel.root";
input = TFile::Open( fname );
// --- Register the regression tree
TTree *signal = (TTree*)input->Get("t_S");
TTree *background = (TTree*)input->Get("t_B");
//Just Some more settings
Double_t signalWeight = 1.0;
Double_t backgroundWeight = 1.0;
// You can add an arbitrary number of regression trees
factory->AddSignalTree( signal, signalWeight );
factory->AddBackgroundTree( background , backgroundWeight );
TCut mycuts ="";
TCut mycutb ="";
// factory->PrepareTrainingAndTestTree(mycuts,mycutb,"nTrain_Signal=9000:nTrain_Background=9000:nTest_Signal=10000:nTest_Background=10000");
factory->SetBackgroundWeightExpression("weightPT*weightXS");
factory->SetSignalWeightExpression("weightPT*weightXS");
TString methodName = "Cuts_FullsampleW_def";
TString methodOptions ="!H:!V:FitMethod=GA:EffMethod=EffSEl";
methodOptions +=":VarProp[0]=FMin:VarProp[1]=FMin:VarProp[2]=FMin:VarProp[3]=FMin:VarProp[4]=FMin";
methodOptions +=":CutRangeMax[0]="+xcS.str();
methodOptions +=":CutRangeMax[1]="+xcH.str();
methodOptions +=":CutRangeMax[2]="+xcC.str();
methodOptions +=":CutRangeMax[3]="+xcN.str();
methodOptions +=":CutRangeMax[4]="+xcP.str();
//************
factory->BookMethod(TMVA::Types::kCuts,methodName,methodOptions);
factory->TrainAllMethods();
factory->TestAllMethods();
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;
}
示例10: 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;
}
示例11: test2
void test2(){
//---------------------------------------------------------------
// This loads the library
TMVA::Tools::Instance();
TString outfileName( "trainingBDT_tZq.root" );
TFile* outputFile = TFile::Open( outfileName, "RECREATE" );
TMVA::Factory *factory = new TMVA::Factory( "BDT_trainning_tzq", outputFile,"!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
TFile *input_sig = TFile::Open( "../TreeReader/outputroot/histofile_tZq.root" );
TFile *input_wz = TFile::Open( "../TreeReader/outputroot/histofile_WZ.root" );
TTree *signal = (TTree*)input_sig->Get("Ttree_tZq");
TTree *background = (TTree*)input_wz->Get("Ttree_WZ");
factory->AddSignalTree ( signal, 1.);
factory->AddBackgroundTree( background, 1.);
std::vector<TString > varList;
varList.push_back("tree_cosThetaStar");;
varList.push_back("tree_topMass");
varList.push_back("tree_totMass");
varList.push_back("tree_deltaPhilb");
varList.push_back("tree_deltaRlb");
varList.push_back("tree_deltaRTopZ");
varList.push_back("tree_asym");
varList.push_back("tree_Zpt");
varList.push_back("tree_ZEta");
varList.push_back("tree_topPt");
varList.push_back("tree_topEta");
varList.push_back("tree_NJets");
varList.push_back("tree_NBJets");
varList.push_back("tree_deltaRZl");
varList.push_back("tree_deltaPhiZmet");
varList.push_back("tree_btagDiscri");
varList.push_back("tree_totPt");
varList.push_back("tree_totEta");
varList.push_back("tree_leptWPt");
varList.push_back("tree_leptWEta");
varList.push_back("tree_leadJetPt");
varList.push_back("tree_leadJetEta");
varList.push_back("tree_deltaRZleptW");
varList.push_back("tree_deltaPhiZleptW");
varList.push_back("tree_met" );
varList.push_back("tree_mTW" );
for(unsigned int i=0; i< varList.size() ; i++) factory->AddVariable( varList[i].Data(), 'F');
factory->SetSignalWeightExpression ("tree_EvtWeight");
factory->SetBackgroundWeightExpression("tree_EvtWeight");
// 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";
factory->PrepareTrainingAndTestTree( mycuts, mycutb,
"nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );
//factory->BookMethod( TMVA::Types::kBDT, "BDT", "!H:!V:NTrees=400:nEventsMin=400:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning:VarTransform=Decorrelate" );
// factory->BookMethod( TMVA::Types::kBDT, "BDT", "!H:!V:NTrees=100:nEventsMin=100:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning:VarTransform=Decorrelate" );
factory->BookMethod( TMVA::Types::kBDT, "BDT", "!H:!V:NTrees=100:nEventsMin=100:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning:VarTransform=Decorrelate" );
// 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 );
//.........这里部分代码省略.........
示例12: TMVAClassification
//.........这里部分代码省略.........
//
// // --- begin ----------------------------------------------------------
// std::vector<Double_t> vars( 4 ); // vector has size of number of input variables
// Float_t treevars[4];
// for (Int_t ivar=0; ivar<4; ivar++) signal->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
// for (Int_t i=0; i<signal->GetEntries(); i++) {
// signal->GetEntry(i);
// for (Int_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) factory->AddSignalTrainingEvent( vars, signalWeight );
// else factory->AddSignalTestEvent ( vars, signalWeight );
// }
//
// for (Int_t ivar=0; ivar<4; ivar++) background->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
// for (Int_t i=0; i<background->GetEntries(); i++) {
// background->GetEntry(i);
// for (Int_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 < background->GetEntries()/2) factory->AddBackgroundTrainingEvent( vars, backgroundWeight );
// else factory->AddBackgroundTestEvent ( vars, backgroundWeight );
// }
// // --- end ------------------------------------------------------------
//
// ====== end of register trees ==============================================
}
// This would set individual event weights (the variables defined in the
// expression need to exist in the original TTree)
// for signal : factory->SetSignalWeightExpression("weight1*weight2");
// for background: factory->SetBackgroundWeightExpression("weight1*weight2");
//factory->SetSignalWeightExpression("eventWeight");
factory->SetBackgroundWeightExpression("1./SLumi");
// Apply additional cuts on the signal and background samples (can be different)
TCut mycuts;
TCut mycutb;
if( charge == "plus" ) {
mycuts = "Charge==1 && SystFlag==0 && NJ>=3 && pT1>20. && pT2>20. && NbJmed>0 && TLCat==0 && Flavor<3 && PassZVeto==1"; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
mycutb = "Charge==1 && SystFlag==0 && NJ>=3 && pT1>20. && pT2>20. && NbJmed>0 && TLCat==0 && Flavor<3 && PassZVeto==1"; // for example: TCut mycutb = "abs(var1)<0.5";
} else if( charge == "minus" ) {
mycuts = "Charge==-1 && SystFlag==0 && NJ>=3 && pT1>20. && pT2>20. && NbJmed>0 && TLCat==0 && Flavor<3 && PassZVeto==1"; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
mycutb = "Charge==-1 && SystFlag==0 && NJ>=3 && pT1>20. && pT2>20. && NbJmed>0 && TLCat==0 && Flavor<3 && PassZVeto==1"; // for example: TCut mycutb = "abs(var1)<0.5";
} else if( charge == "all" ) {
mycuts = " SystFlag==0 && NJ>=3 && pT1>20. && pT2>20. && NbJmed>0 && TLCat==0 && Flavor<3 && PassZVeto==1"; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
mycutb = " SystFlag==0 && NJ>=3 && pT1>20. && pT2>20. && NbJmed>0 && TLCat==0 && Flavor<3 && PassZVeto==1"; // for example: TCut mycutb = "abs(var1)<0.5";
} else {
std::cout << "only 'plus' and 'minus' and 'all' are allowed for charge." <<std::endl;
return;
}
//if( btagMed_presel_ ) {
// mycuts += "NbJmed>0"; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
// mycutb += "NbJmed>0"; // for example: TCut mycutb = "abs(var1)<0.5";
//}
// 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:
示例13: TMVAClassification
//.........这里部分代码省略.........
for (UInt_t ivar=nvars-nvarsWithInt; ivar<nvars; ivar++) vars[ivar] = treevars2[ivar];
// add training and test events; here: first half is training, second is testing
// note that the weight can also be event-wise
//for(int ij=0; ij<nvars; ij++) cout << ij << " " << vars[ij] << endl;
if(isMC && (abs(vars[3])==4)) {
if (i%2==0) factory->AddSignalTrainingEvent( vars, weight );
else factory->AddSignalTestEvent ( vars, weight );
}
}
//
// // Background (has event weights)
background->SetBranchAddress( "weight", &weight );
for (UInt_t ivar=0; ivar<nvars-nvarsWithInt; ivar++) background->SetBranchAddress( variables[ivar].c_str(), &(treevars[ivar]) );
for (UInt_t ivar=nvars-nvarsWithInt; ivar<nvars; ivar++) background->SetBranchAddress( variables[ivar].c_str(), &(treevars2[ivar]) );
for (UInt_t i=0; i<background->GetEntries(); i++) {
background->GetEntry(i);
for (UInt_t ivar=0; ivar<nvars-nvarsWithInt; ivar++) vars[ivar] = treevars[ivar];
for (UInt_t ivar=nvars-nvarsWithInt; ivar<nvars; ivar++) vars[ivar] = treevars2[ivar];
// add training and test events; here: first half is training, second is testing
// note that the weight can also be event-wise
if(isMC && (abs(vars[3])==5)) {
if (i%2==0) factory->AddBackgroundTrainingEvent( vars, weight );
else factory->AddBackgroundTestEvent ( vars, weight );
}
}
// --- end ------------------------------------------------------------
//
// --- end of tree registration
// Set individual event weights (the variables must exist in the original TTree)
// for signal : factory->SetSignalWeightExpression ("weight1*weight2");
// for background: factory->SetBackgroundWeightExpression("weight1*weight2");
factory->SetSignalWeightExpression("weight");
factory->SetBackgroundWeightExpression( "weight" );
// 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
//
// 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" );
// To also specify the number of testing events, use:
// factory->PrepareTrainingAndTestTree( mycut,
// "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" );
factory->PrepareTrainingAndTestTree( mycuts, mycutb,
"nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!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:
// "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable
// Cut optimisation
if (Use["Cuts"])
factory->BookMethod( TMVA::Types::kCuts, "Cuts",
"!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" );
if (Use["CutsD"])
factory->BookMethod( TMVA::Types::kCuts, "CutsD",
"!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" );
示例14: 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");
}
//.........这里部分代码省略.........