禁止转载,侵权必究

前言

我们上一章介绍了MNIST手写数字识别的问题的解法。一步步从单层线性网络升级为多层CNN网络,并且介绍了配套的常用函数,比如relu,softmax,cross_entropy。最后我们还评估了CNN网络的计算量,并且计算了每一层网络的输入、参数、输出的形状。

我们上一章教程介绍的CNN网络叫做LeNet,那么机器学习是不是“一招鲜吃遍天”呢?我们来看看各种CNN算法在iChallenge-PM问题中的表现。

识别目标

iChallenge-PM是百度大脑和中山大学中山眼科中心联合举办的iChallenge比赛中,提供的关于病理性近视(Pathologic Myopia,PM)的医疗类数据集,包含1200个受试者的眼底视网膜图片,训练、验证和测试数据集各400张。

公用代码

import cv2
import random
import numpy as np

# 对读入的图像数据进行预处理
def transform_img(img):
    # 将图片尺寸缩放道 224x224
    img = cv2.resize(img, (224, 224))
    # 读入的图像数据格式是[H, W, C]
    # 使用转置操作将其变成[C, H, W]
    img = np.transpose(img, (2,0,1))
    img = img.astype('float32')
    # 将数据范围调整到[-1.0, 1.0]之间
    img = img / 255.
    img = img * 2.0 - 1.0
    return img

定义训练集数据读取器

# 定义训练集数据读取器
def data_loader(datadir, batch_size=10, mode = 'train'):
    # 将datadir目录下的文件列出来,每条文件都要读入
    filenames = os.listdir(datadir)
    def reader():
        if mode == 'train':
            # 训练时随机打乱数据顺序
            random.shuffle(filenames)
        batch_imgs = []
        batch_labels = []
        for name in filenames:
            filepath = os.path.join(datadir, name)
            img = cv2.imread(filepath)
            img = transform_img(img)
            if name[0] == 'H' or name[0] == 'N':
                # H开头的文件名表示高度近似,N开头的文件名表示正常视力
                # 高度近视和正常视力的样本,都不是病理性的,属于负样本,标签为0
                label = 0
            elif name[0] == 'P':
                # P开头的是病理性近视,属于正样本,标签为1
                label = 1
            else:
                raise('Not excepted file name')
            # 每读取一个样本的数据,就将其放入数据列表中
            batch_imgs.append(img)
            batch_labels.append(label)
            if len(batch_imgs) == batch_size:
                # 当数据列表的长度等于batch_size的时候,
                # 把这些数据当作一个mini-batch,并作为数据生成器的一个输出
                imgs_array = np.array(batch_imgs).astype('float32')
                labels_array = np.array(batch_labels).astype('float32').reshape(-1, 1)
                yield imgs_array, labels_array
                batch_imgs = []
                batch_labels = []

        if len(batch_imgs) > 0:
            # 剩余样本数目不足一个batch_size的数据,一起打包成一个mini-batch
            imgs_array = np.array(batch_imgs).astype('float32')
            labels_array = np.array(batch_labels).astype('float32').reshape(-1, 1)
            yield imgs_array, labels_array

    return reader

定义验证集数据读取器

