当前位置:   article > 正文

PaddlePaddle动态图实现VGG(眼底筛查为例)_基于vgg16的眼底病理性检测

基于vgg16的眼底病理性检测

本案例参考课程:百度架构师手把手教深度学习的内容。 主要目的为练习vgg动态图的PaddlePaddle实现。

本案例已经在AISTUDIO共享,链接为:

https://aistudio.baidu.com/aistudio/projectdetail/244766

数据集iChallenge-PM:

数据集图片 iChallenge-PM中既有病理性近视患者的眼底图片,也有非病理性近视患者的图片,命名规则如下:

病理性近视(PM):文件名以P开头

非病理性近视(non-PM):

高度近似(high myopia):文件名以H开头

正常眼睛(normal):文件名以N开头

我们将病理性患者的图片作为正样本,标签为1; 非病理性患者的图片作为负样本,标签为0。从数据集中选取两张图片,通过LeNet提取特征,构建分类器,对正负样本进行分类,并将图片显示出来。

算法:

VGG VGG是当前最流行的CNN模型之一,2014年由Simonyan和Zisserman提出,其命名来源于论文作者所在的实验室Visual Geometry Group。AlexNet模型通过构造多层网络,取得了较好的效果,但是并没有给出深度神经网络设计的方向。VGG通过使用一系列大小为3x3的小尺寸卷积核和pooling层构造深度卷积神经网络,并取得了较好的效果。VGG模型因为结构简单、应用性极强而广受研究者欢迎,尤其是它的网络结构设计方法,为构建深度神经网络提供了方向。

图3 是VGG-16的网络结构示意图,有13层卷积和3层全连接层。VGG网络的设计严格使用3×33\times 33×3的卷积层和池化层来提取特征,并在网络的最后面使用三层全连接层,将最后一层全连接层的输出作为分类的预测。 在VGG中每层卷积将使用ReLU作为激活函数,在全连接层之后添加dropout来抑制过拟合。使用小的卷积核能够有效地减少参数的个数,使得训练和测试变得更加有效。比如使用两层3×33\times 33×3卷积层,可以得到感受野为5的特征图,而比使用5×55 \times 55×5的卷积层需要更少的参数。由于卷积核比较小,可以堆叠更多的卷积层,加深网络的深度,这对于图像分类任务来说是有利的。VGG模型的成功证明了增加网络的深度,可以更好的学习图像中的特征模式。

关键代码:

  1. import os
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. %matplotlib inline
  5. from PIL import Image
  6. DATADIR = '/home/aistudio/work/palm/PALM-Training400/PALM-Training400'
  7. # 文件名以N开头的是正常眼底图片,以P开头的是病变眼底图片
  8. file1 = 'N0012.jpg'
  9. file2 = 'P0095.jpg'
  10. # 读取图片
  11. img1 = Image.open(os.path.join(DATADIR, file1))
  12. img1 = np.array(img1)
  13. img2 = Image.open(os.path.join(DATADIR, file2))
  14. img2 = np.array(img2)
  15. # 画出读取的图片
  16. plt.figure(figsize=(16, 8))
  17. f = plt.subplot(121)
  18. f.set_title('Normal', fontsize=20)
  19. plt.imshow(img1)
  20. f = plt.subplot(122)
  21. f.set_title('PM', fontsize=20)
  22. plt.imshow(img2)
  23. plt.show()

In[3]

  1. # 查看图片形状
  2. img1.shape, img2.shape
((2056, 2124, 3), (2056, 2124, 3))

