Advertisement

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

阅读量:

前期工作

  • 语言环境:Python3.9.18
  • 编译器:Jupyter Lab
  • 深度学习环境:Pytorch 1.12.1

1.设置GPU

复制代码
    import torch
    import torch.nn as nn
    import torchvision
    from torchvision import transforms,datasets
    
    import os,PIL,random,pathlib
    
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    device
    
    
      
      
      
      
      
      
      
      
      
    

2. 导入数据

复制代码
    data_dir = "F:/365data/P4/"
    data_dir = pathlib.Path(data_dir)
    
    data_path = list(data_dir.glob('*'))
    classNames = [str(path).split('\ ')[3] for path in data_path]
    classNames
    
    
      
      
      
      
      
      
    
复制代码
    transforms = transforms.Compose([
    transforms.Resize([224,224]),
    transforms.ToTensor(),
    transforms.Normalize(
        mean=[0.485,0.456,0.406],
        std=[0.229,0.224,0.225]
    )
    ])
    
    total_dataset = datasets.ImageFolder("F:/365data/P4/",transform=transforms)
    total_dataset
    
    
      
      
      
      
      
      
      
      
      
      
      
    

3.划分训练集测试集

复制代码
    train_size = int(0.8*len(total_dataset))
    test_size = len(total_dataset) - train_size
    train_dataset,test_dataset = torch.utils.data.random_split(total_dataset,[train_size,test_size])
    train_dataset,test_dataset
    
    
      
      
      
      
    
复制代码
    batch_size = 32
    
    train_dl = torch.utils.data.DataLoader(train_dataset,
                                       batch_size = batch_size,
                                       shuffle = True,
                                       num_workers = 1)
    
    test_dl = torch.utils.data.DataLoader(test_dataset,
                                      batch_size = batch_size,
                                      shuffle = True,
                                      num_workers = 1)
    
    
      
      
      
      
      
      
      
      
      
      
      
    
复制代码
    for X,y in test_dl:
    print('Shape of X:',X.shape)
    print('shape of y:',y.shape,y.dtype)
    break
    
    
      
      
      
      
    

4.数据可视化

复制代码
    import matplotlib.pyplot as plt 
    from PIL import Image
    
    imagefolder = "F:/365data/J3/1/"
    imagefile = [f for f in os.listdir(imagefolder) if f.endswith(('.jpeg','.jpg','.png'))]
    
    fig,axes = plt.subplots(3,8,figsize=(16,6))
    
    for ax,imgfile in zip(axes.flat,imagefile):
    img_path = os.path.join(imagefolder,imgfile)
    img = Image.open(img_path)
    ax.imshow(img)
    ax.axis('off')
    
    plt.tight_layout()
    plt.show()
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

二、构建DenseNet模型

1.构造模型

复制代码
    import torch.nn.functional as F
    from collections import OrderedDict
    
    class DenseLayer(nn.Sequential):
    def __init__(self,in_channel,growth_rate,bn_size,drop_rate):
        super(DenseLayer,self).__init__()
        self.add_module('norm1',nn.BatchNorm2d(in_channel))
        self.add_module('relu1',nn.ReLU(inplace=True))
        self.add_module('conv1',nn.Conv2d(in_channel,bn_size*growth_rate,kernel_size=1,stride=1))
        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))
    
        self.drop_rate = drop_rate
    
    def forward(self,x):
        new_feature = super(DenseLayer,self).forward(x)
        if self.drop_rate > 0:
            new_feature = F.dropout(new_feature,p=self.drop_rate,training=self.training)
        return torch.cat([x,new_feature],1)
    
    class DenseBlock(nn.Sequential):
    def __init__(self,num_layers,in_channel,bn_size,growth_rate,drop_rate):
        super(DenseBlock,self).__init__()
        for i in range(num_layers):
            layer = DenseLayer(in_channel+i*growth_rate,growth_rate,bn_size,drop_rate)
            self.add_module('denselayer%d'%(i+1,),layer)
    
    class Transition(nn.Sequential):
    def __init__(self,in_channel,out_channel):
        super(Transition,self).__init__()
        self.add_module('norm',nn.BatchNorm2d(in_channel))
        self.add_module('relu',nn.ReLU(inplace=True))
        self.add_module('conv',nn.Conv2d(in_channel,out_channel,kernel_size=1,stride=1))
        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__()
        self.features = nn.Sequential(OrderedDict([
            ('conv0',nn.Conv2d(3,num_init_features,kernel_size=7,stride=2,padding=3)),
            ('norm0',nn.BatchNorm2d(num_init_features)),
            ('relu0',nn.ReLU(inplace=True)),
            ('pool0',nn.MaxPool2d(kernel_size=3,stride=2,padding=1))
        ]))
        num_features = num_init_features
        for i,num_layers in enumerate(block_config):
            block = DenseBlock(num_layers,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)
    
        self.features.add_module('norm5',nn.BatchNorm2d(num_features))
        self.features.add_module('relu5',nn.ReLU(inplace=True))
        self.classifier = nn.Linear(num_features,num_classes)
    
        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):
        x = self.features(x)
        x = F.avg_pool2d(x,7,stride=1).view(x.size(0),-1)
        x = self.classifier(x)
        return x       
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

这里可以调用官方的预训练权重,只要忽略最后的全连接层权重就好了

