23 def __init__(self, x=None, y=None, activation=None, cost=None, optimizer=None, session=None, **kwargs):
24 """ Constructor of the state object """
38 self.
collection_keyscollection_keys = [
'x',
'y',
'activation',
'cost',
'optimizer']
41 for key, value
in kwargs.items():
43 setattr(self, key, value)
46 """ Add the stored members to the current tensorflow collection """
48 import tensorflow
as tf
50 print(
"Please install tensorflow: pip3 install tensorflow")
54 tf.add_to_collection(key, getattr(self, key))
59 """ Get members from the current tensorflow collection """
61 import tensorflow
as tf
63 print(
"Please install tensorflow: pip3 install tensorflow")
66 if collection_keys
is not None:
70 setattr(self, key, tf.get_collection(key)[0])
73 def feature_importance(state):
75 Return a list containing the feature importances
80 def get_model(number_of_features, number_of_spectators, number_of_events, training_fraction, parameters):
82 Return default tensorflow model
85 import tensorflow
as tf
87 print(
"Please install tensorflow: pip3 install tensorflow")
90 x = tf.placeholder(
"float", [
None, number_of_features])
91 y = tf.placeholder(
"float", [
None, 1])
92 w = tf.placeholder(
"float", [
None, 1])
93 W = tf.Variable(tf.zeros([number_of_features, 1]))
94 b = tf.Variable(tf.zeros([1]))
96 x_clean = tf.select(tf.is_nan(x), tf.ones_like(x) * 0., x)
97 activation = tf.nn.sigmoid(tf.matmul(x_clean, W) + b)
100 cost = -tf.reduce_sum(y * w * tf.log(activation + epsilon) + (1 - y) * w * tf.log(1 - activation + epsilon)) / tf.reduce_sum(w)
102 learning_rate = 0.001
103 global_step = tf.Variable(0, name=
'global_step', trainable=
False)
104 optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost, global_step=global_step)
106 init = tf.global_variables_initializer()
108 config = tf.ConfigProto()
109 config.gpu_options.allow_growth =
True
110 session = tf.Session(config=config)
113 state =
State(x, y, activation, cost, optimizer, session)
120 Load Tensorflow estimator into state
123 import tensorflow
as tf
125 print(
"Please install tensorflow: pip3 install tensorflow")
128 tf.reset_default_graph()
129 config = tf.ConfigProto()
130 config.gpu_options.allow_growth =
True
131 session = tf.Session(config=config)
132 saver = tf.train.import_meta_graph(obj[0])
133 with tempfile.TemporaryDirectory()
as path:
134 with open(os.path.join(path, obj[1] +
'.data-00000-of-00001'),
'w+b')
as file1, open(
135 os.path.join(path, obj[1] +
'.index'),
'w+b')
as file2:
136 file1.write(bytes(obj[2]))
137 file2.write(bytes(obj[3]))
138 tf.train.update_checkpoint_state(path, obj[1])
139 saver.restore(session, os.path.join(path, obj[1]))
140 state =
State(session=session)
142 state.get_from_collection(obj[4])
143 for i, extra
in enumerate(obj[5:]):
144 setattr(state,
'extra_{}'.format(i), extra)
146 state.get_from_collection()
153 Apply estimator to passed data.
155 r = state.session.run(state.activation, feed_dict={state.x: X}).flatten()
156 return np.require(r, dtype=np.float32, requirements=[
'A',
'W',
'C',
'O'])
159 def begin_fit(state, Xtest, Stest, ytest, wtest):
161 Returns just the state object
166 def partial_fit(state, X, S, y, w, epoch):
168 Pass received data to tensorflow session
170 state.session.run(state.optimizer, feed_dict={state.x: X, state.y: y, state.w: w})
171 avg_cost = state.session.run(state.cost, feed_dict={state.x: X, state.y: y, state.w: w})
172 if epoch % 1000 == 0:
173 print(
"Epoch:",
'%04d' % (epoch),
"cost=",
"{:.9f}".format(avg_cost))
181 Store tensorflow session in a graph
184 import tensorflow
as tf
186 print(
"Please install tensorflow: pip3 install tensorflow")
189 keys = state.add_to_collection()
190 saver = tf.train.Saver()
191 with tempfile.TemporaryDirectory()
as path:
192 filename = saver.save(state.session, os.path.join(path,
'mymodel'))
193 with open(filename + str(
'.data-00000-of-00001'),
'rb')
as file1, open(filename + str(
'.index'),
'rb')
as file2:
196 meta_graph = saver.export_meta_graph()
198 return [meta_graph, os.path.basename(filename), data1, data2, keys]
def get_from_collection(self, collection_keys=None)
def add_to_collection(self)
collection_keys
array to save keys for collection
optimizer
optimizer used to minimize cost function
def __init__(self, x=None, y=None, activation=None, cost=None, optimizer=None, session=None, **kwargs)
x
feature matrix placeholder
session
tensorflow session
activation
activation function