PaddlePaddle動態圖實現Resnet(眼底篩查為例)
本案例參考課程:百度架構師手把手教深度學習的內容。 主要目的為練習Resnet動態圖的PaddlePaddle實現。
本案例已經在AISTUDIO共享,連結為:
資料集:
檢視資料集圖片 iChallenge-PM中既有病理性近視患者的眼底圖片,也有非病理性近視患者的圖片,命名規則如下:
病理性近視(PM):檔名以P開頭
非病理性近視(non-PM):
高度近似(high myopia):檔名以H開頭
正常眼睛(normal):檔名以N開頭
我們將病理性患者的圖片作為正樣本,標籤為1; 非病理性患者的圖片作為負樣本,標籤為0。從資料集中選取兩張圖片,透過LeNet提取特徵,構建分類器,對正負樣本進行分類,並將圖片顯示出來。
ResNet
ResNet是2015年ImageNet比賽的冠軍,將識別錯誤率降低到了3.6%,這個結果甚至超出了正常人眼識別的精度。
透過前面幾個經典模型學習,我們可以發現隨著深度學習的不斷髮展,模型的層數越來越多,網路結構也越來越複雜。那麼是否加深網路結構,就一定會得到更好的效果呢?從理論上來說,假設新增加的層都是恆等對映,只要原有的層學出跟原模型一樣的引數,那麼深模型結構就能達到原模型結構的效果。換句話說,原模型的解只是新模型的解的子空間,在新模型解的空間裡應該能找到比原模型解對應的子空間更好的結果。但是實踐表明,增加網路的層數之後,訓練誤差往往不降反升。
Kaiming He等人提出了殘差網路ResNet來解決上述問題,其基本思想如 圖6所示。
圖6(a):表示增加網路的時候,將x對映成y=F(x)y=F(x)y=F(x)輸出。
圖6(b):對圖6(a)作了改進,輸出y=F(x)+xy=F(x) + xy=F(x)+x。這時不是直接學習輸出特徵y的表示,而是學習y−xy-xy−x。
如果想學習出原模型的表示,只需將F(x)的引數全部設定為0,則y=xy=xy=x是恆等對映。
F(x)=y−xF(x) = y - xF(x)=y−x也叫做殘差項,如果x→yx\rightarrow yx→y的對映接近恆等對映,圖6(b)中透過學習殘差項也比圖6(a)學習完整對映形式更加容易。
圖6:殘差塊設計思想
圖6(b)的結構是殘差網路的基礎,這種結構也叫做殘差塊(residual block)。輸入x透過跨層連線,能更快的向前傳播資料,或者向後傳播梯度。殘差塊的具體設計方案如 圖7 所示,這種設計方案也成稱作瓶頸結構(BottleNeck)。
圖7:殘差塊結構示意圖
下圖表示出了ResNet-50的結構,一共包含49層卷積和1層全連線,所以被稱為ResNet-50。
圖8:ResNet-50模型網路結構示意圖
ResNet-50的具體實現如下程式碼所示:
In[2]
import os
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from PIL import Image
DATADIR = '/home/aistudio/work/palm/PALM-Training400/PALM-Training400'
# 檔名以N開頭的是正常眼底圖片,以P開頭的是病變眼底圖片
file1 = 'N0012.jpg'
file2 = 'P0095.jpg'
# 讀取圖片
img1 = Image.open(os.path.join(DATADIR, file1))
img1 = np.array(img1)
img2 = Image.open(os.path.join(DATADIR, file2))
img2 = np.array(img2)
# 畫出讀取的圖片
plt.figure(figsize=(16, 8))
f = plt.subplot(121)
f.set_title('Normal', fontsize=20)
plt.imshow(img1)
f = plt.subplot(122)
f.set_title('PM', fontsize=20)
plt.imshow(img2)
plt.show()
In[4]
# 檢視圖片形狀
img1.shape, img2.shape
((2056, 2124, 3), (2056, 2124, 3))
In[3]
#定義資料讀取器
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
In[5]
# 檢視資料形狀
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))
In[6]
!pip install xlrd
import pandas as pd
df=pd.read_excel('/home/aistudio/work/palm/PALM-Validation-GT/PM_Label_and_Fovea_Location.xlsx')
df.to_csv('/home/aistudio/work/palm/PALM-Validation-GT/labels.csv',index=False)
Looking in indexes:
Collecting xlrd
Downloading (103kB)
|████████████████████████████████| 112kB 9.2MB/s eta 0:00:01
Installing collected packages: xlrd
Successfully installed xlrd-1.2.0
In[7]
#訓練和評估程式碼
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/work/palm/PALM-Validation-GT/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)
# 定義資料讀取器,訓練資料讀取器和驗證資料讀取器
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')
# 定義評估過程
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))
ResNet-50的具體實現如下程式碼所示:
In[8]
# -*- coding:utf-8 -*-
# ResNet模型程式碼
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, FC
from paddle.fluid.dygraph.base import to_variable
# ResNet中使用了BatchNorm層,在卷積層的後面加上BatchNorm以提升數值穩定性
# 定義卷積批歸一化塊
class ConvBNLayer(fluid.dygraph.Layer):
def __init__(self,
name_scope,
num_channels,
num_filters,
filter_size,
stride=1,
groups=1,
act=None):
"""
name_scope, 模組的名字
num_channels, 卷積層的輸入通道數
num_filters, 卷積層的輸出通道數
stride, 卷積層的步幅
groups, 分組卷積的組數,預設groups=1不使用分組卷積
act, 啟用函式型別,預設act=None不使用啟用函式
"""
super(ConvBNLayer, self).__init__(name_scope)
# 建立卷積層
self._conv = Conv2D(
self.full_name(),
num_filters=num_filters,
filter_size=filter_size,
stride=stride,
padding=(filter_size - 1) // 2,
groups=groups,
act=None,
bias_attr=False)
# 建立BatchNorm層
self._batch_norm = BatchNorm(self.full_name(), num_filters, act=act)
def forward(self, inputs):
y = self._conv(inputs)
y = self._batch_norm(y)
return y
# 定義殘差塊
# 每個殘差塊會對輸入圖片做三次卷積,然後跟輸入圖片進行短接
# 如果殘差塊中第三次卷積輸出特徵圖的形狀與輸入不一致,則對輸入圖片做1x1卷積,將其輸出形狀調整成一致
class BottleneckBlock(fluid.dygraph.Layer):
def __init__(self,
name_scope,
num_channels,
num_filters,
stride,
shortcut=True):
super(BottleneckBlock, self).__init__(name_scope)
# 建立第一個卷積層 1x1
self.conv0 = ConvBNLayer(
self.full_name(),
num_channels=num_channels,
num_filters=num_filters,
filter_size=1,
act='relu')
# 建立第二個卷積層 3x3
self.conv1 = ConvBNLayer(
self.full_name(),
num_channels=num_filters,
num_filters=num_filters,
filter_size=3,
stride=stride,
act='relu')
# 建立第三個卷積 1x1,但輸出通道數乘以4
self.conv2 = ConvBNLayer(
self.full_name(),
num_channels=num_filters,
num_filters=num_filters * 4,
filter_size=1,
act=None)
# 如果conv2的輸出跟此殘差塊的輸入資料形狀一致,則shortcut=True
# 否則shortcut = False,新增1個1x1的卷積作用在輸入資料上,使其形狀變成跟conv2一致
if not shortcut:
self.short = ConvBNLayer(
self.full_name(),
num_channels=num_channels,
num_filters=num_filters * 4,
filter_size=1,
stride=stride)
self.shortcut = shortcut
self._num_channels_out = num_filters * 4
def forward(self, inputs):
y = self.conv0(inputs)
conv1 = self.conv1(y)
conv2 = self.conv2(conv1)
# 如果shortcut=True,直接將inputs跟conv2的輸出相加
# 否則需要對inputs進行一次卷積,將形狀調整成跟conv2輸出一致
if self.shortcut:
short = inputs
else:
short = self.short(inputs)
y = fluid.layers.elementwise_add(x=short, y=conv2)
layer_helper = LayerHelper(self.full_name(), act='relu')
return layer_helper.append_activation(y)
# 定義ResNet模型
class ResNet(fluid.dygraph.Layer):
def __init__(self, name_scope, layers=50, class_dim=1):
"""
name_scope,模組名稱
layers, 網路層數,可以是50, 101或者152
class_dim,分類標籤的類別數
"""
super(ResNet, self).__init__(name_scope)
self.layers = layers
supported_layers = [50, 101, 152]
assert layers in supported_layers, \
"supported layers are {} but input layer is {}".format(supported_layers, layers)
if layers == 50:
#ResNet50包含多個模組,其中第2到第5個模組分別包含3、4、6、3個殘差塊
depth = [3, 4, 6, 3]
elif layers == 101:
#ResNet101包含多個模組,其中第2到第5個模組分別包含3、4、23、3個殘差塊
depth = [3, 4, 23, 3]
elif layers == 152:
#ResNet50包含多個模組,其中第2到第5個模組分別包含3、8、36、3個殘差塊
depth = [3, 8, 36, 3]
# 殘差塊中使用到的卷積的輸出通道數
num_filters = [64, 128, 256, 512]
# ResNet的第一個模組,包含1個7x7卷積,後面跟著1個最大池化層
self.conv = ConvBNLayer(
self.full_name(),
num_channels=3,
num_filters=64,
filter_size=7,
stride=2,
act='relu')
self.pool2d_max = Pool2D(
self.full_name(),
pool_size=3,
pool_stride=2,
pool_padding=1,
pool_type='max')
# ResNet的第二到第五個模組c2、c3、c4、c5
self.bottleneck_block_list = []
num_channels = 64
for block in range(len(depth)):
shortcut = False
for i in range(depth[block]):
bottleneck_block = self.add_sublayer(
'bb_%d_%d' % (block, i),
BottleneckBlock(
self.full_name(),
num_channels=num_channels,
num_filters=num_filters[block],
stride=2 if i == 0 and block != 0 else 1, # c3、c4、c5將會在第一個殘差塊使用stride=2;其餘所有殘差塊stride=1
shortcut=shortcut))
num_channels = bottleneck_block._num_channels_out
self.bottleneck_block_list.append(bottleneck_block)
shortcut = True
# 在c5的輸出特徵圖上使用全域性池化
self.pool2d_avg = Pool2D(
self.full_name(), pool_size=7, pool_type='avg', global_pooling=True)
# stdv用來作為全連線層隨機初始化引數的方差
import math
stdv = 1.0 / math.sqrt(2048 * 1.0)
# 建立全連線層,輸出大小為類別數目
self.out = FC(self.full_name(),
size=class_dim,
param_attr=fluid.param_attr.ParamAttr(
initializer=fluid.initializer.Uniform(-stdv, stdv)))
def forward(self, inputs):
y = self.conv(inputs)
y = self.pool2d_max(y)
for bottleneck_block in self.bottleneck_block_list:
y = bottleneck_block(y)
y = self.pool2d_avg(y)
y = self.out(y)
return y
In[9]
with fluid.dygraph.guard():
model = ResNet("ResNet")
train(model)
start training ...
epoch: 0, batch_id: 0, loss is: [0.83079195]
epoch: 0, batch_id: 10, loss is: [0.5477183]
epoch: 0, batch_id: 20, loss is: [0.87052524]
epoch: 0, batch_id: 30, loss is: [1.0255078]
[validation] accuracy/loss: 0.7450000047683716/0.5235034823417664
epoch: 1, batch_id: 0, loss is: [0.41455013]
epoch: 1, batch_id: 10, loss is: [0.54812586]
epoch: 1, batch_id: 20, loss is: [0.17374663]
epoch: 1, batch_id: 30, loss is: [0.30293828]
[validation] accuracy/loss: 0.887499988079071/0.27671539783477783
epoch: 2, batch_id: 0, loss is: [0.38499922]
epoch: 2, batch_id: 10, loss is: [0.29150736]
epoch: 2, batch_id: 20, loss is: [0.3396409]
[validation] accuracy/loss: 0.9274999499320984/0.17061272263526917
epoch: 3, batch_id: 0, loss is: [0.06969612]
epoch: 3, batch_id: 10, loss is: [0.0861987]
epoch: 3, batch_id: 20, loss is: [0.05332329]
epoch: 3, batch_id: 30, loss is: [0.46470308]
[validation] accuracy/loss: 0.9375/0.20805077254772186
epoch: 4, batch_id: 0, loss is: [0.38617897]
epoch: 4, batch_id: 10, loss is: [0.16854036]
epoch: 4, batch_id: 20, loss is: [0.05454079]
epoch: 4, batch_id: 30, loss is: [0.32432565]
[validation] accuracy/loss: 0.8600000143051147/0.3488900661468506
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69922494/viewspace-2673932/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- PaddlePaddle動態圖實現VGG(眼底篩查為例)
- 一眼萬年:AI眼底篩查為什麼能夠成為AI醫療中的“落地之王”AI
- 動態篩選
- django 動態查詢實現過程Django
- vue 實現動態拓撲圖Vue
- Flask SocketIO 實現動態繪圖Flask繪圖
- MVC實現EChatrs動態折線圖MVC
- 前端狀態管理簡易實現(以vuex為例)前端Vue
- 深入解析 ResNet:實現與原理
- C#動態建立介面的實現例項物件C#物件
- 使用Spring Boot實現動態健康檢查HealthChecksSpring Boot
- Qt實現炫酷啟動圖-動態進度條QT
- 實現js檔案動態載入程式碼例項JS
- canvas實現的動態心形效果程式碼例項Canvas
- 有沒有用EJB(CMP)實現動態查詢的方法?
- 動態圖解&例項 ConstraintLayout Chain圖解AI
- spring boot+bootstrap實現動態輪播圖實戰Spring Boot
- 使用單例模式來實現動態資料來源管理單例模式
- javascript動態實現的表單提交效果程式碼例項JavaScript
- js實現的動態引入css檔案程式碼例項JSCSS
- css3實現的動態大白效果程式碼例項CSSS3
- Mybatis連線池_動態sql語句_多表查詢實現MyBatisSQL
- Kettle實現動態SQLSQL
- 動態棧的實現
- PaddlePaddle 實現 DeepLab V3
- javascript實現的動態載入css檔案程式碼例項JavaScriptCSS
- 如何為一個例項動態替換方法
- centos下實現程式開機自啟動(tomcat為例)CentOSTomcat
- 查詢演算法集:順序查詢、二分查詢、插值查詢、動態查詢(陣列實現、連結串列實現)演算法陣列
- 騰訊優圖醫療 AI:讓癌症篩查更精準AI
- 通過vue元件化方式實現常見動態圖示Vue元件化
- CSS或JS實現gif動態圖片的停止與播放CSSJS
- 基礎入門,怎樣用PaddlePaddle優雅地寫VGG與ResNet
- javascript實現的動態設定元素透明度程式碼例項JavaScript
- jQuery實現的動態載入指令碼檔案程式碼例項jQuery指令碼
- 如何用PaddlePaddle實現機器翻譯?
- css3動態背景圖片程式碼例項CSSS3
- Flutter實現自定義篩選框Flutter