7#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
8#include <numpy/arrayobject.h>
24 PyGILState_STATE m_GILState;
27 PyGILRAII() : m_GILState(PyGILState_Ensure()) {}
28 ~PyGILRAII() { PyGILState_Release(m_GILState); }
86 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.");
89 "Write a log during training to visualize and monitor the training performance with TensorBoard");
91 "Write a log during training to visualize and monitor the training performance with TensorBoard");
94 "Specify as 0.2 or 20% to use a fifth of the data set as validation set. "
95 "Specify as 100 to use exactly 100 events. (Default: 20%)");
110 Int_t nValidationSamples = 0;
115 if (fNumValidationString.EndsWith(
"%")) {
120 Double_t valSizeAsDouble = fNumValidationString.Atof() / 100.0;
121 nValidationSamples = GetEventCollection(
Types::kTraining).size() * valSizeAsDouble;
123 Log() << kFATAL <<
"Cannot parse number \"" << fNumValidationString
124 <<
"\". Expected string like \"20%\" or \"20.0%\"." <<
Endl;
126 }
else if (fNumValidationString.IsFloat()) {
127 Double_t valSizeAsDouble = fNumValidationString.Atof();
129 if (valSizeAsDouble < 1.0) {
131 nValidationSamples = GetEventCollection(
Types::kTraining).size() * valSizeAsDouble;
134 nValidationSamples = valSizeAsDouble;
137 Log() << kFATAL <<
"Cannot parse number \"" << fNumValidationString <<
"\". Expected string like \"0.2\" or \"100\"."
143 if (nValidationSamples < 0) {
144 Log() << kFATAL <<
"Validation size \"" << fNumValidationString <<
"\" is negative." <<
Endl;
147 if (nValidationSamples == 0) {
148 Log() << kFATAL <<
"Validation size \"" << fNumValidationString <<
"\" is zero." <<
Endl;
151 if (nValidationSamples >= (
Int_t)trainingSetSize) {
152 Log() << kFATAL <<
"Validation size \"" << fNumValidationString
153 <<
"\" is larger than or equal in size to training set (size=\"" << trainingSetSize <<
"\")." <<
Endl;
156 return nValidationSamples;
171 Log() << kINFO <<
"Using TensorFlow backend - setting special configuration options " <<
Endl;
173 PyRunString(
"from keras.backend import tensorflow_backend as K");
176 PyRunString(
"tf_major_version = int(tf.__version__.split('.')[0])");
179 int tfVersion = PyLong_AsLong(pyTfVersion);
180 Log() << kINFO <<
"Using Tensorflow version " << tfVersion <<
Endl;
183 TString configProto = (tfVersion >= 2) ?
"tf.compat.v1.ConfigProto" :
"tf.ConfigProto";
184 TString session = (tfVersion >= 2) ?
"tf.compat.v1.Session" :
"tf.Session";
188 if (num_threads > 0) {
189 Log() << kINFO <<
"Setting the CPU number of threads = " << num_threads <<
Endl;
192 configProto.
Data(), num_threads,num_threads));
202 for (
int item = 0; item < optlist->
GetEntries(); ++item) {
203 Log() << kINFO <<
"Applying GPU option: gpu_options." << optlist->
At(item)->
GetName() <<
Endl;
212 PyRunString(
"tf.compat.v1.keras.backend.set_session(sess)");
217 Log() << kWARNING <<
"Cannot set the given " <<
fNumThreads <<
" threads when not using tensorflow as backend" <<
Endl;
219 Log() << kWARNING <<
"Cannot set the given GPU option " <<
fGpuOptions <<
" when not using tensorflow as backend" <<
Endl;
236 if (loadTrainedModel) {
242 PyRunString(
"model = keras.models.load_model('"+filenameLoadModel+
"')",
243 "Failed to load Keras model from file: "+filenameLoadModel);
244 Log() << kINFO <<
"Load model from file: " << filenameLoadModel <<
Endl;
255 else Log() << kFATAL <<
"Selected analysis type is not implemented" <<
Endl;
259 npy_intp dimsVals[2] = {(npy_intp)1, (npy_intp)
fNVars};
260 PyArrayObject* pVals = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsVals, NPY_FLOAT, (
void*)
fVals);
264 npy_intp dimsOutput[2] = {(npy_intp)1, (npy_intp)
fNOutputs};
265 PyArrayObject* pOutput = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsOutput, NPY_FLOAT, (
void*)&
fOutput[0]);
274 TMVA::Internal::PyGILRAII raii;
277 Log() << kFATAL <<
"Python is not initialized" <<
Endl;
283 PyRunString(
"import sys; sys.argv = ['']",
"Set sys.argv failed");
284 PyRunString(
"import keras",
"Import Keras failed");
299 UInt_t nTrainingEvents = nAllEvents - nValEvents;
301 Log() << kINFO <<
"Split TMVA training data in " << nTrainingEvents <<
" training events and "
302 << nValEvents <<
" validation events" <<
Endl;
304 float* trainDataX =
new float[nTrainingEvents*
fNVars];
305 float* trainDataY =
new float[nTrainingEvents*
fNOutputs];
306 float* trainDataWeights =
new float[nTrainingEvents];
307 for (
UInt_t i=0; i<nTrainingEvents; i++) {
311 trainDataX[j + i*
fNVars] =
e->GetValue(j);
324 trainDataY[j + i*
fNOutputs] =
e->GetTarget(j);
327 else Log() << kFATAL <<
"Can not fill target vector because analysis type is not known" <<
Endl;
330 trainDataWeights[i] =
e->GetWeight();
333 npy_intp dimsTrainX[2] = {(npy_intp)nTrainingEvents, (npy_intp)
fNVars};
334 npy_intp dimsTrainY[2] = {(npy_intp)nTrainingEvents, (npy_intp)
fNOutputs};
335 npy_intp dimsTrainWeights[1] = {(npy_intp)nTrainingEvents};
336 PyArrayObject* pTrainDataX = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsTrainX, NPY_FLOAT, (
void*)trainDataX);
337 PyArrayObject* pTrainDataY = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsTrainY, NPY_FLOAT, (
void*)trainDataY);
338 PyArrayObject* pTrainDataWeights = (PyArrayObject*)PyArray_SimpleNewFromData(1, dimsTrainWeights, NPY_FLOAT, (
void*)trainDataWeights);
341 PyDict_SetItemString(
fLocalNS,
"trainWeights", (
PyObject*)pTrainDataWeights);
351 float* valDataX =
new float[nValEvents*
fNVars];
352 float* valDataY =
new float[nValEvents*
fNOutputs];
353 float* valDataWeights =
new float[nValEvents];
355 for (
UInt_t i=0; i< nValEvents ; i++) {
356 UInt_t ievt = nTrainingEvents + i;
360 valDataX[j + i*
fNVars] =
e->GetValue(j);
374 else Log() << kFATAL <<
"Can not fill target vector because analysis type is not known" <<
Endl;
376 valDataWeights[i] =
e->GetWeight();
379 npy_intp dimsValX[2] = {(npy_intp)nValEvents, (npy_intp)
fNVars};
380 npy_intp dimsValY[2] = {(npy_intp)nValEvents, (npy_intp)
fNOutputs};
381 npy_intp dimsValWeights[1] = {(npy_intp)nValEvents};
382 PyArrayObject* pValDataX = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsValX, NPY_FLOAT, (
void*)valDataX);
383 PyArrayObject* pValDataY = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsValY, NPY_FLOAT, (
void*)valDataY);
384 PyArrayObject* pValDataWeights = (PyArrayObject*)PyArray_SimpleNewFromData(1, dimsValWeights, NPY_FLOAT, (
void*)valDataWeights);
392 Log() << kINFO <<
"Training Model Summary" <<
Endl;
400 PyDict_SetItemString(
fLocalNS,
"batchSize", pBatchSize);
401 PyDict_SetItemString(
fLocalNS,
"numEpochs", pNumEpochs);
402 PyDict_SetItemString(
fLocalNS,
"verbose", pVerbose);
409 PyRunString(
"callbacks.append(keras.callbacks.ModelCheckpoint('"+
fFilenameTrainedModel+
"', monitor='val_loss', verbose=verbose, save_best_only=True, mode='auto'))",
"Failed to setup training callback: SaveBestOnly");
410 Log() << kINFO <<
"Option SaveBestOnly: Only model weights with smallest validation loss will be stored" <<
Endl;
417 PyRunString(
"callbacks.append(keras.callbacks.EarlyStopping(monitor='val_loss', patience="+tries+
", verbose=verbose, mode='auto'))",
"Failed to setup training callback: TriesEarlyStopping");
418 Log() << kINFO <<
"Option TriesEarlyStopping: Training will stop after " << tries <<
" number of epochs with no improvement of validation loss" <<
Endl;
425 "schedulerSteps = {}\n"
426 "for c in strScheduleSteps.split(';'):\n"
427 " x = c.split(',')\n"
428 " schedulerSteps[int(x[0])] = float(x[1])\n",
432 PyRunString(
"def schedule(epoch, model=model, schedulerSteps=schedulerSteps):\n"
433 " if epoch in schedulerSteps: return float(schedulerSteps[epoch])\n"
434 " else: return float(model.optimizer.lr.get_value())\n",
438 PyRunString(
"callbacks.append(keras.callbacks.LearningRateScheduler(schedule))",
439 "Failed to setup training callback: LearningRateSchedule");
447 "callbacks.append(keras.callbacks.TensorBoard(log_dir=" + logdir +
448 ", histogram_freq=0, batch_size=batchSize, write_graph=True, write_grads=False, write_images=False))",
449 "Failed to setup training callback: TensorBoard");
450 Log() << kINFO <<
"Option TensorBoard: Log files for training monitoring are stored in: " << logdir <<
Endl;
454 PyRunString(
"history = model.fit(trainX, trainY, sample_weight=trainWeights, batch_size=batchSize, epochs=numEpochs, verbose=verbose, validation_data=(valX, valY, valWeights), callbacks=callbacks)",
455 "Failed to train model");
458 std::vector<float> fHistory;
460 npy_intp dimsHistory[1] = { (npy_intp)
fNumEpochs};
461 PyArrayObject* pHistory = (PyArrayObject*)PyArray_SimpleNewFromData(1, dimsHistory, NPY_FLOAT, (
void*)&fHistory[0]);
466 PyRunString(
"number_of_keys=len(history.history.keys())");
468 int nkeys=PyLong_AsLong(PyNkeys);
469 for (iHis=0; iHis<nkeys; iHis++) {
475#if PY_MAJOR_VERSION < 3
481 PyObject* repr = PyObject_Repr(stra);
482 PyObject* str = PyUnicode_AsEncodedString(repr,
"utf-8",
"~E~");
486 Log() << kINFO <<
"Getting training history for item:" << iHis <<
" name = " <<
name <<
Endl;
489 for (
size_t i=0; i<fHistory.size(); i++)
512 delete[] trainDataWeights;
515 delete[] valDataWeights;
536 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
537 "Failed to get predictions");
552 if (firstEvt > lastEvt || lastEvt > nEvents) lastEvt = nEvents;
553 if (firstEvt < 0) firstEvt = 0;
554 nEvents = lastEvt-firstEvt;
563 <<
" sample (" << nEvents <<
" events)" <<
Endl;
565 float* data =
new float[nEvents*
fNVars];
566 for (
UInt_t i=0; i<nEvents; i++) {
570 data[j + i*
fNVars] =
e->GetValue(j);
574 npy_intp dimsData[2] = {(npy_intp)nEvents, (npy_intp)
fNVars};
575 PyArrayObject* pDataMvaValues = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsData, NPY_FLOAT, (
void*)data);
576 if (pDataMvaValues==0)
Log() <<
"Failed to load data to Python array" <<
Endl;
580 if (pModel==0)
Log() << kFATAL <<
"Failed to get model Python object" <<
Endl;
581 PyArrayObject* pPredictions = (PyArrayObject*) PyObject_CallMethod(pModel, (
char*)
"predict", (
char*)
"O", pDataMvaValues);
582 if (pPredictions==0)
Log() << kFATAL <<
"Failed to get predictions" <<
Endl;
587 std::vector<double> mvaValues(nEvents);
588 float* predictionsData = (
float*) PyArray_DATA(pPredictions);
589 for (
UInt_t i=0; i<nEvents; i++) {
595 <<
"Elapsed time for evaluation of " << nEvents <<
" events: "
614 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
615 "Failed to get predictions");
642 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
643 "Failed to get predictions");
655 Log() <<
"Keras is a high-level API for the Theano and Tensorflow packages." <<
Endl;
656 Log() <<
"This method wraps the training and predictions steps of the Keras" <<
Endl;
657 Log() <<
"Python package for TMVA, so that dataloading, preprocessing and" <<
Endl;
658 Log() <<
"evaluation can be done within the TMVA system. To use this Keras" <<
Endl;
659 Log() <<
"interface, you have to generate a model with Keras first. Then," <<
Endl;
660 Log() <<
"this model can be loaded and trained in TMVA." <<
Endl;
667 PyRunString(
"keras_backend_is_set = keras.backend.backend() == \"tensorflow\"");
668 PyObject * keras_backend = PyDict_GetItemString(
fLocalNS,
"keras_backend_is_set");
669 if (keras_backend !=
nullptr && keras_backend == Py_True)
672 PyRunString(
"keras_backend_is_set = keras.backend.backend() == \"theano\"");
673 keras_backend = PyDict_GetItemString(
fLocalNS,
"keras_backend_is_set");
674 if (keras_backend !=
nullptr && keras_backend == Py_True)
677 PyRunString(
"keras_backend_is_set = keras.backend.backend() == \"cntk\"");
678 keras_backend = PyDict_GetItemString(
fLocalNS,
"keras_backend_is_set");
679 if (keras_backend !=
nullptr && keras_backend == Py_True)
#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
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
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
std::vector< float > fOutput
virtual void TestClassification()
initialization
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.
void PyRunString(TString code, TString errorMessage="Failed to run python code", int start=Py_single_input)
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.
Int_t GetEntries() const
Return the number of objects in array (i.e.
TObject * At(Int_t idx) const
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.
create variable transformations
MsgLogger & Endl(MsgLogger &ml)