# 定义验证集数据读取器
def valid_data_loader(datadir, csvfile, batch_size=10, mode='valid'):
    # 训练集读取时通过文件名来确定样本标签,验证集则通过csvfile来读取每个图片对应的标签
    # 请查看解压后的验证集标签数据,观察csvfile文件里面所包含的内容
    # csvfile文件所包含的内容格式如下,每一行代表一个样本,
    # 其中第一列是图片id,第二列是文件名,第三列是图片标签,
    # 第四列和第五列是Fovea的坐标,与分类任务无关
    # ID,imgName,Label,Fovea_X,Fovea_Y
    # 1,V0001.jpg,0,1157.74,1019.87
    # 2,V0002.jpg,1,1285.82,1080.47
    # 打开包含验证集标签的csvfile,并读入其中的内容
    filelists = open(csvfile).readlines()
    def reader():
        batch_imgs = []
        batch_labels = []
        for line in filelists[1:]:
            line = line.strip().split(',')
            name = line[1]
            label = int(line[2])
            # 根据图片文件名加载图片,并对图像数据作预处理
            filepath = os.path.join(datadir, name)
            img = cv2.imread(filepath)
            img = transform_img(img)
            # 每读取一个样本的数据,就将其放入数据列表中
            batch_imgs.append(img)
            batch_labels.append(label)
            if len(batch_imgs) == batch_size:
                # 当数据列表的长度等于batch_size的时候,
                # 把这些数据当作一个mini-batch,并作为数据生成器的一个输出
                imgs_array = np.array(batch_imgs).astype('float32')
                labels_array = np.array(batch_labels).astype('float32').reshape(-1, 1)
                yield imgs_array, labels_array
                batch_imgs = []
                batch_labels = []

        if len(batch_imgs) > 0:
            # 剩余样本数目不足一个batch_size的数据,一起打包成一个mini-batch
            imgs_array = np.array(batch_imgs).astype('float32')
            labels_array = np.array(batch_labels).astype('float32').reshape(-1, 1)
            yield imgs_array, labels_array

    return reader

数据形状

# 查看数据形状
DATADIR = '/home/aistudio/work/palm/PALM-Training400/PALM-Training400'
train_loader = data_loader(DATADIR, 
                           batch_size=10, mode='train')
data_reader = train_loader()
data = next(data_reader)
data[0].shape, data[1].shape

我们可以看到结果:

((10, 3, 224, 224), (10, 1))

每个batch有10张图,3个颜色通道,224×224的尺寸。标签label有10个,维度为1。

经典CNN网络-LeNet

1.import依赖

import os
import random
import paddle
import paddle.fluid as fluid
from paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear
import numpy as np
# 百度AI Studio数据文件路径
DATADIR = '/home/aistudio/work/palm/PALM-Training400/PALM-Training400'
DATADIR2 = '/home/aistudio/work/palm/PALM-Validation400'
CSVFILE = '/home/aistudio/labels.csv'

2.定义模型

# 定义 LeNet 网络结构
class LeNet(fluid.dygraph.Layer):
    def __init__(self, num_classes=1):
        super(LeNet, self).__init__()

        # 创建卷积和池化层块,每个卷积层使用Sigmoid激活函数,后面跟着一个2x2的池化
        self.conv1 = Conv2D(num_channels=3, num_filters=6, filter_size=5, act='sigmoid')
        self.pool1 = Pool2D(pool_size=2, pool_stride=2, pool_type='max')
        self.conv2 = Conv2D(num_channels=6, num_filters=16, filter_size=5, act='sigmoid')
        self.pool2 = Pool2D(pool_size=2, pool_stride=2, pool_type='max')
        # 创建第3个卷积层
        self.conv3 = Conv2D(num_channels=16, num_filters=120, filter_size=4, act='sigmoid')
        # 创建全连接层,第一个全连接层的输出神经元个数为64, 第二个全连接层输出神经元个数为分类标签的类别数
        self.fc1 = Linear(input_dim=300000, output_dim=64, act='sigmoid')
        self.fc2 = Linear(input_dim=64, output_dim=num_classes)
    # 网络的前向计算过程
    def forward(self, x):
        x = self.conv1(x)
        x = self.pool1(x)
        x = self.conv2(x)
        x = self.pool2(x)
        x = self.conv3(x)
        x = fluid.layers.reshape(x, [x.shape[0], -1])
        x = self.fc1(x)
        x = self.fc2(x)
        return x

3.训练过程

