基于tensorflow 训练模型的单幅图像预测

kxeu7u2r  于 2023-01-09  发布在  其他
关注(0)|答案(2)|浏览(205)

我已经在tensorflow 训练模型如下:

batch_size = 128

graph = tf.Graph()
with graph.as_default():
# Input data. For the training data, we use a placeholder that will be fed
# at run time with a training minibatch.
tf_train_dataset = tf.placeholder(tf.float32,
                                  shape=(batch_size, image_size * image_size))
tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
tf_valid_dataset = tf.constant(valid_dataset)
tf_test_dataset = tf.constant(test_dataset)

# Variables.
weights = tf.Variable(
    tf.truncated_normal([image_size * image_size, num_labels]))
biases = tf.Variable(tf.zeros([num_labels]))

# Training computation.
logits = tf.matmul(tf_train_dataset, weights) + biases
loss = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))

# Optimizer.
optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

# Predictions for the training, validation, and test data.
train_prediction = tf.nn.softmax(logits)
valid_prediction = tf.nn.softmax(
    tf.matmul(tf_valid_dataset, weights) + biases)
test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)

num_steps = 3001
with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().run()
  print("Initialized")
    for step in range(num_steps):
     # Pick an offset within the training data, which has been randomized.
     # Note: we could use better randomization across epochs.
     offset = (step * batch_size) % (train_labels.shape[0] - batch_size)
     # Generate a minibatch.
     batch_data = train_dataset[offset:(offset + batch_size), :]
     batch_labels = train_labels[offset:(offset + batch_size), :]
     # Prepare a dictionary telling the session where to feed the minibatch.
     # The key of the dictionary is the placeholder node of the graph to be fed,
     # and the value is the numpy array to feed to it.
     feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}
     _, l, predictions = session.run(
    [optimizer, loss, train_prediction], feed_dict=feed_dict)
    if (step % 500 == 0):
      print("Minibatch loss at step %d: %f" % (step, l))
      print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
      print("Validation accuracy: %.1f%%" % accuracy(
      valid_prediction.eval(), valid_labels))
   print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))

现在,我想使用一个单一的图像作为输入,这是要重塑到相同的格式作为我的训练图像,并获得预测10类的概率。这个问题已经问了很多次,我很难理解他们的解决方案,其中一个最好的答案是使用以下代码:

feed_dict = {x: [your_image]}
classification = tf.run(y, feed_dict)
print classification

在我的代码中,x和y的等价性是什么?假设我从测试数据集中选择一个图像进行预测:

img = train_dataset[678]

我期待一个概率为10的数组。

ghhkc1vu

ghhkc1vu1#

让我回答我自己的问题:首先,必须更改这些代码行,我们必须使用None而不是const batch size,以便稍后可以将单个图像作为输入:

tf_train_dataset = tf.placeholder(tf.float32, shape=(None, image_size * image_size),name="train_to_restore")
tf_train_labels = tf.placeholder(tf.float32, shape=(None, num_labels))

在会话中,我使用以下代码向模型提供新图像:

from skimage import io
img = io.imread('newimage.png', as_grey=True)
nx, ny = img.shape
img_flat = img.reshape(nx * ny)
IMG = np.reshape(img,(1,784))
answer = session.run(train_prediction, feed_dict={tf_train_dataset: IMG})
print(answer)

我的图像在训练集中是2828,所以请确保您的新图像也是2828,您必须将其展平为1*784,并将其提供给您的模型,然后接收预测概率

wvt8vs2t

wvt8vs2t2#

你也可以使用tf.keras.utils.load_img,这样你就可以导入一张图片,然后让你的模型对它进行预测。
这个链接将向您显示要传入的参数及其含义:https://www.tensorflow.org/api_docs/python/tf/keras/utils/load_img
下面是一个使用它的例子。实际上,你所要做的就是从教程中更改文件路径:https://www.tensorflow.org/tutorials/images/classification#predict_on_new_data

相关问题