Day04-经典卷积神经网络解读

文章目录

  • Day04-经典卷积神经网络解读
    • 作业说明
    • 示例代码
      • 一、环境配置
      • 二、数据准备
      • 三、模型配置
      • 四、模型训练
      • 五、模型校验
      • 六、模型预测
    • 完成作业

作业说明

今天的实战项目是基于经典卷积神经网络 VGG的“口罩分类”。

口罩识别,是指可以有效检测在密集人流区域中携带和未携戴口罩的所有人脸,同时判断该者是否佩戴口罩。通常由两个功能单元组成,可以分别完成口罩人脸的检测和口罩人脸的分类。

本次实践相比生产环境中口罩识别的问题,降低了难度,仅实现人脸口罩判断模型,可实现对人脸是否佩戴口罩的判定。本实践旨在通过一个口罩识别的案列,让大家理解和掌握如何使用飞桨动态图搭建一个经典的卷积神经网络。

特别提示:本实践所用数据集均来自互联网,请勿用于商务用途。

作业要求:

  • 1、根据课上所学内容,构建 VGGNet网络并跑通。在此基础上可尝试构造其他网络。
  • 2、思考并动手进行调参、优化,提高测试集准确率。

课件和数据集的链接请去绪论部分寻找 正式学习前的绪论

day04文件夹中包含的就是我们所需要的所有数据。characterData.zip是我们需要使用的数据集,CarID.png是最后用来测试效果的图片。

示例代码

一、环境配置

# 导入需要的包import os
import zipfile
import random
import json
import paddle
import sys
import numpy as np
from PIL import Image
from PIL import ImageEnhance
import paddle.fluid as fluid
from multiprocessing import cpu_count
import matplotlib.pyplot as plt
# 参数配置train_parameters = {"input_size": [3, 224, 224],                              #输入图片的shape"class_dim": -1,                                          #分类数"src_path":"/home/aistudio/work/maskDetect.zip",#原始数据集路径"target_path":"/home/aistudio/data/",                     #要解压的路径"train_list_path": "/home/aistudio/data/train.txt",       #train.txt路径"eval_list_path": "/home/aistudio/data/eval.txt",         #eval.txt路径"readme_path": "/home/aistudio/data/readme.json",         #readme.json路径"label_dict":{},                                          #标签字典"num_epochs": 1,                                         #训练轮数"train_batch_size": 8,                                    #训练时每个批次的大小"learning_strategy": {                                    #优化函数相关的配置"lr": 0.001                                           #超参数学习率}
}

二、数据准备

  1. 解压原始数据集
  2. 按照比例划分训练集与验证集
  3. 乱序,生成数据列表
  4. 构造训练数据集提供器和验证数据集提供器
