我已经编写了一个Tensorflow CNN并完成了训练。我希望恢复它以在一些样本上运行,但不幸的是它输出了以下错误:
ValueError: 没有可保存的变量
我的评估代码可以在以下位置找到:
import tensorflow as tfimport mainimport Processimport Inputeval_dir = "/Users/Zanhuang/Desktop/NNP/model.ckpt-30"checkpoint_dir = "/Users/Zanhuang/Desktop/NNP/checkpoint"init_op = tf.initialize_all_variables()saver = tf.train.Saver()def evaluate(): with tf.Graph().as_default() as g: sess.run(init_op) ckpt = tf.train.get_checkpoint_state(checkpoint_dir) saver.restore(sess, eval_dir) images, labels = Process.eval_inputs(eval_data = eval_data) forward_propgation_results = Process.forward_propagation(images) top_k_op = tf.nn.in_top_k(forward_propgation_results, labels, 1) print(top_k_op)def main(argv=None): evaluate()if __name__ == '__main__': tf.app.run()
回答:
tf.train.Saver
必须在你想要恢复(或保存)的变量之后创建。另外,它必须在与这些变量相同的图中创建。
假设 Process.forward_propagation(…)
也创建了模型中的变量,在这行代码之后添加保存器的创建应该会起作用:
forward_propgation_results = Process.forward_propagation(images)
此外,你必须将新创建的 tf.Graph
传递给 tf.Session
构造函数,所以你需要将 sess
的创建也移到那个 with
块中。
最终的函数将类似于以下内容:
def evaluate(): with tf.Graph().as_default() as g: images, labels = Process.eval_inputs(eval_data = eval_data) forward_propgation_results = Process.forward_propagation(images) init_op = tf.initialize_all_variables() saver = tf.train.Saver() top_k_op = tf.nn.in_top_k(forward_propgation_results, labels, 1) with tf.Session(graph=g) as sess: sess.run(init_op) saver.restore(sess, eval_dir) print(sess.run(top_k_op))