# 定义训练过程
def train(model):
    with fluid.dygraph.guard():
        print('start training ... ')
        model.train()
        epoch_num = 5
        # 定义优化器
        opt = fluid.optimizer.Momentum(learning_rate=0.001, momentum=0.9, parameter_list=model.parameters())
        # 定义数据读取器,训练数据读取器和验证数据读取器
        train_loader = data_loader(DATADIR, batch_size=10, mode='train')
        valid_loader = valid_data_loader(DATADIR2, CSVFILE)
        for epoch in range(epoch_num):
            for batch_id, data in enumerate(train_loader()):
                x_data, y_data = data
                img = fluid.dygraph.to_variable(x_data)
                label = fluid.dygraph.to_variable(y_data)
                # 运行模型前向计算,得到预测值
                logits = model(img)
                # 进行loss计算
                loss = fluid.layers.sigmoid_cross_entropy_with_logits(logits, label)
                avg_loss = fluid.layers.mean(loss)

                if batch_id % 10 == 0:
                    print("epoch: {}, batch_id: {}, loss is: {}".format(epoch, batch_id, avg_loss.numpy()))
                # 反向传播,更新权重,清除梯度
                avg_loss.backward()
                opt.minimize(avg_loss)
                model.clear_gradients()

            model.eval()
            accuracies = []
            losses = []
            for batch_id, data in enumerate(valid_loader()):
                x_data, y_data = data
                img = fluid.dygraph.to_variable(x_data)
                label = fluid.dygraph.to_variable(y_data)
                # 运行模型前向计算,得到预测值
                logits = model(img)
                # 二分类,sigmoid计算后的结果以0.5为阈值分两个类别
                # 计算sigmoid后的预测概率,进行loss计算
                pred = fluid.layers.sigmoid(logits)
                loss = fluid.layers.sigmoid_cross_entropy_with_logits(logits, label)
                # 计算预测概率小于0.5的类别
                pred2 = pred * (-1.0) + 1.0
                # 得到两个类别的预测概率,并沿第一个维度级联
                pred = fluid.layers.concat([pred2, pred], axis=1)
                acc = fluid.layers.accuracy(pred, fluid.layers.cast(label, dtype='int64'))
                accuracies.append(acc.numpy())
                losses.append(loss.numpy())
            print("[validation] accuracy/loss: {}/{}".format(np.mean(accuracies), np.mean(losses)))
            model.train()

        # save params of model
        fluid.save_dygraph(model.state_dict(), 'mnist')
        # save optimizer state
        fluid.save_dygraph(opt.state_dict(), 'mnist')



3.评估过程

# 定义评估过程
def evaluation(model, params_file_path):
    with fluid.dygraph.guard():
        print('start evaluation .......')
        #加载模型参数
        model_state_dict, _ = fluid.load_dygraph(params_file_path)
        model.load_dict(model_state_dict)

        model.eval()
        eval_loader = load_data('eval')

        acc_set = []
        avg_loss_set = []
        for batch_id, data in enumerate(eval_loader()):
            x_data, y_data = data
            img = fluid.dygraph.to_variable(x_data)
            label = fluid.dygraph.to_variable(y_data)
            # 计算预测和精度
            prediction, acc = model(img, label)
            # 计算损失函数值
            loss = fluid.layers.cross_entropy(input=prediction, label=label)
            avg_loss = fluid.layers.mean(loss)
            acc_set.append(float(acc.numpy()))
            avg_loss_set.append(float(avg_loss.numpy()))
        # 求平均精度
        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))

4.查看训练和评估的结果

