如何在tensorflow中恢复会话?

6

我希望能够使用我的神经网络而不必再次训练网络。我了解到

save_path = saver.save(sess, "model.ckpt")
print("Model saved in file: %s" % save_path)

现在这个文件夹里有三个文件:checkpointmodel.ckptmodel.ckpt.meta

我想在另一个 Python 类中还原数据,获取神经网络的权重并进行单一预测。

我该怎么做呢?

1个回答

2
保存模型,您可以按照以下步骤进行操作:
model_checkpoint = 'model.chkpt'

# Create the model
...
...

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())

    # Create a saver so we can save and load the model as we train it
    tf_saver = tf.train.Saver(tf.all_variables())

    # (Optionally) do some training of the model
    ...
    ...

    tf_saver.save(sess, model_checkpoint)

我假设您已经完成了这个步骤,因为您已经得到了三个文件。 当您想在另一个类中加载该模型时,可以像这样操作:

# The same file as we saved earlier
model_checkpoint = 'model.chkpt'

# Create the SAME model as before
...
...

with tf.Session() as sess:
    # Restore the model
    tf_saver = tf.train.Saver()
    tf_saver.restore(sess, model_checkpoint)

    # Now your model is loaded with the same values as when you saved,
    #   and you can do prediction or continue training

你是在尝试恢复模型还是保存模型时遇到了错误? - Ole Steinar Skrede
你看过这个吗:链接。在保存和恢复模型之前,你需要以完全相同的方式设置模型。你确定你正在尝试恢复相同的模型吗? - Ole Steinar Skrede
是的,谢谢。现在当我想要恢复它时,首先它会再次训练网络..但我想做一个单独的预测而不需要重新训练。你有什么建议吗? - Or Perets
也许只需要从网络中获取权重.. - Or Perets
2
当您调用restore()函数时,它会恢复模型中的全部变量/权重。 因此,首先需要构建模型(/图形),然后运行训练以更改图形中的权重,最后保存权重。 当您运行restore()函数时,它会恢复您保存的权重,但不会恢复模型/图形。 因此,在恢复之前,您需要设置与保存权重时相同的模型,以便将加载的权重适合于模型。 在恢复权重后,可以直接进行单次预测,无需先训练权重。 - Ole Steinar Skrede
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接