In[5]

  1. #定义数据读取器
  2. import cv2
  3. import random
  4. import numpy as np
  5. # 对读入的图像数据进行预处理
  6. def transform_img(img):
  7. # 将图片尺寸缩放道 224x224
  8. img = cv2.resize(img, (224, 224))
  9. # 读入的图像数据格式是[H, W, C]
  10. # 使用转置操作将其变成[C, H, W]
  11. img = np.transpose(img, (2,0,1))
  12. img = img.astype('float32')
  13. # 将数据范围调整到[-1.0, 1.0]之间
  14. img = img / 255.
  15. img = img * 2.0 - 1.0
  16. return img
  17. # 定义训练集数据读取器
  18. def data_loader(datadir, batch_size=10, mode = 'train'):
  19. # 将datadir目录下的文件列出来,每条文件都要读入
  20. filenames = os.listdir(datadir)
  21. def reader():
  22. if mode == 'train':
  23. # 训练时随机打乱数据顺序
  24. random.shuffle(filenames)
  25. batch_imgs = []
  26. batch_labels = []
  27. for name in filenames:
  28. filepath = os.path.join(datadir, name)
  29. img = cv2.imread(filepath)
  30. img = transform_img(img)
  31. if name[0] == 'H' or name[0] == 'N':
  32. # H开头的文件名表示高度近似,N开头的文件名表示正常视力
  33. # 高度近视和正常视力的样本,都不是病理性的,属于负样本,标签为0
  34. label = 0
  35. elif name[0] == 'P':
  36. # P开头的是病理性近视,属于正样本,标签为1
  37. label = 1
  38. else:
  39. raise('Not excepted file name')
  40. # 每读取一个样本的数据,就将其放入数据列表中
  41. batch_imgs.append(img)
  42. batch_labels.append(label)
  43. if len(batch_imgs) == batch_size:
  44. # 当数据列表的长度等于batch_size的时候,
  45. # 把这些数据当作一个mini-batch,并作为数据生成器的一个输出
  46. imgs_array = np.array(batch_imgs).astype('float32')
  47. labels_array = np.array(batch_labels).astype('float32').reshape(-1, 1)
  48. yield imgs_array, labels_array
  49. batch_imgs = []
  50. batch_labels = []
  51. if len(batch_imgs) > 0:
  52. # 剩余样本数目不足一个batch_size的数据,一起打包成一个mini-batch
  53. imgs_array = np.array(batch_imgs).astype('float32')
  54. labels_array = np.array(batch_labels).astype('float32').reshape(-1, 1)
  55. yield imgs_array, labels_array
  56. return reader
  1. # 查看数据形状
  2. DATADIR = '/home/aistudio/work/palm/PALM-Training400/PALM-Training400'
  3. train_loader = data_loader(DATADIR,
  4. batch_size=10, mode='train')
  5. data_reader = train_loader()
  6. data = next(data_reader)
  7. data[0].shape, data[1].shape
((10, 3, 224, 224), (10, 1))

