- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊
文章目录
- 一、前言
- 二、前期准备
- 1、设置GPU
- 2、导入数据
- 3、加载数据
- 4、划分数据集
- 三、搭建网络模型
- 1、构建DenseNet
- 2、构建DenseNet121
- 四、训练模型
- 1、编写训练函数
- 2、编写测试函数
- 3、正式训练
- 五、结果可视化
- 1、Loss与Accuracy图
- 2、模型评估
电脑环境:
语言环境:Python 3.8.0
编译器:Jupyter Notebook
深度学习环境:torch 2.4.1+cu121
一、前言
今天带大家探索一下深度学习在医学领域的应用,乳腺癌是女性最常见的癌症形式,浸润性导管癌 (IDC) 是最常见的乳腺癌形式。准确识别和分类乳腺癌亚型是一项重要的临床任务,利用深度学习方法识别可以有效节省时间井减少错误。我们的数据集是由多张以 40 倍扫描的乳腺癌(BCa)标本的完整载玻片图像组成。
二、前期准备
1、设置GPU
import tensorflow as tfgpus = tf.config.list_physical_devices('GPU')if gpus:tf.config.experimental.set_memory_growth(gpus[0], True)tf.config.set_visible_devices(gpus[0], 'GPU')gpus
2、导入数据
import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = Falseimport os, PIL, pathlib
import numpy as npfrom tensorflow import keras
from keras import layers, modelsdata_dir = './J3-1data/'
data_dir = pathlib.Path(data_dir)
data_path = list(data_dir.glob('*'))
classeNames = [str(path).split('/')[-1] for path in data_path]
classeNames
3、加载数据
batch_size = 16
img_height = 224
img_width = 224train_ds = tf.keras.preprocessing.image_dataset_from_directory(data_dir,validation_split=0.2,subset="training",seed=12,image_size=(img_height, img_width),batch_size=batch_size)val_ds = tf.keras.preprocessing.image_dataset_from_directory(data_dir,validation_split=0.2,subset="validation",seed=12,image_size=(img_height, img_width),batch_size=batch_size)total_data = datasets.ImageFolder(data_dir, transform=train_transforms)
total_data
4、划分数据集
train_size = int(0.8 * len(total_data))
test_size = len(total_data) - train_sizetrain_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])
len(train_dataset), len(test_dataset)batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dl = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=True)
三、搭建网络模型
1、构建DenseNet
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDictclass _DenseLayer(nn.Sequential):def __init__(self, num_input_features, growth_rate, bn_size, drop_rate):super(_DenseLayer, self).__init__()# 调用父类的构造方法,这句话的意思是在调用nn.Sequential的构造方法self.add_module('norm1', nn.BatchNorm2d(num_input_features)) # 批量归一化self.add_module('relu1', nn.ReLU(inplace=True)) # ReLU层self.add_module('conv1', nn.Conv2d(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False)) # 表示其输出为4*k 其中bn_size等于4,growth_rate为k 不改变大小,只改变通道的个数self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)), # 批量归一化self.add_module('relu2', nn.ReLU(inplace=True)) # 激活函数self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, stride=1, padding=1, bias=False)) # 输出为growth_rate:表示输出通道数为k 提取特征self.drop_rate = drop_ratedef forward(self, x):new_features = super(_DenseLayer, self).forward(x)if self.drop_rate > 0:new_features = F.dropout(new_features, p=self.drop_rate, training=self.training)return torch.cat([x, new_features], 1) # 通道维度连接class _DenseBlock(nn.Sequential): # 构建稠密块def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate): # 密集块中密集层的数量,第二参数是输入通道数量super(_DenseBlock, self).__init__()for i in range(num_layers):layer = _DenseLayer(num_input_features + i * growth_rate, growth_rate, bn_size, drop_rate)self.add_module('denselayer%d' % (i + 1), layer)class _Transition(nn.Sequential):def __init__(self, num_input_features, num_output_features):# 输入通道数 输出通道数super(_Transition, self).__init__()self.add_module('norm', nn.BatchNorm2d(num_input_features))self.add_module('relu', nn.ReLU(inplace=True))self.add_module('conv', nn.Conv2d(num_input_features, num_output_features,kernel_size=1, stride=1, bias=False))self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2))class DenseNet(nn.Module):def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16), num_init_features=64, bn_size=4, compression_rate=0.5, drop_rate=0, num_classes=1000):super(DenseNet, self).__init__()# First convolutionself.features = nn.Sequential(OrderedDict([('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)),('norm0', nn.BatchNorm2d(num_init_features)),('relu0', nn.ReLU(inplace=True)),('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),]))# Each denseblocknum_features = num_init_featuresfor i, num_layers in enumerate(block_config):block = _DenseBlock(num_layers=num_layers, num_input_features=num_features,bn_size=bn_size, growth_rate=growth_rate, drop_rate=drop_rate)self.features.add_module('denseblock%d' % (i + 1), block)num_features += num_layers * growth_rateif i != len(block_config) - 1:transition = _Transition(num_features, int(num_features*compression_rate))self.features.add_module('transition%d' % (i + 1), transition)num_features = int(num_features*compression_rate)# Final batch normself.features.add_module('norm5', nn.BatchNorm2d(num_features))self.features.add_module('relu5', nn.ReLU(inplace=True))# classification layerself.classifier = nn.Linear(num_features, num_classes)# Official init from torch repo.for m in self.modules():if isinstance(m, nn.Conv2d):nn.init.kaiming_normal(m.weight)elif isinstance(m, nn.BatchNorm2d):nn.init.constant_(m.bias, 0)nn.init.constant_(m.weight, 1)elif isinstance(m, nn.Linear):nn.init.constant_(m.bias, 0)def forward(self, x):features = self.features(x)out = F.avg_pool2d(features, kernel_size=7, stride=1).view(features.size(0), -1)out = self.classifier(out)return out
2、构建DenseNet121
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)densenet121 = DenseNet(num_init_features=64,growth_rate=32,block_config=(6, 12, 24, 16),num_classes=len(classeNames))model = densenet121.to(device)
print(model)
# 统计模型参数量以及其他指标
import torchsummary as summary
summary.summary(model, (3, 224, 224))
四、训练模型
1、编写训练函数
# 训练循环
def train(dataloader, model, loss_fn, optimizer):size = len(dataloader.dataset) # 训练集的大小num_batches = len(dataloader) # 批次数目, (size/batch_size,向上取整)train_loss, train_acc = 0, 0 # 初始化训练损失和正确率for X, y in dataloader: # 获取图片及其标签X, y = X.to(device), y.to(device)# 计算预测误差pred = model(X) # 网络输出loss = loss_fn(pred, y) # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失# 反向传播optimizer.zero_grad() # grad属性归零loss.backward() # 反向传播optimizer.step() # 每一步自动更新# 记录acc与losstrain_acc += (pred.argmax(1) == y).type(torch.float).sum().item()train_loss += loss.item()train_acc /= sizetrain_loss /= num_batchesreturn train_acc, train_loss
2、编写测试函数
def test (dataloader, model, loss_fn):size = len(dataloader.dataset) # 测试集的大小num_batches = len(dataloader) # 批次数目, (size/batch_size,向上取整)test_loss, test_acc = 0, 0# 当不进行训练时,停止梯度更新,节省计算内存消耗with torch.no_grad():for imgs, target in dataloader:imgs, target = imgs.to(device), target.to(device)# 计算losstarget_pred = model(imgs)loss = loss_fn(target_pred, target)test_loss += loss.item()test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()test_acc /= sizetest_loss /= num_batchesreturn test_acc, test_loss
3、正式训练
import copyoptimizer = torch.optim.Adam(model.parameters(), lr= 1e-4)
loss_fn = nn.CrossEntropyLoss() # 创建损失函数epochs = 20train_loss = []
train_acc = []
test_loss = []
test_acc = []best_acc = 0for epoch in range(epochs):model.train()epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)model.eval()epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)if epoch_test_acc > best_acc:best_acc = epoch_test_accbest_model = copy.deepcopy(model)train_acc.append(epoch_train_acc)train_loss.append(epoch_train_loss)test_acc.append(epoch_test_acc)test_loss.append(epoch_test_loss)# 获取当前的学习率lr = optimizer.state_dict()['param_groups'][0]['lr']template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}, Lr:{:.2E}')print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss,epoch_test_acc*100, epoch_test_loss, lr))PATH = './best_model.pth'
torch.save(best_model.state_dict(), PATH)
print('Done')
Epoch: 1, Train_acc:49.8%, Train_loss:5.053, Test_acc:65.5%, Test_loss:3.452, Lr:1.00E-04
Epoch: 2, Train_acc:73.5%, Train_loss:2.091, Test_acc:72.6%, Test_loss:1.617, Lr:1.00E-04
Epoch: 3, Train_acc:81.2%, Train_loss:0.919, Test_acc:77.9%, Test_loss:0.826, Lr:1.00E-04
Epoch: 4, Train_acc:84.5%, Train_loss:0.600, Test_acc:81.4%, Test_loss:0.747, Lr:1.00E-04
Epoch: 5, Train_acc:88.1%, Train_loss:0.444, Test_acc:77.0%, Test_loss:0.736, Lr:1.00E-04
Epoch: 6, Train_acc:91.6%, Train_loss:0.285, Test_acc:83.2%, Test_loss:0.607, Lr:1.00E-04
Epoch: 7, Train_acc:94.5%, Train_loss:0.248, Test_acc:74.3%, Test_loss:0.903, Lr:1.00E-04
Epoch: 8, Train_acc:91.8%, Train_loss:0.275, Test_acc:77.0%, Test_loss:0.535, Lr:1.00E-04
Epoch: 9, Train_acc:96.5%, Train_loss:0.160, Test_acc:82.3%, Test_loss:0.387, Lr:1.00E-04
Epoch:10, Train_acc:97.6%, Train_loss:0.175, Test_acc:86.7%, Test_loss:0.476, Lr:1.00E-04
Epoch:11, Train_acc:94.7%, Train_loss:0.219, Test_acc:85.0%, Test_loss:0.556, Lr:1.00E-04
Epoch:12, Train_acc:98.0%, Train_loss:0.139, Test_acc:88.5%, Test_loss:0.394, Lr:1.00E-04
Epoch:13, Train_acc:95.8%, Train_loss:0.202, Test_acc:84.1%, Test_loss:0.351, Lr:1.00E-04
Epoch:14, Train_acc:95.8%, Train_loss:0.156, Test_acc:83.2%, Test_loss:0.513, Lr:1.00E-04
Epoch:15, Train_acc:98.0%, Train_loss:0.103, Test_acc:80.5%, Test_loss:0.572, Lr:1.00E-04
Epoch:16, Train_acc:96.2%, Train_loss:0.145, Test_acc:77.9%, Test_loss:0.523, Lr:1.00E-04
Epoch:17, Train_acc:98.9%, Train_loss:0.083, Test_acc:84.1%, Test_loss:0.461, Lr:1.00E-04
Epoch:18, Train_acc:99.1%, Train_loss:0.065, Test_acc:81.4%, Test_loss:0.491, Lr:1.00E-04
Epoch:19, Train_acc:98.0%, Train_loss:0.122, Test_acc:81.4%, Test_loss:0.470, Lr:1.00E-04
Epoch:20, Train_acc:99.1%, Train_loss:0.061, Test_acc:84.1%, Test_loss:0.390, Lr:1.00E-04
Done
五、结果可视化
1、Loss与Accuracy图
# coding=utf-8
import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore") #忽略警告信息
plt.rcParams['figure.dpi'] = 100 #分辨率epochs_range = range(epochs)plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
2、模型评估
best_model.load_state_dict(torch.load(PATH), map_location=device)
epoch_test_acc, epoch_test_loss = test(test_dl, best_model, loss_fn)
print(epoch_test_acc, epoch_test_loss)
0.8849557522123894 0.3885981977218762