7#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
8#include <numpy/arrayobject.h>
89 DeclareOptionRef(
fTriesEarlyStopping,
"TriesEarlyStopping",
"Number of epochs with no improvement in validation loss after which training will be stopped. The default or a negative number deactivates this option.");
92 "Write a log during training to visualize and monitor the training performance with TensorBoard");
95 "Specify as 0.2 or 20% to use a fifth of the data set as validation set. "
96 "Specify as 100 to use exactly 100 events. (Default: 20%)");
98 "Optional python code provided by the user to be executed before loading the Keras model");
111 Int_t nValidationSamples = 0;
116 if (fNumValidationString.EndsWith(
"%")) {
121 Double_t valSizeAsDouble = fNumValidationString.Atof() / 100.0;
122 nValidationSamples = GetEventCollection(
Types::kTraining).size() * valSizeAsDouble;
124 Log() <<
kFATAL <<
"Cannot parse number \"" << fNumValidationString
125 <<
"\". Expected string like \"20%\" or \"20.0%\"." <<
Endl;
127 }
else if (fNumValidationString.IsFloat()) {
128 Double_t valSizeAsDouble = fNumValidationString.Atof();
130 if (valSizeAsDouble < 1.0) {
132 nValidationSamples = GetEventCollection(
Types::kTraining).size() * valSizeAsDouble;
135 nValidationSamples = valSizeAsDouble;
138 Log() <<
kFATAL <<
"Cannot parse number \"" << fNumValidationString <<
"\". Expected string like \"0.2\" or \"100\"."
144 if (nValidationSamples < 0) {
145 Log() <<
kFATAL <<
"Validation size \"" << fNumValidationString <<
"\" is negative." <<
Endl;
148 if (nValidationSamples == 0) {
149 Log() <<
kFATAL <<
"Validation size \"" << fNumValidationString <<
"\" is zero." <<
Endl;
152 if (nValidationSamples >= (
Int_t)trainingSetSize) {
153 Log() <<
kFATAL <<
"Validation size \"" << fNumValidationString
154 <<
"\" is larger than or equal in size to training set (size=\"" << trainingSetSize <<
"\")." <<
Endl;
157 return nValidationSamples;
188 bool useTFBackend =
kFALSE;
189 bool kerasIsCompatible =
kTRUE;
190 bool kerasIsPresent =
kFALSE;
197 kerasIsPresent =
kTRUE;
198 if (kerasIsPresent) {
201 useTFBackend =
kTRUE;
203 PyRunString(
"keras_major_version = int(keras.__version__.split('.')[0])");
204 PyRunString(
"keras_minor_version = int(keras.__version__.split('.')[1])");
205 PyObject *pyKerasMajorVersion = PyDict_GetItemString(
fLocalNS,
"keras_major_version");
206 PyObject *pyKerasMinorVersion = PyDict_GetItemString(
fLocalNS,
"keras_minor_version");
207 int kerasMajorVersion = PyLong_AsLong(pyKerasMajorVersion);
208 int kerasMinorVersion = PyLong_AsLong(pyKerasMinorVersion);
209 Log() <<
kINFO <<
"Using Keras version " << kerasMajorVersion <<
"." << kerasMinorVersion <<
Endl;
214 kerasIsCompatible = (kerasMajorVersion >= 2 && kerasMinorVersion == 3);
219 Log() <<
kINFO <<
"Keras is not found. Trying using tf.keras" <<
Endl;
228 if (ret ==
nullptr) {
232 PyRunString(
"tf_major_version = int(tf.__version__.split('.')[0])");
234 int tfVersion = PyLong_AsLong(pyTfVersion);
235 Log() <<
kINFO <<
"Using TensorFlow version " << tfVersion <<
Endl;
239 Log() <<
kWARNING <<
"Using TensorFlow version 1.x which does not contain tf.keras - use then TensorFlow as Keras backend" <<
Endl;
242 if (!kerasIsPresent) {
243 Log() <<
kFATAL <<
"Keras is not present and not a suitable TensorFlow version is found " <<
Endl;
250 if (!kerasIsCompatible) {
251 Log() <<
kWARNING <<
"The Keras version is not compatible with TensorFlow 2. Use instead tf.keras" <<
Endl;
260 Log() <<
kINFO <<
"Use Keras version from TensorFlow : tf.keras" <<
Endl;
266 Log() <<
kINFO <<
"Use TensorFlow as Keras backend" <<
Endl;
268 PyRunString(
"from keras.backend import tensorflow_backend as K");
274 TString configProto = (tfVersion >= 2) ?
"tf.compat.v1.ConfigProto" :
"tf.ConfigProto";
275 TString session = (tfVersion >= 2) ?
"tf.compat.v1.Session" :
"tf.Session";
279 if (num_threads > 0) {
280 Log() <<
kINFO <<
"Setting the CPU number of threads = " << num_threads <<
Endl;
283 TString::Format(
"session_conf = %s(intra_op_parallelism_threads=%d,inter_op_parallelism_threads=%d)",
284 configProto.
Data(), num_threads, num_threads));
293 for (
int item = 0; item < optlist->
GetEntries(); ++item) {
303 PyRunString(
"tf.compat.v1.keras.backend.set_session(sess)");
310 Log() <<
kWARNING <<
"Cannot set the given " <<
fNumThreads <<
" threads when not using tensorflow as backend"
314 <<
" when not using tensorflow as backend" <<
Endl;
334 TString errmsg =
"Error executing the provided user code";
337 PyRunString(
"print('custom objects for loading model : ',load_model_custom_objects)");
342 if (loadTrainedModel) {
350 "', custom_objects=load_model_custom_objects)",
"Failed to load Keras model from file: " + filenameLoadModel);
352 Log() <<
kINFO <<
"Loaded model from file: " << filenameLoadModel <<
Endl;
363 else Log() <<
kFATAL <<
"Selected analysis type is not implemented" <<
Endl;
367 npy_intp dimsVals[2] = {(npy_intp)1, (npy_intp)
fNVars};
368 PyArrayObject* pVals = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsVals, NPY_FLOAT, (
void*)
fVals);
372 npy_intp dimsOutput[2] = {(npy_intp)1, (npy_intp)
fNOutputs};
373 PyArrayObject* pOutput = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsOutput, NPY_FLOAT, (
void*)&
fOutput[0]);
393 PyRunString(
"import sys; sys.argv = ['']",
"Set sys.argv failed");
409 UInt_t nTrainingEvents = nAllEvents - nValEvents;
411 Log() <<
kINFO <<
"Split TMVA training data in " << nTrainingEvents <<
" training events and "
412 << nValEvents <<
" validation events" <<
Endl;
414 float* trainDataX =
new float[nTrainingEvents*
fNVars];
415 float* trainDataY =
new float[nTrainingEvents*
fNOutputs];
416 float* trainDataWeights =
new float[nTrainingEvents];
417 for (
UInt_t i=0; i<nTrainingEvents; i++) {
421 trainDataX[j + i*
fNVars] =
e->GetValue(j);
434 trainDataY[j + i*
fNOutputs] =
e->GetTarget(j);
437 else Log() <<
kFATAL <<
"Can not fill target vector because analysis type is not known" <<
Endl;
440 trainDataWeights[i] =
e->GetWeight();
443 npy_intp dimsTrainX[2] = {(npy_intp)nTrainingEvents, (npy_intp)
fNVars};
444 npy_intp dimsTrainY[2] = {(npy_intp)nTrainingEvents, (npy_intp)
fNOutputs};
445 npy_intp dimsTrainWeights[1] = {(npy_intp)nTrainingEvents};
446 PyArrayObject* pTrainDataX = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsTrainX, NPY_FLOAT, (
void*)trainDataX);
447 PyArrayObject* pTrainDataY = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsTrainY, NPY_FLOAT, (
void*)trainDataY);
448 PyArrayObject* pTrainDataWeights = (PyArrayObject*)PyArray_SimpleNewFromData(1, dimsTrainWeights, NPY_FLOAT, (
void*)trainDataWeights);
451 PyDict_SetItemString(
fLocalNS,
"trainWeights", (
PyObject*)pTrainDataWeights);
461 float* valDataX =
new float[nValEvents*
fNVars];
462 float* valDataY =
new float[nValEvents*
fNOutputs];
463 float* valDataWeights =
new float[nValEvents];
465 for (
UInt_t i=0; i< nValEvents ; i++) {
466 UInt_t ievt = nTrainingEvents + i;
470 valDataX[j + i*
fNVars] =
e->GetValue(j);
484 else Log() <<
kFATAL <<
"Can not fill target vector because analysis type is not known" <<
Endl;
486 valDataWeights[i] =
e->GetWeight();
489 npy_intp dimsValX[2] = {(npy_intp)nValEvents, (npy_intp)
fNVars};
490 npy_intp dimsValY[2] = {(npy_intp)nValEvents, (npy_intp)
fNOutputs};
491 npy_intp dimsValWeights[1] = {(npy_intp)nValEvents};
492 PyArrayObject* pValDataX = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsValX, NPY_FLOAT, (
void*)valDataX);
493 PyArrayObject* pValDataY = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsValY, NPY_FLOAT, (
void*)valDataY);
494 PyArrayObject* pValDataWeights = (PyArrayObject*)PyArray_SimpleNewFromData(1, dimsValWeights, NPY_FLOAT, (
void*)valDataWeights);
510 PyDict_SetItemString(
fLocalNS,
"batchSize", pBatchSize);
511 PyDict_SetItemString(
fLocalNS,
"numEpochs", pNumEpochs);
512 PyDict_SetItemString(
fLocalNS,
"verbose", pVerbose);
519 PyRunString(
"callbacks.append(" +
fKerasString +
".callbacks.ModelCheckpoint('"+
fFilenameTrainedModel+
"', monitor='val_loss', verbose=verbose, save_best_only=True, mode='auto'))",
"Failed to setup training callback: SaveBestOnly");
520 Log() <<
kINFO <<
"Option SaveBestOnly: Only model weights with smallest validation loss will be stored" <<
Endl;
527 PyRunString(
"callbacks.append(" +
fKerasString +
".callbacks.EarlyStopping(monitor='val_loss', patience="+tries+
", verbose=verbose, mode='auto'))",
"Failed to setup training callback: TriesEarlyStopping");
528 Log() <<
kINFO <<
"Option TriesEarlyStopping: Training will stop after " << tries <<
" number of epochs with no improvement of validation loss" <<
Endl;
535 "schedulerSteps = {}\n"
536 "for c in strScheduleSteps.split(';'):\n"
537 " x = c.split(',')\n"
538 " schedulerSteps[int(x[0])] = float(x[1])\n",
542 PyRunString(
"def schedule(epoch, model=model, schedulerSteps=schedulerSteps):\n"
543 " if epoch in schedulerSteps: return float(schedulerSteps[epoch])\n"
544 " else: return float(model.optimizer.lr.get_value())\n",
549 "Failed to setup training callback: LearningRateSchedule");
557 "callbacks.append(" +
fKerasString +
".callbacks.TensorBoard(log_dir=" + logdir +
558 ", histogram_freq=0, batch_size=batchSize, write_graph=True, write_grads=False, write_images=False))",
559 "Failed to setup training callback: TensorBoard");
560 Log() <<
kINFO <<
"Option TensorBoard: Log files for training monitoring are stored in: " << logdir <<
Endl;
564 PyRunString(
"history = model.fit(trainX, trainY, sample_weight=trainWeights, batch_size=batchSize, epochs=numEpochs, verbose=verbose, validation_data=(valX, valY, valWeights), callbacks=callbacks)",
565 "Failed to train model");
568 std::vector<float> fHistory;
570 npy_intp dimsHistory[1] = { (npy_intp)
fNumEpochs};
571 PyArrayObject* pHistory = (PyArrayObject*)PyArray_SimpleNewFromData(1, dimsHistory, NPY_FLOAT, (
void*)&fHistory[0]);
576 PyRunString(
"number_of_keys=len(history.history.keys())");
578 int nkeys=PyLong_AsLong(PyNkeys);
579 for (iHis=0; iHis<nkeys; iHis++) {
584#if PY_MAJOR_VERSION < 3
590 PyObject* repr = PyObject_Repr(stra);
591 PyObject* str = PyUnicode_AsEncodedString(repr,
"utf-8",
"~E~");
595 Log() <<
kINFO <<
"Getting training history for item:" << iHis <<
" name = " <<
name <<
Endl;
598 for (
size_t i=0; i<fHistory.size(); i++)
621 delete[] trainDataWeights;
624 delete[] valDataWeights;
645 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
646 "Failed to get predictions");
661 if (firstEvt > lastEvt || lastEvt > nEvents) lastEvt = nEvents;
662 if (firstEvt < 0) firstEvt = 0;
663 nEvents = lastEvt-firstEvt;
672 <<
" sample (" << nEvents <<
" events)" <<
Endl;
675 for (
UInt_t i=0; i<nEvents; i++) {
683 npy_intp dimsData[2] = {(npy_intp)nEvents, (npy_intp)
fNVars};
684 PyArrayObject* pDataMvaValues = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsData, NPY_FLOAT, (
void*)
data);
685 if (pDataMvaValues==0)
Log() <<
"Failed to load data to Python array" <<
Endl;
689 if (pModel==0)
Log() <<
kFATAL <<
"Failed to get model Python object" <<
Endl;
690 PyArrayObject* pPredictions = (PyArrayObject*) PyObject_CallMethod(pModel, (
char*)
"predict", (
char*)
"O", pDataMvaValues);
691 if (pPredictions==0)
Log() <<
kFATAL <<
"Failed to get predictions" <<
Endl;
696 std::vector<double> mvaValues(nEvents);
697 float* predictionsData = (
float*) PyArray_DATA(pPredictions);
698 for (
UInt_t i=0; i<nEvents; i++) {
704 <<
"Elapsed time for evaluation of " << nEvents <<
" events: "
723 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
724 "Failed to get predictions");
751 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
752 "Failed to get predictions");
764 Log() <<
"Keras is a high-level API for the Theano and Tensorflow packages." <<
Endl;
765 Log() <<
"This method wraps the training and predictions steps of the Keras" <<
Endl;
766 Log() <<
"Python package for TMVA, so that dataloading, preprocessing and" <<
Endl;
767 Log() <<
"evaluation can be done within the TMVA system. To use this Keras" <<
Endl;
768 Log() <<
"interface, you have to generate a model with Keras first. Then," <<
Endl;
769 Log() <<
"this model can be loaded and trained in TMVA." <<
Endl;
780 PyRunString(
"keras_backend_is_set = keras.backend.backend() == \"tensorflow\"");
781 PyObject * keras_backend = PyDict_GetItemString(
fLocalNS,
"keras_backend_is_set");
782 if (keras_backend !=
nullptr && keras_backend == Py_True)
785 PyRunString(
"keras_backend_is_set = keras.backend.backend() == \"theano\"");
786 keras_backend = PyDict_GetItemString(
fLocalNS,
"keras_backend_is_set");
787 if (keras_backend !=
nullptr && keras_backend == Py_True)
790 PyRunString(
"keras_backend_is_set = keras.backend.backend() == \"cntk\"");
791 keras_backend = PyDict_GetItemString(
fLocalNS,
"keras_backend_is_set");
792 if (keras_backend !=
nullptr && keras_backend == Py_True)
#define REGISTER_METHOD(CLASS)
for example
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
R__EXTERN TSystem * gSystem
OptionBase * DeclareOptionRef(T &ref, const TString &name, const TString &desc="")
Class that contains all the data information.
UInt_t GetNClasses() const
UInt_t GetNTargets() const
Types::ETreeType GetCurrentType() const
Long64_t GetNEvents(Types::ETreeType type=Types::kMaxTreeType) const
Long64_t GetNTrainingEvents() const
void SetCurrentEvent(Long64_t ievt) const
void SetTarget(UInt_t itgt, Float_t value)
set the target value (dimension itgt) to value
Float_t GetTarget(UInt_t itgt) const
PyGILState_STATE m_GILState
const char * GetName() const
Types::EAnalysisType GetAnalysisType() const
const TString & GetWeightFileDir() const
const TString & GetMethodName() const
const Event * GetEvent() const
DataSetInfo & DataInfo() const
virtual void TestClassification()
initialization
UInt_t GetNVariables() const
TransformationHandler & GetTransformationHandler(Bool_t takeReroutedIfAvailable=true)
void NoErrorCalc(Double_t *const err, Double_t *const errUpper)
TrainingHistory fTrainHistory
const Event * GetTrainingEvent(Long64_t ievt) const
void GetHelpMessage() const
void Init()
Initialization function called from MethodBase::SetupMethod() Note that option string are not yet fil...
std::vector< float > fOutput
virtual void TestClassification()
initialization
void ProcessOptions()
Function processing the options This is called only when creating the method before training not when...
Bool_t UseTFKeras() const
Int_t fTriesEarlyStopping
EBackendType
enumeration defining the used Keras backend
void SetupKerasModel(Bool_t loadTrainedModel)
std::vector< Float_t > & GetMulticlassValues()
UInt_t GetNumValidationSamples()
Validation of the ValidationSize option.
Double_t GetMvaValue(Double_t *errLower, Double_t *errUpper)
std::vector< Float_t > & GetRegressionValues()
TString fNumValidationString
Bool_t HasAnalysisType(Types::EAnalysisType type, UInt_t numberClasses, UInt_t)
TString GetKerasBackendName()
MethodPyKeras(const TString &jobName, const TString &methodTitle, DataSetInfo &dsi, const TString &theOption="")
TString fLearningRateSchedule
EBackendType GetKerasBackend()
Get the Keras backend (can be: TensorFlow, Theano or CNTK)
TString fFilenameTrainedModel
std::vector< Double_t > GetMvaValues(Long64_t firstEvt, Long64_t lastEvt, Bool_t logProgress)
get all the MVA values for the events of the current Data type
static int PyIsInitialized()
Check Python interpreter initialization status.
static PyObject * fGlobalNS
void PyRunString(TString code, TString errorMessage="Failed to run python code", int start=256)
Execute Python code from string.
Timing information for training and evaluation of MVA methods.
TString GetElapsedTime(Bool_t Scientific=kTRUE)
returns pretty string with elapsed time
void AddValue(TString Property, Int_t stage, Double_t value)
Singleton class for Global types used by TMVA.
@ kSignal
Never change this number - it is elsewhere assumed to be zero !
Int_t GetEntries() const override
Return the number of objects in array (i.e.
TObject * At(Int_t idx) const override
virtual const char * GetName() const
Returns name of object.
Bool_t IsFloat() const
Returns kTRUE if string contains a floating point or integer number.
const char * Data() const
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
virtual const char * Getenv(const char *env)
Get environment variable.
create variable transformations
MsgLogger & Endl(MsgLogger &ml)
Double_t Log(Double_t x)
Returns the natural logarithm of x.