def unzip_data(src_path,target_path):'''解压原始数据集,将src_path路径下的zip包解压至data目录下'''if(not os.path.isdir(target_path + "maskDetect")):     z = zipfile.ZipFile(src_path, 'r')z.extractall(path=target_path)z.close()
def get_data_list(target_path,train_list_path,eval_list_path):'''生成数据列表'''#存放所有类别的信息class_detail = []#获取所有类别保存的文件夹名称data_list_path=target_path+"maskDetect/"class_dirs = os.listdir(data_list_path)  #总的图像数量all_class_images = 0#存放类别标签class_label=0#存放类别数目class_dim = 0#存储要写进eval.txt和train.txt中的内容trainer_list=[]eval_list=[]#读取每个类别,['maskimages', 'nomaskimages']for class_dir in class_dirs:if class_dir != ".DS_Store":class_dim += 1#每个类别的信息class_detail_list = {}eval_sum = 0trainer_sum = 0#统计每个类别有多少张图片class_sum = 0#获取类别路径 path = data_list_path  + class_dir# 获取所有图片img_paths = os.listdir(path)for img_path in img_paths:                                  # 遍历文件夹下的每个图片name_path = path + '/' + img_path                       # 每张图片的路径if class_sum % 10 == 0:                                 # 每10张图片取一个做验证数据eval_sum += 1                                       # test_sum为测试数据的数目eval_list.append(name_path + "\t%d" % class_label + "\n")else:trainer_sum += 1 trainer_list.append(name_path + "\t%d" % class_label + "\n")#trainer_sum测试数据的数目class_sum += 1                                          #每类图片的数目all_class_images += 1                                   #所有类图片的数目# 说明的json文件的class_detail数据class_detail_list['class_name'] = class_dir             #类别名称,如jiangwenclass_detail_list['class_label'] = class_label          #类别标签class_detail_list['class_eval_images'] = eval_sum       #该类数据的测试集数目class_detail_list['class_trainer_images'] = trainer_sum #该类数据的训练集数目class_detail.append(class_detail_list)  #初始化标签列表train_parameters['label_dict'][str(class_label)] = class_dirclass_label += 1 #初始化分类数train_parameters['class_dim'] = class_dim#乱序  random.shuffle(eval_list)with open(eval_list_path, 'a') as f:for eval_image in eval_list:f.write(eval_image) random.shuffle(trainer_list)with open(train_list_path, 'a') as f2:for train_image in trainer_list:f2.write(train_image) # 说明的json文件信息readjson = {}readjson['all_class_name'] = data_list_path                  #文件父目录readjson['all_class_images'] = all_class_imagesreadjson['class_detail'] = class_detailjsons = json.dumps(readjson, sort_keys=True, indent=4, separators=(',', ': '))with open(train_parameters['readme_path'],'w') as f:f.write(jsons)print ('生成数据列表完成!')
def custom_reader(file_list):'''自定义reader'''def reader():with open(file_list, 'r') as f:lines = [line.strip() for line in f]for line in lines:img_path, lab = line.strip().split('\t')img = Image.open(img_path) if img.mode != 'RGB': img = img.convert('RGB') img = img.resize((224, 224), Image.BILINEAR)img = np.array(img).astype('float32') img = img.transpose((2, 0, 1))  # HWC to CHW img = img/255                # 像素值归一化 yield img, int(lab) return reader
# 参数初始化src_path=train_parameters['src_path']
target_path=train_parameters['target_path']
train_list_path=train_parameters['train_list_path']
eval_list_path=train_parameters['eval_list_path']
batch_size=train_parameters['train_batch_size']'''
解压原始数据到指定路径
'''
unzip_data(src_path,target_path)'''
划分训练集与验证集,乱序,生成数据列表
'''#每次生成数据列表前,首先清空train.txt和eval.txtwith open(train_list_path, 'w') as f: f.seek(0)f.truncate()
with open(eval_list_path, 'w') as f: f.seek(0)f.truncate()
#生成数据列表
get_data_list(target_path,train_list_path,eval_list_path)'''
构造数据提供器
'''
train_reader = paddle.batch(custom_reader(train_list_path),batch_size=batch_size,drop_last=True)
eval_reader = paddle.batch(custom_reader(eval_list_path),batch_size=batch_size,drop_last=True)

三、模型配置

VGG的核心是五组卷积操作,每两组之间做Max-Pooling空间降维。同一组内采用多次连续的3X3卷积,卷积核的数目由较浅组的64增多到最深组的512,同一组内的卷积核数目是一样的。卷积之后接两层全连接层,之后是分类层。由于每组内卷积层的不同,有11、13、16、19层这几种模型,上图展示一个16层的网络结构。

