17from tensorflow.keras.layers
import Activation, Dense, Input, Softmax
18from tensorflow.keras.models
import Model
21ROOT.gROOT.SetBatch(
True)
24@contextlib.contextmanager
25def expect_warning(category, message):
26 """Silence a known third-party warning and raise if it stops firing.
28 Notifies us to drop the workaround once the upstream library is fixed.
30 with warnings.catch_warnings(record=
True)
as caught:
31 warnings.simplefilter(
"always")
35 if issubclass(w.category, category)
and message
in str(w.message):
38 warnings.warn_explicit(w.message, w.category, w.filename, w.lineno)
41 f
"Expected {category.__name__} containing {message!r} was not "
42 "emitted. This tutorial's workaround can probably be removed."
50input = Input(shape=(4,), batch_size=2)
52x = Activation(
"relu")(x)
53x = Dense(16, activation=
"relu")(x)
54x = Dense(8, activation=
"relu")(x)
57model = Model(inputs=input, outputs=output)
59randomGenerator = np.random.RandomState(0)
60x_train = randomGenerator.rand(4, 4)
61y_train = randomGenerator.rand(4, 2)
63model.compile(loss=
"mse", optimizer=
"adam")
64model.fit(x_train, y_train, epochs=3, batch_size=2)
69if tuple(
int(p)
for p
in np.__version__.split(
".")[:2]) >= (2, 0):
70 ctx = expect_warning(DeprecationWarning,
"__array__ implementation doesn't accept a copy keyword")
72 ctx = contextlib.nullcontext()
75 model.save(
"KerasModel.keras")
85model = ROOT.TMVA.Experimental.SOFIE.PyKeras.Parse(
"KerasModel.keras")
89model.OutputGenerated()
91print(
"\n**************************************************")
92print(
" Generated code")
93print(
"**************************************************\n")
95print(
"**************************************************\n\n\n")
98ROOT.gInterpreter.Declare(
'#include "KerasModel.hxx"')
106session = ROOT.TMVA_SOFIE_KerasModel.Session()
109x = np.array([[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]], dtype=np.float32)
114print(
"Inference output:", y)