In[6]

  1. !pip install xlrd
  2. import pandas as pd
  3. df=pd.read_excel('/home/aistudio/work/palm/PALM-Validation-GT/PM_Label_and_Fovea_Location.xlsx')
  4. df.to_csv('/home/aistudio/work/palm/PALM-Validation-GT/labels.csv',index=False)

 

  1. #训练和评估代码
  2. import os
  3. import random
  4. import paddle
  5. import paddle.fluid as fluid
  6. import numpy as np
  7. DATADIR = '/home/aistudio/work/palm/PALM-Training400/PALM-Training400'
  8. DATADIR2 = '/home/aistudio/work/palm/PALM-Validation400'
  9. CSVFILE = '/home/aistudio/work/palm/PALM-Validation-GT/labels.csv'
  10. # 定义训练过程
  11. def train(model):
  12. with fluid.dygraph.guard():
  13. print('start training ... ')
  14. model.train()
  15. epoch_num = 5
  16. # 定义优化器
  17. opt = fluid.optimizer.Momentum(learning_rate=0.001, momentum=0.9)
  18. # 定义数据读取器,训练数据读取器和验证数据读取器
  19. train_loader = data_loader(DATADIR, batch_size=10, mode='train')
  20. valid_loader = valid_data_loader(DATADIR2, CSVFILE)
  21. for epoch in range(epoch_num):
  22. for batch_id, data in enumerate(train_loader()):
  23. x_data, y_data = data
  24. img = fluid.dygraph.to_variable(x_data)
  25. label = fluid.dygraph.to_variable(y_data)
  26. # 运行模型前向计算,得到预测值
  27. logits = model(img)
  28. # 进行loss计算
  29. loss = fluid.layers.sigmoid_cross_entropy_with_logits(logits, label)
  30. avg_loss = fluid.layers.mean(loss)
  31. if batch_id % 10 == 0:
  32. print("epoch: {}, batch_id: {}, loss is: {}".format(epoch, batch_id, avg_loss.numpy()))
  33. # 反向传播,更新权重,清除梯度
  34. avg_loss.backward()
  35. opt.minimize(avg_loss)
  36. model.clear_gradients()
  37. model.eval()
  38. accuracies = []
  39. losses = []
  40. for batch_id, data in enumerate(valid_loader()):
  41. x_data, y_data = data
  42. img = fluid.dygraph.to_variable(x_data)
  43. label = fluid.dygraph.to_variable(y_data)
  44. # 运行模型前向计算,得到预测值
  45. logits = model(img)
  46. # 二分类,sigmoid计算后的结果以0.5为阈值分两个类别
  47. # 计算sigmoid后的预测概率,进行loss计算
  48. pred = fluid.layers.sigmoid(logits)
  49. loss = fluid.layers.sigmoid_cross_entropy_with_logits(logits, label)
  50. # 计算预测概率小于0.5的类别
  51. pred2 = pred * (-1.0) + 1.0
  52. # 得到两个类别的预测概率,并沿第一个维度级联
  53. pred = fluid.layers.concat([pred2, pred], axis=1)
  54. acc = fluid.layers.accuracy(pred, fluid.layers.cast(label, dtype='int64'))
  55. accuracies.append(acc.numpy())
  56. losses.append(loss.numpy())
  57. print("[validation] accuracy/loss: {}/{}".format(np.mean(accuracies), np.mean(losses)))
  58. model.train()
  59. # save params of model
  60. fluid.save_dygraph(model.state_dict(), 'mnist')
  61. # save optimizer state
  62. fluid.save_dygraph(opt.state_dict(), 'mnist')
  63. # 定义评估过程
  64. def evaluation(model, params_file_path):
  65. with fluid.dygraph.guard():
  66. print('start evaluation .......')
  67. #加载模型参数
  68. model_state_dict, _ = fluid.load_dygraph(params_file_path)
  69. model.load_dict(model_state_dict)
  70. model.eval()
  71. eval_loader = load_data('eval')
  72. acc_set = []
  73. avg_loss_set = []
  74. for batch_id, data in enumerate(eval_loader()):
  75. x_data, y_data = data
  76. img = fluid.dygraph.to_variable(x_data)
  77. label = fluid.dygraph.to_variable(y_data)
  78. # 计算预测和精度
  79. prediction, acc = model(img, label)
  80. # 计算损失函数值
  81. loss = fluid.layers.cross_entropy(input=prediction, label=label)
  82. avg_loss = fluid.layers.mean(loss)
  83. acc_set.append(float(acc.numpy()))
  84. avg_loss_set.append(float(avg_loss.numpy()))
  85. # 求平均精度
  86. acc_val_mean = np.array(acc_set).mean()
  87. avg_loss_val_mean = np.array(avg_loss_set).mean()
  88. print('loss={}, acc={}'.format(avg_loss_val_mean, acc_val_mean))

