如何使用以前训练过的模型来获取图像标签 - TensorFlow

roi*_*hik 3 python machine-learning neural-network python-2.7 tensorflow

我训练了一个模型(根据MNIST教程)并保存了它:

saver = tf.train.Saver()
save_path = saver.save(sess,'/path/to/model.ckpt')
Run Code Online (Sandbox Code Playgroud)

我想使用保存的模型来查找新批次图像的标签.我加载模型并用数据库测试它:

# load MNIST data
folds = build_database_tuple.load_data(data_home_dir='/path/to/database')

# starting the session. using the InteractiveSession we avoid build the entiee comp. graph before starting the session
sess = tf.InteractiveSession()

# start building the computational graph
...

BUILD AND DEFINE ALL THE LAYERS

...

y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

# TRAIN AND EVALUATION:
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()
# Restore variables from disk.
savepath = '/path/to/model.ckpt'
saver.restore(sess, save_path=savepath)
print("Model restored.")

print("test accuracy %g"%accuracy.eval(feed_dict={x: folds.test.images, y_: folds.test.labels, keep_prob: 1.0}))
Run Code Online (Sandbox Code Playgroud)

虽然我可以加载和测试模型,但如何获得包含数据库图像预测的y'数组?

我扫描了网页并找到了很多关于这个问题的答案,但是我无法将这些答案适合这个特殊情况.例如,我找到了 关于CIFAR10教程的答案,但它与MNIST教程非常不同.

lej*_*lot 6

定义用于执行分类的OP,例如

predictor = tf.argmax(y_conv,1)
Run Code Online (Sandbox Code Playgroud)

然后在带有新输入的训练模型上运行它

print(sess.run(predictor, feed_dict={ x = new_data }))
Run Code Online (Sandbox Code Playgroud)

因为"预测器"不依赖于y你不必提供它,这仍然会执行.

如果您只想查看测试图像的预测,您还可以通过删除准确性评估和执行操作,在一次运行调用中执行这两项操作

acc, predictions = sess.run([accuracy, predictor],
                            feed_dict={x: folds.test.images,
                                       y_: folds.test.labels,
                                       keep_prob: 1.0}))

print('Accuracy', acc)
print('Predictions', predictions)
Run Code Online (Sandbox Code Playgroud)