Reputation: 245
I'm learning to use Tensorflow and I wrote this Python script that learns from mnist db, save the model and make a prediction on a image:
X = tf.placeholder(tf.float32, [None, 28, 28, 1])
W = tf.Variable(tf.zeros([784, 10], name="W"))
b = tf.Variable(tf.zeros([10]), name="b")
Y = tf.nn.softmax(tf.matmul(tf.reshape(X, [-1, 784]), W) + b)
# ...
init = tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init)
# ... learning loop
saver.save(sess, "/tmp/my-model")
# Make a prediction with an image
im = numpy.asarray(Image.open("digit.png")) / 255
im = im[numpy.newaxis, :, :, numpy.newaxis]
dict = {X: im}
print("Prediction: ", numpy.array(sess.run(Y, dict)).argmax())
The prediction is correct, but I can't restore the saved model for reusing. I wrote this other script that tries to restore the model and make the same prediction:
X = tf.placeholder(tf.float32, [None, 28, 28, 1])
W = tf.Variable(tf.zeros([784, 10]), name="W")
b = tf.Variable(tf.ones([10]) / 10, name="b")
Y = tf.nn.softmax(tf.matmul(tf.reshape(X, [-1, 784]), W) + b)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
saver = tf.train.import_meta_graph('/tmp/my-model.meta')
saver.restore(sess, tf.train.latest_checkpoint('/tmp/'))
# Make a prediction with an image
im = numpy.asarray(Image.open("digit.png")) / 255
im = im[numpy.newaxis, :, :, numpy.newaxis]
dict = {X: im}
print("Prediction: ", numpy.array(sess.run(Y, dict)).argmax())
but the prediction is wrong. How can I restore my variables and make a prediction? Thanks
Upvotes: 0
Views: 280
Reputation: 2356
When test, comment this line
# saver = tf.train.import_meta_graph('/tmp/my-model.meta')
will solve your problem.
import_meta_graph
will create a new Graph/model saved in the '.meta' file and the new model will co-exist with the model you created manually. The saver
is assigned to the new model, so saver.restore
restores the trained weights to the new model, but the sess
runs using the model you created manually.
Upvotes: 1