7 #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION 8 #include <numpy/arrayobject.h> 70 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.");
73 "Write a log during training to visualize and monitor the training performance with TensorBoard");
93 TString filenameLoadModel;
94 if (loadTrainedModel) {
100 PyRunString(
"model = keras.models.load_model('"+filenameLoadModel+
"')",
101 "Failed to load Keras model from file: "+filenameLoadModel);
102 Log() << kINFO <<
"Load model from file: " << filenameLoadModel <<
Endl;
112 else Log() << kFATAL <<
"Selected analysis type is not implemented" <<
Endl;
116 npy_intp dimsVals[2] = {(npy_intp)1, (npy_intp)
fNVars};
117 PyArrayObject* pVals = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsVals, NPY_FLOAT, (
void*)
fVals);
121 npy_intp dimsOutput[2] = {(npy_intp)1, (npy_intp)
fNOutputs};
122 PyArrayObject* pOutput = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsOutput, NPY_FLOAT, (
void*)&
fOutput[0]);
131 Log() << kFATAL <<
"Python is not initialized" <<
Endl;
137 PyRunString(
"import sys; sys.argv = ['']",
"Set sys.argv failed");
138 PyRunString(
"import keras",
"Import Keras failed");
153 float* trainDataX =
new float[nTrainingEvents*
fNVars];
154 float* trainDataY =
new float[nTrainingEvents*
fNOutputs];
155 float* trainDataWeights =
new float[nTrainingEvents];
156 for (
UInt_t i=0; i<nTrainingEvents; i++) {
176 else Log() << kFATAL <<
"Can not fill target vector because analysis type is not known" <<
Endl;
182 npy_intp dimsTrainX[2] = {(npy_intp)nTrainingEvents, (npy_intp)
fNVars};
183 npy_intp dimsTrainY[2] = {(npy_intp)nTrainingEvents, (npy_intp)
fNOutputs};
184 npy_intp dimsTrainWeights[1] = {(npy_intp)nTrainingEvents};
185 PyArrayObject* pTrainDataX = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsTrainX, NPY_FLOAT, (
void*)trainDataX);
186 PyArrayObject* pTrainDataY = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsTrainY, NPY_FLOAT, (
void*)trainDataY);
187 PyArrayObject* pTrainDataWeights = (PyArrayObject*)PyArray_SimpleNewFromData(1, dimsTrainWeights, NPY_FLOAT, (
void*)trainDataWeights);
190 PyDict_SetItemString(
fLocalNS,
"trainWeights", (
PyObject*)pTrainDataWeights);
200 float* valDataX =
new float[nValEvents*
fNVars];
201 float* valDataY =
new float[nValEvents*
fNOutputs];
202 float* valDataWeights =
new float[nValEvents];
203 for (
UInt_t i=0; i<nValEvents; i++) {
221 else Log() << kFATAL <<
"Can not fill target vector because analysis type is not known" <<
Endl;
226 npy_intp dimsValX[2] = {(npy_intp)nValEvents, (npy_intp)
fNVars};
227 npy_intp dimsValY[2] = {(npy_intp)nValEvents, (npy_intp)
fNOutputs};
228 npy_intp dimsValWeights[1] = {(npy_intp)nValEvents};
229 PyArrayObject* pValDataX = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsValX, NPY_FLOAT, (
void*)valDataX);
230 PyArrayObject* pValDataY = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsValY, NPY_FLOAT, (
void*)valDataY);
231 PyArrayObject* pValDataWeights = (PyArrayObject*)PyArray_SimpleNewFromData(1, dimsValWeights, NPY_FLOAT, (
void*)valDataWeights);
245 PyDict_SetItemString(
fLocalNS,
"batchSize", pBatchSize);
246 PyDict_SetItemString(
fLocalNS,
"numEpochs", pNumEpochs);
247 PyDict_SetItemString(
fLocalNS,
"verbose", pVerbose);
254 PyRunString(
"callbacks.append(keras.callbacks.ModelCheckpoint('"+
fFilenameTrainedModel+
"', monitor='val_loss', verbose=verbose, save_best_only=True, mode='auto'))",
"Failed to setup training callback: SaveBestOnly");
255 Log() << kINFO <<
"Option SaveBestOnly: Only model weights with smallest validation loss will be stored" <<
Endl;
262 PyRunString(
"callbacks.append(keras.callbacks.EarlyStopping(monitor='val_loss', patience="+tries+
", verbose=verbose, mode='auto'))",
"Failed to setup training callback: TriesEarlyStopping");
263 Log() << kINFO <<
"Option TriesEarlyStopping: Training will stop after " << tries <<
" number of epochs with no improvement of validation loss" <<
Endl;
270 "schedulerSteps = {}\n" 271 "for c in strScheduleSteps.split(';'):\n" 272 " x = c.split(',')\n" 273 " schedulerSteps[int(x[0])] = float(x[1])\n",
277 PyRunString(
"def schedule(epoch, model=model, schedulerSteps=schedulerSteps):\n" 278 " if epoch in schedulerSteps: return float(schedulerSteps[epoch])\n" 279 " else: return float(model.optimizer.lr.get_value())\n",
283 PyRunString(
"callbacks.append(keras.callbacks.LearningRateScheduler(schedule))",
284 "Failed to setup training callback: LearningRateSchedule");
290 TString logdir = TString(
"'") +
fTensorBoard + TString(
"'");
292 "callbacks.append(keras.callbacks.TensorBoard(log_dir=" + logdir +
293 ", histogram_freq=0, batch_size=batchSize, write_graph=True, write_grads=False, write_images=False))",
294 "Failed to setup training callback: TensorBoard");
295 Log() << kINFO <<
"Option TensorBoard: Log files for training monitoring are stored in: " << logdir <<
Endl;
299 PyRunString(
"history = model.fit(trainX, trainY, sample_weight=trainWeights, batch_size=batchSize, nb_epoch=numEpochs, verbose=verbose, validation_data=(valX, valY, valWeights), callbacks=callbacks)",
300 "Failed to train model");
319 delete[] trainDataWeights;
322 delete[] valDataWeights;
343 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
344 "Failed to get predictions");
359 if (firstEvt > lastEvt || lastEvt > nEvents) lastEvt = nEvents;
360 if (firstEvt < 0) firstEvt = 0;
361 nEvents = lastEvt-firstEvt;
364 for (
UInt_t i=0; i<nEvents; i++) {
372 npy_intp dimsData[2] = {(npy_intp)nEvents, (npy_intp)
fNVars};
373 PyArrayObject* pDataMvaValues = (PyArrayObject*)PyArray_SimpleNewFromData(2, dimsData, NPY_FLOAT, (
void*)
data);
374 if (pDataMvaValues==0)
Log() <<
"Failed to load data to Python array" <<
Endl;
378 if (pModel==0)
Log() << kFATAL <<
"Failed to get model Python object" <<
Endl;
379 PyArrayObject* pPredictions = (PyArrayObject*) PyObject_CallMethod(pModel, (
char*)
"predict", (
char*)
"O", pDataMvaValues);
380 if (pPredictions==0)
Log() << kFATAL <<
"Failed to get predictions" <<
Endl;
385 std::vector<double> mvaValues(nEvents);
386 float* predictionsData = (
float*) PyArray_DATA(pPredictions);
387 for (
UInt_t i=0; i<nEvents; i++) {
405 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
406 "Failed to get predictions");
433 PyRunString(
"for i,p in enumerate(model.predict(vals)): output[i]=p\n",
434 "Failed to get predictions");
446 Log() <<
"Keras is a high-level API for the Theano and Tensorflow packages." <<
Endl;
447 Log() <<
"This method wraps the training and predictions steps of the Keras" <<
Endl;
448 Log() <<
"Python package for TMVA, so that dataloading, preprocessing and" <<
Endl;
449 Log() <<
"evaluation can be done within the TMVA system. To use this Keras" <<
Endl;
450 Log() <<
"interface, you have to generate a model with Keras first. Then," <<
Endl;
451 Log() <<
"this model can be loaded and trained in TMVA." <<
Endl;
Double_t GetMvaValue(Double_t *errLower, Double_t *errUpper)
void SetCurrentEvent(Long64_t ievt) const
MsgLogger & Endl(MsgLogger &ml)
Singleton class for Global types used by TMVA.
OptionBase * DeclareOptionRef(T &ref, const TString &name, const TString &desc="")
TransformationHandler & GetTransformationHandler(Bool_t takeReroutedIfAvailable=true)
UInt_t GetNClasses() const
static int PyIsInitialized()
Check Python interpreter initialization status.
const TString & GetWeightFileDir() const
std::vector< Float_t > & GetRegressionValues()
void PyRunString(TString code, TString errorMessage="Failed to run python code", int start=Py_single_input)
Execute Python code from string.
void GetHelpMessage() const
const Event * GetEvent() const
TString fFilenameTrainedModel
DataSetInfo & DataInfo() const
Class that contains all the data information.
Bool_t HasAnalysisType(Types::EAnalysisType type, UInt_t numberClasses, UInt_t)
Double_t GetWeight() const
return the event weight - depending on whether the flag IgnoreNegWeightsInTraining is or not...
Long64_t GetNTrainingEvents() const
const Event * GetTrainingEvent(Long64_t ievt) const
TString fLearningRateSchedule
const Event * GetTestingEvent(Long64_t ievt) const
Float_t GetTarget(UInt_t itgt) const
UInt_t GetNTargets() const
const char * GetName() const
Int_t fTriesEarlyStopping
void SetTarget(UInt_t itgt, Float_t value)
set the target value (dimension itgt) to value
std::vector< Float_t > & GetMulticlassValues()
Long64_t GetNTestEvents() const
UInt_t GetNVariables() const
Float_t GetValue(UInt_t ivar) const
return value of i'th variable
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
virtual void TestClassification()
initialization
you should not use this method at all Int_t Int_t Double_t Double_t Double_t e
#define REGISTER_METHOD(CLASS)
for example
Abstract ClassifierFactory template that handles arbitrary types.
Long64_t GetNEvents(Types::ETreeType type=Types::kMaxTreeType) const
Types::EAnalysisType GetAnalysisType() 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)