我按照MNIST教程训练了一个模型,并保存了它:
saver = tf.train.Saver()save_path = saver.save(sess,'/path/to/model.ckpt')
我想使用这个保存的模型来为新的一批图像找到标签。我加载了模型并用数据库进行测试:
# 加载MNIST数据folds = build_database_tuple.load_data(data_home_dir='/path/to/database')# 启动会话。使用InteractiveSession可以避免在启动会话前构建整个计算图sess = tf.InteractiveSession()# 开始构建计算图...BUILD AND DEFINE ALL THE LAYERS...y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)# 训练和评估:cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))sess.run(tf.initialize_all_variables())saver = tf.train.Saver()# 从磁盘恢复变量savepath = '/path/to/model.ckpt'saver.restore(sess, save_path=savepath)print("模型已恢复。")print("测试准确率 %g"%accuracy.eval(feed_dict={x: folds.test.images, y_: folds.test.labels, keep_prob: 1.0}))
虽然我可以加载并测试模型,但我如何获取包含数据库图像预测的y’数组呢?
我在网上搜索了很多关于这个问题的答案,但无法将这些答案应用到这个特定案例中。例如,我找到了这个关于CIFAR10教程的答案,但它与MNIST教程非常不同。
回答:
定义一个用于执行分类的操作,例如
predictor = tf.argmax(y_conv,1)
然后在训练好的模型上使用新输入运行它
print(sess.run(predictor, feed_dict={ x = new_data }))
因为“predictor”不依赖于y
,所以你不需要提供它,这仍然可以执行。
如果你只想查看测试图像的预测结果,你也可以通过移除你的准确率评估调用,并执行以下操作,在一次运行中完成这两件事:
acc, predictions = sess.run([accuracy, predictor], feed_dict={x: folds.test.images, y_: folds.test.labels, keep_prob: 1.0}))print('准确率', acc)print('预测结果', predictions)