In[8]

  1. # -*- coding:utf-8 -*-
  2. # VGG模型代码
  3. import numpy as np
  4. import paddle
  5. import paddle.fluid as fluid
  6. from paddle.fluid.layer_helper import LayerHelper
  7. from paddle.fluid.dygraph.nn import Conv2D, Pool2D, BatchNorm, FC
  8. from paddle.fluid.dygraph.base import to_variable
  9. # 定义vgg块,包含多层卷积和12x2的最大池化层
  10. class vgg_block(fluid.dygraph.Layer):
  11. def __init__(self, name_scope, num_convs, num_channels):
  12. """
  13. num_convs, 卷积层的数目
  14. num_channels, 卷积层的输出通道数,在同一个Incepition块内,卷积层输出通道数是一样的
  15. """
  16. super(vgg_block, self).__init__(name_scope)
  17. self.conv_list = []
  18. for i in range(num_convs):
  19. conv_layer = self.add_sublayer('conv_' + str(i), Conv2D(self.full_name(),
  20. num_filters=num_channels, filter_size=3, padding=1, act='relu'))
  21. self.conv_list.append(conv_layer)
  22. self.pool = Pool2D(self.full_name(), pool_stride=2, pool_size = 2, pool_type='max')
  23. def forward(self, x):
  24. for item in self.conv_list:
  25. x = item(x)
  26. return self.pool(x)
  27. class VGG(fluid.dygraph.Layer):
  28. def __init__(self, name_scope, conv_arch=((2, 64),
  29. (2, 128), (3, 256), (3, 512), (3, 512))):
  30. super(VGG, self).__init__(name_scope)
  31. self.vgg_blocks=[]
  32. iter_id = 0
  33. # 添加vgg_block
  34. # 这里一共5个vgg_block,每个block里面的卷积层数目和输出通道数由conv_arch指定
  35. for (num_convs, num_channels) in conv_arch:
  36. block = self.add_sublayer('block_' + str(iter_id),
  37. vgg_block(self.full_name(), num_convs, num_channels))
  38. self.vgg_blocks.append(block)
  39. iter_id += 1
  40. self.fc1 = FC(self.full_name(),
  41. size=4096,
  42. act='relu')
  43. self.drop1_ratio = 0.5
  44. self.fc2= FC(self.full_name(),
  45. size=4096,
  46. act='relu')
  47. self.drop2_ratio = 0.5
  48. self.fc3 = FC(self.full_name(),
  49. size=1,
  50. )
  51. def forward(self, x):
  52. for item in self.vgg_blocks:
  53. x = item(x)
  54. x = fluid.layers.dropout(self.fc1(x), self.drop1_ratio)
  55. x = fluid.layers.dropout(self.fc2(x), self.drop2_ratio)
  56. x = self.fc3(x)
  57. return x

 

  1. with fluid.dygraph.guard():
  2. model = VGG("VGG")
  3. train(model)
  1. start training ...
  2. epoch: 0, batch_id: 0, loss is: [0.7242754]
  3. epoch: 0, batch_id: 10, loss is: [0.6634571]
  4. epoch: 0, batch_id: 20, loss is: [0.7898234]
  5. epoch: 0, batch_id: 30, loss is: [0.60537547]
  6. [validation] accuracy/loss: 0.9424999952316284/0.35623037815093994
  7. epoch: 1, batch_id: 0, loss is: [0.31599292]
  8. epoch: 1, batch_id: 10, loss is: [0.1198744]
  9. epoch: 1, batch_id: 20, loss is: [0.46862125]
  10. epoch: 1, batch_id: 30, loss is: [0.2300901]
  11. [validation] accuracy/loss: 0.92249995470047/0.2342415601015091
  12. epoch: 2, batch_id: 0, loss is: [0.22039299]
  13. epoch: 2, batch_id: 10, loss is: [0.65977865]
  14. epoch: 2, batch_id: 20, loss is: [0.37409317]
  15. epoch: 2, batch_id: 30, loss is: [0.1841044]
  16. [validation] accuracy/loss: 0.9325000643730164/0.22097690403461456
  17. epoch: 3, batch_id: 0, loss is: [0.4992897]
  18. epoch: 3, batch_id: 10, loss is: [0.31177607]
  19. epoch: 3, batch_id: 20, loss is: [0.1721839]
  20. epoch: 3, batch_id: 30, loss is: [0.38319916]
  21. [validation] accuracy/loss: 0.9199999570846558/0.20679759979248047
  22. epoch: 4, batch_id: 0, loss is: [0.20610766]
  23. epoch: 4, batch_id: 10, loss is: [0.06688808]
  24. epoch: 4, batch_id: 20, loss is: [0.3352648]
  25. epoch: 4, batch_id: 30, loss is: [0.28062168]
  26. [validation] accuracy/loss: 0.9149999618530273/0.21788272261619568

 

  1. with fluid.dygraph.guard():
  2. model = VGG("VGG")
  3. train(model)
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/92670
推荐阅读
相关标签
  

闽ICP备14008679号