基于飞桨paddle的优化的卷积神经网络构建手写数字识别模型测试代码
原始测试图片为255X252的图片
采用的是多层卷积神经网络实现模型
本次预测的数字是: 0 预测结果正确
测试结果:
PS E:\project\python> & D:/Python39/python.exe e:/project/python/MNIST_Good.py
10.0.0
2.4.2
视觉相关数据集: ['DatasetFolder', 'ImageFolder', 'MNIST', 'FashionMNIST', 'Flowers', 'Cifar10', 'Cifar100', 'VOC2012']
自然语言相关数据集: []
数据处理方法: ['BaseTransform', 'Compose', 'Resize', 'RandomResizedCrop', 'CenterCrop', 'RandomHorizontalFlip', 'RandomVerticalFlip', 'Transpose', 'Normalize', 'BrightnessTransform', 'SaturationTransform', 'ContrastTransform', 'HueTransform', 'ColorJitter', 'RandomCrop', 'Pad', 'RandomAffine', 'RandomRotation', 'RandomPerspective', 'Grayscale', 'ToTensor', 'RandomErasing', 'to_tensor', 'hflip', 'vflip', 'resize', 'pad', 'affine', 'rotate', 'perspective', 'to_grayscale', 'crop', 'center_crop', 'adjust_brightness', 'adjust_contrast', 'adjust_hue', 'normalize', 'erase']
训练数据集数量: 60000
第一个图片为 (28, 28) [5]
loading mnist dataset from ./work/mnist.json.gz ......
mnist dataset load done
训练数据集数量: 50000
epoch: 0, batch: 0, loss is: 2.477492332458496
epoch: 0, batch: 200, loss is: 0.4456450939178467
epoch: 0, batch: 400, loss is: 0.5323783159255981
epoch: 1, batch: 0, loss is: 0.20092853903770447
epoch: 1, batch: 200, loss is: 0.2553440034389496
epoch: 1, batch: 400, loss is: 0.15512971580028534
epoch: 2, batch: 0, loss is: 0.2842020094394684
epoch: 2, batch: 200, loss is: 0.28731051087379456
epoch: 2, batch: 400, loss is: 0.13510549068450928
epoch: 3, batch: 0, loss is: 0.13414797186851501
epoch: 3, batch: 200, loss is: 0.21469420194625854
epoch: 3, batch: 400, loss is: 0.07933782786130905
epoch: 4, batch: 0, loss is: 0.21547366678714752
epoch: 4, batch: 200, loss is: 0.08164089173078537
epoch: 4, batch: 400, loss is: 0.10954642295837402
epoch: 5, batch: 0, loss is: 0.100625179708004
epoch: 5, batch: 200, loss is: 0.0793483555316925
epoch: 5, batch: 400, loss is: 0.07619502395391464
epoch: 6, batch: 0, loss is: 0.15254954993724823
epoch: 6, batch: 200, loss is: 0.06099638342857361
epoch: 6, batch: 400, loss is: 0.06358123570680618
epoch: 7, batch: 0, loss is: 0.14632579684257507
epoch: 7, batch: 200, loss is: 0.046541355550289154
epoch: 7, batch: 400, loss is: 0.06954287737607956
epoch: 8, batch: 0, loss is: 0.10759935528039932
epoch: 8, batch: 200, loss is: 0.08590111881494522
epoch: 8, batch: 400, loss is: 0.041374415159225464
epoch: 9, batch: 0, loss is: 0.10088040679693222
epoch: 9, batch: 200, loss is: 0.021175531670451164
epoch: 9, batch: 400, loss is: 0.0679405927658081
本次预测的数字是: 0
PS E:\project\python>
测试代码如下所示:
#数据处理部分之前的代码,加入部分数据处理的库
import paddle
from paddle.nn import Conv2D, MaxPool2D, Linear
import paddle.nn.functional as F
import os
import gzip
import json
import random
import numpy as np
import matplotlib.pyplot as plt
# 导入图像读取第三方库
from PIL import Image,ImageFilter
print(Image.__version__) #10.0.0
#原来是在pillow的10.0.0版本中,ANTIALIAS方法被删除了,使用新的方法即可Image.LANCZOS
#或降级版本为9.5.0,安装pip install Pillow==9.5.0
print(paddle.__version__) #2.4.2
print('视觉相关数据集:', paddle.vision.datasets.__all__)
print('自然语言相关数据集:', paddle.text.datasets.__all__)
print('数据处理方法:', paddle.vision.transforms.__all__)
#data=json.load(open("./work/train-images-idx3-ubyte.gz"))
#print(len(data))
#获取训练集train_dataset
train_dataset = paddle.vision.datasets.MNIST(mode='train')
print('训练数据集数量:',len(train_dataset)) # 60000
#取第一张图片和标签=5
i=0
#for i in range(20):
train_data0 = np.array(train_dataset[i][0])
train_label_0 = np.array(train_dataset[i][1])
print('第一个图片为',train_data0.shape,train_label_0) #(28,28),5
'''
plt.figure("Image") # 图像窗口名称
plt.figure(figsize=(2,2))
plt.imshow(train_data0, cmap=plt.cm.binary)
plt.axis('on') # 关掉坐标轴为 off
plt.title('image') # 图像题目
plt.show()
def sigmoid(x):
# 直接返回sigmoid函数
return 1. / (1. + np.exp(-x))
# param:起点,终点,间距
x = np.arange(-8, 8, 0.2)
y = sigmoid(x)
plt.plot(x, y)
plt.show()
'''
#===========================================
def load_data(mode='train'):
datafile = './work/mnist.json.gz'
print('loading mnist dataset from {} ......'.format(datafile))
# 加载json数据文件
data = json.load(gzip.open(datafile))
print('mnist dataset load done')
# 数据集相关参数,图片高度IMG_ROWS, 图片宽度IMG_COLS
IMG_ROWS = 28
IMG_COLS = 28
# 读取到的数据区分训练集,验证集,测试集
train_set, val_set, eval_set = data
if mode=='train':
# 获得训练数据集
imgs, labels = train_set[0], train_set[1]
elif mode=='valid':
# 获得验证数据集
imgs, labels = val_set[0], val_set[1]
elif mode=='eval':
# 获得测试数据集
imgs, labels = eval_set[0], eval_set[1]
else:
raise Exception("mode can only be one of ['train', 'valid', 'eval']")
print("训练数据集数量: ", len(imgs))
# 校验数据
imgs_length = len(imgs)
assert len(imgs) == len(labels), \
"length of train_imgs({}) should be the same as train_labels({})".format(len(imgs), len(labels))
# 获得数据集长度
imgs_length = len(imgs)
# 定义数据集每个数据的序号,根据序号读取数据
index_list = list(range(imgs_length))
# 读入数据时用到的批次大小
BATCHSIZE = 100
# 定义数据生成器
def data_generator():
if mode == 'train':
# 训练模式下打乱数据
random.shuffle(index_list)
imgs_list = []
labels_list = []
for i in index_list:
# 将数据处理成希望的类型
img = np.array(imgs[i]).astype('float32')
label = np.array(labels[i]).astype('float32')
# 在使用卷积神经网络结构时,uncomment 下面两行代码
img = np.reshape(imgs[i], [1, IMG_ROWS, IMG_COLS]).astype('float32')
#label = np.reshape(labels[i], [1]).astype('float32')
label = np.reshape(labels[i], [1]).astype('int64')
imgs_list.append(img)
labels_list.append(label)
if len(imgs_list) == BATCHSIZE:
# 获得一个batchsize的数据,并返回
yield np.array(imgs_list), np.array(labels_list)
# 清空数据读取列表
imgs_list = []
labels_list = []
# 如果剩余数据的数目小于BATCHSIZE,
# 则剩余数据一起构成一个大小为len(imgs_list)的mini-batch
if len(imgs_list) > 0:
yield np.array(imgs_list), np.array(labels_list)
return data_generator
#===========================================
#数据处理部分之后的代码,数据读取的部分调用Load_data函数
'''
# 定义多层全连接神经网络
class MNIST(paddle.nn.Layer):
def __init__(self):
super(MNIST, self).__init__()
# 定义两层全连接隐含层,输出维度是10,当前设定隐含节点数为10,可根据任务调整
self.fc1 = Linear(in_features=784, out_features=10)
self.fc2 = Linear(in_features=10, out_features=10)
# 定义一层全连接输出层,输出维度是1
self.fc3 = Linear(in_features=10, out_features=1)
# 定义网络的前向计算,隐含层激活函数为sigmoid,输出层不使用激活函数
def forward(self, inputs):
# inputs = paddle.reshape(inputs, [inputs.shape[0], 784])
outputs1 = self.fc1(inputs)
outputs1 = F.sigmoid(outputs1)
outputs2 = self.fc2(outputs1)
outputs2 = F.sigmoid(outputs2)
outputs_final = self.fc3(outputs2)
return outputs_final
'''
#===========================================
''' '''
# 多层卷积神经网络实现
class MNIST(paddle.nn.Layer):
def __init__(self):
super(MNIST, self).__init__()
# 定义卷积层,输出特征通道out_channels设置为20,卷积核的大小kernel_size为5,卷积步长stride=1,padding=2
self.conv1 = Conv2D(in_channels=1, out_channels=20, kernel_size=5, stride=1, padding=2)
# 定义池化层,池化核的大小kernel_size为2,池化步长为2
self.max_pool1 = MaxPool2D(kernel_size=2, stride=2)
# 定义卷积层,输出特征通道out_channels设置为20,卷积核的大小kernel_size为5,卷积步长stride=1,padding=2
self.conv2 = Conv2D(in_channels=20, out_channels=20, kernel_size=5, stride=1, padding=2)
# 定义池化层,池化核的大小kernel_size为2,池化步长为2
self.max_pool2 = MaxPool2D(kernel_size=2, stride=2)
# 定义一层全连接层,输出维度是10
self.fc = Linear(in_features=980, out_features=10)
# 定义网络前向计算过程,卷积后紧接着使用池化层,最后使用全连接层计算最终输出
# 卷积层激活函数使用Relu,全连接层不使用激活函数
def forward(self, inputs):
x = self.conv1(inputs)
x = F.relu(x)
x = self.max_pool1(x)
x = self.conv2(x)
x = F.relu(x)
x = self.max_pool2(x)
x = paddle.reshape(x, [x.shape[0], -1])
x = self.fc(x)
return x
#===========================================
# 训练配置,并启动训练过程
#网络结构部分之后的代码,保持不变
def train(model):
model.train()
#调用加载数据的函数,获得MNIST训练数据集
train_loader = load_data('train')
# 使用SGD优化器,learning_rate设置为0.01
opt = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters())
# 训练5轮
EPOCH_NUM = 10
# MNIST图像高和宽
IMG_ROWS, IMG_COLS = 28, 28
loss_list = []
for epoch_id in range(EPOCH_NUM):
for batch_id, data in enumerate(train_loader()):
#准备数据
images, labels = data
images = paddle.to_tensor(images)
labels = paddle.to_tensor(labels)
#前向计算的过程
predicts = model(images)
#计算损失,使用交叉熵损失函数,取一个批次样本损失的平均值
loss = F.cross_entropy(predicts, labels)
avg_loss = paddle.mean(loss)
#每训练200批次的数据,打印下当前Loss的情况
if batch_id % 200 == 0:
loss = avg_loss.numpy()[0]
loss_list.append(loss)
print("epoch: {}, batch: {}, loss is: {}".format(epoch_id, batch_id, loss))
#后向传播,更新参数的过程
avg_loss.backward()
# 最小化loss,更新参数
opt.step()
# 清除梯度
opt.clear_grad()
#保存模型参数
paddle.save(model.state_dict(), 'mnist.pdparams')
return loss_list
model = MNIST()
loss_list = train(model)
# 读取一张本地的样例图片,转变成模型输入的格式
def load_image(img_path):
# 从img_path中读取图像,并转为灰度图
im = Image.open(img_path).convert('L')
im = im.resize((28, 28), Image.LANCZOS)
im = np.array(im).reshape(1, 1, 28, 28).astype(np.float32)
# 图像归一化
im = 1.0 - im / 255.
return im
# 定义预测过程
model = MNIST()
params_file_path = 'mnist.pdparams'
img_path = 'example_0.jpg'
# 加载模型参数
param_dict = paddle.load(params_file_path)
model.load_dict(param_dict)
# 灌入数据
model.eval()
tensor_img = load_image(img_path)
#模型反馈10个分类标签的对应概率
results = model(paddle.to_tensor(tensor_img))
#取概率最大的标签作为预测输出
lab = np.argsort(results.numpy())
print("本次预测的数字是: ", lab[0][-1])