本案例參考課程:百度架構師手把手教深度學習的內容嘱巾。 主要目的為練習vgg動態(tài)圖的PaddlePaddle實現(xiàn)旬昭。
本案例已經在AISTUDIO共享问拘,鏈接為:
https://aistudio.baidu.com/aistudio/projectdetail/244766
數(shù)據(jù)集iChallenge-PM:
數(shù)據(jù)集圖片 iChallenge-PM中既有病理性近視患者的眼底圖片骤坐,也有非病理性近視患者的圖片纽绍,命名規(guī)則如下:
病理性近視(PM):文件名以P開頭
非病理性近視(non-PM):
高度近似(high myopia):文件名以H開頭
正常眼睛(normal):文件名以N開頭
我們將病理性患者的圖片作為正樣本势似,標簽為1履因; 非病理性患者的圖片作為負樣本,標簽為0站故。從數(shù)據(jù)集中選取兩張圖片,通過LeNet提取特征岂津,構建分類器礁鲁,對正負樣本進行分類仅醇,并將圖片顯示出來析二。
算法:
VGG VGG是當前最流行的CNN模型之一节预,2014年由Simonyan和Zisserman提出安拟,其命名來源于論文作者所在的實驗室Visual Geometry Group蛤吓。AlexNet模型通過構造多層網(wǎng)絡,取得了較好的效果会傲,但是并沒有給出深度神經網(wǎng)絡設計的方向拙泽。VGG通過使用一系列大小為3x3的小尺寸卷積核和pooling層構造深度卷積神經網(wǎng)絡淌山,并取得了較好的效果顾瞻。VGG模型因為結構簡單泼疑、應用性極強而廣受研究者歡迎,尤其是它的網(wǎng)絡結構設計方法荷荤,為構建深度神經網(wǎng)絡提供了方向。
圖3 是VGG-16的網(wǎng)絡結構示意圖,有13層卷積和3層全連接層袱蚓。VGG網(wǎng)絡的設計嚴格使用3×33\times 33×3的卷積層和池化層來提取特征,并在網(wǎng)絡的最后面使用三層全連接層颖低,將最后一層全連接層的輸出作為分類的預測蹬敲。 在VGG中每層卷積將使用ReLU作為激活函數(shù)暇昂,在全連接層之后添加dropout來抑制過擬合。使用小的卷積核能夠有效地減少參數(shù)的個數(shù)伴嗡,使得訓練和測試變得更加有效急波。比如使用兩層3×33\times 33×3卷積層,可以得到感受野為5的特征圖瘪校,而比使用5×55 \times 55×5的卷積層需要更少的參數(shù)澄暮。由于卷積核比較小,可以堆疊更多的卷積層阱扬,加深網(wǎng)絡的深度泣懊,這對于圖像分類任務來說是有利的。VGG模型的成功證明了增加網(wǎng)絡的深度麻惶,可以更好的學習圖像中的特征模式馍刮。
關鍵代碼:
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[3]
# 查看圖片形狀
img1.shape, img2.shape
((2056, 2124, 3), (2056, 2124, 3))
In[5]
#定義數(shù)據(jù)讀取器
import cv2
import random
import numpy as np
# 對讀入的圖像數(shù)據(jù)進行預處理
def transform_img(img):
? ? # 將圖片尺寸縮放道 224x224
? ? img = cv2.resize(img, (224, 224))
? ? # 讀入的圖像數(shù)據(jù)格式是[H, W, C]
? ? # 使用轉置操作將其變成[C, H, W]
? ? img = np.transpose(img, (2,0,1))
? ? img = img.astype('float32')
? ? # 將數(shù)據(jù)范圍調整到[-1.0, 1.0]之間
? ? img = img / 255.
? ? img = img * 2.0 - 1.0
? ? return img
# 定義訓練集數(shù)據(jù)讀取器
def data_loader(datadir, batch_size=10, mode = 'train'):
? ? # 將datadir目錄下的文件列出來用踩,每條文件都要讀入
? ? filenames = os.listdir(datadir)
? ? def reader():
? ? ? ? if mode == 'train':
? ? ? ? ? ? # 訓練時隨機打亂數(shù)據(jù)順序
? ? ? ? ? ? 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')
? ? ? ? ? ? # 每讀取一個樣本的數(shù)據(jù),就將其放入數(shù)據(jù)列表中
? ? ? ? ? ? batch_imgs.append(img)
? ? ? ? ? ? batch_labels.append(label)
? ? ? ? ? ? if len(batch_imgs) == batch_size:
? ? ? ? ? ? ? ? # 當數(shù)據(jù)列表的長度等于batch_size的時候恰梢,
? ? ? ? ? ? ? ? # 把這些數(shù)據(jù)當作一個mini-batch佛南,并作為數(shù)據(jù)生成器的一個輸出
? ? ? ? ? ? ? ? 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:
? ? ? ? ? ? # 剩余樣本數(shù)目不足一個batch_size的數(shù)據(jù),一起打包成一個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
# 查看數(shù)據(jù)形狀
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)
#訓練和評估代碼
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
? ? ? ? # 定義優(yōu)化器
? ? ? ? opt = fluid.optimizer.Momentum(learning_rate=0.001, momentum=0.9)
? ? ? ? # 定義數(shù)據(jù)讀取器嵌言,訓練數(shù)據(jù)讀取器和驗證數(shù)據(jù)讀取器
? ? ? ? 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)
? ? ? ? ? ? ? ? # 進行l(wèi)oss計算
? ? ? ? ? ? ? ? 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后的預測概率苛白,進行l(wèi)oss計算
? ? ? ? ? ? ? ? pred = fluid.layers.sigmoid(logits)
? ? ? ? ? ? ? ? loss = fluid.layers.sigmoid_cross_entropy_with_logits(logits, label)
? ? ? ? ? ? ? ? # 計算預測概率小于0.5的類別
? ? ? ? ? ? ? ? pred2 = pred * (-1.0) + 1.0
? ? ? ? ? ? ? ? # 得到兩個類別的預測概率娃豹,并沿第一個維度級聯(lián)
? ? ? ? ? ? ? ? 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 .......')
? ? ? ? #加載模型參數(shù)
? ? ? ? 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)
? ? ? ? ? ? # 計算損失函數(shù)值
? ? ? ? ? ? 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))
In[8]
# -*- coding:utf-8 -*-
# VGG模型代碼
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
# 定義vgg塊,包含多層卷積和1層2x2的最大池化層
class vgg_block(fluid.dygraph.Layer):
? ? def __init__(self, name_scope, num_convs, num_channels):
? ? ? ? """
? ? ? ? num_convs, 卷積層的數(shù)目
? ? ? ? num_channels, 卷積層的輸出通道數(shù)购裙,在同一個Incepition塊內懂版,卷積層輸出通道數(shù)是一樣的
? ? ? ? """
? ? ? ? super(vgg_block, self).__init__(name_scope)
? ? ? ? self.conv_list = []
? ? ? ? for i in range(num_convs):
? ? ? ? ? ? conv_layer = self.add_sublayer('conv_' + str(i), Conv2D(self.full_name(),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? num_filters=num_channels, filter_size=3, padding=1, act='relu'))
? ? ? ? ? ? self.conv_list.append(conv_layer)
? ? ? ? self.pool = Pool2D(self.full_name(), 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, name_scope, conv_arch=((2, 64),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (2, 128), (3, 256), (3, 512), (3, 512))):
? ? ? ? super(VGG, self).__init__(name_scope)
? ? ? ? self.vgg_blocks=[]
? ? ? ? iter_id = 0
? ? ? ? # 添加vgg_block
? ? ? ? # 這里一共5個vgg_block,每個block里面的卷積層數(shù)目和輸出通道數(shù)由conv_arch指定
? ? ? ? for (num_convs, num_channels) in conv_arch:
? ? ? ? ? ? block = self.add_sublayer('block_' + str(iter_id),
? ? ? ? ? ? ? ? ? ? vgg_block(self.full_name(), num_convs, num_channels))
? ? ? ? ? ? self.vgg_blocks.append(block)
? ? ? ? ? ? iter_id += 1
? ? ? ? self.fc1 = FC(self.full_name(),
? ? ? ? ? ? ? ? ? ? ? size=4096,
? ? ? ? ? ? ? ? ? ? ? act='relu')
? ? ? ? self.drop1_ratio = 0.5
? ? ? ? self.fc2= FC(self.full_name(),
? ? ? ? ? ? ? ? ? ? ? size=4096,
? ? ? ? ? ? ? ? ? ? ? act='relu')
? ? ? ? self.drop2_ratio = 0.5
? ? ? ? self.fc3 = FC(self.full_name(),
? ? ? ? ? ? ? ? ? ? ? size=1,
? ? ? ? ? ? ? ? ? ? ? )
? ? def forward(self, x):
? ? ? ? for item in self.vgg_blocks:
? ? ? ? ? ? x = item(x)
? ? ? ? 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
with fluid.dygraph.guard():
? ? model = VGG("VGG")
train(model)
start training ...
epoch: 0, batch_id: 0, loss is: [0.7242754]
epoch: 0, batch_id: 10, loss is: [0.6634571]
epoch: 0, batch_id: 20, loss is: [0.7898234]
epoch: 0, batch_id: 30, loss is: [0.60537547]
[validation] accuracy/loss: 0.9424999952316284/0.35623037815093994
epoch: 1, batch_id: 0, loss is: [0.31599292]
epoch: 1, batch_id: 10, loss is: [0.1198744]
epoch: 1, batch_id: 20, loss is: [0.46862125]
epoch: 1, batch_id: 30, loss is: [0.2300901]
[validation] accuracy/loss: 0.92249995470047/0.2342415601015091
epoch: 2, batch_id: 0, loss is: [0.22039299]
epoch: 2, batch_id: 10, loss is: [0.65977865]
epoch: 2, batch_id: 20, loss is: [0.37409317]
epoch: 2, batch_id: 30, loss is: [0.1841044]
[validation] accuracy/loss: 0.9325000643730164/0.22097690403461456
epoch: 3, batch_id: 0, loss is: [0.4992897]
epoch: 3, batch_id: 10, loss is: [0.31177607]
epoch: 3, batch_id: 20, loss is: [0.1721839]
epoch: 3, batch_id: 30, loss is: [0.38319916]
[validation] accuracy/loss: 0.9199999570846558/0.20679759979248047
epoch: 4, batch_id: 0, loss is: [0.20610766]
epoch: 4, batch_id: 10, loss is: [0.06688808]
epoch: 4, batch_id: 20, loss is: [0.3352648]
epoch: 4, batch_id: 30, loss is: [0.28062168]
[validation] accuracy/loss: 0.9149999618530273/0.21788272261619568
with fluid.dygraph.guard():
? ? model = VGG("VGG")
train(model)