使用TensorFlow的卷积神经网络识别手写数字(3)-识别篇

  1 from PIL import Image
  2 import numpy as np
  3 import tensorflow as tf
  4 import time 
  5 
  6 
  7 bShowAccuracy = True
  8 
  9 
 10 # 加载手写图片
 11 def loadHandWritingImage(strFilePath):
 12     im = Image.open(strFilePath, 'r')
 13     ndarrayImg = np.array(im.convert("L"), dtype='float')
 14 
 15     return ndarrayImg
 16 
 17 
 18 # 最大最小值归一化
 19 def normalizeImage(ndarrayImg, maxVal = 255, minVal = 0):
 20     ndarrayImg = (ndarrayImg - minVal) / (maxVal - minVal)
 21     return ndarrayImg
 22 
 23 
 24 
 25 # 1)构造自己的手写图片集合,用加载的已训练好的模型识别
 26 print('构造待识别数据...')
 27 
 28 # 待识别的手写图片,文件名是0...39
 29 fileList = range(0, 39+1) 
 30 
 31 ndarrayImgs = np.zeros((len(fileList), 784)) # x行784列
 32 
 33 for index in range(len(fileList)):
 34     
 35     # 加载图片
 36     ndarrayImg = loadHandWritingImage('28-pixel-numbers/' + str(index) + '.png')
 37 
 38     # 归一化
 39     normalizeImage(ndarrayImg)
 40 
 41     # 转为1x784的数组
 42     ndarrayImg = ndarrayImg.reshape((1, 784))
 43 
 44     # 加入到测试集中
 45     ndarrayImgs[index] = ndarrayImg
 46 
 47 
 48 ##import sys
 49 ##sys.exit()
 50 
 51 # 构建测试样本的实际值集合,用于计算正确率
 52 
 53 # 真实结果,用于测试准确度。40行10列
 54 ndarrayLabels = np.eye(10, k=0, dtype='float')
 55 ndarrayLabels = np.vstack((ndarrayLabels, ndarrayLabels))
 56 ndarrayLabels = np.vstack((ndarrayLabels, ndarrayLabels))
 57 
 58 
 59 # 2)下面开始CNN相关
 60 
 61 print('定义Tensor...')
 62 
 63 #定义变量和计算公式
 64 
 65 def conv2d(x, W):
 66     return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
 67 
 68 def max_pool_2x2(x):
 69     return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
 70                         strides=[1, 2, 2, 1], padding='SAME')
 71 
 72 def weight_variable(shape):
 73     initial = tf.truncated_normal(shape, stddev=0.1)
 74     return tf.Variable(initial)
 75 
 76 def bias_variable(shape):
 77     initial = tf.constant(0.1, shape=shape)
 78     return tf.Variable(initial)
 79 
 80 
 81 x = tf.placeholder(tf.float32, shape=[None, 784])
 82 y_ = tf.placeholder(tf.float32, shape=[None, 10])
 83 
 84 
 85 W_conv1 = weight_variable([5, 5, 1, 32])
 86 b_conv1 = bias_variable([32])
 87 
 88 x_image = tf.reshape(x, [-1, 28, 28, 1])
 89 
 90 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
 91 h_pool1 = max_pool_2x2(h_conv1)
 92 
 93 
 94 W_conv2 = weight_variable([5, 5, 32, 64])
 95 b_conv2 = bias_variable([64])
 96 
 97 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
 98 h_pool2 = max_pool_2x2(h_conv2)
 99 
100 
101 
102 W_fc1 = weight_variable([7 * 7 * 64, 1024])
103 b_fc1 = bias_variable([1024])
104 
105 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
106 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
107 
108 
109 keep_prob = tf.placeholder(tf.float32)
110 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
111 
112 
113 W_fc2 = weight_variable([1024, 10])
114 b_fc2 = bias_variable([10])
115 
116 y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
117 
118 correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
119 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
120 
121 
122 with tf.Session() as sess:
123     sess.run(tf.global_variables_initializer())
124 
125     # 3)创建saver对象并加载模型
126     print('加载已训练好的CNN模型...')
127     saver = tf.train.Saver()
128     saver.restore(sess, "saved_model/cnn_handwrite_number.ckpt")
129 
130     # 测试耗时
131     print('进行预测:')
132   
133     start = time.time()
134 
135     # 4)执行预测
136     output = sess.run(y_conv, feed_dict={x: ndarrayImgs, keep_prob:1.0})  
137 
138     end = time.time()
139 
140     print('预测数字为:
', output.argmax(axis=1)) # axis:0表示按列,1表示按行
141     print('实际数字为:
', ndarrayLabels.argmax(axis=1))
142 
143 
144     if(bShowAccuracy):      
145         accu = accuracy.eval(feed_dict={x: ndarrayImgs, y_: ndarrayLabels, keep_prob: 1.0})
146         print('识别HateMath苍劲有力的手写数据%d个, 准确率为 %.2f%%, 每个耗时%.5f秒' %
147               (len(ndarrayImgs), accu*100, (end-start)/len(ndarrayImgs)))
148 
149         
150 
151 # todo
152 # 图像分割的准确度
153 
154   
本文由hATEmATH原创 转载请注明出处:http://www.cnblogs.com/hatemath/
原文地址:https://www.cnblogs.com/hatemath/p/8513799.html