深度学习Day-21:ResNet与DenseNet结合

 🍨 本文为:[🔗365天深度学习训练营] 中的学习记录博客
 🍖 原作者:[K同学啊 | 接辅导、项目定制]

要求:

  1. 探索ResNet与DenseNet结合的可能性
  2. 根据模型特性构建新的模型框架
  3. 验证改进后模型的效果

一、 基础配置

  • 语言环境:Python3.8
  • 编译器选择:Pycharm
  • 深度学习环境:
    • torch==1.12.1+cu113
    • torchvision==0.13.1+cu113

二、 前期准备 

1.设置GPU

import pathlib
import torch
import torch.nn as nn
from torchvision import transforms, datasets

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

print(device)

2. 导入数据

本项目所采用的数据集未收录于公开数据中,故需要自己在文件目录中导入相应数据集合,并设置对应文件目录,以供后续学习过程中使用。

运行下述代码:

data_dir = './data/bird_photos'
data_dir = pathlib.Path(data_dir)

data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[2] for path in data_paths]
print(classeNames)

image_count = len(list(data_dir.glob('*/*')))
print("图片总数为:", image_count)

得到如下输出:

['Bananaquit', 'Black Skimmer', 'Black Throated Bushtiti', 'Cockatoo']
图片总数为: 565

接下来,我们通过transforms.Compose对整个数据集进行预处理:

