关于20200820的paddle深度学习基础的作业

今天学习的是机器视觉-图像分类及几个图像网络库的介绍,学习了几个典型cv处理网络:

  • LeNet
  • AlexNet
  • VGG
  • GooleNet
  • ResNet
    然后今天的实践作业,是“将LeNet模型中的中间层的激活函数Sigmoid换成ReLU,并在眼底筛查数据集上得出结果”,打开作业后,发现老师已经把环境都给准备了,内容与上课的项目内容相同,只需要我们修改网络中的几个层次的激活函数就可以了。

0. aiStudio平台提供的源码

# 初次运行时将注释取消,以便解压文件
# 如果已经解压过了,则不需要运行此段代码,否则文件已经存在解压会报错
!unzip -o -q -d /home/aistudio/work/palm /home/aistudio/data/data23828/training.zip
%cd /home/aistudio/work/palm/PALM-Training400/
!unzip -o -q PALM-Training400.zip
!unzip -o -q -d /home/aistudio/work/palm /home/aistudio/data/data23828/validation.zip
!unzip -o -q -d /home/aistudio/work/palm /home/aistudio/data/data23828//valid_gt.zip

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

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

# LeNet 识别眼疾图片

import os
import random
import paddle
import paddle.fluid as fluid
import numpy as np

DATADIR = '/home/aistudio/work/palm/PALM-Training400/PALM-Training400'
DATADIR2 = '/home/aistudio/work/palm/PALM-Validation400'
CSVFILE = '/home/aistudio/labels.csv'

# 定义训练过程
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(), 'palm')
        # save optimizer state
        fluid.save_dygraph(opt.state_dict(), 'palm')

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

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

        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='relu')
        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='relu')
        # 创建全连接层,第一个全连接层的输出神经元个数为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, label=None):
        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)
        if label is not None:
            acc = fluid.layers.accuracy(input=x, label=label)
            return x, acc
        else:
            return x

if __name__ == '__main__':
    # 创建模型
    with fluid.dygraph.guard():
        model = LeNet(num_classes=1)

    train(model)

在完成作业过程中,逐步实践了以下的几个修改:

1. act 全部为 sigmoid 的运行结果(原题目):

运行时长: 5分50秒107毫秒

结束时间: 2020-08-20 19:53:30

start training ...

epoch: 0, batch_id: 0, loss is: [0.6463254]

epoch: 0, batch_id: 10, loss is: [0.73084]

epoch: 0, batch_id: 20, loss is: [0.70952296]

epoch: 0, batch_id: 30, loss is: [0.6596403]

[validation] accuracy/loss: 0.5275000333786011/0.6916258335113525

epoch: 1, batch_id: 0, loss is: [0.6843369]

epoch: 1, batch_id: 10, loss is: [0.7203565]

epoch: 1, batch_id: 20, loss is: [0.6807879]

epoch: 1, batch_id: 30, loss is: [0.65060884]

[validation] accuracy/loss: 0.5275000333786011/0.6918826103210449

epoch: 2, batch_id: 0, loss is: [0.6961876]

epoch: 2, batch_id: 10, loss is: [0.6750331]

epoch: 2, batch_id: 20, loss is: [0.7093759]

epoch: 2, batch_id: 30, loss is: [0.7380558]

[validation] accuracy/loss: 0.5275000333786011/0.6918379068374634

epoch: 3, batch_id: 0, loss is: [0.71128255]

epoch: 3, batch_id: 10, loss is: [0.66349745]

epoch: 3, batch_id: 20, loss is: [0.66459733]

epoch: 3, batch_id: 30, loss is: [0.7126867]

[validation] accuracy/loss: 0.5275000333786011/0.6916722059249878

epoch: 4, batch_id: 0, loss is: [0.6689138]

epoch: 4, batch_id: 10, loss is: [0.7064802]

epoch: 4, batch_id: 20, loss is: [0.6834978]

epoch: 4, batch_id: 30, loss is: [0.6974033]

[validation] accuracy/loss: 0.5275000333786011/0.6918940544128418

2. 将 conv2 的act 修改为relu的结果:

运行时长: 5分43秒720毫秒

