Logo ROOT   6.16/01
Reference Guide
MethodPyAdaBoost.cxx
Go to the documentation of this file.
1// @(#)root/tmva/pymva $Id$
2// Authors: Omar Zapata, Lorenzo Moneta, Sergei Gleyzer 2015
3
4/**********************************************************************************
5 * Project: TMVA - a Root-integrated toolkit for multivariate data analysis *
6 * Package: TMVA *
7 * Class : MethodPyAdaBoost *
8 * Web : http://oproject.org *
9 * *
10 * Description: *
11 * AdaBoost Classifier from Scikit learn *
12 * *
13 * *
14 * Redistribution and use in source and binary forms, with or without *
15 * modification, are permitted according to the terms listed in LICENSE *
16 * (http://tmva.sourceforge.net/LICENSE) *
17 * *
18 **********************************************************************************/
19
20#include <Python.h> // Needs to be included first to avoid redefinition of _POSIX_C_SOURCE
22
23#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
24#include <numpy/arrayobject.h>
25
26#include "TMVA/Config.h"
27#include "TMVA/Configurable.h"
29#include "TMVA/DataSet.h"
30#include "TMVA/Event.h"
31#include "TMVA/IMethod.h"
32#include "TMVA/MsgLogger.h"
33#include "TMVA/PDF.h"
34#include "TMVA/Ranking.h"
35#include "TMVA/Tools.h"
36#include "TMVA/Types.h"
37#include "TMVA/Timer.h"
39#include "TMVA/Results.h"
40
41#include "TMath.h"
42#include "Riostream.h"
43#include "TMatrix.h"
44#include "TMatrixD.h"
45#include "TVectorD.h"
46
47#include <iomanip>
48#include <fstream>
49
50using namespace TMVA;
51
52REGISTER_METHOD(PyAdaBoost)
53
55
56//_______________________________________________________________________
57MethodPyAdaBoost::MethodPyAdaBoost(const TString &jobName,
58 const TString &methodTitle,
59 DataSetInfo &dsi,
60 const TString &theOption) :
61 PyMethodBase(jobName, Types::kPyAdaBoost, methodTitle, dsi, theOption),
62 fBaseEstimator("None"),
63 fNestimators(50),
64 fLearningRate(1.0),
65 fAlgorithm("SAMME.R"),
66 fRandomState("None")
67{
68}
69
70//_______________________________________________________________________
72 const TString &theWeightFile) :
73 PyMethodBase(Types::kPyAdaBoost, theData, theWeightFile),
74 fBaseEstimator("None"),
75 fNestimators(50),
76 fLearningRate(1.0),
77 fAlgorithm("SAMME.R"),
78 fRandomState("None")
79{
80}
81
82//_______________________________________________________________________
84{
85}
86
87//_______________________________________________________________________
89{
90 if (type == Types::kClassification && numberClasses == 2) return kTRUE;
91 if (type == Types::kMulticlass && numberClasses >= 2) return kTRUE;
92 return kFALSE;
93}
94
95//_______________________________________________________________________
97{
99
100 DeclareOptionRef(fBaseEstimator, "BaseEstimator", "object, optional (default=DecisionTreeClassifier)\
101 The base estimator from which the boosted ensemble is built.\
102 Support for sample weighting is required, as well as proper `classes_`\
103 and `n_classes_` attributes.");
104
105 DeclareOptionRef(fNestimators, "NEstimators", "integer, optional (default=50)\
106 The maximum number of estimators at which boosting is terminated.\
107 In case of perfect fit, the learning procedure is stopped early.");
108
109 DeclareOptionRef(fLearningRate, "LearningRate", "float, optional (default=1.)\
110 Learning rate shrinks the contribution of each classifier by\
111 ``learning_rate``. There is a trade-off between ``learning_rate`` and\
112 ``n_estimators``.");
113
114 DeclareOptionRef(fAlgorithm, "Algorithm", "{'SAMME', 'SAMME.R'}, optional (default='SAMME.R')\
115 If 'SAMME.R' then use the SAMME.R real boosting algorithm.\
116 ``base_estimator`` must support calculation of class probabilities.\
117 If 'SAMME' then use the SAMME discrete boosting algorithm.\
118 The SAMME.R algorithm typically converges faster than SAMME,\
119 achieving a lower test error with fewer boosting iterations.");
120
121 DeclareOptionRef(fRandomState, "RandomState", "int, RandomState instance or None, optional (default=None)\
122 If int, random_state is the seed used by the random number generator;\
123 If RandomState instance, random_state is the random number generator;\
124 If None, the random number generator is the RandomState instance used\
125 by `np.random`.");
126
127 DeclareOptionRef(fFilenameClassifier, "FilenameClassifier",
128 "Store trained classifier in this file");
129}
130
131//_______________________________________________________________________
132// Check options and load them to local python namespace
134{
136 if (!pBaseEstimator) {
137 Log() << kFATAL << Form("BaseEstimator = %s ... that does not work!", fBaseEstimator.Data())
138 << " The options are Object or None." << Endl;
139 }
140 PyDict_SetItemString(fLocalNS, "baseEstimator", pBaseEstimator);
141
142 if (fNestimators <= 0) {
143 Log() << kFATAL << "NEstimators <=0 ... that does not work!" << Endl;
144 }
146 PyDict_SetItemString(fLocalNS, "nEstimators", pNestimators);
147
148 if (fLearningRate <= 0) {
149 Log() << kFATAL << "LearningRate <=0 ... that does not work!" << Endl;
150 }
152 PyDict_SetItemString(fLocalNS, "learningRate", pLearningRate);
153
154 if (fAlgorithm != "SAMME" && fAlgorithm != "SAMME.R") {
155 Log() << kFATAL << Form("Algorithm = %s ... that does not work!", fAlgorithm.Data())
156 << " The options are SAMME of SAMME.R." << Endl;
157 }
158 pAlgorithm = Eval(Form("'%s'", fAlgorithm.Data()));
159 PyDict_SetItemString(fLocalNS, "algorithm", pAlgorithm);
160
162 if (!pRandomState) {
163 Log() << kFATAL << Form(" RandomState = %s... that does not work !! ", fRandomState.Data())
164 << "If int, random_state is the seed used by the random number generator;"
165 << "If RandomState instance, random_state is the random number generator;"
166 << "If None, the random number generator is the RandomState instance used by `np.random`." << Endl;
167 }
168 PyDict_SetItemString(fLocalNS, "randomState", pRandomState);
169
170 // If no filename is given, set default
171 if(fFilenameClassifier.IsNull()) {
172 fFilenameClassifier = GetWeightFileDir() + "/PyAdaBoostModel_" + GetName() + ".PyData";
173 }
174}
175
176//_______________________________________________________________________
178{
179 _import_array(); //require to use numpy arrays
180
181 // Check options and load them to local python namespace
183
184 // Import module for ada boost classifier
185 PyRunString("import sklearn.ensemble");
186
187 // Get data properties
190}
191
192//_______________________________________________________________________
194{
195 // Load training data (data, classes, weights) to python arrays
196 int fNrowsTraining = Data()->GetNTrainingEvents(); //every row is an event, a class type and a weight
197 npy_intp dimsData[2];
198 dimsData[0] = fNrowsTraining;
199 dimsData[1] = fNvars;
200 fTrainData = (PyArrayObject *)PyArray_SimpleNew(2, dimsData, NPY_FLOAT);
201 PyDict_SetItemString(fLocalNS, "trainData", (PyObject*)fTrainData);
202 float *TrainData = (float *)(PyArray_DATA(fTrainData));
203
204 npy_intp dimsClasses = (npy_intp) fNrowsTraining;
205 fTrainDataClasses = (PyArrayObject *)PyArray_SimpleNew(1, &dimsClasses, NPY_FLOAT);
206 PyDict_SetItemString(fLocalNS, "trainDataClasses", (PyObject*)fTrainDataClasses);
207 float *TrainDataClasses = (float *)(PyArray_DATA(fTrainDataClasses));
208
209 fTrainDataWeights = (PyArrayObject *)PyArray_SimpleNew(1, &dimsClasses, NPY_FLOAT);
210 PyDict_SetItemString(fLocalNS, "trainDataWeights", (PyObject*)fTrainDataWeights);
211 float *TrainDataWeights = (float *)(PyArray_DATA(fTrainDataWeights));
212
213 for (int i = 0; i < fNrowsTraining; i++) {
214 // Fill training data matrix
215 const TMVA::Event *e = Data()->GetTrainingEvent(i);
216 for (UInt_t j = 0; j < fNvars; j++) {
217 TrainData[j + i * fNvars] = e->GetValue(j);
218 }
219
220 // Fill target classes
221 TrainDataClasses[i] = e->GetClass();
222
223 // Get event weight
224 TrainDataWeights[i] = e->GetWeight();
225 }
226
227 // Create classifier object
228 PyRunString("classifier = sklearn.ensemble.AdaBoostClassifier(base_estimator=baseEstimator, n_estimators=nEstimators, learning_rate=learningRate, algorithm=algorithm, random_state=randomState)",
229 "Failed to setup classifier");
230
231 // Fit classifier
232 // NOTE: We dump the output to a variable so that the call does not pollute stdout
233 PyRunString("dump = classifier.fit(trainData, trainDataClasses, trainDataWeights)", "Failed to train classifier");
234
235 // Store classifier
236 fClassifier = PyDict_GetItemString(fLocalNS, "classifier");
237 if(fClassifier == 0) {
238 Log() << kFATAL << "Can't create classifier object from AdaBoostClassifier" << Endl;
239 Log() << Endl;
240 }
241
242 if (IsModelPersistence()) {
243 Log() << Endl;
244 Log() << gTools().Color("bold") << "Saving state file: " << gTools().Color("reset") << fFilenameClassifier << Endl;
245 Log() << Endl;
247 }
248}
249
250//_______________________________________________________________________
252{
254}
255
256//_______________________________________________________________________
257std::vector<Double_t> MethodPyAdaBoost::GetMvaValues(Long64_t firstEvt, Long64_t lastEvt, Bool_t logProgress)
258{
259 // Load model if not already done
260 if (fClassifier == 0) ReadModelFromFile();
261
262 // Determine number of events
263 Long64_t nEvents = Data()->GetNEvents();
264 if (firstEvt > lastEvt || lastEvt > nEvents) lastEvt = nEvents;
265 if (firstEvt < 0) firstEvt = 0;
266 nEvents = lastEvt-firstEvt;
267
268 // use timer
269 Timer timer( nEvents, GetName(), kTRUE );
270
271 if (logProgress)
272 Log() << kHEADER << Form("[%s] : ",DataInfo().GetName())
273 << "Evaluation of " << GetMethodName() << " on "
274 << (Data()->GetCurrentType() == Types::kTraining ? "training" : "testing")
275 << " sample (" << nEvents << " events)" << Endl;
276
277 // Get data
278 npy_intp dims[2];
279 dims[0] = nEvents;
280 dims[1] = fNvars;
281 PyArrayObject *pEvent= (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_FLOAT);
282 float *pValue = (float *)(PyArray_DATA(pEvent));
283
284 for (Int_t ievt=0; ievt<nEvents; ievt++) {
285 Data()->SetCurrentEvent(ievt);
286 const TMVA::Event *e = Data()->GetEvent();
287 for (UInt_t i = 0; i < fNvars; i++) {
288 pValue[ievt * fNvars + i] = e->GetValue(i);
289 }
290 }
291
292 // Get prediction from classifier
293 PyArrayObject *result = (PyArrayObject *)PyObject_CallMethod(fClassifier, const_cast<char *>("predict_proba"), const_cast<char *>("(O)"), pEvent);
294 double *proba = (double *)(PyArray_DATA(result));
295
296 // Return signal probabilities
297 if(Long64_t(mvaValues.size()) != nEvents) mvaValues.resize(nEvents);
298 for (int i = 0; i < nEvents; ++i) {
300 }
301
302 Py_DECREF(pEvent);
303 Py_DECREF(result);
304
305 if (logProgress) {
306 Log() << kINFO
307 << "Elapsed time for evaluation of " << nEvents << " events: "
308 << timer.GetElapsedTime() << " " << Endl;
309 }
310
311 return mvaValues;
312}
313
314//_______________________________________________________________________
316{
317 // cannot determine error
318 NoErrorCalc(errLower, errUpper);
319
320 // Load model if not already done
321 if (fClassifier == 0) ReadModelFromFile();
322
323 // Get current event and load to python array
324 const TMVA::Event *e = Data()->GetEvent();
325 npy_intp dims[2];
326 dims[0] = 1;
327 dims[1] = fNvars;
328 PyArrayObject *pEvent= (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_FLOAT);
329 float *pValue = (float *)(PyArray_DATA(pEvent));
330 for (UInt_t i = 0; i < fNvars; i++) pValue[i] = e->GetValue(i);
331
332 // Get prediction from classifier
333 PyArrayObject *result = (PyArrayObject *)PyObject_CallMethod(fClassifier, const_cast<char *>("predict_proba"), const_cast<char *>("(O)"), pEvent);
334 double *proba = (double *)(PyArray_DATA(result));
335
336 // Return MVA value
337 Double_t mvaValue;
338 mvaValue = proba[TMVA::Types::kSignal]; // getting signal probability
339
340 Py_DECREF(result);
341 Py_DECREF(pEvent);
342
343 return mvaValue;
344}
345
346//_______________________________________________________________________
348{
349 // Load model if not already done
350 if (fClassifier == 0) ReadModelFromFile();
351
352 // Get current event and load to python array
353 const TMVA::Event *e = Data()->GetEvent();
354 npy_intp dims[2];
355 dims[0] = 1;
356 dims[1] = fNvars;
357 PyArrayObject *pEvent= (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_FLOAT);
358 float *pValue = (float *)(PyArray_DATA(pEvent));
359 for (UInt_t i = 0; i < fNvars; i++) pValue[i] = e->GetValue(i);
360
361 // Get prediction from classifier
362 PyArrayObject *result = (PyArrayObject *)PyObject_CallMethod(fClassifier, const_cast<char *>("predict_proba"), const_cast<char *>("(O)"), pEvent);
363 double *proba = (double *)(PyArray_DATA(result));
364
365 // Return MVA values
366 if(UInt_t(classValues.size()) != fNoutputs) classValues.resize(fNoutputs);
367 for(UInt_t i = 0; i < fNoutputs; i++) classValues[i] = proba[i];
368
369 return classValues;
370}
371
372//_______________________________________________________________________
374{
375 if (!PyIsInitialized()) {
376 PyInitialize();
377 }
378
379 Log() << Endl;
380 Log() << gTools().Color("bold") << "Loading state file: " << gTools().Color("reset") << fFilenameClassifier << Endl;
381 Log() << Endl;
382
383 // Load classifier from file
385 if(err != 0)
386 {
387 Log() << kFATAL << Form("Failed to load classifier from file (error code: %i): %s", err, fFilenameClassifier.Data()) << Endl;
388 }
389
390 // Book classifier object in python dict
391 PyDict_SetItemString(fLocalNS, "classifier", fClassifier);
392
393 // Load data properties
394 // NOTE: This has to be repeated here for the reader application
397}
398
399//_______________________________________________________________________
401{
402 // Get feature importance from classifier as an array with length equal
403 // number of variables, higher value signals a higher importance
404 PyArrayObject* pRanking = (PyArrayObject*) PyObject_GetAttrString(fClassifier, "feature_importances_");
405 // The python object is null if the base estimator does not support
406 // variable ranking. Then, return NULL, which disables ranking.
407 if(pRanking == 0) return NULL;
408
409 // Fill ranking object and return it
410 fRanking = new Ranking(GetName(), "Variable Importance");
411 Double_t* rankingData = (Double_t*) PyArray_DATA(pRanking);
412 for(UInt_t iVar=0; iVar<fNvars; iVar++){
413 fRanking->AddRank(Rank(GetInputLabel(iVar), rankingData[iVar]));
414 }
415
416 Py_DECREF(pRanking);
417
418 return fRanking;
419}
420
421//_______________________________________________________________________
423{
424 // typical length of text line:
425 // "|--------------------------------------------------------------|"
426 Log() << "An AdaBoost classifier is a meta-estimator that begins by fitting" << Endl;
427 Log() << "a classifier on the original dataset and then fits additional copies" << Endl;
428 Log() << "of the classifier on the same dataset but where the weights of incorrectly" << Endl;
429 Log() << "classified instances are adjusted such that subsequent classifiers focus" << Endl;
430 Log() << "more on difficult cases." << Endl;
431 Log() << Endl;
432 Log() << "Check out the scikit-learn documentation for more information." << Endl;
433}
#define REGISTER_METHOD(CLASS)
for example
#define e(i)
Definition: RSha256.hxx:103
int Int_t
Definition: RtypesCore.h:41
unsigned int UInt_t
Definition: RtypesCore.h:42
const Bool_t kFALSE
Definition: RtypesCore.h:88
bool Bool_t
Definition: RtypesCore.h:59
double Double_t
Definition: RtypesCore.h:55
long long Long64_t
Definition: RtypesCore.h:69
const Bool_t kTRUE
Definition: RtypesCore.h:87
#define ClassImp(name)
Definition: Rtypes.h:363
int type
Definition: TGX11.cxx:120
_object PyObject
Definition: TPyArg.h:20
char * Form(const char *fmt,...)
OptionBase * DeclareOptionRef(T &ref, const TString &name, const TString &desc="")
MsgLogger & Log() const
Definition: Configurable.h:122
Class that contains all the data information.
Definition: DataSetInfo.h:60
UInt_t GetNClasses() const
Definition: DataSetInfo.h:136
const Event * GetEvent() const
Definition: DataSet.cxx:202
Types::ETreeType GetCurrentType() const
Definition: DataSet.h:205
Long64_t GetNEvents(Types::ETreeType type=Types::kMaxTreeType) const
Definition: DataSet.h:217
Long64_t GetNTrainingEvents() const
Definition: DataSet.h:79
void SetCurrentEvent(Long64_t ievt) const
Definition: DataSet.h:99
const Event * GetTrainingEvent(Long64_t ievt) const
Definition: DataSet.h:85
virtual void DeclareCompatibilityOptions()
options that are used ONLY for the READER to ensure backward compatibility they are hence without any...
Definition: MethodBase.cxx:601
const char * GetName() const
Definition: MethodBase.h:325
const TString & GetWeightFileDir() const
Definition: MethodBase.h:481
const TString & GetMethodName() const
Definition: MethodBase.h:322
DataSetInfo & DataInfo() const
Definition: MethodBase.h:401
virtual void TestClassification()
initialization
UInt_t GetNVariables() const
Definition: MethodBase.h:336
Bool_t IsModelPersistence()
Definition: MethodBase.h:374
void NoErrorCalc(Double_t *const err, Double_t *const errUpper)
Definition: MethodBase.cxx:841
const TString & GetInputLabel(Int_t i) const
Definition: MethodBase.h:341
Ranking * fRanking
Definition: MethodBase.h:576
DataSet * Data() const
Definition: MethodBase.h:400
std::vector< Double_t > GetMvaValues(Long64_t firstEvt=0, Long64_t lastEvt=-1, Bool_t logProgress=false)
get all the MVA values for the events of the current Data type
Double_t GetMvaValue(Double_t *errLower=0, Double_t *errUpper=0)
std::vector< Double_t > mvaValues
const Ranking * CreateRanking()
std::vector< Float_t > classValues
MethodPyAdaBoost(const TString &jobName, const TString &methodTitle, DataSetInfo &theData, const TString &theOption="")
Bool_t HasAnalysisType(Types::EAnalysisType type, UInt_t numberClasses, UInt_t numberTargets)
virtual void TestClassification()
initialization
virtual void ReadModelFromFile()
std::vector< Float_t > & GetMulticlassValues()
static int PyIsInitialized()
Check Python interpreter initialization status.
PyArrayObject * fTrainData
Definition: PyMethodBase.h:122
PyObject * Eval(TString code)
Evaluate Python code.
static void PyInitialize()
Initialize Python interpreter.
static void Serialize(TString file, PyObject *classifier)
Serialize Python object.
PyArrayObject * fTrainDataWeights
Definition: PyMethodBase.h:123
static Int_t UnSerialize(TString file, PyObject **obj)
Unserialize Python object.
PyObject * fClassifier
Definition: PyMethodBase.h:120
PyArrayObject * fTrainDataClasses
Definition: PyMethodBase.h:124
void PyRunString(TString code, TString errorMessage="Failed to run python code", int start=Py_single_input)
Execute Python code from string.
PyObject * fLocalNS
Definition: PyMethodBase.h:143
Ranking for variables in method (implementation)
Definition: Ranking.h:48
virtual void AddRank(const Rank &rank)
Add a new rank take ownership of it.
Definition: Ranking.cxx:86
Timing information for training and evaluation of MVA methods.
Definition: Timer.h:58
TString GetElapsedTime(Bool_t Scientific=kTRUE)
returns pretty string with elapsed time
Definition: Timer.cxx:134
const TString & Color(const TString &)
human readable color strings
Definition: Tools.cxx:840
Singleton class for Global types used by TMVA.
Definition: Types.h:73
@ kSignal
Definition: Types.h:136
EAnalysisType
Definition: Types.h:127
@ kMulticlass
Definition: Types.h:130
@ kClassification
Definition: Types.h:128
@ kTraining
Definition: Types.h:144
Abstract ClassifierFactory template that handles arbitrary types.
Tools & gTools()
MsgLogger & Endl(MsgLogger &ml)
Definition: MsgLogger.h:158