train_transforms = transforms.Compose([
    transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸
    # transforms.RandomHorizontalFlip(), # 随机水平翻转
    transforms.ToTensor(),  # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
    transforms.Normalize(  # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225])  # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])

test_transform = transforms.Compose([
    transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸
    transforms.ToTensor(),  # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
    transforms.Normalize(  # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225])  # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])

total_data = datasets.ImageFolder("./data/bird_photos/", transform=train_transforms)
print(total_data.class_to_idx)

得到如下输出:

{'Bananaquit': 0, 'Black Skimmer': 1, 'Black Throated Bushtiti': 2, 'Cockatoo': 3}

3. 划分数据集

 此处数据集需要做按比例划分的操作:

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

接下来,根据划分得到的训练集和验证集对数据集进行包装:

batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset,
                                       batch_size=batch_size,
                                       shuffle=True,
                                       num_workers=0)
test_dl = torch.utils.data.DataLoader(test_dataset,
                                      batch_size=batch_size,
                                      shuffle=True,
                                      num_workers=0)

并通过:

for X, y in test_dl:
    print("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break

输出测试数据集的数据分布情况:

Shape of X [N, C, H, W]:  torch.Size([32, 3, 224, 224])
Shape of y:  torch.Size([32]) torch.int64

4.搭建模型

DPN网络通过High Order RNN(HORNN)将ResNet和DenseNet进行了融合,实现了ResNet特征复用及DenseNet特征生成,在保持了二者复用特征+挖掘特征能力的同时,避免了像原始DenseNet那样臃肿的结构。

1.模型搭建


class Block(nn.Module):
    def __init__(self, in_channel, mid_channel, out_channel, dense_channel, stride, groups, is_shortcut=False):
        # in_channel,是输入通道数,mid_channel是中间经历的通道数,out_channels是经过一次板块之后的输出通道数。
        # dense_channels设置这个参数的原因就是一边进行着resnet方式的卷积运算,另一边也同时进行着dense的卷积计算,之后特征图融合形成新的特征图
        super().__init__()
        self.is_shortcut = is_shortcut
        self.out_channel = out_channel
        self.conv1 = nn.Sequential(
            nn.Conv2d(in_channel, mid_channel, kernel_size=1, bias=False),
            nn.BatchNorm2d(mid_channel),
            nn.ReLU()
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(mid_channel, mid_channel, kernel_size=3, stride=stride, padding=1, groups=groups, bias=False),
            nn.BatchNorm2d(mid_channel),
            nn.ReLU()
        )
        self.conv3 = nn.Sequential(
            nn.Conv2d(mid_channel, out_channel + dense_channel, kernel_size=1, bias=False),
            nn.BatchNorm2d(out_channel + dense_channel)
        )
        if self.is_shortcut:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_channel, out_channel + dense_channel, kernel_size=3, padding=1, stride=stride, bias=False),
                nn.BatchNorm2d(out_channel + dense_channel)
            )
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        a = x
        x = self.conv1(x)
        x = self.conv2(x)
        x = self.conv3(x)
        if self.is_shortcut:
            a = self.shortcut(a)
        d = self.out_channel
        x = torch.cat([a[:, :d, :, :] + x[:, :d, :, :], a[:, d:, :, :], x[:, d:, :, :]], dim=1)
        x = self.relu(x)
        return x


class DPN(nn.Module):
    def __init__(self, cfg):
        super(DPN, self).__init__()
        self.group = cfg['group']
        self.in_channel = cfg['in_channel']
        mid_channels = cfg['mid_channels']
        out_channels = cfg['out_channels']
        dense_channels = cfg['dense_channels']
        num = cfg['num']
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, self.in_channel, 7, stride=2, padding=3, bias=False, padding_mode='zeros'),
            nn.BatchNorm2d(self.in_channel),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=0)
        )
        self.conv2 = self._make_layers(mid_channels[0], out_channels[0], dense_channels[0], num[0], stride=1)
        self.conv3 = self._make_layers(mid_channels[1], out_channels[1], dense_channels[1], num[1], stride=2)
        self.conv4 = self._make_layers(mid_channels[2], out_channels[2], dense_channels[2], num[2], stride=2)
        self.conv5 = self._make_layers(mid_channels[3], out_channels[3], dense_channels[3], num[3], stride=2)
        self.pool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(cfg['out_channels'][3] + (num[3] + 1) * cfg['dense_channels'][3], cfg['classes'])  # fc层需要计算

    def _make_layers(self, mid_channel, out_channel, dense_channel, num, stride=2):
        layers = []
        layers.append(Block(self.in_channel, mid_channel, out_channel, dense_channel, stride=stride, groups=self.group,
                            is_shortcut=True))
        # block_1里面is_shortcut=True就是resnet中的shortcut连接,将浅层的特征进行一次卷积之后与进行三次卷积的特征图相加
        # 后面几次相同的板块is_shortcut=False简单的理解就是一个多次重复的板块,第一次利用就可以满足浅层特征的利用,后面重复的不在需要
        self.in_channel = out_channel + dense_channel * 2
        # 由于里面包含dense这种一直在叠加的特征图计算,
        # 所以第一次是2倍的dense_channel,后面每次一都会多出1倍,所以有(i+2)*dense_channel
        for i in range(1, num):
            layers.append(Block(self.in_channel, mid_channel, out_channel, dense_channel, stride=1, groups=self.group))
            self.in_channel = self.in_channel + dense_channel
            # self.in_channel = out_channel + (i+2)*dense_channel
        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = self.conv3(x)
        x = self.conv4(x)
        x = self.conv5(x)
        x = self.pool(x)
        x = torch.flatten(x, start_dim=1)
        x = self.fc(x)
        return x


def DPN92(n_class=10):
    cfg = {
        'group': 32,
        'in_channel': 64,
        'mid_channels': (96, 192, 384, 768),
        'out_channels': (256, 512, 1024, 2048),
        'dense_channels': (16, 32, 24, 128),
        'num': (3, 4, 20, 3),
        'classes': (n_class)
    }
    return DPN(cfg)


def DPN98(n_class=10):
    cfg = {
        'group': 40,
        'in_channel': 96,
        'mid_channels': (160, 320, 640, 1280),
        'out_channels': (256, 512, 1024, 2048),
        'dense_channels': (16, 32, 32, 128),
        'num': (3, 6, 20, 3),
        'classes': (n_class)
    }
    return DPN(cfg)

2.查看模型信息

x = torch.randn(2, 3, 224, 224)
model = DPN98(4)
model.to(device)
import torchsummary as summary
summary.summary(model, (3, 224, 224))

得到如下输出:

----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1         [-1, 96, 112, 112]          14,112
       BatchNorm2d-2         [-1, 96, 112, 112]             192
              ReLU-3         [-1, 96, 112, 112]               0
         MaxPool2d-4           [-1, 96, 55, 55]               0
            Conv2d-5          [-1, 160, 55, 55]          15,360
       BatchNorm2d-6          [-1, 160, 55, 55]             320
              ReLU-7          [-1, 160, 55, 55]               0
            Conv2d-8          [-1, 160, 55, 55]           5,760
       BatchNorm2d-9          [-1, 160, 55, 55]             320
             ReLU-10          [-1, 160, 55, 55]               0
           Conv2d-11          [-1, 272, 55, 55]          43,520
      BatchNorm2d-12          [-1, 272, 55, 55]             544
           Conv2d-13          [-1, 272, 55, 55]         235,008
      BatchNorm2d-14          [-1, 272, 55, 55]             544
             ReLU-15          [-1, 288, 55, 55]               0
            Block-16          [-1, 288, 55, 55]               0
           Conv2d-17          [-1, 160, 55, 55]          46,080
      BatchNorm2d-18          [-1, 160, 55, 55]             320
             ReLU-19          [-1, 160, 55, 55]               0
           Conv2d-20          [-1, 160, 55, 55]           5,760
      BatchNorm2d-21          [-1, 160, 55, 55]             320
             ReLU-22          [-1, 160, 55, 55]               0
           Conv2d-23          [-1, 272, 55, 55]          43,520
      BatchNorm2d-24          [-1, 272, 55, 55]             544
             ReLU-25          [-1, 304, 55, 55]               0
            Block-26          [-1, 304, 55, 55]               0
           Conv2d-27          [-1, 160, 55, 55]          48,640
      BatchNorm2d-28          [-1, 160, 55, 55]             320
             ReLU-29          [-1, 160, 55, 55]               0
           Conv2d-30          [-1, 160, 55, 55]           5,760
      BatchNorm2d-31          [-1, 160, 55, 55]             320
             ReLU-32          [-1, 160, 55, 55]               0
           Conv2d-33          [-1, 272, 55, 55]          43,520
      BatchNorm2d-34          [-1, 272, 55, 55]             544
             ReLU-35          [-1, 320, 55, 55]               0
            Block-36          [-1, 320, 55, 55]               0
           Conv2d-37          [-1, 320, 55, 55]         102,400
      BatchNorm2d-38          [-1, 320, 55, 55]             640
             ReLU-39          [-1, 320, 55, 55]               0
           Conv2d-40          [-1, 320, 28, 28]          23,040
      BatchNorm2d-41          [-1, 320, 28, 28]             640
             ReLU-42          [-1, 320, 28, 28]               0
           Conv2d-43          [-1, 544, 28, 28]         174,080
      BatchNorm2d-44          [-1, 544, 28, 28]           1,088
           Conv2d-45          [-1, 544, 28, 28]       1,566,720
      BatchNorm2d-46          [-1, 544, 28, 28]           1,088
             ReLU-47          [-1, 576, 28, 28]               0
            Block-48          [-1, 576, 28, 28]               0
           Conv2d-49          [-1, 320, 28, 28]         184,320
      BatchNorm2d-50          [-1, 320, 28, 28]             640
             ReLU-51          [-1, 320, 28, 28]               0
           Conv2d-52          [-1, 320, 28, 28]          23,040
      BatchNorm2d-53          [-1, 320, 28, 28]             640
             ReLU-54          [-1, 320, 28, 28]               0
           Conv2d-55          [-1, 544, 28, 28]         174,080
      BatchNorm2d-56          [-1, 544, 28, 28]           1,088
             ReLU-57          [-1, 608, 28, 28]               0
            Block-58          [-1, 608, 28, 28]               0
           Conv2d-59          [-1, 320, 28, 28]         194,560
      BatchNorm2d-60          [-1, 320, 28, 28]             640
             ReLU-61          [-1, 320, 28, 28]               0
           Conv2d-62          [-1, 320, 28, 28]          23,040
      BatchNorm2d-63          [-1, 320, 28, 28]             640
             ReLU-64          [-1, 320, 28, 28]               0
           Conv2d-65          [-1, 544, 28, 28]         174,080
      BatchNorm2d-66          [-1, 544, 28, 28]           1,088
             ReLU-67          [-1, 640, 28, 28]               0
            Block-68          [-1, 640, 28, 28]               0
           Conv2d-69          [-1, 320, 28, 28]         204,800
      BatchNorm2d-70          [-1, 320, 28, 28]             640
             ReLU-71          [-1, 320, 28, 28]               0
           Conv2d-72          [-1, 320, 28, 28]          23,040
      BatchNorm2d-73          [-1, 320, 28, 28]             640
             ReLU-74          [-1, 320, 28, 28]               0
           Conv2d-75          [-1, 544, 28, 28]         174,080
      BatchNorm2d-76          [-1, 544, 28, 28]           1,088
             ReLU-77          [-1, 672, 28, 28]               0
            Block-78          [-1, 672, 28, 28]               0
           Conv2d-79          [-1, 320, 28, 28]         215,040
      BatchNorm2d-80          [-1, 320, 28, 28]             640
             ReLU-81          [-1, 320, 28, 28]               0
           Conv2d-82          [-1, 320, 28, 28]          23,040
      BatchNorm2d-83          [-1, 320, 28, 28]             640
             ReLU-84          [-1, 320, 28, 28]               0
           Conv2d-85          [-1, 544, 28, 28]         174,080
      BatchNorm2d-86          [-1, 544, 28, 28]           1,088
             ReLU-87          [-1, 704, 28, 28]               0
            Block-88          [-1, 704, 28, 28]               0
           Conv2d-89          [-1, 320, 28, 28]         225,280
      BatchNorm2d-90          [-1, 320, 28, 28]             640
             ReLU-91          [-1, 320, 28, 28]               0
           Conv2d-92          [-1, 320, 28, 28]          23,040
      BatchNorm2d-93          [-1, 320, 28, 28]             640
             ReLU-94          [-1, 320, 28, 28]               0
           Conv2d-95          [-1, 544, 28, 28]         174,080
      BatchNorm2d-96          [-1, 544, 28, 28]           1,088
             ReLU-97          [-1, 736, 28, 28]               0
            Block-98          [-1, 736, 28, 28]               0
           Conv2d-99          [-1, 640, 28, 28]         471,040
     BatchNorm2d-100          [-1, 640, 28, 28]           1,280
            ReLU-101          [-1, 640, 28, 28]               0
          Conv2d-102          [-1, 640, 14, 14]          92,160
     BatchNorm2d-103          [-1, 640, 14, 14]           1,280
            ReLU-104          [-1, 640, 14, 14]               0
          Conv2d-105         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-106         [-1, 1056, 14, 14]           2,112
          Conv2d-107         [-1, 1056, 14, 14]       6,994,944
     BatchNorm2d-108         [-1, 1056, 14, 14]           2,112
            ReLU-109         [-1, 1088, 14, 14]               0
           Block-110         [-1, 1088, 14, 14]               0
          Conv2d-111          [-1, 640, 14, 14]         696,320
     BatchNorm2d-112          [-1, 640, 14, 14]           1,280
            ReLU-113          [-1, 640, 14, 14]               0
          Conv2d-114          [-1, 640, 14, 14]          92,160
     BatchNorm2d-115          [-1, 640, 14, 14]           1,280
            ReLU-116          [-1, 640, 14, 14]               0
          Conv2d-117         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-118         [-1, 1056, 14, 14]           2,112
            ReLU-119         [-1, 1120, 14, 14]               0
           Block-120         [-1, 1120, 14, 14]               0
          Conv2d-121          [-1, 640, 14, 14]         716,800
     BatchNorm2d-122          [-1, 640, 14, 14]           1,280
            ReLU-123          [-1, 640, 14, 14]               0
          Conv2d-124          [-1, 640, 14, 14]          92,160
     BatchNorm2d-125          [-1, 640, 14, 14]           1,280
            ReLU-126          [-1, 640, 14, 14]               0
          Conv2d-127         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-128         [-1, 1056, 14, 14]           2,112
            ReLU-129         [-1, 1152, 14, 14]               0
           Block-130         [-1, 1152, 14, 14]               0
          Conv2d-131          [-1, 640, 14, 14]         737,280
     BatchNorm2d-132          [-1, 640, 14, 14]           1,280
            ReLU-133          [-1, 640, 14, 14]               0
          Conv2d-134          [-1, 640, 14, 14]          92,160
     BatchNorm2d-135          [-1, 640, 14, 14]           1,280
            ReLU-136          [-1, 640, 14, 14]               0
          Conv2d-137         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-138         [-1, 1056, 14, 14]           2,112
            ReLU-139         [-1, 1184, 14, 14]               0
           Block-140         [-1, 1184, 14, 14]               0
          Conv2d-141          [-1, 640, 14, 14]         757,760
     BatchNorm2d-142          [-1, 640, 14, 14]           1,280
            ReLU-143          [-1, 640, 14, 14]               0
          Conv2d-144          [-1, 640, 14, 14]          92,160
     BatchNorm2d-145          [-1, 640, 14, 14]           1,280
            ReLU-146          [-1, 640, 14, 14]               0
          Conv2d-147         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-148         [-1, 1056, 14, 14]           2,112
            ReLU-149         [-1, 1216, 14, 14]               0
           Block-150         [-1, 1216, 14, 14]               0
          Conv2d-151          [-1, 640, 14, 14]         778,240
     BatchNorm2d-152          [-1, 640, 14, 14]           1,280
            ReLU-153          [-1, 640, 14, 14]               0
          Conv2d-154          [-1, 640, 14, 14]          92,160
     BatchNorm2d-155          [-1, 640, 14, 14]           1,280
            ReLU-156          [-1, 640, 14, 14]               0
          Conv2d-157         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-158         [-1, 1056, 14, 14]           2,112
            ReLU-159         [-1, 1248, 14, 14]               0
           Block-160         [-1, 1248, 14, 14]               0
          Conv2d-161          [-1, 640, 14, 14]         798,720
     BatchNorm2d-162          [-1, 640, 14, 14]           1,280
            ReLU-163          [-1, 640, 14, 14]               0
          Conv2d-164          [-1, 640, 14, 14]          92,160
     BatchNorm2d-165          [-1, 640, 14, 14]           1,280
            ReLU-166          [-1, 640, 14, 14]               0
          Conv2d-167         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-168         [-1, 1056, 14, 14]           2,112
            ReLU-169         [-1, 1280, 14, 14]               0
           Block-170         [-1, 1280, 14, 14]               0
          Conv2d-171          [-1, 640, 14, 14]         819,200
     BatchNorm2d-172          [-1, 640, 14, 14]           1,280
            ReLU-173          [-1, 640, 14, 14]               0
          Conv2d-174          [-1, 640, 14, 14]          92,160
     BatchNorm2d-175          [-1, 640, 14, 14]           1,280
            ReLU-176          [-1, 640, 14, 14]               0
          Conv2d-177         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-178         [-1, 1056, 14, 14]           2,112
            ReLU-179         [-1, 1312, 14, 14]               0
           Block-180         [-1, 1312, 14, 14]               0
          Conv2d-181          [-1, 640, 14, 14]         839,680
     BatchNorm2d-182          [-1, 640, 14, 14]           1,280
            ReLU-183          [-1, 640, 14, 14]               0
          Conv2d-184          [-1, 640, 14, 14]          92,160
     BatchNorm2d-185          [-1, 640, 14, 14]           1,280
            ReLU-186          [-1, 640, 14, 14]               0
          Conv2d-187         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-188         [-1, 1056, 14, 14]           2,112
            ReLU-189         [-1, 1344, 14, 14]               0
           Block-190         [-1, 1344, 14, 14]               0
          Conv2d-191          [-1, 640, 14, 14]         860,160
     BatchNorm2d-192          [-1, 640, 14, 14]           1,280
            ReLU-193          [-1, 640, 14, 14]               0
          Conv2d-194          [-1, 640, 14, 14]          92,160
     BatchNorm2d-195          [-1, 640, 14, 14]           1,280
            ReLU-196          [-1, 640, 14, 14]               0
          Conv2d-197         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-198         [-1, 1056, 14, 14]           2,112
            ReLU-199         [-1, 1376, 14, 14]               0
           Block-200         [-1, 1376, 14, 14]               0
          Conv2d-201          [-1, 640, 14, 14]         880,640
     BatchNorm2d-202          [-1, 640, 14, 14]           1,280
            ReLU-203          [-1, 640, 14, 14]               0
          Conv2d-204          [-1, 640, 14, 14]          92,160
     BatchNorm2d-205          [-1, 640, 14, 14]           1,280
            ReLU-206          [-1, 640, 14, 14]               0
          Conv2d-207         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-208         [-1, 1056, 14, 14]           2,112
            ReLU-209         [-1, 1408, 14, 14]               0
           Block-210         [-1, 1408, 14, 14]               0
          Conv2d-211          [-1, 640, 14, 14]         901,120
     BatchNorm2d-212          [-1, 640, 14, 14]           1,280
            ReLU-213          [-1, 640, 14, 14]               0
          Conv2d-214          [-1, 640, 14, 14]          92,160
     BatchNorm2d-215          [-1, 640, 14, 14]           1,280
            ReLU-216          [-1, 640, 14, 14]               0
          Conv2d-217         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-218         [-1, 1056, 14, 14]           2,112
            ReLU-219         [-1, 1440, 14, 14]               0
           Block-220         [-1, 1440, 14, 14]               0
          Conv2d-221          [-1, 640, 14, 14]         921,600
     BatchNorm2d-222          [-1, 640, 14, 14]           1,280
            ReLU-223          [-1, 640, 14, 14]               0
          Conv2d-224          [-1, 640, 14, 14]          92,160
     BatchNorm2d-225          [-1, 640, 14, 14]           1,280
            ReLU-226          [-1, 640, 14, 14]               0
          Conv2d-227         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-228         [-1, 1056, 14, 14]           2,112
            ReLU-229         [-1, 1472, 14, 14]               0
           Block-230         [-1, 1472, 14, 14]               0
          Conv2d-231          [-1, 640, 14, 14]         942,080
     BatchNorm2d-232          [-1, 640, 14, 14]           1,280
            ReLU-233          [-1, 640, 14, 14]               0
          Conv2d-234          [-1, 640, 14, 14]          92,160
     BatchNorm2d-235          [-1, 640, 14, 14]           1,280
            ReLU-236          [-1, 640, 14, 14]               0
          Conv2d-237         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-238         [-1, 1056, 14, 14]           2,112
            ReLU-239         [-1, 1504, 14, 14]               0
           Block-240         [-1, 1504, 14, 14]               0
          Conv2d-241          [-1, 640, 14, 14]         962,560
     BatchNorm2d-242          [-1, 640, 14, 14]           1,280
            ReLU-243          [-1, 640, 14, 14]               0
          Conv2d-244          [-1, 640, 14, 14]          92,160
     BatchNorm2d-245          [-1, 640, 14, 14]           1,280
            ReLU-246          [-1, 640, 14, 14]               0
          Conv2d-247         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-248         [-1, 1056, 14, 14]           2,112
            ReLU-249         [-1, 1536, 14, 14]               0
           Block-250         [-1, 1536, 14, 14]               0
          Conv2d-251          [-1, 640, 14, 14]         983,040
     BatchNorm2d-252          [-1, 640, 14, 14]           1,280
            ReLU-253          [-1, 640, 14, 14]               0
          Conv2d-254          [-1, 640, 14, 14]          92,160
     BatchNorm2d-255          [-1, 640, 14, 14]           1,280
            ReLU-256          [-1, 640, 14, 14]               0
          Conv2d-257         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-258         [-1, 1056, 14, 14]           2,112
            ReLU-259         [-1, 1568, 14, 14]               0
           Block-260         [-1, 1568, 14, 14]               0
          Conv2d-261          [-1, 640, 14, 14]       1,003,520
     BatchNorm2d-262          [-1, 640, 14, 14]           1,280
            ReLU-263          [-1, 640, 14, 14]               0
          Conv2d-264          [-1, 640, 14, 14]          92,160
     BatchNorm2d-265          [-1, 640, 14, 14]           1,280
            ReLU-266          [-1, 640, 14, 14]               0
          Conv2d-267         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-268         [-1, 1056, 14, 14]           2,112
            ReLU-269         [-1, 1600, 14, 14]               0
           Block-270         [-1, 1600, 14, 14]               0
          Conv2d-271          [-1, 640, 14, 14]       1,024,000
     BatchNorm2d-272          [-1, 640, 14, 14]           1,280
            ReLU-273          [-1, 640, 14, 14]               0
          Conv2d-274          [-1, 640, 14, 14]          92,160
     BatchNorm2d-275          [-1, 640, 14, 14]           1,280
            ReLU-276          [-1, 640, 14, 14]               0
          Conv2d-277         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-278         [-1, 1056, 14, 14]           2,112
            ReLU-279         [-1, 1632, 14, 14]               0
           Block-280         [-1, 1632, 14, 14]               0
          Conv2d-281          [-1, 640, 14, 14]       1,044,480
     BatchNorm2d-282          [-1, 640, 14, 14]           1,280
            ReLU-283          [-1, 640, 14, 14]               0
          Conv2d-284          [-1, 640, 14, 14]          92,160
     BatchNorm2d-285          [-1, 640, 14, 14]           1,280
            ReLU-286          [-1, 640, 14, 14]               0
          Conv2d-287         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-288         [-1, 1056, 14, 14]           2,112
            ReLU-289         [-1, 1664, 14, 14]               0
           Block-290         [-1, 1664, 14, 14]               0
          Conv2d-291          [-1, 640, 14, 14]       1,064,960
     BatchNorm2d-292          [-1, 640, 14, 14]           1,280
            ReLU-293          [-1, 640, 14, 14]               0
          Conv2d-294          [-1, 640, 14, 14]          92,160
     BatchNorm2d-295          [-1, 640, 14, 14]           1,280
            ReLU-296          [-1, 640, 14, 14]               0
          Conv2d-297         [-1, 1056, 14, 14]         675,840
     BatchNorm2d-298         [-1, 1056, 14, 14]           2,112
            ReLU-299         [-1, 1696, 14, 14]               0
           Block-300         [-1, 1696, 14, 14]               0
          Conv2d-301         [-1, 1280, 14, 14]       2,170,880
     BatchNorm2d-302         [-1, 1280, 14, 14]           2,560
            ReLU-303         [-1, 1280, 14, 14]               0
          Conv2d-304           [-1, 1280, 7, 7]         368,640
     BatchNorm2d-305           [-1, 1280, 7, 7]           2,560
            ReLU-306           [-1, 1280, 7, 7]               0
          Conv2d-307           [-1, 2176, 7, 7]       2,785,280
     BatchNorm2d-308           [-1, 2176, 7, 7]           4,352
          Conv2d-309           [-1, 2176, 7, 7]      33,214,464
     BatchNorm2d-310           [-1, 2176, 7, 7]           4,352
            ReLU-311           [-1, 2304, 7, 7]               0
           Block-312           [-1, 2304, 7, 7]               0
          Conv2d-313           [-1, 1280, 7, 7]       2,949,120
     BatchNorm2d-314           [-1, 1280, 7, 7]           2,560
            ReLU-315           [-1, 1280, 7, 7]               0
          Conv2d-316           [-1, 1280, 7, 7]         368,640
     BatchNorm2d-317           [-1, 1280, 7, 7]           2,560
            ReLU-318           [-1, 1280, 7, 7]               0
          Conv2d-319           [-1, 2176, 7, 7]       2,785,280
     BatchNorm2d-320           [-1, 2176, 7, 7]           4,352
            ReLU-321           [-1, 2432, 7, 7]               0
           Block-322           [-1, 2432, 7, 7]               0
          Conv2d-323           [-1, 1280, 7, 7]       3,112,960
     BatchNorm2d-324           [-1, 1280, 7, 7]           2,560
            ReLU-325           [-1, 1280, 7, 7]               0
          Conv2d-326           [-1, 1280, 7, 7]         368,640
     BatchNorm2d-327           [-1, 1280, 7, 7]           2,560
            ReLU-328           [-1, 1280, 7, 7]               0
          Conv2d-329           [-1, 2176, 7, 7]       2,785,280
     BatchNorm2d-330           [-1, 2176, 7, 7]           4,352
            ReLU-331           [-1, 2560, 7, 7]               0
           Block-332           [-1, 2560, 7, 7]               0
AdaptiveAvgPool2d-333           [-1, 2560, 1, 1]               0
          Linear-334                    [-1, 4]          10,244
================================================================
Total params: 95,008,356
Trainable params: 95,008,356
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.57
Forward/backward pass size (MB): 664.46
Params size (MB): 362.43
Estimated Total Size (MB): 1027.47
----------------------------------------------------------------

三、 训练模型 

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)  # 批次数目
    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 = 10

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

