2017-03-28 268 views
0

我學習使用Tensorflow,我寫道,從MNIST分貝得知這個Python腳本,保存模型,並進行圖像上的預測:如何恢復Tensorflow模型

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()) 

的預測是正確的,但我無法恢復保存的模型以供重複使用。 我寫道,試圖恢復模型,並作出同樣的預測這個其他腳本:

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()) 

但預測是錯誤的。 如何恢復我的變量並進行預測? 感謝

回答

1

當測試,註釋此行

# saver = tf.train.import_meta_graph('/tmp/my-model.meta') 

將解決你的問題。

import_meta_graph將創建保存在'.meta'文件中的新圖形/模型,並且新模型將與您手動創建的模型共存。 saver已分配給新模型,因此saver.restore會將訓練後的權重恢復到新模型,但sess將使用您手動創建的模型運行。

相關問題