结束时间: 2020-08-20 19:44:25

start training ...

epoch: 0, batch_id: 0, loss is: [0.69988203]

epoch: 0, batch_id: 10, loss is: [0.7812995]

epoch: 0, batch_id: 20, loss is: [0.69273716]

epoch: 0, batch_id: 30, loss is: [0.69190454]

[validation] accuracy/loss: 0.4725000262260437/0.6938989758491516

epoch: 1, batch_id: 0, loss is: [0.69313776]

epoch: 1, batch_id: 10, loss is: [0.6859175]

epoch: 1, batch_id: 20, loss is: [0.693638]

epoch: 1, batch_id: 30, loss is: [0.6997932]

[validation] accuracy/loss: 0.5275000333786011/0.6936731934547424

epoch: 2, batch_id: 0, loss is: [0.7722538]

epoch: 2, batch_id: 10, loss is: [0.6794897]

epoch: 2, batch_id: 20, loss is: [0.756631]

epoch: 2, batch_id: 30, loss is: [0.7419652]

[validation] accuracy/loss: 0.5275000333786011/0.6916639804840088

epoch: 3, batch_id: 0, loss is: [0.71749735]

epoch: 3, batch_id: 10, loss is: [0.68747807]

epoch: 3, batch_id: 20, loss is: [0.6913865]

epoch: 3, batch_id: 30, loss is: [0.69376105]

[validation] accuracy/loss: 0.5275000333786011/0.6929201483726501

epoch: 4, batch_id: 0, loss is: [0.74191105]

epoch: 4, batch_id: 10, loss is: [0.6757732]

epoch: 4, batch_id: 20, loss is: [0.71385324]

epoch: 4, batch_id: 30, loss is: [0.7045916]

[validation] accuracy/loss: 0.5275000333786011/0.6916219592094421

3. conv2、conv3修改为relu的运行结果:

运行时长: 7分52秒576毫秒

结束时间: 2020-08-20 19:40:36

start training ...

epoch: 0, batch_id: 0, loss is: [0.89798486]

epoch: 0, batch_id: 10, loss is: [1.0111783]

epoch: 0, batch_id: 20, loss is: [0.68013984]

epoch: 0, batch_id: 30, loss is: [0.6448096]

[validation] accuracy/loss: 0.7649999856948853/0.6854694485664368

epoch: 1, batch_id: 0, loss is: [0.6812264]

epoch: 1, batch_id: 10, loss is: [0.68561953]

epoch: 1, batch_id: 20, loss is: [0.6985636]

epoch: 1, batch_id: 30, loss is: [0.6763868]

[validation] accuracy/loss: 0.8725000619888306/0.6362115740776062

epoch: 2, batch_id: 0, loss is: [0.62318325]

epoch: 2, batch_id: 10, loss is: [0.64589375]

epoch: 2, batch_id: 20, loss is: [0.5127075]

epoch: 2, batch_id: 30, loss is: [0.5829197]

[validation] accuracy/loss: 0.8675000071525574/0.42109450697898865

epoch: 3, batch_id: 0, loss is: [0.3432079]

epoch: 3, batch_id: 10, loss is: [0.38489157]

epoch: 3, batch_id: 20, loss is: [0.3031845]

epoch: 3, batch_id: 30, loss is: [0.47202072]

[validation] accuracy/loss: 0.9125000238418579/0.30460885167121887

epoch: 4, batch_id: 0, loss is: [0.20293155]

epoch: 4, batch_id: 10, loss is: [0.48390704]

epoch: 4, batch_id: 20, loss is: [0.24503107]

epoch: 4, batch_id: 30, loss is: [0.13655852]

[validation] accuracy/loss: 0.8225000500679016/0.37707147002220154

最高acc/最低loss 如下:

[validation] accuracy/loss: 0.9125000238418579/0.30460885167121887

另外发现一个问题,每次运行的结果都会有变化

4. conv1、conv2、conv3修改为relu的运行结果:

运行时长: 7分59秒417毫秒

结束时间: 2020-08-20 20:00:32

start training ...

epoch: 0, batch_id: 0, loss is: [0.74864405]

