T M V A S O F I E Keras

This macro provides a simple example for the parsing of Keras .h5 file into RModel object and further generating the .hxx header files for inference.

Author: Sanjiban Sengupta
This notebook tutorial was automatically generated with ROOTBOOK-izer from the macro found in the ROOT repository on Thursday, December 09, 2021 at 10:49 AM.

In [1]:
using namespace TMVA::Experimental;

TString pythonSrc = "\
import os\n\
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\
\n\
import numpy as np\n\
from tensorflow.keras.models import Model\n\
from tensorflow.keras.layers import Input,Dense,Activation,ReLU\n\
from tensorflow.keras.optimizers import SGD\n\
\n\
input=Input(shape=(64,),batch_size=4)\n\
x=Dense(32)(input)\n\
x=Activation('relu')(x)\n\
x=Dense(16,activation='relu')(x)\n\
x=Dense(8,activation='relu')(x)\n\
x=Dense(4)(x)\n\
output=ReLU()(x)\n\
model=Model(inputs=input,outputs=output)\n\
\n\
randomGenerator=np.random.RandomState(0)\n\
x_train=randomGenerator.rand(4,64)\n\
y_train=randomGenerator.rand(4,4)\n\
\n\
model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01))\n\
model.fit(x_train, y_train, epochs=5, batch_size=4)\n\
model.save('KerasModel.h5')\n";
In [2]:
//Running the Python script to generate Keras .h5 file
 TMVA::PyMethodBase::PyInitialize();

 TMacro m;
 m.AddLine(pythonSrc);
 m.SaveSource("make_keras_model.py");
 gSystem->Exec("python make_keras_model.py");

 //Parsing the saved Keras .h5 file into RModel object
 SOFIE::RModel model = SOFIE::PyKeras::Parse("KerasModel.h5");


 //Generating inference code
 model.Generate();
 model.OutputGenerated("KerasModel.hxx");

 //Printing required input tensors
 std::cout<<"\n\n";
 model.PrintRequiredInputTensors();

 //Printing initialized tensors (weights)
 std::cout<<"\n\n";
 model.PrintInitializedTensors();

 //Printing intermediate tensors
 std::cout<<"\n\n";
 model.PrintIntermediateTensors();

 //Checking if tensor already exist in model
 std::cout<<"\n\nTensor \"dense2bias0\" already exist: "<<std::boolalpha<<model.CheckIfTensorAlreadyExist("dense2bias0")<<"\n\n";
 std::vector<size_t> tensorShape = model.GetTensorShape("dense2bias0");
 std::cout<<"Shape of tensor \"dense2bias0\": ";
 for(auto& it:tensorShape){
     std::cout<<it<<",";
 }
 std::cout<<"\n\nData type of tensor \"dense2bias0\": ";
 SOFIE::ETensorType tensorType = model.GetTensorType("dense2bias0");
 std::cout<<SOFIE::ConvertTypeToString(tensorType);

 //Printing generated inference code
 std::cout<<"\n\n";
 model.PrintGenerated();
Traceback (most recent call last):
  File "make_keras_model.py", line 5, in <module>
    from tensorflow.keras.models import Model
ImportError: No module named tensorflow.keras.models