【问题标题】:Predict single Image after training model in tensorflow在张量流中训练模型后预测单个图像
【发布时间】:2018-04-10 01:17:27
【问题描述】:

我在 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 个概率的数组。

【问题讨论】:

    标签: python tensorflow machine-learning prediction


    【解决方案1】:

    让我回答我自己的问题: 首先必须更改这些代码行,我们必须使用 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)
    

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

    【讨论】:

    • 谢谢,这正是我所需要的。
    猜你喜欢
    • 2019-02-22
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多