用BP神经网络算法,基于Tensorflow训练了mnist数据集,在训练的python脚本中可以得到test上的精确度为96%,然后在另一个python脚本中,恢复出这个模型,输入手写数字的图片进行预测,100张图片识别的精确度只有70%多,请教各路大神帮忙解决一下,预测脚本的代码如下:
import sys
import tensorflow as tf
import os
from PIL import Image, ImageFilter
from pylab import *
def predictint(imvalue):
with tf.Graph().as_default():
def addlayer(input_data,insize,outsize,act_function=None):
W=tf.Variable(tf.random_normal([insize,outsize]))
b=tf.Variable(tf.zeros([outsize]))+0.1
out_data=tf.matmul(input_data,W)+b
if act_function==None:
return out_data
elif act_function=="relu":
return tf.nn.relu(out_data)
elif act_function=="softmax":
#result=tf.nn.softmax(out_data)
return tf.nn.softmax(out_data)
else:
return tf.nn.sigmoid(out_data)
x_input=tf.placeholder(tf.float32,[None,784])
#y_input=tf.placeholder(tf.float32,[None,10])
l1=addlayer(x_input,784,64,act_function="relu")
l2=addlayer(l1,64,10,act_function="softmax")
init_op = tf.initialize_all_variables()
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(init_op)
saver.restore(sess, "./model.ckpt")
prediction=tf.argmax(l2,1)
return prediction.eval(feed_dict={x_input: [imvalue]}, session=sess)
def imageprepare(argv):
im = Image.open(argv).convert('L')
width = float(im.size[0])
height = float(im.size[1])
newImage = Image.new('L', (28, 28), (255)) #creates white canvas of 28x28 pixels
if width > height: #check which dimension is bigger
#Width is bigger. Width becomes 20 pixels.
nheight = int(round((20.0/width*height),0)) #resize height according to ratio width
if (nheigth == 0): #rare case but minimum is 1 pixel
nheigth = 1
# resize and sharpen
img = im.resize((20,nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
wtop = int(round(((28 - nheight)/2),0)) #caculate horizontal pozition
newImage.paste(img, (4, wtop)) #paste resized image on white canvas
else:
#Height is bigger. Heigth becomes 20 pixels.
nwidth = int(round((20.0/height*width),0)) #resize width according to ratio height
if (nwidth == 0): #rare case but minimum is 1 pixel
nwidth = 1
# resize and sharpen
img = im.resize((nwidth,20), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
wleft = int(round(((28 - nwidth)/2),0)) #caculate vertical pozition
newImage.paste(img, (wleft, 4)) #paste resized image on white canvas
newImage.show()
tv = list(newImage.getdata()) #get pixel values
#normalize pixels to 0 and 1. 0 is pure white, 1 is pure black.
tva = [ (255-x)*1.0/255.0 for x in tv]
return tva
#print(tva)
def main(argv):
imvalue = imageprepare(argv)
predint = predictint(imvalue)
print (predint[0]) #first value in list
f1 = open('/home/wch/MNIST_data/traindata_predict.txt','a')
f1.writelines('%d ' % predint[0])
f1.close()
def VisitDir(path):
for root,dirs,files in os.walk(path):
for filepath in files:
print(os.path.join(root,filepath))
main(os.path.join(root,filepath))
if __name__ == "__main__":
path = r"/home/wch/MNIST_data/data_convert2"
VisitDir(path)