23#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
24#include <numpy/arrayobject.h>
57MethodPyAdaBoost::MethodPyAdaBoost(
const TString &jobName,
58 const TString &methodTitle,
60 const TString &theOption) :
62 fBaseEstimator(
"None"),
65 fAlgorithm(
"SAMME.R"),
72 const TString &theWeightFile) :
74 fBaseEstimator(
"None"),
77 fAlgorithm(
"SAMME.R"),
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.");
106 The maximum number of estimators at which boosting is terminated.\
107 In case of perfect fit, the learning procedure is stopped early.");
110 Learning rate shrinks the contribution of each classifier by\
111 ``learning_rate``. There is a trade-off between ``learning_rate`` and\
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.");
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\
128 "Store trained classifier in this file");
138 <<
" The options are Object or None." <<
Endl;
143 Log() << kFATAL <<
"NEstimators <=0 ... that does not work!" <<
Endl;
149 Log() << kFATAL <<
"LearningRate <=0 ... that does not work!" <<
Endl;
155 Log() << kFATAL <<
Form(
"Algorithm = %s ... that does not work!",
fAlgorithm.Data())
156 <<
" The options are SAMME of SAMME.R." <<
Endl;
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;
197 npy_intp dimsData[2];
198 dimsData[0] = fNrowsTraining;
200 fTrainData = (PyArrayObject *)PyArray_SimpleNew(2, dimsData, NPY_FLOAT);
202 float *TrainData = (
float *)(PyArray_DATA(
fTrainData));
204 npy_intp dimsClasses = (npy_intp) fNrowsTraining;
205 fTrainDataClasses = (PyArrayObject *)PyArray_SimpleNew(1, &dimsClasses, NPY_FLOAT);
209 fTrainDataWeights = (PyArrayObject *)PyArray_SimpleNew(1, &dimsClasses, NPY_FLOAT);
213 for (
int i = 0; i < fNrowsTraining; i++) {
217 TrainData[j + i *
fNvars] =
e->GetValue(j);
221 TrainDataClasses[i] =
e->GetClass();
224 TrainDataWeights[i] =
e->GetWeight();
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");
233 PyRunString(
"dump = classifier.fit(trainData, trainDataClasses, trainDataWeights)",
"Failed to train classifier");
238 Log() << kFATAL <<
"Can't create classifier object from AdaBoostClassifier" <<
Endl;
264 if (firstEvt > lastEvt || lastEvt > nEvents) lastEvt = nEvents;
265 if (firstEvt < 0) firstEvt = 0;
266 nEvents = lastEvt-firstEvt;
275 <<
" sample (" << nEvents <<
" events)" <<
Endl;
281 PyArrayObject *pEvent= (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_FLOAT);
282 float *pValue = (
float *)(PyArray_DATA(pEvent));
284 for (
Int_t ievt=0; ievt<nEvents; ievt++) {
288 pValue[ievt *
fNvars + i] =
e->GetValue(i);
293 PyArrayObject *result = (PyArrayObject *)PyObject_CallMethod(
fClassifier,
const_cast<char *
>(
"predict_proba"),
const_cast<char *
>(
"(O)"), pEvent);
294 double *proba = (
double *)(PyArray_DATA(result));
298 for (
int i = 0; i < nEvents; ++i) {
307 <<
"Elapsed time for evaluation of " << nEvents <<
" events: "
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);
333 PyArrayObject *result = (PyArrayObject *)PyObject_CallMethod(
fClassifier,
const_cast<char *
>(
"predict_proba"),
const_cast<char *
>(
"(O)"), pEvent);
334 double *proba = (
double *)(PyArray_DATA(result));
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);
362 PyArrayObject *result = (PyArrayObject *)PyObject_CallMethod(
fClassifier,
const_cast<char *
>(
"predict_proba"),
const_cast<char *
>(
"(O)"), pEvent);
363 double *proba = (
double *)(PyArray_DATA(result));
404 PyArrayObject* pRanking = (PyArrayObject*) PyObject_GetAttrString(
fClassifier,
"feature_importances_");
407 if(pRanking == 0)
return NULL;
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;
432 Log() <<
"Check out the scikit-learn documentation for more information." <<
Endl;
#define REGISTER_METHOD(CLASS)
for example
char * Form(const char *fmt,...)
OptionBase * DeclareOptionRef(T &ref, const TString &name, const TString &desc="")
Class that contains all the data information.
UInt_t GetNClasses() const
const Event * GetEvent() const
Types::ETreeType GetCurrentType() const
Long64_t GetNEvents(Types::ETreeType type=Types::kMaxTreeType) const
Long64_t GetNTrainingEvents() const
void SetCurrentEvent(Long64_t ievt) const
const Event * GetTrainingEvent(Long64_t ievt) const
virtual void DeclareCompatibilityOptions()
options that are used ONLY for the READER to ensure backward compatibility they are hence without any...
const char * GetName() const
const TString & GetWeightFileDir() const
const TString & GetMethodName() const
DataSetInfo & DataInfo() const
virtual void TestClassification()
initialization
UInt_t GetNVariables() const
Bool_t IsModelPersistence()
void NoErrorCalc(Double_t *const err, Double_t *const errUpper)
const TString & GetInputLabel(Int_t i) const
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
PyObject * pBaseEstimator
Double_t GetMvaValue(Double_t *errLower=0, Double_t *errUpper=0)
std::vector< Double_t > mvaValues
TString fFilenameClassifier
void GetHelpMessage() const
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
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
static Int_t UnSerialize(TString file, PyObject **obj)
Unserialize Python object.
PyArrayObject * fTrainDataClasses
void PyRunString(TString code, TString errorMessage="Failed to run python code", int start=Py_single_input)
Execute Python code from string.
Ranking for variables in method (implementation)
virtual void AddRank(const Rank &rank)
Add a new rank take ownership of it.
Timing information for training and evaluation of MVA methods.
TString GetElapsedTime(Bool_t Scientific=kTRUE)
returns pretty string with elapsed time
Singleton class for Global types used by TMVA.
Abstract ClassifierFactory template that handles arbitrary types.
MsgLogger & Endl(MsgLogger &ml)