6 import tensorflow
as tf
7 import tensorflow.contrib.keras
as keras
9 from keras.layers
import Input, Dense, Concatenate
10 from keras.models
import Model, load_model
11 from keras.optimizers
import adam
12 from keras.losses
import binary_crossentropy
20 def __init__(self, model=None, custom_objects=None, **kwargs):
21 """ Constructor of the state object """
30 for key, value
in kwargs.items():
32 setattr(self, key, value)
35 def feature_importance(state):
37 Return a list containing the feature importances
42 def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
44 Return default tensorflow model
46 input = Input(shape=(number_of_features,))
47 net = Dense(units=1)(input)
49 state =
State(Model(input, net))
51 state.model.compile(optimizer=adam(), loss=binary_crossentropy, metrics=[
'accuracy'])
60 Load Tensorflow estimator into state
62 with tempfile.TemporaryDirectory()
as path:
63 with open(os.path.join(path,
'weights.h5'),
'w+b')
as file:
64 file.write(bytes(obj[0]))
65 state =
State(load_model(os.path.join(path,
'weights.h5'), custom_objects=obj[1]))
67 for index, key
in enumerate(obj[2]):
68 setattr(state, key, obj[index + 3])
75 Apply estimator to passed data.
77 r = state.model.predict(X).flatten()
78 return np.require(r, dtype=np.float32, requirements=[
'A',
'W',
'C',
'O'])
81 def begin_fit(state, Xtest, Stest, ytest, wtest):
83 Returns just the state object
88 def partial_fit(state, X, S, y, w, epoch):
90 Pass received data to tensorflow session
92 state.model.fit(X, y, batch_size=100, epochs=10)
98 Store tensorflow session in a graph
101 with tempfile.TemporaryDirectory()
as path:
102 state.model.save(os.path.join(path,
'weights.h5'))
103 with open(os.path.join(path,
'weights.h5'),
'rb')
as file:
106 obj_to_save = [data, state.custom_objects, state.collection_keys]
107 for key
in state.collection_keys:
108 obj_to_save.append(getattr(state, key))