13from os.path
import exists
17from keras
import layers, models
18from sklearn.model_selection
import train_test_split
21@contextlib.contextmanager
22def expect_warning(category, message):
23 """Silence a known third-party warning and raise if it stops firing.
25 Notifies us to drop the workaround once the upstream library is fixed.
27 with warnings.catch_warnings(record=
True)
as caught:
28 warnings.simplefilter(
"always")
32 if issubclass(w.category, category)
and message
in str(w.message):
35 warnings.warn_explicit(w.message, w.category, w.filename, w.lineno)
38 f
"Expected {category.__name__} containing {message!r} was not "
39 "emitted. This tutorial's workaround can probably be removed."
43def CreateModel(nlayers=4, nunits=64):
44 input = layers.Input(shape=(7,))
46 for i
in range(1, nlayers):
47 y = layers.Dense(nunits, activation=
"relu")(x)
50 output = layers.Dense(1, activation=
"sigmoid")(x)
51 model = models.Model(input, output)
52 model.compile(loss=
"binary_crossentropy", optimizer=
"adam", weighted_metrics=[
"accuracy"])
59 inputFile = str(ROOT.gROOT.GetTutorialDir()) +
"/machine_learning/data/Higgs_data.root"
62 sigData = df1.AsNumpy(columns=[
"m_jj",
"m_jjj",
"m_lv",
"m_jlv",
"m_bb",
"m_wbb",
"m_wwbb"])
66 xsig = np.column_stack(list(sigData.values()))
67 data_sig_size = xsig.shape[0]
68 print(
"size of data", data_sig_size)
72 bkgData = df2.AsNumpy(columns=[
"m_jj",
"m_jjj",
"m_lv",
"m_jlv",
"m_bb",
"m_wbb",
"m_wwbb"])
73 xbkg = np.column_stack(list(bkgData.values()))
74 data_bkg_size = xbkg.shape[0]
76 ysig = np.ones(data_sig_size)
77 ybkg = np.zeros(data_bkg_size)
78 inputs_data = np.concatenate((xsig, xbkg), axis=0)
79 inputs_targets = np.concatenate((ysig, ybkg), axis=0)
83 x_train, x_test, y_train, y_test = train_test_split(inputs_data, inputs_targets, test_size=0.50, random_state=1234)
85 return x_train, y_train, x_test, y_test
88def TrainModel(model, x, y, name):
89 model.fit(x, y, epochs=5, batch_size=50)
90 modelFile = name +
".keras"
95 if tuple(
int(p)
for p
in np.__version__.split(
".")[:2]) >= (2, 0):
96 ctx = expect_warning(DeprecationWarning,
"__array__ implementation doesn't accept a copy keyword")
98 ctx = contextlib.nullcontext()
101 model.save(modelFile)
103 return model, modelFile
106def GenerateCode(modelFile="model.keras"):
109 if not exists(modelFile):
110 raise FileNotFoundError(
111 "INput model file not existing. You need to run TMVA_Higgs_Classification.C to generate the Keras trained model"
115 model = ROOT.TMVA.Experimental.SOFIE.PyKeras.Parse(modelFile)
119 model.OutputGenerated()
121 modelName = modelFile.replace(
".keras",
"")
129x_train, y_train, x_test, y_test = PrepareData()
131model = CreateModel(3, 64)
132model, modelFile = TrainModel(model, x_train, y_train,
"HiggsModel")
138modelName = GenerateCode(modelFile)
139modelHeaderFile = modelName +
".hxx"
145ROOT.gInterpreter.Declare(
'#include "' + modelHeaderFile +
'"')
152sofie = getattr(ROOT,
"TMVA_SOFIE_" + modelName)
153session = sofie.Session()
155x = np.random.normal(0, 1, 7).astype(np.float32)
157ykeras = model(x.reshape(1, 7)).numpy()
159print(
"input to model is ", x,
"\n\t -> output using SOFIE = ", y[0],
" using Keras = ", ykeras[0])
161if abs(y[0] - ykeras[0]) > 0.01:
162 raise RuntimeError(
"ERROR: Result is different between SOFIE and Keras")
ROOT's RDataFrame offers a modern, high-level interface for analysis of data stored in TTree ,...