我正在尝试使用Google的TensorFlow GitHub中的这个示例,后者构建CNN,然后对MNIST数据集进行训练和测试:
https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/examples/tutorials/mnist/mnist_deep.py
但不是像上面那样测试MNIST的例子:
print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
我想一次一个地测试我自己的图像。我画了10张图片,Paint中的数字0 - 9,这里有几个例子:
根据此帖子进行一些更改,该帖子基于softmax Google示例:
Tensorflow - Testing a mnist neural net with my own images
这是我到目前为止所做的:
我似乎无法弄清楚如何更改上面的行以使用单个.png或.jpg而不是预先配置的MNIST数据集中的多个图像。这是我到目前为止我的整个main()函数:
#######################################################################################################################
def main():
# import data
print("obtaining MNIST data . . .")
mnistData = mnistDataLib.read_data_sets("C:\\mnist", one_hot=True)
print("building graph . . .")
# create the model
x = tf.placeholder(tf.float32, [None, 784])
# define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
# build the graph for the deep net
y_conv, keep_prob = deepnn(x)
with tf.name_scope('loss'):
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)
# end with
cross_entropy = tf.reduce_mean(cross_entropy)
with tf.name_scope('adam_optimizer'):
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# end with
with tf.name_scope('accuracy'):
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
correct_prediction = tf.cast(correct_prediction, tf.float32)
# end with
accuracy = tf.reduce_mean(correct_prediction)
print("training . . .")
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# ToDo: reduced training size for the moment to save time, restore to 20000 when get program working
#for i in range(20000):
for i in range(150):
batch = mnistData.train.next_batch(50)
if i % 100 == 0:
train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
print("step " + str(i) + ", training accuracy = " + str(train_accuracy))
# end if
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
# end for
print("testing . . .")
# this is the original code by Google to test on the MNIST data:
# testAccuracy = accuracy.eval(feed_dict={x: mnistData.test.images, y_: mnistData.test.labels, keep_prob: 1.0})
# print("test accuracy = " + str(testAccuracy))
image = cv2.imread("3.jpg", cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT))
imgFlattened = np.vectorize(lambda x: 255 - x)(np.ndarray.flatten(image))
npaResult = sess.run(tf.argmax(y_, 1), feed_dict={x: [imgFlattened]})
strResult = str(' '.join(map(str, npaResult)))
print("result = " + strResult)
# end with
# write the graph to file so we can view with TensorBoard
print("writing graph to file . . .")
fileWriter = tf.summary.FileWriter(os.getcwd())
fileWriter.add_graph(sess.graph)
fileWriter.close()
print("done !!")
# end main
其他函数调用与上面链接的Google CNN示例相同,我不想发布整个代码以防止此帖更长,如果看到整个程序是相关的,请参阅上面的GitHub链接。< / p>
目前我遇到了很多错误,但我认为最相关的是这一行:
npaResult = sess.run(tf.argmax(y_, 1), feed_dict={x: [imgFlattened]})
我收到了这个错误:
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1' with dtype float and shape [?,10]
[[Node: Placeholder_1 = Placeholder[dtype=DT_FLOAT, shape=[?,10], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
似乎我需要向feed_dict =添加更多参数,但我不确定要添加什么。
如果我将sess.run()行更改为:
npaResult = sess.run(tf.argmax(y_, 1), feed_dict={x: [imgFlattened], y_: mnistData.test.labels, keep_prob: 1.0})
至少程序没有崩溃,但我得到了输出:
result = 7 2 1 0 4 1 4 9 5 9 0 6 9 0 1 5 9 7 3 4 9 6 6 5 4 0 7 4 0 1 3 1 3 4 7 2 7 1 2 1 1 7 4 2 3 5 1 (many more numbers omitted)
结果行应该说
result = 3
我认为除了这一系列之外,我的一切都是正确的:
image = cv2.imread("3.jpg", cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT))
imgFlattened = np.vectorize(lambda x: 255 - x)(np.ndarray.flatten(image))
npaResult = sess.run(tf.argmax(y_, 1), feed_dict={x: [imgFlattened]})
strResult = str(' '.join(map(str, npaResult)))
print("result = " + strResult)
如何更改此选项才能成功测试一个.jpg图像?