下你所需,载你所想!
IT技术源码资料下载网站

实现TensorFlow的手写数字识别

:其他软件 2020-09-13 19:07:31

实现TensorFlow的手写数字识别

1.数字识别数据集获取
1.1 导入相关模块
导入keras.utils模块是因为后续用到独热编码:
import numpy as np
import pandas as pd
from keras.utils import np_utils
np.random.seed(10)
Keras已经提供了下载、读取MNIST数据的模块,可以直接导入:
from keras.datasets import mnist
1.2 MNIST数据的下载和读取
第一次执行mnist.load_data()方法时,程序检查目录是否有MNIST数据集文件,若无,则下载。
#下载代码、加载代码相同,如下
(x_train_image,y_train_label),(x_test_image,y_test_label) = mnist.load_data()
#查看数据,此处笔者加注释
# print('train data=',len(x_train_image))
# print(' test data=',len(x_test_image))
# 下载完成之后,显示图像格式
print('x_train_image:',x_train_image.shape)
print('y_train_image:',y_train_label.shape)
1.3查看训练数据
为了能够显示images数字图像,创建plot_image函数:
(1)首先导入matplotlib.pyplot模块;
(2)定义函数的输入参数为image;
(3、4)设置显示图形大小为(2,2),单位为英寸;
(5)使用plt.imshow显示图像,传入参数为28*28的图像,cmap参数为binary,以灰度显示
import matplotlib.pylot as plt
def plot_image(image):
fig = plt.gcf()
fig.set_size_inches(2,2)
plt.imshow(image,cmap='binary')
plt.show()
plot_image(x_train_image[0]) #画一个数字
1.4查看数据images以及label
导入pyplot模块,后续用plt引用.
定义plot_images_labels_prediction()函数,各数据如下:
images(数字图像),labels(真实值),prediction(预测结果),idx(开始显示的数据index),num=10(要显示的数据项数,默认时10,不超过25).
import matplotlib.pyplot as plt
def plot_images_labels_prediction(images,labels,prediction,idx,num=10):
fig = plt.gcf()
fig.set_size_inches(12,14) #设置图像的大小
if num>25 : num =25 #设置显示最大项数
for i in range(0,num): #for循环画出num个数字图像
ax=plt.subplot(5,5,i+1)
ax.imshow(images[idx],cmap='binary') #建立subgraph子图形为五行五列
title = "label="+str(labels[idx]) #设置子图形title,显示标签字段
if len(prediction)>0: #如果传入了预测结果
title+=",prediction="+str(prediction[idx]) #标题
ax.set_title(title,fontsize=10) #设置子图形的标题
ax.set_xticks([]);ax.set_yticks([]) #设置不显示刻度
idx+=1 #读取下一项
plt.show()
开始画图,查看前十项数据.
plot_images_labels_prediction(x_train_image,y_train_label,[],0,10) #查看训练集数据
plot_images_labels_prediction(x_test_image, y_test_label, [],0,10) #查看测试集数据
部分训练集结果如下:
训练集的数据图像
2. 图像数据预处理
2.1 features数据预处理
(1)将原本28*28的数字图像reshape(整形)为一维向量,长度为784,数据类型为Float.
(1)数字图像image的数字标准化(我理解是归一化).
#整形
x_Train = x_train_image.reshape(60000,784).astype('float32')
x_Test = x_test_image.reshape(10000,784).astype('float32')
#归一化
x_Train_nomalize = x_Train/255
x_Test_nomalize = x_Test/255
2.2 label数据预处理
(1)lael标签字段进行独热编码(One-Hot Encoding)
#One-Hot Encoding 转换
y_TrainOneHot = np_utils.to_categorical(y_train_label)
y_TestOneHot = np_utils.to_categorical(y_test_label)
3.小结
在使用TensorFlow进行图像处理之前,首先要进行的一步是数据的预处理,代码对处理的对象格式有一定的要求,输入数据要整形成一维,对输出结果进行独热编码更有利于结果匹配。