I'm trying to load a previous saved TENSOFLOW model (both graph and variables).
Here's how I exported the model during the training session
tf.global_variables_initializer().run()
y = tf.matmul(x, W) + b
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
for batch_index in range(batch_size):
batch_xs, batch_ys = sample_dataframe(train_df, N=batch_size)
#print(batch_xs.shape)
#print(batch_ys.shape)
sess.run(train_step, feed_dict = {x: batch_xs, y_:batch_ys})
if batch_index % 100 == 0:
print("Batch "+str(batch_index))
correct_predictions = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
print("Accuracy: "+str(sess.run(accuracy,
feed_dict = {x: batch_xs, y_: batch_ys})))
#print("Predictions "+str(y))
#print("Training accuracy: %.1f%%" %accuracy())
if batch_index + 1 == batch_size:
#Save the trained model
print("Exporting trained model")
builder = saved_model_builder.SavedModelBuilder(EXPORT_DIR)
builder.add_meta_graph_and_variables(sess, ['simple-MNIST'])
builder.save(as_text=True)
Please ignore how the model is defined (it's just a toy example), and check only the last lines where the save method is invoked. Everything went fine and the model is correctly saved in the FS.
When I try lo load the exported model I always get the following error:
TypeError: Can not convert a MetaGraphDef into a Tensor or Operation.
Here's how I load the model:
with tf.Session() as sess:
print(tf.saved_model.loader.maybe_saved_model_directory(export_dir))
saved_model = tf.saved_model.loader.load(sess, ['simple-MNIST'], export_dir)
sess.run(saved_model)
Any idea how to solve it? It seems that the model has been exported with a wrong format, but I can't figure out how to change it.
Here's a simple script for load the model and scoring it.
with tf.device("/cpu:0"):
x = tf.placeholder(tf.float32, shape =(batch_size, 784))
W = tf.Variable(tf.truncated_normal(shape=(784, 10), stddev=0.1))
b = tf.Variable(tf.zeros([10]))
y_ = tf.placeholder(tf.float32, shape=(batch_size, 10))
with tf.Session() as sess:
tf.global_variables_initializer().run()
print(tf.saved_model.loader.maybe_saved_model_directory(export_dir))
saved_model = tf.saved_model.loader.load(sess, ['simple-MNIST'], export_dir)
batch_xs, batch_ys = sample_dataframe(train_df, N=batch_size)
y = tf.matmul(x, W) + b
correct_predictions = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
print("Test Accuracy: "+ str(sess.run(accuracy, feed_dict = {x: batch_xs, y_: batch_ys})))
Running this script in a brand new PYTHON context, will score the model with a very low accuracy (it seems that the load model method hasn't correctly set the graph variables)
Thank you!