【问题标题】:Define variables to load MNIST images app定义变量以加载 MNIST 图像应用程序
【发布时间】:2018-04-03 06:50:48
【问题描述】:

我正在使用 TensorFlow 学习机器学习,然后我有了一个简单的 MNIST 模型。

这是模型代码,遵循官方教程

import tensorflow as tf
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for _ in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

现在,我想通过传递数字图像来练习这个模型。 所以,问题是我如何(在 Python 中)定义要加载到图像中的变量(.bmp、.jpg、 .png...)。我们的想法是首先在我的计算机中练习本地文件,然后才能 从客户端发送图像数据(假设是通过 JSON 以 REST API 方式)到模型 显示关于图像中出现的数字的预测。

【问题讨论】:

    标签: python tensorflow mnist


    【解决方案1】:

    使用Python PIL包加载图片:

    from PIL import Image
    im = Image.open("bride.jpg")
    

    将其转换为 numpy 数组,传递给 tensorflow 的所有内容都必须为 numpy 格式:

    import numpy as np
    img3d = np.array(im)
    

    这些图像当前的形状为 [28, 28] 或 [28, 28, 1],将它们重新整形为 784:

    img_flat = np.reshape(img3d, (1, 784))
    

    您需要批量处理其中的一些,使用tf.vstack 将它们组合起来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 2021-09-21
      • 2023-03-28
      • 2015-02-05
      • 2019-09-25
      • 1970-01-01
      相关资源
      最近更新 更多