epoch: 0, batch_id: 10, loss is: [0.37895158]

epoch: 0, batch_id: 20, loss is: [0.39838415]

epoch: 0, batch_id: 30, loss is: [0.33033034]

[validation] accuracy/loss: 0.9149999618530273/0.2107178121805191

epoch: 1, batch_id: 0, loss is: [0.23456383]

epoch: 1, batch_id: 10, loss is: [0.07768808]

epoch: 1, batch_id: 20, loss is: [0.22898602]

epoch: 1, batch_id: 30, loss is: [0.0580753]

[validation] accuracy/loss: 0.9199999570846558/0.24478484690189362

epoch: 2, batch_id: 0, loss is: [0.32877427]

epoch: 2, batch_id: 10, loss is: [0.08360158]

epoch: 2, batch_id: 20, loss is: [0.14537154]

epoch: 2, batch_id: 30, loss is: [0.1711683]

[validation] accuracy/loss: 0.9150000810623169/0.2535829246044159

epoch: 3, batch_id: 0, loss is: [0.26906672]

epoch: 3, batch_id: 10, loss is: [0.12395986]

epoch: 3, batch_id: 20, loss is: [0.04331874]

epoch: 3, batch_id: 30, loss is: [0.3079676]

[validation] accuracy/loss: 0.9125000238418579/0.24775908887386322

epoch: 4, batch_id: 0, loss is: [0.0608796]

epoch: 4, batch_id: 10, loss is: [0.09999402]

epoch: 4, batch_id: 20, loss is: [0.09481613]

epoch: 4, batch_id: 30, loss is: [0.09299953]

[validation] accuracy/loss: 0.9474999308586121/0.16001039743423462

最高acc/最低loss 如下:

[validation] accuracy/loss: 0.9474999308586121/0.16001039743423462

5. conv2、conv3、fc1修改为relu的运行结果:

运行时长: 7分56秒636毫秒

结束时间: 2020-08-20 19:48:50

start training ...

epoch: 0, batch_id: 0, loss is: [1.0672896]

epoch: 0, batch_id: 10, loss is: [0.96203375]

epoch: 0, batch_id: 20, loss is: [0.8995679]

epoch: 0, batch_id: 30, loss is: [0.67188084]

[validation] accuracy/loss: 0.4725000262260437/0.6935534477233887

epoch: 1, batch_id: 0, loss is: [0.6982776]

epoch: 1, batch_id: 10, loss is: [0.69318163]

epoch: 1, batch_id: 20, loss is: [0.69346607]

epoch: 1, batch_id: 30, loss is: [0.69397753]

[validation] accuracy/loss: 0.5275000333786011/0.6930052042007446

epoch: 2, batch_id: 0, loss is: [0.69459146]

epoch: 2, batch_id: 10, loss is: [0.69275916]

epoch: 2, batch_id: 20, loss is: [0.6938231]

epoch: 2, batch_id: 30, loss is: [0.69157326]

[validation] accuracy/loss: 0.5275000333786011/0.6927353739738464

epoch: 3, batch_id: 0, loss is: [0.6931397]

epoch: 3, batch_id: 10, loss is: [0.69082963]

epoch: 3, batch_id: 20, loss is: [0.68886006]

epoch: 3, batch_id: 30, loss is: [0.68994486]

[validation] accuracy/loss: 0.5275000333786011/0.6923792958259583

epoch: 4, batch_id: 0, loss is: [0.69315374]

epoch: 4, batch_id: 10, loss is: [0.6901361]

epoch: 4, batch_id: 20, loss is: [0.687753]

epoch: 4, batch_id: 30, loss is: [0.6852927]

[validation] accuracy/loss: 0.5275000333786011/0.691582202911377

最高acc/最低loss 如下: [validation] accuracy/loss: 0.5275000333786011/0.691582202911377

6. 小结

1) 通过修改发现,修改conv1, conv2,conv3的 act 为 relu 函数能得到较好的效果。
2) 相同的网络、参数、训练过程,得到的准确率 acc 和 loss 的值都会不同,可能是因为随机梯度下降和batch_size比较小的原因。