Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TMVA_SOFIE_Keras.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_ml
3/// \notebook -nodraw
4/// This macro provides a simple example for the parsing of Keras .h5 file
5/// into RModel object and further generating the .hxx header files for inference.
6///
7/// \macro_code
8/// \macro_output
9/// \author Sanjiban Sengupta
10
11using namespace TMVA::Experimental;
12
14import os\n\
15os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\
16\n\
17import numpy as np\n\
18from tensorflow.keras.models import Model\n\
19from tensorflow.keras.layers import Input,Dense,Activation,ReLU\n\
20from tensorflow.keras.optimizers import SGD\n\
21\n\
22input=Input(shape=(64,),batch_size=4)\n\
23x=Dense(32)(input)\n\
24x=Activation('relu')(x)\n\
25x=Dense(16,activation='relu')(x)\n\
26x=Dense(8,activation='relu')(x)\n\
27x=Dense(4)(x)\n\
28output=ReLU()(x)\n\
29model=Model(inputs=input,outputs=output)\n\
30\n\
31randomGenerator=np.random.RandomState(0)\n\
32x_train=randomGenerator.rand(4,64)\n\
33y_train=randomGenerator.rand(4,4)\n\
34\n\
35model.compile(loss='mean_squared_error', optimizer=SGD(learning_rate=0.01))\n\
36model.fit(x_train, y_train, epochs=5, batch_size=4)\n\
37model.save('KerasModel.h5')\n";
38
39
40void TMVA_SOFIE_Keras(const char * modelFile = nullptr, bool printModelInfo = true){
41
42 // Running the Python script to generate Keras .h5 file
43
44 if (modelFile == nullptr) {
45 TMacro m;
46 m.AddLine(pythonSrc);
47 m.SaveSource("make_keras_model.py");
48 gSystem->Exec("python3 make_keras_model.py");
49 modelFile = "KerasModel.h5";
50 }
51
52 //Parsing the saved Keras .h5 file into RModel object
53 SOFIE::RModel model = SOFIE::PyKeras::Parse(modelFile);
54
55
56 //Generating inference code
57 model.Generate();
58 // generate output header. By default it will be modelName.hxx
59 model.OutputGenerated();
60
61 if (!printModelInfo) return;
62
63 //Printing required input tensors
64 std::cout<<"\n\n";
66
67 //Printing initialized tensors (weights)
68 std::cout<<"\n\n";
70
71 //Printing intermediate tensors
72 std::cout<<"\n\n";
74
75 //Printing generated inference code
76 std::cout<<"\n\n";
77 model.PrintGenerated();
78}
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
R__EXTERN TSystem * gSystem
Definition TSystem.h:572
void OutputGenerated(std::string filename="", bool append=false)
Definition RModel.cxx:1430
void Generate(std::underlying_type_t< Options > options, int batchSize=-1, long pos=0, bool verbose=false)
Definition RModel.cxx:1062
Class supporting a collection of lines with C++ code.
Definition TMacro.h:31
Basic string class.
Definition TString.h:138
virtual Int_t Exec(const char *shellcmd)
Execute a command.
Definition TSystem.cxx:651
TMarker m
Definition textangle.C:8