best_acc = 0  # 设置一个最佳准确率,作为最佳模型的判别指标

for epoch in range(epochs):
    # 更新学习率(使用自定义学习率时使用)
    # adjust_learning_rate(optimizer, epoch, learn_rate)

    model.train()
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)
    # scheduler.step() # 更新学习率(调用官方动态学习率接口时使用)

    model.eval()
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)

    # 保存最佳模型到 best_model
    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(model.state_dict(), PATH)

print('Done')

得到如下输出:

Epoch: 1, Train_acc:35.0%, Train_loss:1.512, Test_acc:15.0%, Test_loss:2.101, Lr:1.00E-04
Epoch: 2, Train_acc:55.1%, Train_loss:1.088, Test_acc:15.9%, Test_loss:5.737, Lr:1.00E-04
Epoch: 3, Train_acc:71.0%, Train_loss:0.773, Test_acc:39.8%, Test_loss:2.180, Lr:1.00E-04
Epoch: 4, Train_acc:76.3%, Train_loss:0.616, Test_acc:62.8%, Test_loss:1.222, Lr:1.00E-04
Epoch: 5, Train_acc:79.4%, Train_loss:0.565, Test_acc:61.1%, Test_loss:2.034, Lr:1.00E-04
Epoch: 6, Train_acc:79.6%, Train_loss:0.492, Test_acc:61.9%, Test_loss:1.497, Lr:1.00E-04
Epoch: 7, Train_acc:83.2%, Train_loss:0.480, Test_acc:69.0%, Test_loss:1.305, Lr:1.00E-04
Epoch: 8, Train_acc:84.1%, Train_loss:0.403, Test_acc:56.6%, Test_loss:2.690, Lr:1.00E-04
Epoch: 9, Train_acc:90.0%, Train_loss:0.304, Test_acc:71.7%, Test_loss:1.104, Lr:1.00E-04
Epoch:10, Train_acc:93.8%, Train_loss:0.190, Test_acc:55.8%, Test_loss:2.481, Lr:1.00E-04
Done
预测结果是:Cockatoo

