我看过一些有关恢复TF模型的帖子,以及Google文档页面上有关导出图形的内容,但我认为我还是缺少了些什么。
我使用这个Gist中的代码来保存模型,以及这个utils文件来定义模型。
现在,我想将其恢复并在先前未见过的测试数据上运行,如下所示:
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
total_loss = 0
sess = tf.get_default_session()
acc_steps = len(X_data) // BATCH_SIZE
for i in range(acc_steps):
batch_x, batch_y = next_batch(X_val, Y_val, BATCH_SIZE)
loss, accuracy = sess.run([loss_value, acc], feed_dict={
images_placeholder: batch_x,
labels_placeholder: batch_y,
keep_prob: 0.5
})
total_accuracy += (accuracy * len(batch_x))
total_loss += (loss * len(batch_x))
return (total_accuracy / num_examples, total_loss / num_examples)
## re-execute the code that defines the model
# Image Tensor
images_placeholder = tf.placeholder(tf.float32, shape=[None, 32, 32, 3], name='x')
gray = tf.image.rgb_to_grayscale(images_placeholder, name='gray')
gray /= 255.
# Label Tensor
labels_placeholder = tf.placeholder(tf.float32, shape=(None, 43), name='y')
# dropout Tensor
keep_prob = tf.placeholder(tf.float32, name='drop')
# construct model
logits = inference(gray, keep_prob)
# calculate loss
loss_value = loss(logits, labels_placeholder)
# training
train_op = training(loss_value, 0.001)
# accuracy
acc = accuracy(logits, labels_placeholder)
with tf.Session() as sess:
loader = tf.train.import_meta_graph('gtsd.meta')
loader.restore(sess, tf.train.latest_checkpoint('./'))
sess.run(tf.initialize_all_variables())
test_accuracy = evaluate(X_test, y_test)
print("Test Accuracy = {:.3f}".format(test_accuracy[0]))
我的测试准确度只有 3%。然而,如果我在训练模型后不关闭笔记本,立即运行测试代码,我可以得到 95% 的准确度。
这使我认为我没有正确地加载模型?
tf.train.import_meta_graph()
将在当前图中加载模型结构的第二个副本。如果在创建tf.Session
之前的代码中构建了图的副本(包括所有权重),那么那些权重将保持未初始化状态,只有第二个副本中的权重将被恢复。有两种方法可以解决这个问题:(1)不使用tf.train.import_meta_graph()
,直接创建tf.train.Saver
并使用它来将检查点恢复到图的初始副本中;或者... - mrrytf.train.import_meta_graph()
之前避免构建评估图,而是使用内省方法,如tf.get_default_graph().get_operation_by_name()
查找原始图中的损失、精确度和占位符张量。这两种方法都可能需要一些重构(基本上您必须确保变量名称在图形和检查点中相同),但我期望选项(1)将涉及更少的工作。 - mrry1.0
?声明一个新的tf.placeholder()
就可以吗,还是应该从训练中恢复placeholder? - Nicolai Anton Lynnerup