24 """ Constructor of the state object """
30 def feature_importance(state):
32 Return a list containing the feature importances
37 def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
39 Return default tensorflow model
42 import tensorflow
as tf
44 print(
"Please install tensorflow: pip3 install tensorflow")
47 gpus = tf.config.list_physical_devices(
'GPU')
50 tf.config.experimental.set_memory_growth(gpu,
True)
52 class my_model(tf.Module):
58 self.W = tf.Variable(tf.ones(shape=(number_of_features, 1)), name=
"W")
59 self.b = tf.Variable(tf.ones(shape=(1, 1)), name=
"b")
61 self.optimizer = tf.optimizers.SGD(0.01)
63 @tf.function(input_signature=[tf.TensorSpec(shape=[None, number_of_features], dtype=tf.float32)])
64 def __call__(self, x):
65 return tf.nn.sigmoid(tf.matmul(self.clean_nans(x), self.W) + self.b)
67 def clean_nans(self, x):
68 return tf.where(tf.math.is_nan(x), tf.zeros_like(x), x)
70 def loss(self, predicted_y, target_y, w):
73 diff_from_truth = tf.where(target_y == 1., predicted_y, 1. - predicted_y)
74 return - tf.reduce_sum(w * tf.math.log(diff_from_truth + epsilon)) / tf.reduce_sum(w)
76 state =
State(model=my_model())
82 Load Tensorflow estimator into state
85 import tensorflow
as tf
87 print(
"Please install tensorflow: pip3 install tensorflow")
90 gpus = tf.config.list_physical_devices(
'GPU')
93 tf.config.experimental.set_memory_growth(gpu,
True)
95 with tempfile.TemporaryDirectory()
as path:
98 for subfolder
in [
'variables',
'assets']:
99 os.makedirs(os.path.join(path, subfolder))
102 for file_index, file_name
in enumerate(file_names):
103 with open(f
'{path}/{file_name}',
'w+b')
as file:
104 file.write(bytes(obj[1][file_index]))
106 model = tf.saved_model.load(path)
108 state =
State(model=model)
114 Apply estimator to passed data.
117 import tensorflow
as tf
119 print(
"Please install tensorflow: pip3 install tensorflow")
122 r = state.model(tf.convert_to_tensor(np.atleast_2d(X), dtype=tf.float32)).numpy()
125 return np.require(r, dtype=np.float32, requirements=[
'A',
'W',
'C',
'O'])
128 def begin_fit(state, Xtest, Stest, ytest, wtest, nBatches):
130 Returns just the state object
132 state.nBatches = nBatches
136 def partial_fit(state, X, S, y, w, epoch, batch):
138 Pass batches of received data to tensorflow
141 import tensorflow
as tf
143 print(
"Please install tensorflow: pip3 install tensorflow")
146 with tf.GradientTape()
as tape:
147 avg_cost = state.model.loss(state.model(X), y, w)
148 grads = tape.gradient(avg_cost, state.model.trainable_variables)
150 state.model.optimizer.apply_gradients(zip(grads, state.model.trainable_variables))
152 if batch == 0
and epoch == 0:
153 state.avg_costs = [avg_cost]
154 elif batch != state.nBatches-1:
155 state.avg_costs.append(avg_cost)
158 print(f
"Epoch: {epoch:04d} cost= {np.mean(state.avg_costs):.9f}")
159 state.avg_costs = [avg_cost]
168 Store tensorflow model in a graph
171 import tensorflow
as tf
173 print(
"Please install tensorflow: pip3 install tensorflow")
175 with tempfile.TemporaryDirectory()
as path:
177 tf.saved_model.save(state.model, path)
184 file_names = [
'saved_model.pb',
185 'variables/variables.index',
186 'variables/variables.data-00000-of-00001']
189 assets_path = os.path.join(path,
'assets/')
190 file_names.extend([f
'assets/{f.name}' for f
in os.scandir(assets_path)
if os.path.isfile(os.path.join(assets_path, f))])
193 for file_name
in file_names:
194 with open(os.path.join(path, file_name),
'rb')
as file:
195 files.append(file.read())
197 return [file_names, files]
model
tensorflow model inheriting from tf.Module
def __init__(self, model=None, **kwargs)