基于飞桨在MNIST数据集分类提升准确率到0.985以上实践
本实践通过尝试数据增强、更换优化器、学习率等各种办法来提高准确率。
1.导入库
# 飞桨库 import paddle # numpy库 import numpy as np #数据处理 from data_process import get_MNIST_dataloader #加载数据 train_loader, test_loader = get_MNIST_dataloader()
2.data_process.py数据处理
主要是导入飞桨数据增强库,这次用到了随机颜色变幻、亮度调整和归一化。
import paddle from paddle.vision.transforms import Compose, ColorJitter, BrightnessTransform, Normalize def get_MNIST_dataloader(): # 定义图像归一化处理方法,这里的CHW指图像格式需为 [C通道数,H图像高度,W图像宽度] transform = Compose([ColorJitter(), BrightnessTransform(0.3), Normalize(mean=[127.5], std=[127.5], data_format='CHW')]) # 下载数据集并初始化 DataSet train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform) test_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform) # 定义并初始化数据读取器 train_loader = paddle.io.DataLoader(train_dataset, batch_size=1024, shuffle=True, num_workers=1, drop_last=True) test_loader = paddle.io.DataLoader(test_dataset, batch_size=256, shuffle=False, num_workers=1, drop_last=False) return train_loader, test_loader
由上可见,对数据进行了增强,同时使用了GPU,训练batch_size拉大到1024,提高了训练速度。
3.模型定义
如修改网络结构、优化器、损失函数、学习率等,提升模型评估准确率
# 定义模型结构 import paddle.nn.functional as F from paddle.nn import Conv2D, MaxPool2D, Linear # 多层卷积神经网络实现(可修改,例如加深网络层级) 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) self.dropout = paddle.nn.Dropout(0.2) # 定义网络前向计算过程,卷积后紧接着使用池化层,最后使用全连接层计算最终输出 # 卷积层激活函数使用Relu,全连接层激活函数使用softmax def forward(self, inputs, label): x = self.conv1(inputs) x = F.relu(x) x = self.max_pool1(x) x = self.conv2(x) x = F.relu(x) x = self.dropout(x) paddle.nn.Dropout(0.2), x = self.max_pool2(x) x = paddle.reshape(x, [x.shape[0], 980]) x = self.fc(x) if label is not None: acc = paddle.metric.accuracy(input=x, label=label) return x, acc else: return x
模型定义使用了最常见的CNN模型,其中:
- 使用了relu
- 使用了dropout
- 试用了卷积
- 使用了最大池化
4.模型训练
训练主要是:
- 使用train()模式
- 定义优化器
- 使用Adamx算法
- 按batch读取数据并转换为tensor
- 进行前向计算
- 计算交叉损失
- 计算acc
- 加入逻辑判断,保存最佳训练模型
#在使用GPU机器时,可以将use_gpu变量设置成True use_gpu = True # paddle.set_device('gpu:0') if use_gpu else paddle.set_device('cpu') #仅优化算法的设置有所差别 def train(model): model = MNIST() model.train() #可以选择其他优化算法的设置方案(可修改) scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.001, step_size=2, gamma=0.1) opt = paddle.optimizer.Adamax(scheduler, parameters=model.parameters()) # opt = paddle.optimizer.Adamax(learning_rate=0.001, parameters=model.parameters()) best_acc=0.0 #训练epoch(可修改) EPOCH_NUM = 50 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, acc = model(images, labels) #计算损失,取一个批次样本损失的平均值(可修改) loss = F.cross_entropy(predicts, labels) avg_loss = paddle.mean(loss) #每训练了100批次的数据,打印下当前Loss的情况 if batch_id % 100 == 0: print("epoch: {}, batch: {}, loss is: {}, acc is {}".format(epoch_id, batch_id, avg_loss.numpy(), acc.numpy())) # 保存最佳模型 if acc.numpy()> best_acc: best_acc=acc.numpy() #保存模型参数 paddle.save(model.state_dict(), 'mnist.pdparams') #后向传播,更新参数,消除梯度的过程 avg_loss.backward() opt.step() opt.clear_grad() #创建模型 model = MNIST() #启动训练过程 train(model)
epoch: 37, batch: 0, loss is: [0.02620594], acc is [0.9921875] epoch: 38, batch: 0, loss is: [0.0320667], acc is [0.9863281] epoch: 39, batch: 0, loss is: [0.04298836], acc is [0.9892578] epoch: 40, batch: 0, loss is: [0.03134251], acc is [0.9892578] epoch: 41, batch: 0, loss is: [0.03572175], acc is [0.9892578] epoch: 42, batch: 0, loss is: [0.03592779], acc is [0.9902344] epoch: 43, batch: 0, loss is: [0.04096694], acc is [0.98535156] epoch: 44, batch: 0, loss is: [0.03150718], acc is [0.9921875] epoch: 45, batch: 0, loss is: [0.02737371], acc is [0.99316406] epoch: 46, batch: 0, loss is: [0.0292511], acc is [0.9892578] epoch: 47, batch: 0, loss is: [0.02851657], acc is [0.9892578] epoch: 48, batch: 0, loss is: [0.03205686], acc is [0.9892578] epoch: 49, batch: 0, loss is: [0.0311618], acc is [0.9873047]
5.模型评估
主要是:
- 使用Paddle.load()加载保存的模型
- 使用paddle.eval()模式
- 加载验证数据集
- 计算多个batch的平均损失和准确率
def evaluation(model): print('start evaluation .......') # 定义预测过程 params_file_path = 'mnist.pdparams' # 加载模型参数 param_dict = paddle.load(params_file_path) model.load_dict(param_dict) model.eval() eval_loader = test_loader acc_set = [] avg_loss_set = [] for batch_id, data in enumerate(eval_loader()): images, labels = data images = paddle.to_tensor(images) labels = paddle.to_tensor(labels) predicts, acc = model(images, labels) loss = F.cross_entropy(input=predicts, label=labels) avg_loss = paddle.mean(loss) acc_set.append(float(acc.numpy())) avg_loss_set.append(float(avg_loss.numpy())) #计算多个batch的平均损失和准确率 acc_val_mean = np.array(acc_set).mean() avg_loss_val_mean = np.array(avg_loss_set).mean() print('loss={}, acc={}'.format(avg_loss_val_mean, acc_val_mean)) model = MNIST() evaluation(model)
start evaluation ....... loss=0.037210724089527504, acc=0.988671875
6.优化总结
- 将学习率改为 0.001
- 修改epoch为 50
- 修改Adam 为 Adamx
- 修改数据增强,添加 ColorJitter 、 BrightnessTransform 模式
- 修改模型保存机制,只保存最佳模型,而不是最后一轮的模型