Ask Your Question
0

How should a tensorflow model be saved so that it can be loaded in opencv3.3.1

asked 2017-12-15 02:54:51 -0500

AyushP123 gravatar image

updated 2017-12-15 03:17:03 -0500

berak gravatar image

Hi, I am using Tensorflow to train a neural network ( The neural network doesn't contain any variables ). This is my neural network graph in Tensorflow.

X =  tf.placeholder(tf.float32, [None,training_set.shape[1]],name = 'X')
Y = tf.placeholder(tf.float32,[None,training_labels.shape[1]], name = 'Y')

A1 = tf.contrib.layers.fully_connected(X, num_outputs = 50, activation_fn = tf.nn.relu)
A1 = tf.nn.dropout(A1, 0.8)
A2 = tf.contrib.layers.fully_connected(A1, num_outputs = 2, activation_fn = None)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = A2, labels = Y))
global_step = tf.Variable(0, trainable=False)
start_learning_rate = 0.001
learning_rate = tf.train.exponential_decay(start_learning_rate, global_step, 100, 0.1, True )
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

I wanted to know how this graph should be saved in tensorflow so as to load it using readNetFromTensorflow

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2017-12-15 04:34:00 -0500

dkurt gravatar image

@AyushP123, I guess a first question is how to save the graph at least to load it in TensorFlow again? Because you need to find a way to restore it. There is some way to do it:

-- Save

# Save a graph definition (once)
tf.train.write_graph(sess.graph.as_graph_def(), "", "graph.pb")

# Weights initialization
sess.run(tf.global_variables_initializer())

# Training
...

# Save a checkpoint (weights only, no graph definition)
saver = tf.train.Saver()
saver.save(sess, 'tmp.ckpt')

-- Freeze (merge graph definition with weights, remove training-only nodes)

python ~/tensorflow/tensorflow/python/tools/freeze_graph.py \
  --input_graph=graph.pb \
  --input_checkpoint=tmp.ckpt \
  --output_graph=frozen_graph.pb \
  --output_node_names="NameOfOutputNode"

Only after these steps you might load frozen_graph.pb contains both graph definition and weights using OpenCV.

edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2017-12-15 02:54:51 -0500

Seen: 543 times

Last updated: Dec 15 '17