15import tensorflow
as tf
16tf.config.threading.set_intra_op_parallelism_threads(1)
17tf.config.threading.set_inter_op_parallelism_threads(1)
26 """ Constructor of the state object """
32def feature_importance(state):
34 Return a list containing the feature importances
39def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
41 Return default tensorflow model
43 gpus = tf.config.list_physical_devices('GPU')
46 tf.config.experimental.set_memory_growth(gpu,
True)
48 class my_model(tf.Module):
54 self.W = tf.Variable(tf.ones(shape=(number_of_features, 1)), name=
"W")
55 self.b = tf.Variable(tf.ones(shape=(1, 1)), name=
"b")
57 self.optimizer = tf.optimizers.SGD(0.01)
59 @tf.function(input_signature=[tf.TensorSpec(shape=[None, number_of_features], dtype=tf.float32)])
60 def __call__(self, x):
61 return tf.nn.sigmoid(tf.matmul(self.clean_nans(x), self.W) + self.b)
63 def clean_nans(self, x):
64 return tf.where(tf.math.is_nan(x), tf.zeros_like(x), x)
66 def loss(self, predicted_y, target_y, w):
69 diff_from_truth = tf.where(target_y == 1., predicted_y, 1. - predicted_y)
70 return - tf.reduce_sum(w * tf.math.log(diff_from_truth + epsilon)) / tf.reduce_sum(w)
72 state =
State(model=my_model())
78 Load Tensorflow estimator into state
80 gpus = tf.config.list_physical_devices('GPU')
83 tf.config.experimental.set_memory_growth(gpu,
True)
85 with tempfile.TemporaryDirectory()
as path:
88 for subfolder
in [
'variables',
'assets']:
89 os.makedirs(os.path.join(path, subfolder))
92 for file_index, file_name
in enumerate(file_names):
93 with open(f
'{path}/{file_name}',
'w+b')
as file:
94 file.write(bytes(obj[1][file_index]))
96 model = tf.saved_model.load(path)
98 state =
State(model=model)
104 Apply estimator to passed data.
106 r = state.model(tf.convert_to_tensor(np.atleast_2d(X), dtype=tf.float32)).numpy()
109 return np.require(r, dtype=np.float32, requirements=[
'A',
'W',
'C',
'O'])
112def begin_fit(state, Xtest, Stest, ytest, wtest, nBatches):
114 Returns just the state object
116 state.nBatches = nBatches
120def partial_fit(state, X, S, y, w, epoch, batch):
122 Pass batches of received data to tensorflow
124 with tf.GradientTape()
as tape:
125 avg_cost = state.model.loss(state.model(X), y, w)
126 grads = tape.gradient(avg_cost, state.model.trainable_variables)
128 state.model.optimizer.apply_gradients(zip(grads, state.model.trainable_variables))
130 if batch == 0
and epoch == 0:
131 state.avg_costs = [avg_cost]
132 elif batch != state.nBatches-1:
133 state.avg_costs.append(avg_cost)
136 print(f
"Epoch: {epoch:04d} cost= {np.mean(state.avg_costs):.9f}")
137 state.avg_costs = [avg_cost]
146 Store tensorflow model in a graph
148 with tempfile.TemporaryDirectory()
as path:
150 tf.saved_model.save(state.model, path)
157 file_names = [
'saved_model.pb',
158 'variables/variables.index',
159 'variables/variables.data-00000-of-00001']
162 assets_path = os.path.join(path,
'assets/')
163 file_names.extend([f
'assets/{f.name}' for f
in os.scandir(assets_path)
if os.path.isfile(os.path.join(assets_path, f))])
166 for file_name
in file_names:
167 with open(os.path.join(path, file_name),
'rb')
as file:
168 files.append(file.read())
170 return [file_names, files]
model
tensorflow model inheriting from tf.Module
def __init__(self, model=None, **kwargs)