Logo ROOT   6.10/09
Reference Guide
VariableImportance.cxx
Go to the documentation of this file.
1 // @(#)root/tmva $Id$
2 // Author: Omar Zapata and Sergei Gleyzer
3 
4 /*! \class TMVA::VariableImportanceResult
5 \ingroup TMVA
6 */
7 
8 /*! \class TMVA::VariableImportance
9 \ingroup TMVA
10 */
11 
13 
14 #include "TMVA/Config.h"
15 #include "TMVA/DataSetInfo.h"
16 #include "TMVA/Envelope.h"
17 #include "TMVA/Factory.h"
18 #include "TMVA/OptionMap.h"
19 #include "TMVA/MethodBase.h"
20 #include "TMVA/MethodCategory.h"
21 #include "TMVA/MsgLogger.h"
22 #include "TMVA/Types.h"
24 
25 #include "TAxis.h"
26 #include "TGraph.h"
27 #include "TCanvas.h"
28 #include "TH1.h"
29 #include "TRandom3.h"
30 #include "TStyle.h"
31 #include "TSystem.h"
32 
33 #include <bitset>
34 #include <iostream>
35 #include <memory>
36 #include <utility>
37 
38 
39 //number of bits for bitset
40 #define NBITS 32
41 
42 ////////////////////////////////////////////////////////////////////////////////
43 
44 TMVA::VariableImportanceResult::VariableImportanceResult():fImportanceValues("VariableImportance"),
45  fImportanceHist(nullptr)
46 {
47 
48 }
49 
50 ////////////////////////////////////////////////////////////////////////////////
51 
53 {
56 }
57 
58 ////////////////////////////////////////////////////////////////////////////////
59 
61 {
64 
65  MsgLogger fLogger("VariableImportance");
66  if(fType==VIType::kShort)
67  {
68  fLogger<<kINFO<<"Variable Importance Results (Short)"<<Endl;
69  }else if(fType==VIType::kAll)
70  {
71  fLogger<<kINFO<<"Variable Importance Results (All)"<<Endl;
72  }else{
73  fLogger<<kINFO<<"Variable Importance Results (Random)"<<Endl;
74  }
75 
78 }
79 
80 ////////////////////////////////////////////////////////////////////////////////
81 
83 {
84  TCanvas *c=new TCanvas(name.Data());
85  fImportanceHist->Draw("");
86  fImportanceHist->GetXaxis()->SetTitle(" Variable Names ");
87  fImportanceHist->GetYaxis()->SetTitle(" Importance (%) ");
88  c->Draw();
89  return c;
90 }
91 
92 ////////////////////////////////////////////////////////////////////////////////
93 
94 TMVA::VariableImportance::VariableImportance(TMVA::DataLoader *dataloader):TMVA::Envelope("VariableImportance",dataloader,nullptr),fType(VIType::kShort)
95 {
96  fClassifier=std::unique_ptr<Factory>(new TMVA::Factory("VariableImportance","!V:!ROC:!ModelPersistence:Silent:Color:!DrawProgressBar:AnalysisType=Classification"));
97 }
98 
99 ////////////////////////////////////////////////////////////////////////////////
100 
102 {
103  fClassifier=nullptr;
104 }
105 
106 ////////////////////////////////////////////////////////////////////////////////
107 
109 {
110  TString methodName = fMethod.GetValue<TString>("MethodName");
111  TString methodTitle = fMethod.GetValue<TString>("MethodTitle");
112  TString methodOptions = fMethod.GetValue<TString>("MethodOptions");
113 
114  //NOTE: Put the type of VI Algorithm in the results Print
115  if(fType==VIType::kShort)
116  {
118  }else if(fType==VIType::kAll)
119  {
121  }else{
122  UInt_t nbits=fDataLoader->GetDefaultDataSetInfo().GetNVariables();
123  if(nbits<10)
124  Log()<<kERROR<<"Running variable importance with less that 10 varibales in Random mode "<<
125  "can to produce inconsisten results"<<Endl;
126  EvaluateImportanceRandom(pow(nbits,2));
127  }
128  fResults.fType = fType;
131  Log()<<kINFO<<"Evaluation done."<<Endl;
133 }
134 
135 ////////////////////////////////////////////////////////////////////////////////
136 
138 {
139  ULong_t sum=0;
140  for(ULong_t n=0;n<i;n++) sum+=pow(2,n);
141  return sum;
142 }
143 
144 ////////////////////////////////////////////////////////////////////////////////
145 
146 TH1F* TMVA::VariableImportance::GetImportance(const UInt_t nbits,std::vector<Float_t> &importances,std::vector<TString> &varNames)
147 {
148  TH1F *vihist = new TH1F("vihist", "", nbits, 0, nbits);
149 
150  gStyle->SetOptStat(000000);
151 
152  Float_t normalization = 0.0;
153  for (UInt_t i = 0; i < nbits; i++) normalization += importances[i];
154 
155  Float_t roc = 0.0;
156 
157  gStyle->SetTitleXOffset(0.4);
158  gStyle->SetTitleXOffset(1.2);
159 
160 
161  for (UInt_t i = 1; i < nbits + 1; i++) {
162  roc = 100.0 * importances[i - 1] / normalization;
163  vihist->GetXaxis()->SetBinLabel(i, varNames[i - 1].Data());
164  vihist->SetBinContent(i, roc);
165  }
166 
167  vihist->LabelsOption("v >", "X");
168  vihist->SetBarWidth(0.97);
169  vihist->SetFillColor(TColor::GetColor("#006600"));
170 
171  vihist->GetXaxis()->SetTitle(" Variable Names ");
172  vihist->GetXaxis()->SetTitleSize(0.045);
173  vihist->GetXaxis()->CenterTitle();
174  vihist->GetXaxis()->SetTitleOffset(1.24);
175 
176  vihist->GetYaxis()->SetTitle(" Importance (%)");
177  vihist->GetYaxis()->SetTitleSize(0.045);
178  vihist->GetYaxis()->CenterTitle();
179  vihist->GetYaxis()->SetTitleOffset(1.24);
180 
181  vihist->GetYaxis()->SetRangeUser(-7, 50);
182  vihist->SetDirectory(0);
183 
184  return vihist;
185 }
186 
187 ////////////////////////////////////////////////////////////////////////////////
188 
190 {
191  TString methodName = fMethod.GetValue<TString>("MethodName");
192  TString methodTitle = fMethod.GetValue<TString>("MethodTitle");
193  TString methodOptions = fMethod.GetValue<TString>("MethodOptions");
194 
195  uint32_t x = 0;
196  uint32_t y = 0;
197  //getting number of variables and variable names from loader
198  const UInt_t nbits = fDataLoader->GetDefaultDataSetInfo().GetNVariables();
199  std::vector<TString> varNames = fDataLoader->GetDefaultDataSetInfo().GetListOfVariables();
200 
201  ULong_t range = Sum(nbits);
202 
203  //vector to save importances
204  std::vector<Float_t> importances(nbits);
205  for (UInt_t i = 0; i < nbits; i++)importances[i] = 0;
206 
207  Float_t SROC, SSROC; //computed ROC value for every Seed and SubSeed
208 
209  x = range;
210 
211  std::bitset<NBITS> xbitset(x);
212  if (x == 0) Log()<<kFATAL<<"Error: need at least one variable."; //dataloader need at least one variable
213 
214 
215  //creating loader for seed
216  TMVA::DataLoader *seeddl = new TMVA::DataLoader(xbitset.to_string());
217 
218  //adding variables from seed
219  for (UInt_t index = 0; index < nbits; index++){
220  if (xbitset[index]) seeddl->AddVariable(varNames[index], 'F');
221  }
222 
223  //Loading Dataset
224  DataLoaderCopy(seeddl,fDataLoader.get());
225 
226  //Booking Seed
227  fClassifier->BookMethod(seeddl, methodName, methodTitle, methodOptions);
228 
229  //Train/Test/Evaluation
230  fClassifier->TrainAllMethods();
231  fClassifier->TestAllMethods();
232  fClassifier->EvaluateAllMethods();
233 
234  //getting ROC
235  SROC = fClassifier->GetROCIntegral(xbitset.to_string(), methodTitle);
236 
237  delete seeddl;
238  fClassifier->DeleteAllMethods();
239  fClassifier->fMethodsMap.clear();
240 
241  for (uint32_t i = 0; i < NBITS; ++i) {
242  if (x & (1 << i)) {
243  y = x & ~(1 << i);
244  std::bitset<NBITS> ybitset(y);
245  //need at least one variable
246  //NOTE: if subssed is zero then is the special case
247  //that count in xbitset is 1
248  Double_t ny = log(x - y) / 0.693147;
249  if (y == 0) {
250  importances[ny] = SROC - 0.5;
251  continue;
252  }
253 
254  //creating loader for subseed
255  TMVA::DataLoader *subseeddl = new TMVA::DataLoader(ybitset.to_string());
256  //adding variables from subseed
257  for (UInt_t index = 0; index < nbits; index++) {
258  if (ybitset[index]) subseeddl->AddVariable(varNames[index], 'F');
259  }
260 
261  //Loading Dataset
262  DataLoaderCopy(subseeddl,fDataLoader.get());
263 
264  //Booking SubSeed
265  fClassifier->BookMethod(subseeddl, methodName, methodTitle, methodOptions);
266 
267  //Train/Test/Evaluation
268  fClassifier->TrainAllMethods();
269  fClassifier->TestAllMethods();
270  fClassifier->EvaluateAllMethods();
271 
272  //getting ROC
273  SSROC = fClassifier->GetROCIntegral(ybitset.to_string(), methodTitle);
274  importances[ny] += SROC - SSROC;
275 
276  delete subseeddl;
277  fClassifier->DeleteAllMethods();
278  fClassifier->fMethodsMap.clear();
279  }
280  }
281  Float_t normalization = 0.0;
282  for (UInt_t i = 0; i < nbits; i++) normalization += importances[i];
283 
284  for(UInt_t i=0;i<nbits;i++){
285  //adding values
286  fResults.fImportanceValues[varNames[i]]=(100.0 * importances[i] / normalization);
287  //adding sufix
288  fResults.fImportanceValues[varNames[i]]=fResults.fImportanceValues.GetValue<TString>(varNames[i])+" % ";
289  }
290  fResults.fImportanceHist = std::shared_ptr<TH1F>(GetImportance(nbits,importances,varNames));
291 }
292 
293 ////////////////////////////////////////////////////////////////////////////////
294 
296 {
297  TString methodName = fMethod.GetValue<TString>("MethodName");
298  TString methodTitle = fMethod.GetValue<TString>("MethodTitle");
299  TString methodOptions = fMethod.GetValue<TString>("MethodOptions");
300 
301  TRandom3 *rangen = new TRandom3(0); //Random Gen.
302 
303  uint32_t x = 0;
304  uint32_t y = 0;
305 
306  //getting number of variables and variable names from loader
307  const UInt_t nbits = fDataLoader->GetDefaultDataSetInfo().GetNVariables();
308  std::vector<TString> varNames = fDataLoader->GetDefaultDataSetInfo().GetListOfVariables();
309 
310  ULong_t range = pow(2, nbits);
311 
312  //vector to save importances
313  std::vector<Float_t> importances(nbits);
314  Float_t importances_norm = 0;
315 
316  for (UInt_t i = 0; i < nbits; i++)importances[i] = 0;
317 
318  Float_t SROC, SSROC; //computed ROC value for every Seed and SubSeed
319 
320  x = range;
321 
322  for (UInt_t n = 0; n < seeds; n++) {
323  x = rangen -> Integer(range);
324 
325  std::bitset<NBITS> xbitset(x);
326  if (x == 0) continue; //dataloader need at least one variable
327 
328 
329  //creating loader for seed
330  TMVA::DataLoader *seeddl = new TMVA::DataLoader(xbitset.to_string());
331 
332  //adding variables from seed
333  for (UInt_t index = 0; index < nbits; index++) {
334  if (xbitset[index]) seeddl->AddVariable(varNames[index], 'F');
335  }
336 
337  //Loading Dataset
338  DataLoaderCopy(seeddl,fDataLoader.get());
339 
340  //Booking Seed
341  fClassifier->BookMethod(seeddl, methodName, methodTitle, methodOptions);
342 
343  //Train/Test/Evaluation
344  fClassifier->TrainAllMethods();
345  fClassifier->TestAllMethods();
346  fClassifier->EvaluateAllMethods();
347 
348  //getting ROC
349  SROC = fClassifier->GetROCIntegral(xbitset.to_string(), methodTitle);
350 
351  delete seeddl;
352  fClassifier->DeleteAllMethods();
353  fClassifier->fMethodsMap.clear();
354 
355  for (uint32_t i = 0; i < 32; ++i) {
356  if (x & (1 << i)) {
357  y = x & ~(1 << i);
358  std::bitset<NBITS> ybitset(y);
359  //need at least one variable
360  //NOTE: if subssed is zero then is the special case
361  //that count in xbitset is 1
362  Double_t ny = log(x - y) / 0.693147;
363  if (y == 0) {
364  importances[ny] = SROC - 0.5;
365  importances_norm += importances[ny];
366  continue;
367  }
368 
369  //creating loader for subseed
370  TMVA::DataLoader *subseeddl = new TMVA::DataLoader(ybitset.to_string());
371  //adding variables from subseed
372  for (UInt_t index = 0; index < nbits; index++) {
373  if (ybitset[index]) subseeddl->AddVariable(varNames[index], 'F');
374  }
375 
376  //Loading Dataset
377  DataLoaderCopy(subseeddl,fDataLoader.get());
378 
379  //Booking SubSeed
380  fClassifier->BookMethod(subseeddl, methodName, methodTitle, methodOptions);
381 
382  //Train/Test/Evaluation
383  fClassifier->TrainAllMethods();
384  fClassifier->TestAllMethods();
385  fClassifier->EvaluateAllMethods();
386 
387  //getting ROC
388  SSROC = fClassifier->GetROCIntegral(ybitset.to_string(), methodTitle);
389  importances[ny] += SROC - SSROC;
390 
391  delete subseeddl;
392  fClassifier->DeleteAllMethods();
393  fClassifier->fMethodsMap.clear();
394  }
395  }
396  }
397 
398  Float_t normalization = 0.0;
399  for (UInt_t i = 0; i < nbits; i++) normalization += importances[i];
400 
401  for(UInt_t i=0;i<nbits;i++){
402  //adding values
403  fResults.fImportanceValues[varNames[i]]=(100.0 * importances[i] / normalization);
404  //adding sufix
405  fResults.fImportanceValues[varNames[i]]=fResults.fImportanceValues.GetValue<TString>(varNames[i])+" % ";
406  }
407  fResults.fImportanceHist = std::shared_ptr<TH1F>(GetImportance(nbits,importances,varNames));
408  delete rangen;
409 
410 }
411 
412 ////////////////////////////////////////////////////////////////////////////////
413 
415 {
416 
417  TString methodName = fMethod.GetValue<TString>("MethodName");
418  TString methodTitle = fMethod.GetValue<TString>("MethodTitle");
419  TString methodOptions = fMethod.GetValue<TString>("MethodOptions");
420 
421  uint32_t x = 0;
422  uint32_t y = 0;
423 
424  //getting number of variables and variable names from loader
425  const UInt_t nbits = fDataLoader->GetDefaultDataSetInfo().GetNVariables();
426  std::vector<TString> varNames = fDataLoader->GetDefaultDataSetInfo().GetListOfVariables();
427 
428  ULong_t range = pow(2, nbits);
429 
430  //vector to save importances
431  std::vector<Float_t> importances(nbits);
432 
433  //vector to save ROC-Integral values
434  std::vector<Float_t> ROC(range);
435  ROC[0]=0.5;
436  for (UInt_t i = 0; i < nbits; i++) importances[i] = 0;
437 
438  Float_t SROC, SSROC; //computed ROC value
439  for ( x = 1; x <range ; x++) {
440 
441  std::bitset<NBITS> xbitset(x);
442  if (x == 0) continue; //dataloader need at least one variable
443 
444  //creating loader for seed
445  TMVA::DataLoader *seeddl = new TMVA::DataLoader(xbitset.to_string());
446 
447  //adding variables from seed
448  for (UInt_t index = 0; index < nbits; index++) {
449  if (xbitset[index]) seeddl->AddVariable(varNames[index], 'F');
450  }
451 
452  DataLoaderCopy(seeddl,fDataLoader.get());
453 
454  seeddl->PrepareTrainingAndTestTree(fDataLoader->GetDefaultDataSetInfo().GetCut("Signal"), fDataLoader->GetDefaultDataSetInfo().GetCut("Background"), fDataLoader->GetDefaultDataSetInfo().GetSplitOptions());
455 
456  //Booking Seed
457  fClassifier->BookMethod(seeddl, methodName, methodTitle, methodOptions);
458 
459  //Train/Test/Evaluation
460  fClassifier->TrainAllMethods();
461  fClassifier->TestAllMethods();
462  fClassifier->EvaluateAllMethods();
463 
464  //getting ROC
465  ROC[x] = fClassifier->GetROCIntegral(xbitset.to_string(), methodTitle);
466 
467  delete seeddl;
468  fClassifier->DeleteAllMethods();
469  fClassifier->fMethodsMap.clear();
470  }
471 
472 
473  for ( x = 0; x <range ; x++)
474  {
475  SROC=ROC[x];
476  for (uint32_t i = 0; i < NBITS; ++i) {
477  if (x & (1 << i)) {
478  y = x & ~(1 << i);
479  std::bitset<NBITS> ybitset(y);
480 
481  Float_t ny = log(x - y) / 0.693147;
482  if (y == 0) {
483  importances[ny] = SROC - 0.5;
484  continue;
485  }
486 
487  //getting ROC
488  SSROC = ROC[y];
489  importances[ny] += SROC - SSROC;
490  }
491 
492  }
493  }
494  Float_t normalization = 0.0;
495  for (UInt_t i = 0; i < nbits; i++) normalization += importances[i];
496 
497  for(UInt_t i=0;i<nbits;i++){
498  //adding values
499  fResults.fImportanceValues[varNames[i]]=(100.0 * importances[i] / normalization);
500  //adding sufix
501  fResults.fImportanceValues[varNames[i]]=fResults.fImportanceValues.GetValue<TString>(varNames[i])+" % ";
502  }
503  fResults.fImportanceHist = std::shared_ptr<TH1F>(GetImportance(nbits,importances,varNames));
504 }
virtual void SetTitleOffset(Float_t offset=1)
Set distance between the axis and the axis title Offset is a correction factor with respect to the "s...
Definition: TAttAxis.cxx:262
static long int sum(long int i)
Definition: Factory.cxx:2162
Random number generator class based on M.
Definition: TRandom3.h:27
MsgLogger & Endl(MsgLogger &ml)
Definition: MsgLogger.h:158
virtual void LabelsOption(Option_t *option="h", Option_t *axis="X")
Set option(s) to draw axis with labels.
Definition: TH1.cxx:4935
float Float_t
Definition: RtypesCore.h:53
virtual void SetDirectory(TDirectory *dir)
By default when an histogram is created, it is added to the list of histogram objects in the current ...
Definition: TH1.cxx:8053
virtual void Evaluate()
Virtual method to be implemented with your algorithm.
T GetValue(const TString &key)
Definition: OptionMap.h:144
R__EXTERN TStyle * gStyle
Definition: TStyle.h:402
THist< 1, float, THistStatContent, THistStatUncertainty > TH1F
Definition: THist.hxx:311
Config & gConfig()
MsgLogger & Log() const
Definition: Configurable.h:122
Basic string class.
Definition: TString.h:129
tomato 1-D histogram with a float per channel (see TH1 documentation)}
Definition: TH1.h:551
void DataLoaderCopy(TMVA::DataLoader *des, TMVA::DataLoader *src)
void CenterTitle(Bool_t center=kTRUE)
Center axis title.
Definition: TAxis.h:184
void AddVariable(const TString &expression, const TString &title, const TString &unit, char type='F', Double_t min=0, Double_t max=0)
user inserts discriminating variable in data set info
Definition: DataLoader.cxx:491
std::shared_ptr< TH1F > fImportanceHist
virtual void SetBarWidth(Float_t width=0.5)
Definition: TH1.h:338
TCanvas * Draw(const TString name="VariableImportance") const
virtual void SetRangeUser(Double_t ufirst, Double_t ulast)
Set the viewing range for the axis from ufirst to ulast (in user coordinates).
Definition: TAxis.cxx:927
Double_t x[n]
Definition: legend1.C:17
OptionMap fMethod
Definition: Envelope.h:38
const int ny
Definition: kalman.C:17
std::unique_ptr< Factory > fClassifier
double pow(double, double)
std::vector< std::vector< double > > Data
Base class for all machine learning algorithms.
Definition: Envelope.h:35
VariableImportance(DataLoader *loader)
void Print() const
Definition: OptionMap.h:135
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition: TAttFill.h:37
virtual void SetBinContent(Int_t bin, Double_t content)
Set bin content see convention for numbering bins in TH1::GetBin In case the bin number is greater th...
Definition: TH1.cxx:8325
unsigned int UInt_t
Definition: RtypesCore.h:42
static Int_t GetColor(const char *hexcolor)
Static method returning color number for color specified by hex color string of form: "#rrggbb"...
Definition: TColor.cxx:1707
TAxis * GetYaxis()
Definition: TH1.h:301
This is the main MVA steering class.
Definition: Factory.h:81
virtual void SetTitleSize(Float_t size=0.04)
Set size of axis title The size is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:272
const Bool_t kFALSE
Definition: RtypesCore.h:92
The Canvas class.
Definition: TCanvas.h:31
#define NBITS
void PrepareTrainingAndTestTree(const TCut &cut, const TString &splitOpt)
prepare the training and test trees -> same cuts for signal and background
Definition: DataLoader.cxx:629
double Double_t
Definition: RtypesCore.h:55
std::shared_ptr< DataLoader > fDataLoader
Definition: Envelope.h:39
unsigned long ULong_t
Definition: RtypesCore.h:51
Double_t y[n]
Definition: legend1.C:17
virtual void SetBinLabel(Int_t bin, const char *label)
Set label for bin.
Definition: TAxis.cxx:809
TH1F * GetImportance(const UInt_t nbits, std::vector< Float_t > &importances, std::vector< TString > &varNames)
ostringstream derivative to redirect and format output
Definition: MsgLogger.h:59
virtual void Draw(Option_t *option="")
Draw a canvas.
Definition: TCanvas.cxx:817
void SetTitleXOffset(Float_t offset=1)
Definition: TStyle.h:382
Abstract ClassifierFactory template that handles arbitrary types.
void SetSilent(Bool_t s)
Definition: Config.h:60
void SetOptStat(Int_t stat=1)
The type of information printed in the histogram statistics box can be selected via the parameter mod...
Definition: TStyle.cxx:1267
static void EnableOutput()
Definition: MsgLogger.cxx:75
VariableImportanceResult fResults
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition: TNamed.cxx:155
const Bool_t kTRUE
Definition: RtypesCore.h:91
void EvaluateImportanceRandom(UInt_t nseeds)
const Int_t n
Definition: legend1.C:16
double log(double)
TAxis * GetXaxis()
Definition: TH1.h:300
const char * Data() const
Definition: TString.h:347