23 """ Constructor of the state object """
29def feature_importance(state):
31 Return a list containing the feature importances
36def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
38 Return default tensorflow model
41 import tensorflow
as tf
43 print(
"Please install tensorflow: pip3 install tensorflow")
46 gpus = tf.config.list_physical_devices(
'GPU')
49 tf.config.experimental.set_memory_growth(gpu,
True)
51 class my_model(tf.Module):
57 self.W = tf.Variable(tf.ones(shape=(number_of_features, 1)), name=
"W")
58 self.b = tf.Variable(tf.ones(shape=(1, 1)), name=
"b")
60 self.optimizer = tf.optimizers.SGD(0.01)
62 @tf.function(input_signature=[tf.TensorSpec(shape=[None, number_of_features], dtype=tf.float32)])
63 def __call__(self, x):
64 return tf.nn.sigmoid(tf.matmul(self.clean_nans(x), self.W) + self.b)
66 def clean_nans(self, x):
67 return tf.where(tf.math.is_nan(x), tf.zeros_like(x), x)
69 def loss(self, predicted_y, target_y, w):
72 diff_from_truth = tf.where(target_y == 1., predicted_y, 1. - predicted_y)
73 return - tf.reduce_sum(w * tf.math.log(diff_from_truth + epsilon)) / tf.reduce_sum(w)
75 state =
State(model=my_model())
81 Load Tensorflow estimator into state
84 import tensorflow
as tf
86 print(
"Please install tensorflow: pip3 install tensorflow")
89 gpus = tf.config.list_physical_devices(
'GPU')
92 tf.config.experimental.set_memory_growth(gpu,
True)
94 with tempfile.TemporaryDirectory()
as path:
97 for subfolder
in [
'variables',
'assets']:
98 os.makedirs(os.path.join(path, subfolder))
101 for file_index, file_name
in enumerate(file_names):
102 with open(f
'{path}/{file_name}',
'w+b')
as file:
103 file.write(bytes(obj[1][file_index]))
105 model = tf.saved_model.load(path)
107 state =
State(model=model)
113 Apply estimator to passed data.
116 import tensorflow
as tf
118 print(
"Please install tensorflow: pip3 install tensorflow")
121 r = state.model(tf.convert_to_tensor(np.atleast_2d(X), dtype=tf.float32)).numpy()
124 return np.require(r, dtype=np.float32, requirements=[
'A',
'W',
'C',
'O'])
127def begin_fit(state, Xtest, Stest, ytest, wtest, nBatches):
129 Returns just the state object
131 state.nBatches = nBatches
135def partial_fit(state, X, S, y, w, epoch, batch):
137 Pass batches of received data to tensorflow
140 import tensorflow
as tf
142 print(
"Please install tensorflow: pip3 install tensorflow")
145 with tf.GradientTape()
as tape:
146 avg_cost = state.model.loss(state.model(X), y, w)
147 grads = tape.gradient(avg_cost, state.model.trainable_variables)
149 state.model.optimizer.apply_gradients(zip(grads, state.model.trainable_variables))
151 if batch == 0
and epoch == 0:
152 state.avg_costs = [avg_cost]
153 elif batch != state.nBatches-1:
154 state.avg_costs.append(avg_cost)
157 print(f
"Epoch: {epoch:04d} cost= {np.mean(state.avg_costs):.9f}")
158 state.avg_costs = [avg_cost]
167 Store tensorflow model in a graph
170 import tensorflow
as tf
172 print(
"Please install tensorflow: pip3 install tensorflow")
174 with tempfile.TemporaryDirectory()
as path:
176 tf.saved_model.save(state.model, path)
183 file_names = [
'saved_model.pb',
184 'variables/variables.index',
185 'variables/variables.data-00000-of-00001']
188 assets_path = os.path.join(path,
'assets/')
189 file_names.extend([f
'assets/{f.name}' for f
in os.scandir(assets_path)
if os.path.isfile(os.path.join(assets_path, f))])
192 for file_name
in file_names:
193 with open(os.path.join(path, file_name),
'rb')
as file:
194 files.append(file.read())
196 return [file_names, files]
model
tensorflow model inheriting from tf.Module
def __init__(self, model=None, **kwargs)