Process finished with exit code 0

四、 结果可视化

1. Loss&Accuracy

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

得到的可视化结果:

 2. 指定图片进行预测

首先,先定义出一个用于预测的函数:

 
from PIL import Image
 
classes = list(total_data.class_to_idx)
 
 
from PIL import Image
 
classes = list(total_data.class_to_idx)
 
 
def predict_one_image(image_path, model, transform, classes):
    test_img = Image.open(image_path).convert('RGB')
    plt.imshow(test_img)  # 展示预测的图片
 
    test_img = transform(test_img)
    img = test_img.to(device).unsqueeze(0)
 
    model.eval()
    output = model(img)
 
    _, pred = torch.max(output, 1)
    pred_class = classes[pred]
    print(f'预测结果是:{pred_class}')

接着调用函数对指定图片进行预测:

# 预测训练集中的某张照片
predict_one_image(image_path='./data/bird_photos/Cockatoo/011.jpg',
                  model=model,
                  transform=train_transforms,
                  classes=classes)

得到如下结果:

预测结果是:Cockatoo

五、网络架构及参数

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/732364.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【教程】PVE下uhd630核显直通HDMI输出 以NUC9为例村雨Murasame

大家好,村雨本雨又来发教程了 最近在搞小主机,之前hp400g3仅仅200多元成功核显直通HDMI,作为简单NAS、解码机、伺服机、中控都非常棒,待机仅9w 村雨Murasame:【教程】7代核显直通HDMI成功输出画面 PVE下7代intel核显…

