23#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
24#include <numpy/arrayobject.h>
56 PyGILState_STATE m_GILState;
59 PyGILRAII() : m_GILState(PyGILState_Ensure()) {}
60 ~PyGILRAII() { PyGILState_Release(m_GILState); }
70MethodPyGTB::MethodPyGTB(
const TString &jobName,
81 fMinWeightFractionLeaf(0.0),
87 fMaxLeafNodes(
"None"),
101 fMinWeightFractionLeaf(0.0),
104 fRandomState(
"None"),
105 fMaxFeatures(
"None"),
107 fMaxLeafNodes(
"None"),
133 loss function to be optimized. 'deviance' refers to\
134 deviance (= logistic regression) for classification\
135 with probabilistic outputs. For loss 'exponential' gradient\
136 boosting recovers the AdaBoost algorithm.");
139 learning rate shrinks the contribution of each tree by `learning_rate`.\
140 There is a trade-off between learning_rate and n_estimators.");
143 The number of boosting stages to perform. Gradient boosting\
144 is fairly robust to over-fitting so a large number usually\
145 results in better performance.");
148 The fraction of samples to be used for fitting the individual base\
149 learners. If smaller than 1.0 this results in Stochastic Gradient\
150 Boosting. `subsample` interacts with the parameter `n_estimators`.\
151 Choosing `subsample < 1.0` leads to a reduction of variance\
152 and an increase in bias.");
155 The minimum number of samples required to split an internal node.");
158 The minimum number of samples in newly created leaves. A split is \
159 discarded if after the split, one of the leaves would contain less then \
160 ``min_samples_leaf`` samples.");
163 The minimum weighted fraction of the input samples required to be at a \
167 The maximum depth of the tree. If None, then nodes are expanded until \
168 all leaves are pure or until all leaves contain less than \
169 min_samples_split samples. \
170 Ignored if ``max_leaf_nodes`` is not None.");
173 An estimator object that is used to compute the initial\
174 predictions. ``init`` has to provide ``fit`` and ``predict``.\
175 If None it uses ``loss.init_estimator`");
178 If int, random_state is the seed used by the random number generator;\
179 If RandomState instance, random_state is the random number generator;\
180 If None, the random number generator is the RandomState instance used\
186 Controls the verbosity of the tree building process.");
189 Grow trees with ``max_leaf_nodes`` in best-first fashion.\
190 Best nodes are defined as relative reduction in impurity.\
191 If None then unlimited number of leaf nodes.\
192 If not None then ``max_depth`` will be ignored.");
195 When set to ``True``, reuse the solution of the previous call to fit\
196 and add more estimators to the ensemble, otherwise, just fit a whole\
200 "Store trained classifier in this file");
207 if (
fLoss !=
"deviance" &&
fLoss !=
"exponential") {
209 <<
" The options are 'deviance' or 'exponential'." <<
Endl;
215 Log() << kFATAL <<
"LearningRate <= 0 ... that does not work!" <<
Endl;
221 Log() << kFATAL <<
"NEstimators <= 0 ... that does not work!" <<
Endl;
227 Log() << kFATAL <<
"MinSamplesSplit < 0 ... that does not work!" <<
Endl;
233 Log() << kFATAL <<
"Subsample < 0 ... that does not work!" <<
Endl;
239 Log() << kFATAL <<
"MinSamplesLeaf < 0 ... that does not work!" <<
Endl;
245 Log() << kFATAL <<
"MinSamplesSplit < 0 ... that does not work!" <<
Endl;
251 Log() << kFATAL <<
"MinWeightFractionLeaf < 0 ... that does not work !" <<
Endl;
257 Log() << kFATAL <<
" MaxDepth <= 0 ... that does not work !! " <<
Endl;
265 <<
" The options are None or BaseEstimator, which is an estimator object that"
266 <<
"is used to compute the initial predictions. "
267 <<
"'init' has to provide 'fit' and 'predict' methods."
268 <<
" If None it uses 'loss.init_estimator'." <<
Endl;
275 <<
" If int, random_state is the seed used by the random number generator;"
276 <<
" If RandomState instance, random_state is the random number generator;"
277 <<
" If None, the random number generator is the RandomState instance used by 'np.random'."
290 <<
"int, float, string or None, optional (default='auto')"
291 <<
"The number of features to consider when looking for the best split:"
292 <<
"If int, then consider `max_features` features at each split."
293 <<
"If float, then `max_features` is a percentage and"
294 <<
"`int(max_features * n_features)` features are considered at each split."
295 <<
"If 'auto', then `max_features=sqrt(n_features)`."
296 <<
"If 'sqrt', then `max_features=sqrt(n_features)`."
297 <<
"If 'log2', then `max_features=log2(n_features)`."
298 <<
"If None, then `max_features=n_features`." <<
Endl;
304 <<
" The options are None or integer." <<
Endl;
323 TMVA::Internal::PyGILRAII raii;
341 npy_intp dimsData[2];
342 dimsData[0] = fNrowsTraining;
344 fTrainData = (PyArrayObject *)PyArray_SimpleNew(2, dimsData, NPY_FLOAT);
346 float *TrainData = (
float *)(PyArray_DATA(
fTrainData));
348 npy_intp dimsClasses = (npy_intp) fNrowsTraining;
349 fTrainDataClasses = (PyArrayObject *)PyArray_SimpleNew(1, &dimsClasses, NPY_FLOAT);
353 fTrainDataWeights = (PyArrayObject *)PyArray_SimpleNew(1, &dimsClasses, NPY_FLOAT);
357 for (
int i = 0; i < fNrowsTraining; i++) {
361 TrainData[j + i *
fNvars] =
e->GetValue(j);
365 TrainDataClasses[i] =
e->GetClass();
368 TrainDataWeights[i] =
e->GetWeight();
372 PyRunString(
"classifier = sklearn.ensemble.GradientBoostingClassifier(loss=loss, learning_rate=learningRate, n_estimators=nEstimators, max_depth=maxDepth, min_samples_split=minSamplesSplit, min_samples_leaf=minSamplesLeaf, min_weight_fraction_leaf=minWeightFractionLeaf, subsample=subsample, max_features=maxFeatures, max_leaf_nodes=maxLeafNodes, init=init, verbose=verbose, warm_start=warmStart, random_state=randomState)",
373 "Failed to setup classifier");
377 PyRunString(
"dump = classifier.fit(trainData, trainDataClasses, trainDataWeights)",
"Failed to train classifier");
382 Log() << kFATAL <<
"Can't create classifier object from GradientBoostingClassifier" <<
Endl;
408 if (firstEvt > lastEvt || lastEvt > nEvents) lastEvt = nEvents;
409 if (firstEvt < 0) firstEvt = 0;
410 nEvents = lastEvt-firstEvt;
419 <<
" sample (" << nEvents <<
" events)" <<
Endl;
425 PyArrayObject *pEvent= (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_FLOAT);
426 float *pValue = (
float *)(PyArray_DATA(pEvent));
428 for (
Int_t ievt=0; ievt<nEvents; ievt++) {
432 pValue[ievt *
fNvars + i] =
e->GetValue(i);
437 PyArrayObject *result = (PyArrayObject *)PyObject_CallMethod(
fClassifier,
const_cast<char *
>(
"predict_proba"),
const_cast<char *
>(
"(O)"), pEvent);
438 double *proba = (
double *)(PyArray_DATA(result));
442 for (
int i = 0; i < nEvents; ++i) {
451 <<
"Elapsed time for evaluation of " << nEvents <<
" events: "
473 PyArrayObject *pEvent= (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_FLOAT);
474 float *pValue = (
float *)(PyArray_DATA(pEvent));
475 for (
UInt_t i = 0; i <
fNvars; i++) pValue[i] =
e->GetValue(i);
478 PyArrayObject *result = (PyArrayObject *)PyObject_CallMethod(
fClassifier,
const_cast<char *
>(
"predict_proba"),
const_cast<char *
>(
"(O)"), pEvent);
479 double *proba = (
double *)(PyArray_DATA(result));
502 PyArrayObject *pEvent= (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_FLOAT);
503 float *pValue = (
float *)(PyArray_DATA(pEvent));
504 for (
UInt_t i = 0; i <
fNvars; i++) pValue[i] =
e->GetValue(i);
507 PyArrayObject *result = (PyArrayObject *)PyObject_CallMethod(
fClassifier,
const_cast<char *
>(
"predict_proba"),
const_cast<char *
>(
"(O)"), pEvent);
508 double *proba = (
double *)(PyArray_DATA(result));
552 PyArrayObject* pRanking = (PyArrayObject*) PyObject_GetAttrString(
fClassifier,
"feature_importances_");
553 if(pRanking == 0)
Log() << kFATAL <<
"Failed to get ranking from classifier" <<
Endl;
572 Log() <<
"A gradient tree boosting classifier builds a model from an ensemble" <<
Endl;
573 Log() <<
"of decision trees, which are adapted each boosting step to fit better" <<
Endl;
574 Log() <<
"to previously misclassified events." <<
Endl;
576 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
PyObject * pMinSamplesLeaf
Double_t fMinWeightFractionLeaf
std::vector< Double_t > mvaValues
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
std::vector< Float_t > classValues
Bool_t HasAnalysisType(Types::EAnalysisType type, UInt_t numberClasses, UInt_t numberTargets)
void GetHelpMessage() const
MethodPyGTB(const TString &jobName, const TString &methodTitle, DataSetInfo &theData, const TString &theOption="")
const Ranking * CreateRanking()
virtual void TestClassification()
initialization
std::vector< Float_t > & GetMulticlassValues()
virtual void ReadModelFromFile()
TString fFilenameClassifier
PyObject * pMinSamplesSplit
PyObject * pMinWeightFractionLeaf
Double_t GetMvaValue(Double_t *errLower=0, Double_t *errUpper=0)
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.
const char * Data() const
create variable transformations
MsgLogger & Endl(MsgLogger &ml)