项目简介:
如今近视已经成为困扰人们健康的一项全球性负担,在近视人群中,有超过35%的人患有重度近视。近视会拉长眼睛的光轴,也可能引起视网膜或者络网膜的病变。随着近视度数的不断加深,高度近视有可能引发病理性病变,这将会导致以下几种症状:视网膜或者络网膜发生退化、视盘区域萎缩、漆裂样纹损害、Fuchs斑等。因此,及早发现近视患者眼睛的病变并采取治疗,显得非常重要。
数据集
https://pan.baidu.com/s/1XF-pn6h04SmU-4zONfCnig
提取码:iuzy
数据集下载自官网
iChallenge - PM是百度大脑和中山大学中山眼科中心联合举办的iChallenge比赛中,提供的关于病理性近视(Pathologic Myopia,PM)的医疗类数据集,包含1200个受试者的眼底视网膜图片,训练、验证和测试数据集各400张。
iChallenge - PM中既有病理性近视患者的眼底图片,也有非病理性近视患者的图片,命名规则如下:
- 病理性近视(PM):文件名以P开头
- 非病理性近视(non - PM):
- 高度近似(high)
- 正常眼睛(normal):文件名以N开头
- 我们将病理性患者的图片作为正样本,标签为1; 非病理性患者的图片作为负样本,标签为0。
模型
1. VGG
点击查看代码
# -*- coding = utf-8 -*-
# @Time : 2022/12/19 16:29
# @File : VGG.py
# @File : PyCharm
# coding:utf-8
import os
import cv2
import random
import numpy as np
import paddle
from paddle.nn import Conv2D, MaxPool2D, Linear, BatchNorm2D
import paddle.nn.functional as F
# 图像预处理
def transform_img(img):
img = cv2.resize(img, (224, 224))
img = np.transpose(img, (2, 0, 1))
img = img.astype('float32')
img = img / 255.0
img = img * 2.0 - 1.0
return img
# 定义训练集数据读取器
def data_loader(datadir, batch_size=10, mode='train'):
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':
label = 0
elif name[0] == 'P':
label = 1
else:
raise ('Not excepted file name')
batch_imgs.append(img)
batch_labels.append(label)
if len(batch_imgs) == batch_size:
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:
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'):
filelists = open(csvfile).readlines()
def reader():
batch_imgs = []
batch_labels = []
for line in filelists[1:]:
line = line.strip().split(',')
if line[0] == '':
break
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:
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:
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 = './data/PALM-Training400'
DATADIR2 = './data/PALM-Validation400'
CSVFILE = './data/labels.csv'
EPOCH_NUM = 20
def train_pm(model, optimizer):
use_gpu = True
paddle.set_device('gpu:0') if use_gpu else paddle.set_device('cpu')
print('start training ...')
model.train()
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 = paddle.to_tensor(x_data)
label = paddle.to_tensor(y_data)
logits = model(img)
loss = F.binary_cross_entropy_with_logits(logits, label)
avg_loss = paddle.mean(loss)
if batch_id % 20 == 0:
print("epoch:{}, batch_id:{}, loss:{:.4f}".format(epoch + 1, batch_id, float(avg_loss.numpy())))
avg_loss.backward()
optimizer.step()
optimizer.clear_grad()
model.eval()
accuracies = []
losses = []
for batch_id, data in enumerate(valid_loader()):
x_data, y_data = data
img = paddle.to_tensor(x_data)
label = paddle.to_tensor(y_data)
logits = model(img)
pred = F.sigmoid(logits)
loss = F.binary_cross_entropy_with_logits(logits, label)
pred2 = pred * (-1.0) + 1.0
pred = paddle.concat([pred2, pred], axis=1)
acc = paddle.metric.accuracy(pred, paddle.cast(label, dtype='int64'))
accuracies.append(acc.numpy())
losses.append(loss.numpy())
print("[validation] accuracy/loss: {:.4f}/{:.4f}".format(np.mean(accuracies), np.mean(losses)))
model.train()
paddle.save(model.state_dict(), 'palm.pdparams')
paddle.save(optimizer.state_dict(), 'palm.pdopt')
class VGG(paddle.nn.Layer):
def __init__(self):
super(VGG, self).__init__()
in_channels = [3, 64, 128, 256, 512, 512]
self.conv1_1 = Conv2D(in_channels=in_channels[0], out_channels=in_channels[1], kernel_size=3, padding=1,
stride=1)
self.conv1_2 = Conv2D(in_channels=in_channels[1], out_channels=in_channels[1], kernel_size=3, padding=1,
stride=1)
self.conv2_1 = Conv2D(in_channels=in_channels[1], out_channels=in_channels[2], kernel_size=3, padding=1,
stride=1)
self.conv2_2 = Conv2D(in_channels=in_channels[2], out_channels=in_channels[2], kernel_size=3, padding=1,
stride=1)
self.conv3_1 = Conv2D(in_channels=in_channels[2], out_channels=in_channels[3], kernel_size=3, padding=1,
stride=1)
self.conv3_2 = Conv2D(in_channels=in_channels[3], out_channels=in_channels[3], kernel_size=3, padding=1,
stride=1)
self.conv3_3 = Conv2D(in_channels=in_channels[3], out_channels=in_channels[3], kernel_size=3, padding=1,
stride=1)
self.conv4_1 = Conv2D(in_channels=in_channels[3], out_channels=in_channels[4], kernel_size=3, padding=1,
stride=1)
self.conv4_2 = Conv2D(in_channels=in_channels[4], out_channels=in_channels[4], kernel_size=3, padding=1,
stride=1)
self.conv4_3 = Conv2D(in_channels=in_channels[4], out_channels=in_channels[4], kernel_size=3, padding=1,
stride=1)
self.conv5_1 = Conv2D(in_channels=in_channels[4], out_channels=in_channels[5], kernel_size=3, padding=1,
stride=1)
self.conv5_2 = Conv2D(in_channels=in_channels[5], out_channels=in_channels[5], kernel_size=3, padding=1,
stride=1)
self.conv5_3 = Conv2D(in_channels=in_channels[5], out_channels=in_channels[5], kernel_size=3, padding=1,
stride=1)
self.fc1 = paddle.nn.Sequential(paddle.nn.Linear(512 * 7 * 7, 4096), paddle.nn.ReLU())
self.drop1_ratio = 0.5
self.dropout1 = paddle.nn.Dropout(self.drop1_ratio, mode='upscale_in_train')
self.fc2 = paddle.nn.Sequential(paddle.nn.Linear(4096, 4096), paddle.nn.ReLU())
self.drop2_ratio = 0.5
self.dropout2 = paddle.nn.Dropout(self.drop2_ratio, mode='upscale_in_train')
self.fc3 = paddle.nn.Linear(4096, 1)
self.relu = paddle.nn.ReLU()
self.pool = MaxPool2D(stride=2, kernel_size=2)
def forward(self, x):
x = self.relu(self.conv1_1(x))
x = self.relu(self.conv1_2(x))
x = self.pool(x)
x = self.relu(self.conv2_1(x))
x = self.relu(self.conv2_2(x))
x = self.pool(x)
x = self.relu(self.conv3_1(x))
x = self.relu(self.conv3_2(x))
x = self.relu(self.conv3_3(x))
x = self.pool(x)
x = self.relu(self.conv4_1(x))
x = self.relu(self.conv4_2(x))
x = self.relu(self.conv4_3(x))
x = self.pool(x)
x = self.relu(self.conv5_1(x))
x = self.relu(self.conv5_2(x))
x = self.relu(self.conv5_3(x))
x = self.pool(x)
x = paddle.flatten(x, 1, -1)
x = self.dropout1(self.relu(self.fc1(x)))
x = self.dropout2(self.relu(self.fc2(x)))
x = self.fc3(x)
return x
model = VGG()
opt = paddle.optimizer.Momentum(learning_rate=0.001, momentum=0.9, parameters=model.parameters())
train_pm(model, opt)
2.LeNet
点击查看代码
# -*- coding = utf-8 -*-
# @Time : 2022/12/18 9:50
# @File : predict_Pathologic_Myopia.py
# @File : PyCharm
# coding:utf-8
#数据集介绍:
# iChallenge - PM是百度大脑和中山大学中山眼科中心联合举办的iChallenge比赛中,提供的关于病理性近视(Pathologic
# Myopia,PM)的医疗类数据集,包含1200个受试者的眼底视网膜图片,训练、验证和测试数据集各400张。
# iChallenge - PM中既有病理性近视患者的眼底图片,也有非病理性近视患者的图片,命名规则如下:
# 病理性近视(PM):文件名以P开头
# 非病理性近视(non - PM):
# 高度近似(high
# 正常眼睛(normal):文件名以N开头
# 我们将病理性患者的图片作为正样本,标签为1; 非病理性患者的图片作为负样本,标签为0。
import os
import cv2
import random #随机打乱数据
import numpy as np
import paddle
from paddle.nn import Conv2D, MaxPool2D, Linear, BatchNorm2D#卷积网络 层
import paddle.nn.functional as F
# 1.对读入的图像进行预处理
def transform_img(img):
#将图片尺寸缩放到224*224
img = cv2.resize(img, (224, 224))
# 读入的图像数据格式是[H,W,C]
# 使用转置操作将其变成[C,H,W],通道的调换顺序调换为RGB
img = np.transpose(img, (2, 0, 1))
#将每个元素转成float32
img = img.astype('float32')
# 将其数据范围调整到[-1.0,1.0]之间
img = img / 255.0#[0,1]
img = img * 2.0 - 1.0#[-1,1]
return img
# 2.定义训练集数据读取器
def data_loader(datadir, batch_size=10, mode='train'):
# 将datadir目录下文件列出来,每条文件都要读入
filenames = os.listdir(datadir)
def reader():
if mode == 'train':
# 将训练集的数据随机打乱
random.shuffle(filenames)
#两个list装每个batch中的数据与标签
batch_imgs = []
batch_labels = []
for name in filenames:
# 拼接出每张图片的完整路径
filepath = os.path.join(datadir, name)
# 调用cv2.imread来读取图片
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_imgs的时候,
# 把这些数据当作一个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
# 设置迭代轮数5
EPOCH_NUM = 5
#3.定义训练过程
def train_pm(model, optimizer):
# 选择gpu或者cpu,此处gpu:0
# use_gpu = True
# paddle.set_device('gpu:0') if use_gpu else paddle.set_device('cpu')
print('start training ...')
model.train()
# 定义数据读取器,训练数据读取器和验证数据读取器
train_loader = data_loader(DATADIR, batch_size=10, mode='train')
for epoch in range(EPOCH_NUM):
for batch_id, data in enumerate(train_loader()):
x_data, y_data = data
img = paddle.to_tensor(x_data)
label = paddle.to_tensor(y_data)
# 运行模型前向计算,得到预测值
logits = model(img)
loss = F.binary_cross_entropy_with_logits(logits, label)
avg_loss = paddle.mean(loss)
if batch_id % 20 == 0:
print("epoch:{}, batch_id:{}, loss:{:.4f}".format(epoch + 1, batch_id, float(avg_loss.numpy())))
# 反向传播,更新权重,清除梯度
avg_loss.backward()
optimizer.step()
optimizer.clear_grad()
model.eval()
accuracies = []
losses = []
valid_loader = data_loader(DATADIR, batch_size=10, mode='eval')
# 分批次 验证
for batch_id, data in enumerate(valid_loader()):
x_data, y_data = data
img = paddle.to_tensor(x_data)
label = paddle.to_tensor(y_data)
# 运行模型的前向计算,得到预测值
logits = model(img)
# 二分类,sigmoid计算后的记过以0.5为阈值分成两类
# 计算sigmoid后的预测概率,进行loss计算
pred = F.sigmoid(logits)
loss = F.binary_cross_entropy_with_logits(logits, label)
# 计算概率小于0.5的类别
pred2 = pred * (-1.0) + 1.0
# 得到两个类别(pred:正例,pred2:负例)的预测概率,并沿第一个维度级联
pred = paddle.concat([pred2, pred], axis=1)
acc = paddle.metric.accuracy(pred, paddle.cast(label, dtype='int64'))
accuracies.append(acc.numpy())
losses.append(loss.numpy())
print("[validation] accuracy/loss: {:.4f}/{:.4f}".format(np.mean(accuracies), np.mean(losses)))
model.train()
# 保存模型中参数,保存优化器的参数
paddle.save(model.state_dict(), 'palm.pdparams')
paddle.save(optimizer.state_dict(), 'palm.pdopt')
#4.定义评估过程
def evaluation(model, params_file_path):
# use_gpu = True
# paddle.set_device('gpu:0') if use_gpu else paddle.set_device('cpu')
print('start evaluation .......')
#加载之前保存的模型参数
model_state_dict = paddle.load(params_file_path)
model.load_dict(model_state_dict)
model.eval()
# 调用data_loader,获取reader
eval_loader = data_loader(DATADIR, batch_size=10, mode='eval')
acc_set = []
avg_loss_set = []
for batch_id, data in enumerate(eval_loader()):
x_data, y_data = data
img = paddle.to_tensor(x_data)
label = paddle.to_tensor(y_data)
y_data = y_data.astype(np.int64)
label_64 = paddle.to_tensor(y_data)
# model.forward计算预测和精度
prediction, acc = model(img, label_64)
# 计算损失函数值
loss = F.binary_cross_entropy_with_logits(prediction, label)
avg_loss = paddle.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={:.4f}, acc={:.4f}'.format(avg_loss_val_mean, acc_val_mean))
# 定义 LeNet 网络结构
class LeNet(paddle.nn.Layer):
def __init__(self, num_classes=1):
super(LeNet, self).__init__()
# 创建卷积和池化层块,每个卷积层使用Sigmoid激活函数,后面跟着一个2x2的池化
self.conv1 = Conv2D(in_channels=3, out_channels=6, kernel_size=5)
self.max_pool1 = MaxPool2D(kernel_size=2,stride=2)
self.conv2 = Conv2D(in_channels=6, out_channels=16, kernel_size=5)
self.max_pool2 = MaxPool2D(kernel_size=2,stride=2)
# 创建第3个卷积层
self.conv3 = Conv2D(in_channels=16, out_channels=120, kernel_size=4)
# 创建全连接层,第一个全连接层的输出神经元个数为64, 第二个全连接层输出神经元个数为分类标签的类别数
self.fc1 = Linear(in_features=300000, out_features=64)
self.fc2 = Linear(in_features=64, out_features=num_classes)
# 网络的前向计算过程,定义输出每一层的结果,
# 后续将结果写入VisualDL日志文件,实现每一层输出图片的可视化
def forward(self, x,label=None):
x = self.conv1(x)
x = F.sigmoid(x)
x = self.max_pool1(x)
x = self.conv2(x)
x = F.sigmoid(x)
x = self.max_pool2(x)
x = self.conv3(x)
x = F.sigmoid(x)
x = paddle.reshape(x,[x.shape[0],-1])#做reshape连接全连接层
x = self.fc1(x)
x = F.sigmoid(x)
x = self.fc2(x)
if label is not None:
acc = paddle.metric.accuracy(input=x,label=label)
return x, acc
else:
return x
# 查看数据形状:
DATADIR = './data/PALM-Training400'
# 创建模型
model = LeNet(num_classes=1)
# 启动训练过程
opt = paddle.optimizer.Momentum(learning_rate=0.001, momentum=0.9, parameters=model.parameters())
train_pm(model,optimizer=opt)
evaluation(model, params_file_path="palm.pdparams")
3.AlexNet
点击查看代码
# -*- coding = utf-8 -*-
# @Time : 2022/12/18 9:50
# @File : predict_Pathologic_Myopia.py
# @File : PyCharm
# coding:utf-8
import os
import cv2
import random #随机打乱数据
import numpy as np
import paddle
from paddle import nn
from paddle.nn import Conv2D, MaxPool2D, Linear, BatchNorm2D, AdaptiveAvgPool2D, Dropout # 卷积网络 层
import paddle.nn.functional as F
# 1.对读入的图像进行预处理
def transform_img(img):
#将图片尺寸缩放到224*224
img = cv2.resize(img, (224, 224))
# 读入的图像数据格式是[H,W,C]
# 使用转置操作将其变成[C,H,W],通道的调换顺序调换为RGB
img = np.transpose(img, (2, 0, 1))
#将每个元素转成float32
img = img.astype('float32')
# 将其数据范围调整到[-1.0,1.0]之间
img = img / 255.0#[0,1]
img = img * 2.0 - 1.0#[-1,1]
return img
# 2.定义训练集数据读取器
def data_loader(datadir, batch_size=10, mode='train'):
# 将datadir目录下文件列出来,每条文件都要读入
filenames = os.listdir(datadir)
def reader():
if mode == 'train':
# 将训练集的数据随机打乱
random.shuffle(filenames)
#两个list装每个batch中的数据与标签
batch_imgs = []
batch_labels = []
for name in filenames:
# 拼接出每张图片的完整路径
filepath = os.path.join(datadir, name)
# 调用cv2.imread来读取图片
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_imgs的时候,
# 把这些数据当作一个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
# 设置迭代轮数5
EPOCH_NUM = 5
#3.定义训练过程
def train_pm(model, optimizer):
# 选择gpu或者cpu,此处gpu:0
# use_gpu = True
# paddle.set_device('gpu:0') if use_gpu else paddle.set_device('cpu')
print('start training ...')
model.train()
# 定义数据读取器,训练数据读取器和验证数据读取器
train_loader = data_loader(DATADIR, batch_size=10, mode='train')
for epoch in range(EPOCH_NUM):
for batch_id, data in enumerate(train_loader()):
x_data, y_data = data
img = paddle.to_tensor(x_data)
label = paddle.to_tensor(y_data)
# 运行模型前向计算,得到预测值
logits = model(img)
loss = F.binary_cross_entropy_with_logits(logits, label)
avg_loss = paddle.mean(loss)
if batch_id % 20 == 0:
print("epoch:{}, batch_id:{}, loss:{:.4f}".format(epoch + 1, batch_id, float(avg_loss.numpy())))
# 反向传播,更新权重,清除梯度
avg_loss.backward()
optimizer.step()
optimizer.clear_grad()
model.eval()
accuracies = []
losses = []
valid_loader = data_loader(DATADIR, batch_size=10, mode='eval')
# 分批次 验证
for batch_id, data in enumerate(valid_loader()):
x_data, y_data = data
img = paddle.to_tensor(x_data)
label = paddle.to_tensor(y_data)
# 运行模型的前向计算,得到预测值
logits = model(img)
# 二分类,sigmoid计算后的记过以0.5为阈值分成两类
# 计算sigmoid后的预测概率,进行loss计算
pred = F.sigmoid(logits)
loss = F.binary_cross_entropy_with_logits(logits, label)
# 计算概率小于0.5的类别
pred2 = pred * (-1.0) + 1.0
# 得到两个类别(pred:正例,pred2:负例)的预测概率,并沿第一个维度级联
pred = paddle.concat([pred2, pred], axis=1)
acc = paddle.metric.accuracy(pred, paddle.cast(label, dtype='int64'))
accuracies.append(acc.numpy())
losses.append(loss.numpy())
print("[validation] accuracy/loss: {:.4f}/{:.4f}".format(np.mean(accuracies), np.mean(losses)))
model.train()
# 保存模型中参数,保存优化器的参数
paddle.save(model.state_dict(), 'palm.pdparams')
paddle.save(optimizer.state_dict(), 'palm.pdopt')
#4.定义评估过程
def evaluation(model, params_file_path):
# use_gpu = True
# paddle.set_device('gpu:0') if use_gpu else paddle.set_device('cpu')
print('start evaluation .......')
#加载之前保存的模型参数
model_state_dict = paddle.load(params_file_path)
model.load_dict(model_state_dict)
model.eval()
# 调用data_loader,获取reader
eval_loader = data_loader(DATADIR, batch_size=10, mode='eval')
acc_set = []
avg_loss_set = []
for batch_id, data in enumerate(eval_loader()):
x_data, y_data = data
img = paddle.to_tensor(x_data)
label = paddle.to_tensor(y_data)
y_data = y_data.astype(np.int64)
label_64 = paddle.to_tensor(y_data)
# model.forward计算预测和精度
prediction, acc = model(img, label_64)
# 计算损失函数值
loss = F.binary_cross_entropy_with_logits(prediction, label)
avg_loss = paddle.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={:.4f}, acc={:.4f}'.format(avg_loss_val_mean, acc_val_mean))
# 定义 AlexNet 网络结构
class AlexNet(paddle.nn.Layer):
def __init__(self, num_classes=1):
super(AlexNet, self).__init__()
# AlexNet与LeNet一样也会同时使用卷积和池化层提取图像特征
# 与LeNet不同的是激活函数换成了‘relu’
self.conv1 = Conv2D(in_channels=3, out_channels=96, kernel_size=11, stride=4, padding=5)
self.max_pool1 = MaxPool2D(kernel_size=2, stride=2)
self.conv2 = Conv2D(in_channels=96, out_channels=256, kernel_size=5, stride=1, padding=2)
self.max_pool2 = MaxPool2D(kernel_size=2, stride=2)
self.conv3 = Conv2D(in_channels=256, out_channels=384, kernel_size=3, stride=1, padding=1)
self.conv4 = Conv2D(in_channels=384, out_channels=384, kernel_size=3, stride=1, padding=1)
self.conv5 = Conv2D(in_channels=384, out_channels=256, kernel_size=3, stride=1, padding=1)
self.max_pool5 = MaxPool2D(kernel_size=2, stride=2)
self.fc1 = Linear(in_features=12544, out_features=4096)
self.drop_ratio1 = 0.5
self.drop1 = Dropout(self.drop_ratio1)
self.fc2 = Linear(in_features=4096, out_features=4096)
self.drop_ratio2 = 0.5
self.drop2 = Dropout(self.drop_ratio2)
self.fc3 = Linear(in_features=4096, out_features=num_classes)
# 网络的前向计算过程,定义输出每一层的结果,
# 后续将结果写入VisualDL日志文件,实现每一层输出图片的可视化
def forward(self, x,label=None):
x = self.conv1(x)
x = F.relu(x)
x = self.max_pool1(x)
x = self.conv2(x)
x = F.relu(x)
x = self.max_pool2(x)
x = self.conv3(x)
x = F.relu(x)
x = self.conv4(x)
x = F.relu(x)
x = self.conv5(x)
x = F.relu(x)
x = self.max_pool5(x)
x = paddle.reshape(x,[x.shape[0],-1])#做reshape连接全连接层
x = self.fc1(x)
x = F.relu(x)
# 在全连接之后使用dropout抑制过拟合
x = self.drop1(x)
x = self.fc2(x)
x = F.relu(x)
# 在全连接之后使用dropout抑制过拟合
x = self.drop2(x)
x = self.fc3(x)
if label is not None:
acc = paddle.metric.accuracy(input=x, label=label)
return x, acc
else:
return x
# 数据集所在文件:
DATADIR = './data/PALM-Training400'
# 创建模型
model = AlexNet(num_classes=1)
# 启动训练过程
opt = paddle.optimizer.Momentum(learning_rate=0.001, momentum=0.9, parameters=model.parameters())
train_pm(model,optimizer=opt)#训练模型
evaluation(model, params_file_path="palm.pdparams")#评估模型
实验结果
LeNet:
通过观察可以发现:loss没有下降,accuracy也没有上升
AlexNet:
loss明显下降,accuracy达到90%以上
VGG:
loss有效下降,accuracy达到90%以上