【问题标题】:How to restore a Tensorflow model如何恢复 TensorFlow 模型
【发布时间】:2017-08-21 06:23:57
【问题描述】:

我正在学习使用 Tensorflow,我编写了这个 Python 脚本,它从 mnist db 中学习、保存模型并对图像进行预测:

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

但预测是错误的。 如何恢复我的变量并做出预测? 谢谢

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    测试时,注释这一行

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

    将解决您的问题。

    import_meta_graph 将创建一个保存在“.meta”文件中的新图形/模型,新模型将与您手动创建的模型共存。 saver 分配给新模型,因此 saver.restore 将训练的权重恢复到新模型,但 sess 使用您手动创建的模型运行。

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 2016-05-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      相关资源
      最近更新 更多