是的,我还在纠结MNIST手写数字识别。
之前虽然改进了网络,把2层加到了3层,实测正确率从50%提高到了75%,但这还是不够啊。我手敲的模型是最基础的SGD法,那么站在巨人的肩膀上,用现成的模型如何呢?
我从K同学那里抄来了TensorFlow的用法,摸索着封装了一个可以实测自己手写数字的程序:
import numpy as np
from PIL import Image
import tensorflow as tf
# 加载训练好的权重
model = tf.keras.models.load_model('D:/.../model/1_model.h5')
# 把图片变成28*28像素
def get_data(fn):
img0=Image.open(fn).convert('L')
if img0.size[0] !=28 or img0.size[1]!=28:
img0.resize((28,28))
arr = []
for i in range(28):
for j in range(28):
#pixel = 1-float(img0.getpixel((j, i)))/255.0 #用于白底黑字
pixel = float(img0.getpixel((j, i)))/255.0 #用于黑底白字
arr.append(pixel)
arr1=np.array(arr).reshape(28,28)
return arr1
之后,可以一张一张图片的玩:
# 单图预测
k=input('\n输入图片文件名,不带后缀:')
fn='C:/.../'+str(k)+'.png'
x=get_data(fn)
x=x.reshape(1,28,28,1)
pre = model.predict(x)
res_list=pre[0]
res=np.argmax(res_list)
print('预测结果:',res)
也可以进行小规模测试:
# 小规模测试
count=0
for k in range(10):
fn='C:/.../'+str(k)+'.jpg'
x=get_data(fn)
x=x.reshape(1,28,28,1)
pre = model.predict(x)
res_list=pre[0]
res=np.argmax(res_list)
print('正解:',k,' | 预测结果:',res,end='')
if k==res:
print(' 正确')
count+=1
else:
print(' 错误!')
acc=count/10*100
print('整体正确率:', acc, '%')