我一直在使用这个程序来预测我的手写图像,以使用以前训练过的数据来预测数字。以下是该计划。 请帮助我。新的这个
此代码用于图像处理:
import numpy as np
import matplotlib.image as mpimg
img=mpimg.imread(/images.png')
def rgb2gray(rgb):
... return np.dot(rgb[...,:3], [0.299, 0.587, 0.114])
...
>>> gray=rgb2gray(img)
>>> resized_image=cv2.resize(gray,(28,28))
>>> cv2.imwrite("/test.png",resized_image)
True
这是我使用的代码片段。变量已经过训练,保存和恢复。
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
import tensorflow as tf
import matplotlib.image as mpimg
import numpy as np
FLAGS = None
def deepnn(x):
# Reshape to use within a convolutional neural net.
# Last dimension is for "features" - there is only one here, since images are
# grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
with tf.name_scope('reshape'):
x_image = tf.reshape(x,[-1, 28, 28, 1])
# First convolutional layer - maps one grayscale image to 32 feature maps.
with tf.name_scope('conv1'):
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
# Pooling layer - downsamples by 2X.
with tf.name_scope('pool1'):
h_pool1 = max_pool_2x2(h_conv1)
# Second convolutional layer -- maps 32 feature maps to 64.
with tf.name_scope('conv2'):
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
# Second pooling layer.
with tf.name_scope('pool2'):
h_pool2 = max_pool_2x2(h_conv2)
# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
# is down to 7x7x64 feature maps -- maps this to 1024 features.
with tf.name_scope('fc1'):
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# Dropout - controls the complexity of the model, prevents co-adaptation of
# features.
with tf.name_scope('dropout'):
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# Map the 1024 features to 10 classes, one for each digit
with tf.name_scope('fc2'):
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
return y_conv, keep_prob
def conv2d(x, W):
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
"""max_pool_2x2 downsamples a feature map by 2X."""
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def weight_variable(shape):
"""weight_variable generates a weight variable of a given shape."""
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
"""bias_variable generates a bias variable of a given shape."""
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def main(_):
# Create the model
x = tf.placeholder(tf.float32, [None, 784])
# Build the graph for the deep net
y_conv, keep_prob = deepnn(x)
saver=tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess,"C:/Users/Joe_John/Desktop/model.ckpt")
print("Model restored.")
img = mpimg.imread('C:/Users/Joe_John/Desktop/test.png')
p = np.asarray(img).reshape(1, 784)
print(p)
z=sess.run(y_conv
,feed_dict={x:p,keep_prob:1.0})
print('this is z',z)
prediction=tf.argmax(y_conv,1)
print(sess.run(prediction,feed_dict={x:p,keep_prob:1.0}))
predict_=tf.nn.softmax(y_conv)
print(sess.run(predict_,feed_dict={x:p,keep_prob:1.0}))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str,
default='/tmp/tensorflow/mnist/input_data',
help='Directory for storing input data')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed'
following is the output
after accuracy [-0.10007022 0.19623001 -0.03660678 -0.08034142 0.05941308 0.25028974
-0.02256322 0.14994892 -0.3642419 -0.05205835]
[[ 0.09007561 0.11646919 0.09577192 0.09184043 0.10344592 0.12991495
0.09663657 0.11345788 0.06937791 0.0930096 ]]
6
以下是我使用的图像文件:
答案 0 :(得分:0)
我对TF不太熟悉,但是一些快速的在线研究让我相信你没有将argmax的结果传递给sess.run(),而是:
prediction=tf.argmax(y_conv,1)
print prediction.eval(feed_dict={x:p,keep_prob:1.0})
另一种选择,我相信你可能会这样做:
prediction=tf.argmax(logits,1)
best = sess.run([prediction],feed_dict)
同样,我不是很熟悉,但也许这是朝着正确方向迈出的一步。
我的回答来源:https://github.com/tensorflow/tensorflow/issues/97
快乐深度学习:)
答案 1 :(得分:0)
看起来你的图像是白底黑字。但是,MNIST数据集在白色上是黑色的,因此您可能希望反转像素值。此外,如果您将mnist数据标准化为[0,1]的标度,您可能还必须通过除以255.0将像素值标准化为该标度。希望这有帮助!