复制代码
    import re
    import torch.utils.model_zoo as model_zoo
    from torchvision.models.densenet import model_urls
    
    def densenet121(pretrained=False,**kwargs):
    model = DenseNet(num_init_features=64,growth_rate=32,block_config=(6,12,24,16),num_classes=len(classNames),**kwargs)
    
    if pretrained:
        pattern = re.compile(r'^(.*denselayer\d+\.(?:norm|relu|conv))\.((?:[12])\.(?:weight|bias|running_mean|running_var))$')
        state_dict = model_zoo.load_url(model_urls['densenet121'])
        for key in list(state_dict.keys()):
            res = pattern.match(key)
            if res:
                new_key = res.group(1) + res.group(2)
                state_dict[new_key] = state_dict[key]
                del state_dict[key]
        state_dict.pop('classifier.weight')
        state_dict.pop('classifier.bias')
        model.load_state_dict(state_dict,strict=False)
        nn.init.kaiming_normal_(model.classifier.weight)
        nn.init.zeros_(model.classifier.bias)
    
    return model
    
    model = densenet121(pretrained=False).to(device)
    model
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

DenseNet与ResNetV的最大区别在于:ResNetV的残差块中,跳跃连接的值与主干的输出是进行的矩阵乘法;DenseNet则是将跳跃连接的输出与主干连接进行堆叠

2. 统计模型参数

复制代码
    # 统计模型参数量以及其他指标
    import torchsummary as summary
    summary.summary(model, (3, 224, 224))
    
    
      
      
      
    

三、训练模型

1. 构建训练函数

复制代码
    def train(dataloader,model,optimizer,loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    
    train_acc,train_loss = 0,0
    
    for X,y in dataloader:
        X,y = X.to(device),y.to(device)
    
        pred = model(X)
        loss = loss_fn(pred,y)
    
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    
        train_loss += loss.item()
        train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
    
    train_loss /= num_batches
    train_acc /= size
    
    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. 优化器和学习率

复制代码
    loss_fn = nn.CrossEntropyLoss()
    learn_rate = 1e-4
    opt = torch.optim.Adam(model.parameters(),lr=learn_rate)
    
    
      
      
      
    

4. 训练

复制代码
    import copy 
    
    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,opt,loss_fn)
    
    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 = opt.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 = 'F:/365data/J3best_model.pth'  # 保存的参数文件名
    torch.save(best_model.state_dict(), PATH)
    
    print('Done')
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
复制代码
    Epoch: 1, Train_acc:84.7%, Train_loss:0.357, Test_acc:87.8%, Test_loss:0.297, Lr:1.00E-04
    Epoch: 2, Train_acc:88.1%, Train_loss:0.292, Test_acc:86.5%, Test_loss:0.329, Lr:1.00E-04
    Epoch: 3, Train_acc:89.2%, Train_loss:0.268, Test_acc:89.9%, Test_loss:0.259, Lr:1.00E-04
    Epoch: 4, Train_acc:90.0%, Train_loss:0.243, Test_acc:90.2%, Test_loss:0.244, Lr:1.00E-04
    Epoch: 5, Train_acc:90.8%, Train_loss:0.233, Test_acc:90.7%, Test_loss:0.223, Lr:1.00E-04
    Epoch: 6, Train_acc:91.6%, Train_loss:0.210, Test_acc:90.5%, Test_loss:0.242, Lr:1.00E-04
    Epoch: 7, Train_acc:91.8%, Train_loss:0.203, Test_acc:91.6%, Test_loss:0.201, Lr:1.00E-04
    Epoch: 8, Train_acc:92.5%, Train_loss:0.190, Test_acc:91.8%, Test_loss:0.228, Lr:1.00E-04
    Epoch: 9, Train_acc:93.1%, Train_loss:0.174, Test_acc:92.5%, Test_loss:0.201, Lr:1.00E-04
    Epoch:10, Train_acc:93.7%, Train_loss:0.165, Test_acc:86.5%, Test_loss:0.337, Lr:1.00E-04
    Epoch:11, Train_acc:93.6%, Train_loss:0.160, Test_acc:91.3%, Test_loss:0.226, Lr:1.00E-04
    Epoch:12, Train_acc:94.4%, Train_loss:0.141, Test_acc:91.6%, Test_loss:0.213, Lr:1.00E-04
    Epoch:13, Train_acc:94.6%, Train_loss:0.140, Test_acc:86.1%, Test_loss:0.344, Lr:1.00E-04
    Epoch:14, Train_acc:95.5%, Train_loss:0.124, Test_acc:83.2%, Test_loss:0.536, Lr:1.00E-04
    Epoch:15, Train_acc:94.2%, Train_loss:0.150, Test_acc:90.9%, Test_loss:0.232, Lr:1.00E-04
    Epoch:16, Train_acc:96.3%, Train_loss:0.104, Test_acc:92.1%, Test_loss:0.212, Lr:1.00E-04
    Epoch:17, Train_acc:95.4%, Train_loss:0.117, Test_acc:92.1%, Test_loss:0.230, Lr:1.00E-04
    Epoch:18, Train_acc:97.2%, Train_loss:0.073, Test_acc:93.2%, Test_loss:0.226, Lr:1.00E-04
    Epoch:19, Train_acc:97.2%, Train_loss:0.076, Test_acc:91.7%, Test_loss:0.252, Lr:1.00E-04
    Epoch:20, Train_acc:97.4%, Train_loss:0.081, Test_acc:91.9%, Test_loss:0.263, Lr:1.00E-04
    Done
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    

训练准确率较高,但是训练时间太长了

复制代码
    import matplotlib.pyplot as plt
    #隐藏警告
    import warnings
    warnings.filterwarnings("ignore")               #忽略警告信息
    plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
    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()
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
在这里插入图片描述

全部评论 (0)

还没有任何评论哟~