class ConvPool(fluid.dygraph.Layer):'''卷积+池化'''def __init__(self,num_channels,num_filters,filter_size,pool_size,pool_stride,groups,pool_padding=1,pool_type='max',conv_stride=1,conv_padding=0,act=None):super(ConvPool, self).__init__()  self._conv2d_list = []for i in range(groups):conv2d = self.add_sublayer(   #返回一个由所有子层组成的列表。'bb_%d' % i,fluid.dygraph.Conv2D(num_channels=num_channels, #通道数num_filters=num_filters,   #卷积核个数filter_size=filter_size,   #卷积核大小stride=conv_stride,        #步长padding=conv_padding,      #padding大小,默认为0act=act))self._conv2d_list.append(conv2d)   self._pool2d = fluid.dygraph.Pool2D(pool_size=pool_size,           #池化核大小pool_type=pool_type,           #池化类型,默认是最大池化pool_stride=pool_stride,       #池化步长pool_padding=pool_padding      #填充大小)def forward(self, inputs):x = inputsfor conv in self._conv2d_list:x = conv(x)x = self._pool2d(x)return x

请完成 VGG网络的定义


class VGGNet(fluid.dygraph.Layer):'''VGG网络'''def __init__(self):super(VGGNet, self).__init__()def forward(self, inputs, label=None):"""前向计算"""

四、模型训练

all_train_iter=0
all_train_iters=[]
all_train_costs=[]
all_train_accs=[]def draw_train_process(title,iters,costs,accs,label_cost,lable_acc):plt.title(title, fontsize=24)plt.xlabel("iter", fontsize=20)plt.ylabel("cost/acc", fontsize=20)plt.plot(iters, costs,color='red',label=label_cost) plt.plot(iters, accs,color='green',label=lable_acc) plt.legend()plt.grid()plt.show()def draw_process(title,color,iters,data,label):plt.title(title, fontsize=24)plt.xlabel("iter", fontsize=20)plt.ylabel(label, fontsize=20)plt.plot(iters, data,color=color,label=label) plt.legend()plt.grid()plt.show()
'''
模型训练
'''
# with fluid.dygraph.guard(place = fluid.CUDAPlace(0)):
with fluid.dygraph.guard():print(train_parameters['class_dim'])print(train_parameters['label_dict'])vgg = VGGNet()optimizer=fluid.optimizer.AdamOptimizer(learning_rate=train_parameters['learning_strategy']['lr'],parameter_list=vgg.parameters()) for epoch_num in range(train_parameters['num_epochs']):for batch_id, data in enumerate(train_reader()):dy_x_data = np.array([x[0] for x in data]).astype('float32')           y_data = np.array([x[1] for x in data]).astype('int64')      y_data = y_data[:, np.newaxis]#将Numpy转换为DyGraph接收的输入img = fluid.dygraph.to_variable(dy_x_data)label = fluid.dygraph.to_variable(y_data)out,acc = vgg(img,label)loss = fluid.layers.cross_entropy(out, label)avg_loss = fluid.layers.mean(loss)#使用backward()方法可以执行反向网络avg_loss.backward()optimizer.minimize(avg_loss)#将参数梯度清零以保证下一轮训练的正确性vgg.clear_gradients()all_train_iter=all_train_iter+train_parameters['train_batch_size']all_train_iters.append(all_train_iter)all_train_costs.append(loss.numpy()[0])all_train_accs.append(acc.numpy()[0])if batch_id % 1 == 0:print("Loss at epoch {} step {}: {}, acc: {}".format(epoch_num, batch_id, avg_loss.numpy(), acc.numpy()))draw_train_process("training",all_train_iters,all_train_costs,all_train_accs,"trainning cost","trainning acc")  draw_process("trainning loss","red",all_train_iters,all_train_costs,"trainning loss")draw_process("trainning acc","green",all_train_iters,all_train_accs,"trainning acc")  #保存模型参数fluid.save_dygraph(vgg.state_dict(), "vgg")   print("Final loss: {}".format(avg_loss.numpy()))

五、模型校验

'''
模型校验
'''
with fluid.dygraph.guard():model, _ = fluid.load_dygraph("vgg")vgg = VGGNet()vgg.load_dict(model)vgg.eval()accs = []for batch_id, data in enumerate(eval_reader()):dy_x_data = np.array([x[0] for x in data]).astype('float32')y_data = np.array([x[1] for x in data]).astype('int')y_data = y_data[:, np.newaxis]img = fluid.dygraph.to_variable(dy_x_data)label = fluid.dygraph.to_variable(y_data)out, acc = vgg(img, label)lab = np.argsort(out.numpy())accs.append(acc.numpy()[0])
print(np.mean(accs))

六、模型预测

def load_image(img_path):'''预测图片预处理'''img = Image.open(img_path) if img.mode != 'RGB': img = img.convert('RGB') img = img.resize((224, 224), Image.BILINEAR)img = np.array(img).astype('float32') img = img.transpose((2, 0, 1))  # HWC to CHW img = img/255                # 像素值归一化 return imglabel_dic = train_parameters['label_dict']'''
模型预测
'''with fluid.dygraph.guard():model, _ = fluid.dygraph.load_dygraph("vgg")vgg = VGGNet()vgg.load_dict(model)vgg.eval()#展示预测图片infer_path='/home/aistudio/data/data23615/infer_mask01.jpg'img = Image.open(infer_path)plt.imshow(img)          #根据数组绘制图像plt.show()               #显示图像#对预测图片进行预处理infer_imgs = []infer_imgs.append(load_image(infer_path))infer_imgs = np.array(infer_imgs)for  i in range(len(infer_imgs)):data = infer_imgs[i]dy_x_data = np.array(data).astype('float32')dy_x_data=dy_x_data[np.newaxis,:, : ,:]img = fluid.dygraph.to_variable(dy_x_data)out = vgg(img)lab = np.argmax(out.numpy())  #argmax():返回最大数的索引print("第{}个样本,被预测为:{}".format(i+1,label_dic[str(lab)]))print("结束")

完成作业

定义 VGG网络:

代码和前几天相似,但今天的示例代码将整个模型众多的参数进行了统一的封装处理,并增加了一个 ConvPool类,将卷积和池化合在一起了,这样会比较方便一些,我们也就这么使用了。

class VGGNet(fluid.dygraph.Layer):'''VGG网络'''def __init__(self):super(VGGNet, self).__init__()# 通道数、卷积核个数、卷积核大小、池化核大小、池化步长、连续卷积个数self.convpool01 = ConvPool(3, 64, 3, 2, 2, 2, act='relu')self.convpool02 = ConvPool(64, 128, 3, 2, 2, 2, act='relu')self.convpool03 = ConvPool(128, 256, 3, 2, 2, 3, act='relu')self.convpool04 = ConvPool(256, 512, 3, 2, 2, 3, act='relu')self.convpool05 = ConvPool(512, 512, 3, 2, 2, 3, act='relu')self.pool_5_shape = 512*7*7self.fc01 = fluid.dygraph.Linear(self.pool_5_shape, 4096, act='relu')self.fc02 = fluid.dygraph.Linear(4096, 4096, act='relu')self.fc03 = fluid.dygraph.Linear(4096, 2, act='softmax')def forward(self, inputs, label=None):"""前向计算"""out = self.convpool01(inputs)out = self.convpool02(out)out = self.convpool03(out)out = self.convpool04(out)out = self.convpool05(out)out = fluid.layers.reshape(out, shape=[-1, 512*7*7])out = self.fc01(out)out = self.fc02(out)out = self.fc03(out)if label is not None:acc = fluid.layers.accuracy(input=out, label=label)return out, accelse:return out

我们初始采取的训练轮数是 10,可以看到模型训练的准确率是忽上忽下的。

绘制出来的图像也是如此,训练模型的准确率一直在震荡。

测试集上的准确率在 0.6左右。

口罩识别是个二分类问题,结果只有戴口罩和不戴口罩两种。我们用口罩图片进行预测时还勉强能预测成功。

准确率只有 0.6 左右我们肯定还是要想着去优化的,从以下三个方面进行了调参。

  • 训练轮数,也就是迭代次数(num_epochs)
  • 学习率(learningrate)
  • 训练时各批次大小(batch_size)

我们增加了训练轮数,增加为 20轮次,下调了学习率,降至0.0001,增加了训练时每个批次的大小,增加为 16。这些参数在第一步的环境配置中就可以修改。

这里强调一句,稍微调高训练批次大小是可以提高准确率的,但是batch_size的大小不是随便调的,一般是 8 的倍数,这样 GPU 内部的并行运算效率最高

训练之后可以看到,训练集上的准确率逐渐收敛为 1.0。

测试集上的准确率也达到了 1.0,很nice。

因为此次的学习数据比较少,模型的泛化能力不强,群里的大佬们反馈说,可以适当采用 数据增强(Data Augmentation) 的方法来提高真实场景下预测的成功率。

Day04-经典卷积神经网络解读相关推荐

  1. 深度学习教程(10) | 卷积神经网络解读(吴恩达·完整版)

    作者:韩信子@ShowMeAI 教程地址:http://www.showmeai.tech/tutorials/35 本文地址:http://www.showmeai.tech/article-det ...

  2. 【深度学习基础】经典卷积神经网络

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 导语 卷积神经网络(Convolutional Neural Ne ...

  3. Pytorch之CNN:基于Pytorch框架实现经典卷积神经网络的算法(LeNet、AlexNet、VGG、NIN、GoogleNet、ResNet)——从代码认知CNN经典架构

    Pytorch之CNN:基于Pytorch框架实现经典卷积神经网络的算法(LeNet.AlexNet.VGG.NIN.GoogleNet.ResNet)--从代码认知CNN经典架构 目录 CNN经典算 ...

  4. AI基础:经典卷积神经网络

    导语 卷积神经网络(Convolutional Neural Networks, CNN)是一类包含卷积计算且具有深度结构的前馈神经网络(Feedforward Neural Networks),是深 ...

  5. 一文总结经典卷积神经网络CNN模型

    一般的DNN直接将全部信息拉成一维进行全连接,会丢失图像的位置等信息. CNN(卷积神经网络)更适合计算机视觉领域.下面总结从1998年至今的优秀CNN模型,包括LeNet.AlexNet.ZFNet ...

  6. tensorflow预定义经典卷积神经网络和数据集tf.keras.applications

    自己开发了一个股票软件,功能很强大,需要的点击下面的链接获取: https://www.cnblogs.com/bclshuai/p/11380657.html 1.1  tensorflow预定义经 ...

  7. Tensorflow系列 | TensorFlowNews五大经典卷积神经网络介绍

    编译 | fendouai 编辑 | 安可 [导读]:这个系列文章将会从经典的卷积神经网络历史开始,然后逐个讲解卷积神经网络结构,代码实现和优化方向.下一篇文章将会是 LeNet 卷积神经网络结构,代 ...

  8. CNN(经典卷积神经网络)来了!

    导语 卷积神经网络(Convolutional Neural Networks, CNN)是一类包含卷积计算且具有深度结构的前馈神经网络(Feedforward Neural Networks),是深 ...

  9. 【经典卷积神经网络CNN模型 之 VGG16Net】模型实验,强烈建议使用GPU来跑,经试验,若使用CPU,普通PC理论上需要超过100小时

    声明:仅学习使用~ 建议回顾基础知识: 包含但不限于 [模型实验]几个 经典卷积神经网络CNN模型 回顾:分组卷积–AlexNet,使用3x3卷积核----VGG,使用多种卷积核结构----Googl ...

最新文章

  1. P114、面试题17:合并两个排序的链表
  2. 禅道项目管理软件介绍
  3. 【原创】C++变量作用域(三)
  4. netcore redis 存储集合_.net core redis的全套操作
  5. 快钱如何快-企业级效率提升实践
  6. aistudio/jupyter 相关
  7. [转]Zookeeper入门看这篇就够了
  8. js常用方法,JS实用方法,jq获得文件后缀,解析window。location,解析URL参数
  9. ajax 防止用户反复提交
  10. fashionmnist数据集_Keras实现Fashion MNIST数据集分类
  11. maven使用中央仓库没有的jar包001---Maven自定义上传第三方包到3rd party(第三方无依赖jar和本地扩展类加入maven统一管理)
  12. QDebug输出彩色消息
  13. 完美解决:Could not open the editor: Editor could not be initialized
  14. 判断 localStorage 在不同浏览器的最大支持内存
  15. 利用奇异值分解(SVD)进行彩色图片压缩
  16. css 3d环形,CSS3 飞行的3D圆环
  17. 如何利用ArcMap 10.1生成一个tpk文件
  18. 显示当前数据库服务器的ip,怎么查看服务器数据库的ip地址
  19. 21 python - 字典
  20. LiteOS学习笔记-9LiteOS SDK oc流程之MQTT

热门文章

  1. 怎样通过css控制table的部分td
  2. html的li浮动之后往下移动,多个li浮动后居中显示问题
  3. 我国大型数据中心占比已达12.7%,大而不强成制约因素
  4. 你以为ACI=SDN?大错特错!
  5. PDU知识全集,值得收藏!
  6. shell怎么把负数变成正数_excel怎么计算平方根-记住简单的收藏复杂的
  7. 成功解决WARNING: Ignoring invalid distribution -illow (E:\program files\python\python36\lib\site-package
  8. DL框架之TensorFlow:深度学习框架TensorFlow Core(低级别TensorFlow API)的简介、安装、使用方法之详细攻略
  9. 成功解决 class 'AttributeError' : 'Editor' object has no attribute '_Editor__markerMap'
  10. ML之LoRBaggingRF:依次利用Bagging、RF算法对泰坦尼克号数据集 (Kaggle经典案例)获救人员进行二分类预测——模型融合