start training ... 
epoch: 0, batch_id: 0, loss is: [0.78380126]
epoch: 0, batch_id: 10, loss is: [0.7035402]
epoch: 0, batch_id: 20, loss is: [0.69243866]
epoch: 0, batch_id: 30, loss is: [0.6760834]
[validation] accuracy/loss: 0.5275000333786011/0.6938738822937012
epoch: 1, batch_id: 0, loss is: [0.6761131]
epoch: 1, batch_id: 10, loss is: [0.6756402]
epoch: 1, batch_id: 20, loss is: [0.67702425]
epoch: 1, batch_id: 30, loss is: [0.6707235]
[validation] accuracy/loss: 0.5275000333786011/0.6917563080787659
epoch: 2, batch_id: 0, loss is: [0.69567424]
epoch: 2, batch_id: 10, loss is: [0.6799297]
epoch: 2, batch_id: 20, loss is: [0.6792191]
epoch: 2, batch_id: 30, loss is: [0.6964021]
[validation] accuracy/loss: 0.5275000333786011/0.691692054271698
epoch: 3, batch_id: 0, loss is: [0.7113117]
epoch: 3, batch_id: 10, loss is: [0.69906384]
epoch: 3, batch_id: 20, loss is: [0.69818497]
epoch: 3, batch_id: 30, loss is: [0.67282254]
[validation] accuracy/loss: 0.5275000333786011/0.6927729249000549
epoch: 4, batch_id: 0, loss is: [0.6572024]
epoch: 4, batch_id: 10, loss is: [0.65163314]
epoch: 4, batch_id: 20, loss is: [0.702415]
epoch: 4, batch_id: 30, loss is: [0.7255191]
[validation] accuracy/loss: 0.5275000333786011/0.691861629486084

结论:LeNet并不能解决iChallenge-PM问题。

CNN网络-AlexNet

1.定义AlexNet网络

# -*- coding:utf-8 -*-

# 导入需要的包
import paddle
import paddle.fluid as fluid
import numpy as np
from paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear


# 定义 AlexNet 网络结构
class AlexNet(fluid.dygraph.Layer):
    def __init__(self, num_classes=1):
        super(AlexNet, self).__init__()
        
        # AlexNet与LeNet一样也会同时使用卷积和池化层提取图像特征
        # 与LeNet不同的是激活函数换成了‘relu’
        self.conv1 = Conv2D(num_channels=3, num_filters=96, filter_size=11, stride=4, padding=5, act='relu')
        self.pool1 = Pool2D(pool_size=2, pool_stride=2, pool_type='max')
        self.conv2 = Conv2D(num_channels=96, num_filters=256, filter_size=5, stride=1, padding=2, act='relu')
        self.pool2 = Pool2D(pool_size=2, pool_stride=2, pool_type='max')
        self.conv3 = Conv2D(num_channels=256, num_filters=384, filter_size=3, stride=1, padding=1, act='relu')
        self.conv4 = Conv2D(num_channels=384, num_filters=384, filter_size=3, stride=1, padding=1, act='relu')
        self.conv5 = Conv2D(num_channels=384, num_filters=256, filter_size=3, stride=1, padding=1, act='relu')
        self.pool5 = Pool2D(pool_size=2, pool_stride=2, pool_type='max')

        self.fc1 = Linear(input_dim=12544, output_dim=4096, act='relu')
        self.drop_ratio1 = 0.5
        self.fc2 = Linear(input_dim=4096, output_dim=4096, act='relu')
        self.drop_ratio2 = 0.5
        self.fc3 = Linear(input_dim=4096, output_dim=num_classes)

        
    def forward(self, x):
        x = self.conv1(x)
        x = self.pool1(x)
        x = self.conv2(x)
        x = self.pool2(x)
        x = self.conv3(x)
        x = self.conv4(x)
        x = self.conv5(x)
        x = self.pool5(x)
        x = fluid.layers.reshape(x, [x.shape[0], -1])
        x = self.fc1(x)
        # 在全连接之后使用dropout抑制过拟合
        x= fluid.layers.dropout(x, self.drop_ratio1)
        x = self.fc2(x)
        # 在全连接之后使用dropout抑制过拟合
        x = fluid.layers.dropout(x, self.drop_ratio2)
        x = self.fc3(x)
        return x

2. 复用LeNet的训练&评估过程

with fluid.dygraph.guard():
    model = AlexNet()

train(model)

3.查看训练和评估的结果

