当前位置: 首页 > article >正文

第J3-1周:DenseNet算法实现乳腺癌识别

  • 🍨 本文为🔗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 tf

gpus = 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 plt

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

import os, PIL, pathlib
import numpy as np

from tensorflow import keras
from keras import layers, models

data_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 = 224

train_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_size

train_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 OrderedDict

class _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_rate

    def 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 convolution
        self.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 denseblock
        num_features = num_init_features
        for 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_rate
            if 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 norm
        self.features.add_module('norm5', nn.BatchNorm2d(num_features))
        self.features.add_module('relu5', nn.ReLU(inplace=True))

        # classification layer
        self.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与loss
        train_acc  += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()

    train_acc  /= size
    train_loss /= num_batches

    return 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)

            # 计算loss
            target_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  /= size
    test_loss /= num_batches

    return test_acc, test_loss

3、正式训练

import copy

optimizer  = torch.optim.Adam(model.parameters(), lr= 1e-4)
loss_fn    = nn.CrossEntropyLoss() # 创建损失函数

epochs     = 20

train_loss = []
train_acc  = []
test_loss  = []
test_acc   = []

best_acc = 0

for 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_acc
        best_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


http://www.kler.cn/news/355132.html

相关文章:

  • spring-boot学习(2)
  • 从美的第二届远见者大会看AI与能源转型的未来
  • 牛客习题—线性DP 【mari和shiny】C++
  • Java后端基础自测
  • 【人工智能/计算机工程/大数据】第五届人工智能与计算工程国际学术会议(ICAICE 2024,2024年11月8-10日)
  • Android——发送彩信
  • ANSYS Workbench纤维混凝土3D
  • 笔试强训10.19
  • Vue(3) 组件
  • [搜索] 质数
  • openresty通过header_filter_by_lua记录特定的请求头和特定的响应头到日志文件
  • 人工智能产业链发展状况
  • 设计模式之组合模式(Composite)
  • Torch JIT加速推理
  • Matlab中实现类属性仅在首次创建类实例时初始化
  • 芯知识 | NVH-FLASH语音芯片支持平台做语音—打造音频IC技术革新
  • 隐私保护机器学习技术与实践
  • 【C++标准模版库】unordered_map和unordered_set的介绍及使用
  • DMP驱动库
  • 【H5】关于react移动端H5的滚动吸顶方案实践总结