7 #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
8 #include <numpy/arrayobject.h>
28 fContinueTraining =
false;
30 fTriesEarlyStopping = -1;
31 fLearningRateSchedule =
"";
32 fFilenameTrainedModel =
"";
67 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.");
88 TString filenameLoadModel;
89 if (loadTrainedModel) {
95 PyRunString(
"model = keras.models.load_model('"+filenameLoadModel+
"')",
96 "Failed to load Keras model from file: "+filenameLoadModel);
97 Log() << kINFO <<
"Load model from file: " << filenameLoadModel <<
Endl;
107 else Log() << kFATAL <<
"Selected analysis type is not implemented" <<
Endl;
111 npy_intp dimsVals[2] = {(npy_intp)1, (npy_intp)
fNVars};
112 PyArrayObject* pVals = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsVals, NPY_FLOAT, (
void*)
fVals);
116 npy_intp dimsOutput[2] = {(npy_intp)1, (npy_intp)
fNOutputs};
117 PyArrayObject* pOutput = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsOutput, NPY_FLOAT, (
void*)&
fOutput[0]);
126 Log() << kFATAL <<
"Python is not initialized" <<
Endl;
131 PyRunString(
"import keras",
"Import Keras failed");
146 float* trainDataX =
new float[nTrainingEvents*
fNVars];
147 float* trainDataY =
new float[nTrainingEvents*
fNOutputs];
148 float* trainDataWeights =
new float[nTrainingEvents];
149 for (
UInt_t i=0; i<nTrainingEvents; i++) {
169 else Log() << kFATAL <<
"Can not fill target vector because analysis type is not known" <<
Endl;
175 npy_intp dimsTrainX[2] = {(npy_intp)nTrainingEvents, (npy_intp)
fNVars};
176 npy_intp dimsTrainY[2] = {(npy_intp)nTrainingEvents, (npy_intp)
fNOutputs};
177 npy_intp dimsTrainWeights[1] = {(npy_intp)nTrainingEvents};
178 PyArrayObject* pTrainDataX = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsTrainX, NPY_FLOAT, (
void*)trainDataX);
179 PyArrayObject* pTrainDataY = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsTrainY, NPY_FLOAT, (
void*)trainDataY);
180 PyArrayObject* pTrainDataWeights = (PyArrayObject*)PyArray_SimpleNewFromData(1, dimsTrainWeights, NPY_FLOAT, (
void*)trainDataWeights);
183 PyDict_SetItemString(
fLocalNS,
"trainWeights", (
PyObject*)pTrainDataWeights);
193 float* valDataX =
new float[nValEvents*
fNVars];
194 float* valDataY =
new float[nValEvents*
fNOutputs];
195 float* valDataWeights =
new float[nValEvents];
196 for (
UInt_t i=0; i<nValEvents; i++) {
214 else Log() << kFATAL <<
"Can not fill target vector because analysis type is not known" <<
Endl;
219 npy_intp dimsValX[2] = {(npy_intp)nValEvents, (npy_intp)
fNVars};
220 npy_intp dimsValY[2] = {(npy_intp)nValEvents, (npy_intp)
fNOutputs};
221 npy_intp dimsValWeights[1] = {(npy_intp)nValEvents};
222 PyArrayObject* pValDataX = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsValX, NPY_FLOAT, (
void*)valDataX);
223 PyArrayObject* pValDataY = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsValY, NPY_FLOAT, (
void*)valDataY);
224 PyArrayObject* pValDataWeights = (PyArrayObject*)PyArray_SimpleNewFromData(1, dimsValWeights, NPY_FLOAT, (
void*)valDataWeights);
238 PyDict_SetItemString(
fLocalNS,
"batchSize", pBatchSize);
239 PyDict_SetItemString(
fLocalNS,
"numEpochs", pNumEpochs);
240 PyDict_SetItemString(
fLocalNS,
"verbose", pVerbose);
247 PyRunString(
"callbacks.append(keras.callbacks.ModelCheckpoint('"+
fFilenameTrainedModel+
"', monitor='val_loss', verbose=verbose, save_best_only=True, mode='auto'))",
"Failed to setup training callback: SaveBestOnly");
248 Log() << kINFO <<
"Option SaveBestOnly: Only model weights with smallest validation loss will be stored" <<
Endl;
255 PyRunString(
"callbacks.append(keras.callbacks.EarlyStopping(monitor='val_loss', patience="+tries+
", verbose=verbose, mode='auto'))",
"Failed to setup training callback: TriesEarlyStopping");
256 Log() << kINFO <<
"Option TriesEarlyStopping: Training will stop after " << tries <<
" number of epochs with no improvement of validation loss" <<
Endl;
263 "schedulerSteps = {}\n"
264 "for c in strScheduleSteps.split(';'):\n"
265 " x = c.split(',')\n"
266 " schedulerSteps[int(x[0])] = float(x[1])\n",
270 PyRunString(
"def schedule(epoch, model=model, schedulerSteps=schedulerSteps):\n"
271 " if epoch in schedulerSteps: return float(schedulerSteps[epoch])\n"
272 " else: return float(model.optimizer.lr.get_value())\n",
276 PyRunString(
"callbacks.append(keras.callbacks.LearningRateScheduler(schedule))",
277 "Failed to setup training callback: LearningRateSchedule");
282 PyRunString(
"history = model.fit(trainX, trainY, sample_weight=trainWeights, batch_size=batchSize, nb_epoch=numEpochs, verbose=verbose, validation_data=(valX, valY, valWeights), callbacks=callbacks)",
283 "Failed to train model");
302 delete[] trainDataWeights;
305 delete[] valDataWeights;
326 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
327 "Failed to get predictions");
342 if (firstEvt > lastEvt || lastEvt > nEvents) lastEvt =
nEvents;
343 if (firstEvt < 0) firstEvt = 0;
344 nEvents = lastEvt-firstEvt;
355 npy_intp dimsData[2] = {(npy_intp)nEvents, (npy_intp)
fNVars};
356 PyArrayObject* pDataMvaValues = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsData, NPY_FLOAT, (
void*)
data);
357 if (pDataMvaValues==0)
Log() <<
"Failed to load data to Python array" <<
Endl;
361 if (pModel==0)
Log() << kFATAL <<
"Failed to get model Python object" <<
Endl;
362 PyArrayObject* pPredictions = (PyArrayObject*) PyObject_CallMethod(pModel, (
char*)
"predict", (
char*)
"O", pDataMvaValues);
363 if (pPredictions==0)
Log() << kFATAL <<
"Failed to get predictions" <<
Endl;
368 std::vector<double> mvaValues(nEvents);
369 float* predictionsData = (
float*) PyArray_DATA(pPredictions);
388 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
389 "Failed to get predictions");
416 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
417 "Failed to get predictions");
429 Log() <<
"Keras is a high-level API for the Theano and Tensorflow packages." <<
Endl;
430 Log() <<
"This method wraps the training and predictions steps of the Keras" <<
Endl;
431 Log() <<
"Python package for TMVA, so that dataloading, preprocessing and" <<
Endl;
432 Log() <<
"evaluation can be done within the TMVA system. To use this Keras" <<
Endl;
433 Log() <<
"interface, you have to generate a model with Keras first. Then," <<
Endl;
434 Log() <<
"this model can be loaded and trained in TMVA." <<
Endl;
Double_t GetMvaValue(Double_t *errLower, Double_t *errUpper)
const TString & GetWeightFileDir() const
Long64_t GetNTestEvents() const
MsgLogger & Endl(MsgLogger &ml)
Singleton class for Global types used by TMVA.
const char * GetName() const
UInt_t GetNClasses() const
OptionBase * DeclareOptionRef(T &ref, const TString &name, const TString &desc="")
const Event * GetTestingEvent(Long64_t ievt) const
UInt_t GetNTargets() const
TransformationHandler & GetTransformationHandler(Bool_t takeReroutedIfAvailable=true)
Double_t GetWeight() const
return the event weight - depending on whether the flag IgnoreNegWeightsInTraining is or not...
static int PyIsInitialized()
Check Python interpreter initialization status.
Float_t GetValue(UInt_t ivar) const
return value of i'th variable
std::vector< Float_t > & GetRegressionValues()
Types::EAnalysisType GetAnalysisType() const
void PyRunString(TString code, TString errorMessage="Failed to run python code", int start=Py_single_input)
Execute Python code from string.
TString fFilenameTrainedModel
void SetCurrentEvent(Long64_t ievt) const
Class that contains all the data information.
Bool_t HasAnalysisType(Types::EAnalysisType type, UInt_t numberClasses, UInt_t)
TString fLearningRateSchedule
UInt_t GetNVariables() const
const Event * GetTrainingEvent(Long64_t ievt) const
Int_t fTriesEarlyStopping
const Event * GetEvent() const
void SetTarget(UInt_t itgt, Float_t value)
set the target value (dimension itgt) to value
std::vector< Float_t > & GetMulticlassValues()
void GetHelpMessage() const
void SetupKerasModel(Bool_t loadTrainedModel)
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
Long64_t GetNEvents(Types::ETreeType type=Types::kMaxTreeType) const
virtual void TestClassification()
initialization
you should not use this method at all Int_t Int_t Double_t Double_t Double_t e
DataSetInfo & DataInfo() const
Float_t GetTarget(UInt_t itgt) const
#define REGISTER_METHOD(CLASS)
for example
Long64_t GetNTrainingEvents() const
MethodPyKeras(const TString &jobName, const TString &methodTitle, DataSetInfo &dsi, const TString &theOption="")
virtual void TestClassification()
initialization
std::vector< float > fOutput
void NoErrorCalc(Double_t *const err, Double_t *const errUpper)