Android studio安卓期末大作业,智学英语App

目录 1 系统主要功能 2 登陆 3 主菜单界面 4 单词查询 5 美文阅读 6 客服聊天 7 关于我们 1 系统主要功能 应用启动 打开应用,将看到一个欢迎界面,这通常是一个简短的动画或静态图像,用于引导进入主界面。 登录功能 (1…

R语言数据分析案例32-针对芬兰污染指数的分析与考察

一、 研究背景及意义 近年来,随着我国科技和经济高速发展,人们生活质量也随之显著提高。但是, 环境污染问题也日趋严重,给人们的生活质量和社会生产的各个方面都造成了许多不 利的影响。空气污染作为环境污染主要方面&#xff0c…

keepalive+nginx高可用架构

keepalivenginx架构 一.配置真实服务器web1和web2 1.关闭防火墙,并在真实服务器下载http服务 [rootlocalhost ~]# systemctl stop firewalld.service [rootlocalhost ~]# setenforce 0 [rootlocalhost ~]# yum install httpd -y 2.分别在web1和web2上制作网页…

慎投!新增7本期刊被“On Hold“,14本影响因子下降!

本周投稿推荐 SSCI • 中科院2区,6.0-7.0(录用友好) EI • 各领域沾边均可(2天录用) CNKI • 7天录用-检索(急录友好) SCI&EI • 4区生物医学类,0.5-1.0(录用…

如何使用Excel与Outlook实现邮件群发:详细教程

引言 在工作中,我们经常需要发送大量邮件。手动发送既费时又容易出错。本教程将教你如何使用Excel和Outlook,通过简单的VBA代码实现邮件的自动群发,提高工作效率。 准备工作 在开始之前,你需要确保以下工具已经安装在电脑上&am…

骨传导耳机值不值得入手?五款运动好物骨传导耳机推荐!

开放式耳机在如今社会中已经迅速成为大家购买耳机的新趋势,开放式蓝牙耳机作为骨传导耳机,深受喜欢听歌和热爱运动的人群欢迎。当大家谈到佩戴的稳固性时,后挂式骨传导耳机都会收到一致好评。对于热爱运动的人士而言,高品质的骨传…

WordPress插件:子比zibll主题插件 炙焰美化全开源插件V3.2

在网络世界中,开源内容管理系统(CMS)已经成为了网站构建的关键工具之一。WordPress,作为最受欢迎的开源CMS之一,其广泛的应用及其灵活性使得它成为了创建和管理各种类型网站的理想选择。而Zibll主题插件,作…

vue3中h函数的使用

h函数是用于创建一个 vnodes ,它既可以用于创建原生元素,也可以创建组件,其渲染后的效果等同于使用模版语言来进行创建。 h函数的传参如下: // 完整参数签名 function h(type: string | Component,props?: object | null,child…

【GD32F303红枫派使用手册】第二十二节 IIC-IIC OLED显示实验

22.1 实验内容 通过本实验主要学习以下内容: OLED驱动原理 IIC驱动OLED显示操作 22.2 实验原理 OLED模块的驱动芯片为SSD1306,其显存大小总共为 128*64bit 大小,SSD1306 将这些显存分为了 8 页,其对应关系如下所示&#xff1…

如何将办公文档压缩成rar格式文件?

压缩包格式是我们生活工作中常用到的文件格式,那么如何得到一个rar格式的压缩文件?或者说如何将文件压缩成rar格式而不是zip格式呢?今天我们来了解一下如何压缩为rar格式文件。 首先,下载并安装WinRAR,然后用鼠标选择需…

FlinkCDC介绍及使用

CDC简介 什么是CDC? cdc是Change Data Capture(变更数据获取)的简称。核心思想是,监测并捕获数据库的 变动(包括数据或数据表的插入,更新以及删除等),将这些变更按发生的顺序完整记录下来,写入到消息中间件以供其它服…

修复 Android 手机卡在启动屏幕上的 7 种方法

Android 手机卡在启动屏幕上的情况并不常见。通常,问题出现在应用新更新或安装未知来源的应用程序后。幸运的是,您可以让您的 Android 手机跳过启动屏幕,而无需前往最近的服务中心。 当您的 Android 手机在启动屏幕上陷入无限循环时&#xf…

计算机组成原理 —— 存储系统(概述)

计算机组成原理 —— 存储系统(概述) 存储系统按层次划分按照存储介质分类按照存储方式分类按照信息可更改性分类根据信息的可保存性分类存储器性能指标 我们今天来学习计算机组成原理中的存储系统: 存储系统 存储系统是计算机系统中用于存…

css文字镂空加描边

css文字镂空加描边 <!DOCTYPE html> <html><head><meta charset"utf-8"><title>文字镂空</title><style>/* 公用样式 */html,body{width: 100%;height: 100%;position: relative;}/* html{overflow-y: scroll;} */*{margi…

【机器学习 复习】 第1章 概述

一、概念 1.机器学习是一种通过先验信息来提升模型能力的方式。 即从数据中产生“模型”( model )的算法&#xff0c;然后对新的数据集进行预测。 2.数据集&#xff08;Dataset&#xff09;&#xff1a;所有数据的集合称为数据集。 训练集&#xff1a;用来训练出一个适合模…

Android (已解决)Execution failed for task ‘:app:lint‘

文章目录 一、错误原因二、解决方法 一、错误原因 这个错误信息表示在执行 Lint 检查时发现了错误&#xff0c;导致构建过程被中断。Lint 是一个用于检测 Android 项目中潜在问题的工具&#xff0c;比如性能、安全性、可用性等方面的问题。当Lint检查到严重错误时&#xff0c;…

库卡机器人减速机维修齿轮磨损故障

一、KUKA机器人减速器齿轮磨损故障的原因 1. 润滑不足&#xff1a;润滑油不足或质量不佳可能导致齿轮磨损。 2. 负载过重&#xff1a;超过库卡机械臂减速器额定负载可能导致齿轮磨损。 3. 操作不当&#xff1a;未按照说明书操作可能导致KUKA机器人减速器齿轮磨损。 4. 维护不足…

2024年全国青少信息素养大赛python编程复赛集训第四天编程题分享

整理资料不容易,感谢各位大佬给个点赞和分享吧,谢谢 大家如果不想阅读前边的比赛内容介绍,可以直接跳过:拉到底部看集训题目 (一)比赛内容: 【小学组】 1.了解输入与输出的概念,掌握使用基本输入输出和简单运算 为主的标准函数; 2.掌握注释的方法; 3.掌握基本数…

Ubuntu配置ssh+vnc(完整版)

Ubuntu配置sshvnc&#xff08;完整版&#xff09; 1 配置ssh 1. 安装openssh-server&#xff0c;配置开机自启 # 更新包 sudo apt-get update # 安装openssh-server sudo apt-get install -y openssh-server # 启动服务 sudo service ssh start # 配置开机自启 sudo systemc…