start training ... 
epoch: 0, batch_id: 0, loss is: [0.8983343]
epoch: 0, batch_id: 10, loss is: [0.78235567]
epoch: 0, batch_id: 20, loss is: [0.5539009]
epoch: 0, batch_id: 30, loss is: [0.60531735]
[validation] accuracy/loss: 0.8999999761581421/0.5300776958465576
epoch: 1, batch_id: 0, loss is: [0.56365806]
epoch: 1, batch_id: 10, loss is: [0.435232]
epoch: 1, batch_id: 20, loss is: [0.37820452]
epoch: 1, batch_id: 30, loss is: [0.34011936]
[validation] accuracy/loss: 0.9325000047683716/0.25468358397483826
epoch: 2, batch_id: 0, loss is: [0.32455772]
epoch: 2, batch_id: 10, loss is: [0.5270335]
epoch: 2, batch_id: 20, loss is: [0.41049075]
epoch: 2, batch_id: 30, loss is: [0.14482744]
[validation] accuracy/loss: 0.9175001382827759/0.25097012519836426
epoch: 3, batch_id: 0, loss is: [0.43380293]
epoch: 3, batch_id: 10, loss is: [0.12313936]
epoch: 3, batch_id: 20, loss is: [0.5423292]
epoch: 3, batch_id: 30, loss is: [0.7778549]
[validation] accuracy/loss: 0.9049999117851257/0.28984639048576355
epoch: 4, batch_id: 0, loss is: [0.14641385]
epoch: 4, batch_id: 10, loss is: [0.5889987]
epoch: 4, batch_id: 20, loss is: [0.0941387]
epoch: 4, batch_id: 30, loss is: [0.20460884]
[validation] accuracy/loss: 0.9149999618530273/0.2128506302833557

结论:AlexNet可以解决iChallenge-PM问题。

CNN网络-VGG

1.import依赖包

import numpy as np
import paddle
import paddle.fluid as fluid
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.dygraph.nn import Conv2D, Pool2D, BatchNorm, Linear
from paddle.fluid.dygraph.base import to_variable

1.定义VGG网络

因为VGG网络是深度神经网络,我们把重复的部分作为一个block单独定义。总共定义5个block,第一个block有2个卷积层和1个池化层,第二个block有2个卷积层和1个池化层,第三个block有3个卷积层和1个池化层,第四个block有3个卷积层和1个池化层,第五个block有3个卷积层和1个池化层。最后还有3个全连接层。因此:VGG总共有13层卷积+3层全连接,是典型的深度神经网络。

# 定义vgg块,包含多层卷积和1层2x2的最大池化层
class vgg_block(fluid.dygraph.Layer):
    def __init__(self, num_convs, in_channels, out_channels):
        """
        num_convs, 卷积层的数目
        num_channels, 卷积层的输出通道数,在同一个Incepition块内,卷积层输出通道数是一样的
        """
        super(vgg_block, self).__init__()
        self.conv_list = []
        for i in range(num_convs):
            conv_layer = self.add_sublayer('conv_' + str(i), Conv2D(num_channels=in_channels, 
                                        num_filters=out_channels, filter_size=3, padding=1, act='relu'))
            self.conv_list.append(conv_layer)
            in_channels = out_channels
        self.pool = Pool2D(pool_stride=2, pool_size = 2, pool_type='max')
    def forward(self, x):
        for item in self.conv_list:
            x = item(x)
        return self.pool(x)
