17 def __init__(self, x=None, y=None, activation=None, cost=None, optimizer=None, session=None, **kwargs):
18 """ Constructor of the state object """
35 for key, value
in kwargs.items():
37 setattr(self, key, value)
40 """ Add the stored members to the current tensorflow collection """
42 import tensorflow
as tf
44 print(
"Please install tensorflow: pip3 install tensorflow")
48 tf.add_to_collection(key, getattr(self, key))
53 """ Get members from the current tensorflow collection """
55 import tensorflow
as tf
57 print(
"Please install tensorflow: pip3 install tensorflow")
60 if collection_keys
is not None:
64 setattr(self, key, tf.get_collection(key)[0])
67 def feature_importance(state):
69 Return a list containing the feature importances
74 def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
76 Return default tensorflow model
79 import tensorflow
as tf
81 print(
"Please install tensorflow: pip3 install tensorflow")
84 x = tf.placeholder(
"float", [
None, number_of_features])
85 y = tf.placeholder(
"float", [
None, 1])
86 w = tf.placeholder(
"float", [
None, 1])
87 W = tf.Variable(tf.zeros([number_of_features, 1]))
88 b = tf.Variable(tf.zeros([1]))
90 x_clean = tf.select(tf.is_nan(x), tf.ones_like(x) * 0., x)
91 activation = tf.nn.sigmoid(tf.matmul(x_clean, W) + b)
94 cost = -tf.reduce_sum(y * w * tf.log(activation + epsilon) + (1 - y) * w * tf.log(1 - activation + epsilon)) / tf.reduce_sum(w)
97 global_step = tf.Variable(0, name=
'global_step', trainable=
False)
98 optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost, global_step=global_step)
100 init = tf.global_variables_initializer()
102 config = tf.ConfigProto()
103 config.gpu_options.allow_growth =
True
104 session = tf.Session(config=config)
107 state =
State(x, y, activation, cost, optimizer, session)
114 Load Tensorflow estimator into state
117 import tensorflow
as tf
119 print(
"Please install tensorflow: pip3 install tensorflow")
122 tf.reset_default_graph()
123 config = tf.ConfigProto()
124 config.gpu_options.allow_growth =
True
125 session = tf.Session(config=config)
126 saver = tf.train.import_meta_graph(obj[0])
127 with tempfile.TemporaryDirectory()
as path:
128 with open(os.path.join(path, obj[1] +
'.data-00000-of-00001'),
'w+b')
as file1, open(
129 os.path.join(path, obj[1] +
'.index'),
'w+b')
as file2:
130 file1.write(bytes(obj[2]))
131 file2.write(bytes(obj[3]))
132 tf.train.update_checkpoint_state(path, obj[1])
133 saver.restore(session, os.path.join(path, obj[1]))
134 state =
State(session=session)
136 state.get_from_collection(obj[4])
137 for i, extra
in enumerate(obj[5:]):
138 setattr(state,
'extra_{}'.format(i), extra)
140 state.get_from_collection()
147 Apply estimator to passed data.
149 r = state.session.run(state.activation, feed_dict={state.x: X}).flatten()
150 return np.require(r, dtype=np.float32, requirements=[
'A',
'W',
'C',
'O'])
153 def begin_fit(state, Xtest, Stest, ytest, wtest):
155 Returns just the state object
160 def partial_fit(state, X, S, y, w, epoch):
162 Pass received data to tensorflow session
164 state.session.run(state.optimizer, feed_dict={state.x: X, state.y: y, state.w: w})
165 avg_cost = state.session.run(state.cost, feed_dict={state.x: X, state.y: y, state.w: w})
166 if epoch % 1000 == 0:
167 print(
"Epoch:",
'%04d' % (epoch),
"cost=",
"{:.9f}".format(avg_cost))
175 Store tensorflow session in a graph
178 import tensorflow
as tf
180 print(
"Please install tensorflow: pip3 install tensorflow")
183 keys = state.add_to_collection()
184 saver = tf.train.Saver()
185 with tempfile.TemporaryDirectory()
as path:
186 filename = saver.save(state.session, os.path.join(path,
'mymodel'))
187 with open(filename + str(
'.data-00000-of-00001'),
'rb')
as file1, open(filename + str(
'.index'),
'rb')
as file2:
190 meta_graph = saver.export_meta_graph()
192 return [meta_graph, os.path.basename(filename), data1, data2, keys]