class VGG(fluid.dygraph.Layer):
    def __init__(self, conv_arch=((2, 64), 
                                (2, 128), (3, 256), (3, 512), (3, 512))):
        super(VGG, self).__init__()
        self.vgg_blocks=[]
        iter_id = 0
        # 添加vgg_block
        # 这里一共5个vgg_block,每个block里面的卷积层数目和输出通道数由conv_arch指定
        in_channels = [3, 64, 128, 256, 512, 512]
        for (num_convs, num_channels) in conv_arch:
            block = self.add_sublayer('block_' + str(iter_id), 
                    vgg_block(num_convs, in_channels=in_channels[iter_id], 
                              out_channels=num_channels))
            self.vgg_blocks.append(block)
            iter_id += 1
        self.fc1 = Linear(input_dim=512*7*7, output_dim=4096,
                      act='relu')
        self.drop1_ratio = 0.5
        self.fc2= Linear(input_dim=4096, output_dim=4096,
                      act='relu')
        self.drop2_ratio = 0.5
        self.fc3 = Linear(input_dim=4096, output_dim=1)
        
    def forward(self, x):
        for item in self.vgg_blocks:
            x = item(x)
        x = fluid.layers.reshape(x, [x.shape[0], -1])
        x = fluid.layers.dropout(self.fc1(x), self.drop1_ratio)
        x = fluid.layers.dropout(self.fc2(x), self.drop2_ratio)
        x = self.fc3(x)
        return x

2. 复用LeNet的训练&评估过程

with fluid.dygraph.guard():
    model = VGG()

train(model)

3.查看训练和评估的结果

start training ... 
epoch: 0, batch_id: 0, loss is: [0.77041894]
epoch: 0, batch_id: 10, loss is: [0.68711454]
epoch: 0, batch_id: 20, loss is: [0.68020743]
epoch: 0, batch_id: 30, loss is: [0.53936696]
[validation] accuracy/loss: 0.5300000309944153/0.547136664390564
epoch: 1, batch_id: 0, loss is: [0.623295]
epoch: 1, batch_id: 10, loss is: [0.6252886]
epoch: 1, batch_id: 20, loss is: [0.27016944]
epoch: 1, batch_id: 30, loss is: [0.72312546]
[validation] accuracy/loss: 0.92249995470047/0.2480151355266571
epoch: 2, batch_id: 0, loss is: [0.19115444]
epoch: 2, batch_id: 10, loss is: [0.22194262]
epoch: 2, batch_id: 20, loss is: [0.33472323]
epoch: 2, batch_id: 30, loss is: [0.59723985]
[validation] accuracy/loss: 0.925000011920929/0.22546321153640747
epoch: 3, batch_id: 0, loss is: [0.5138165]
epoch: 3, batch_id: 10, loss is: [0.38347217]
epoch: 3, batch_id: 20, loss is: [0.6232009]
epoch: 3, batch_id: 30, loss is: [0.34507117]
[validation] accuracy/loss: 0.8949999809265137/0.305342435836792
epoch: 4, batch_id: 0, loss is: [0.21837215]
epoch: 4, batch_id: 10, loss is: [0.5486041]
epoch: 4, batch_id: 20, loss is: [0.488666]
epoch: 4, batch_id: 30, loss is: [0.27352032]
[validation] accuracy/loss: 0.9274999499320984/0.21110011637210846

结论:VGG也可以解决iChallenge-PM问题。

评估VGG-16的算力消耗

Cin输出形状乘法次数
block1_conv03[10,64,224,224]约8.67亿
block1_conv164[10,64,224,224]约185亿
pooling164[10,64,112,112]
block2_conv064[10,128,112,112]约92.5亿
block2_conv1128[10,128,112,112]约185亿
pooling2128[10,128,56,56]
block3_conv0128[10,256,56,56]约92.5亿
block3_conv1256[10,256,56,56]约185亿
block3_conv2256[10,256,56,56]约185亿
pooling3256[10,256,28,28]
block4_conv0256[10,512,28,28]约92.5亿
block4_conv1512[10,512,28,28]约185亿
block4_conv2512[10,512,28,28]约185亿
pooling4512[10,512,14,14]
block5_conv0512[10,512,14,14]约46.2亿
block5_conv1512[10,512,14,14]约46.2亿
block5_conv2512[10,512,14,14]约46.2亿
pooling5512[10,512,7,7]
fc125088[10,4096]
fc24096[10,4096]
fc34096[10,1]

所以本例中VGG-16每一个批次的乘法数约1534.77亿。因为加法和乘法算力消耗相当,所以总算力消耗为3069.54亿次。