• 分类神经网络3:DenseNet模型复现


    目录

    DenseNet网络架构

    DenseNet部分实现代码


    DenseNet网络架构

    论文原址:https://arxiv.org/pdf/1608.06993.pdf

    稠密连接神经网络(DenseNet)实质上是ResNet的进阶模型了解ResNet模型请点击),二者均是通过建立前面层与后面层之间的“短路连接”,但不同的是,DenseNet建立的是前面所有层与后面层的密集连接,其一大特点是通过特征在通道上的连接来实现特征重用,这让DenseNet在参数和计算成本更少的情形下实现比ResNet更优的性能。DenseNet 网络的模型结构如下:

    DenseNet 的网络结构主要由DenseBlockTransition Layer组成。

    DenseBlock:密集连接机制。互相连接所有的层,即每一层的输入都来自于它前面所有层的特征图,每一层的输出均会直接连接到它后面所有层的输入,这可以实现特征重用(即对不同“级别”的特征——不同表征进行总体性地再探索),提升效率。具体的连接方式如下图示:

    在同一个DenseBlock当中,特征层的高宽不会发生改变,但是通道数会发生改变可以看出DenseBlock中采用了BN+ReLU+Conv的结构,然而一般网络是用Conv+BN+ReLU的结构。这是由于卷积层的输入包含了它前面所有层的输出特征,它们来自不同层的输出,因此数值分布差异比较大,所以它们在输入到下一个卷积层时,必须先经过BN层将其数值进行标准化,然后再进行卷积操作。通常为了减少参数,一般还会先加一个1x1 卷积来减少参数量。所以DenseBlock中的每一层采用BN+ReLU+1x1Conv 、Conv+BN+ReLU+3x3 Conv的结构。

    Transition Layer:用于将不同DenseBlock之间进行连接,整合上一个DenseBlock获得的特征,并且缩小上一个DenseBlock的宽高,达到下采样的效果,实质上起到压缩模型的作用。Transition Layer中一般包含一个1x1卷积(用于调整通道数)和2x2平均池化(用于降低特征图大小),结构为BN+ReLU+1x1 Conv+2x2 AvgPooling

    DenseNet网络的具体配置信息如下:

    可以看出,一个DenseNet中一般有3个或4个DenseBlock,最后的DenseBlock后连接了一个最大池化层,然后是一个包含1000个类别的全连接层,通过softmax激活函数得到类别属性。

    DenseNet部分实现代码

    直接上干货

    1. import torch
    2. import torch.nn as nn
    3. import torch.nn.functional as F
    4. import torch.utils.checkpoint as cp
    5. from collections import OrderedDict
    6. __all__ = ["densenet121", "densenet161", "densenet169", "densenet201"]
    7. class DenseLayer(nn.Module):
    8. def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, memory_efficient = False):
    9. super(DenseLayer,self).__init__()
    10. self.norm1 = nn.BatchNorm2d(num_input_features)
    11. self.relu1 = nn.ReLU(inplace=True)
    12. self.conv1 = nn.Conv2d(num_input_features, bn_size * growth_rate, kernel_size=1, stride=1, bias=False)
    13. self.norm2 = nn.BatchNorm2d(bn_size * growth_rate)
    14. self.relu2 = nn.ReLU(inplace=True)
    15. self.conv2 = nn.Conv2d(bn_size * growth_rate, growth_rate, kernel_size=3, stride=1, padding=1, bias=False)
    16. self.drop_rate = float(drop_rate)
    17. self.memory_efficient = memory_efficient
    18. def bn_function(self, inputs):
    19. concated_features = torch.cat(inputs, 1)
    20. bottleneck_output = self.conv1(self.relu1(self.norm1(concated_features)))
    21. return bottleneck_output
    22. def any_requires_grad(self, input):
    23. for tensor in input:
    24. if tensor.requires_grad:
    25. return True
    26. return False
    27. @torch.jit.unused
    28. def call_checkpoint_bottleneck(self, input):
    29. def closure(*inputs):
    30. return self.bn_function(inputs)
    31. return cp.checkpoint(closure, *input)
    32. def forward(self, input):
    33. if isinstance(input, torch.Tensor):
    34. prev_features = [input]
    35. else:
    36. prev_features = input
    37. if self.memory_efficient and self.any_requires_grad(prev_features):
    38. if torch.jit.is_scripting():
    39. raise Exception("Memory Efficient not supported in JIT")
    40. bottleneck_output = self.call_checkpoint_bottleneck(prev_features)
    41. else:
    42. bottleneck_output = self.bn_function(prev_features)
    43. new_features = self.conv2(self.relu2(self.norm2(bottleneck_output)))
    44. if self.drop_rate > 0:
    45. new_features = F.dropout(new_features, p=self.drop_rate, training=self.training)
    46. return new_features
    47. class DenseBlock(nn.ModuleDict):
    48. def __init__(self,num_layers,num_input_features,bn_size,growth_rate,
    49. drop_rate,memory_efficient = False,):
    50. super(DenseBlock,self).__init__()
    51. for i in range(num_layers):
    52. layer = DenseLayer(
    53. num_input_features + i * growth_rate,
    54. growth_rate=growth_rate,
    55. bn_size=bn_size,
    56. drop_rate=drop_rate,
    57. memory_efficient=memory_efficient,
    58. )
    59. self.add_module("denselayer%d" % (i + 1), layer)
    60. def forward(self, init_features):
    61. features = [init_features]
    62. for name, layer in self.items():
    63. new_features = layer(features)
    64. features.append(new_features)
    65. return torch.cat(features, 1)
    66. class Transition(nn.Sequential):
    67. """
    68. Densenet Transition Layer:
    69. 1 × 1 conv
    70. 2 × 2 average pool, stride 2
    71. """
    72. def __init__(self, num_input_features, num_output_features):
    73. super(Transition,self).__init__()
    74. self.norm = nn.BatchNorm2d(num_input_features)
    75. self.relu = nn.ReLU(inplace=True)
    76. self.conv = nn.Conv2d(num_input_features, num_output_features, kernel_size=1, stride=1, bias=False)
    77. self.pool = nn.AvgPool2d(kernel_size=2, stride=2)
    78. class DenseNet(nn.Module):
    79. def __init__(self,growth_rate = 32,num_init_features = 64,block_config = None,num_classes = 1000,
    80. bn_size = 4,drop_rate = 0.,memory_efficient = False,):
    81. super(DenseNet,self).__init__()
    82. # First convolution
    83. self.features = nn.Sequential(
    84. OrderedDict(
    85. [
    86. ("conv0", nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, padding=3, bias=False)),
    87. ("norm0", nn.BatchNorm2d(num_init_features)),
    88. ("relu0", nn.ReLU(inplace=True)),
    89. ("pool0", nn.MaxPool2d(kernel_size=3, stride=2, padding=1)),
    90. ]
    91. )
    92. )
    93. # Each denseblock
    94. num_features = num_init_features
    95. for i, num_layers in enumerate(block_config):
    96. block = DenseBlock(
    97. num_layers=num_layers,
    98. num_input_features=num_features,
    99. bn_size=bn_size,
    100. growth_rate=growth_rate,
    101. drop_rate=drop_rate,
    102. memory_efficient=memory_efficient,
    103. )
    104. self.features.add_module("denseblock%d" % (i + 1), block)
    105. num_features = num_features + num_layers * growth_rate
    106. if i != len(block_config) - 1:
    107. trans = Transition(num_input_features=num_features, num_output_features=num_features // 2)
    108. self.features.add_module("transition%d" % (i + 1), trans)
    109. num_features = num_features // 2
    110. # Final batch norm
    111. self.features.add_module("norm5", nn.BatchNorm2d(num_features))
    112. # Linear layer
    113. self.classifier = nn.Linear(num_features, num_classes)
    114. # Official init from torch repo.
    115. for m in self.modules():
    116. if isinstance(m, nn.Conv2d):
    117. nn.init.kaiming_normal_(m.weight)
    118. elif isinstance(m, nn.BatchNorm2d):
    119. nn.init.constant_(m.weight, 1)
    120. nn.init.constant_(m.bias, 0)
    121. elif isinstance(m, nn.Linear):
    122. nn.init.constant_(m.bias, 0)
    123. def forward(self, x):
    124. features = self.features(x)
    125. out = F.relu(features, inplace=True)
    126. out = F.adaptive_avg_pool2d(out, (1, 1))
    127. out = torch.flatten(out, 1)
    128. out = self.classifier(out)
    129. return out
    130. def densenet121(num_classes):
    131. """Densenet-121 model"""
    132. return DenseNet(32, 64, (6, 12, 24, 16),num_classes=num_classes)
    133. def densenet161(num_classes):
    134. """Densenet-161 model"""
    135. return DenseNet(48, 96, (6, 12, 36, 24), num_classes=num_classes)
    136. def densenet169(num_classes):
    137. """Densenet-169 model"""
    138. return DenseNet(32, 64, (6, 12, 32, 32), num_classes=num_classes)
    139. def densenet201(num_classes):
    140. """Densenet-201 model"""
    141. return DenseNet(32, 64, (6, 12, 48, 32), num_classes=num_classes)
    142. if __name__=="__main__":
    143. # from torchsummaryX import summary
    144. device = 'cuda' if torch.cuda.is_available() else 'cpu'
    145. input = torch.ones(2, 3, 224, 224).to(device)
    146. net = densenet121(num_classes=4)
    147. net = net.to(device)
    148. out = net(input)
    149. print(out)
    150. print(out.shape)
    151. # summary(net, torch.ones((1, 3, 224, 224)).to(device))

    希望对大家能够有所帮助呀!

  • 相关阅读:
    Laravel关于TrimStrings请求参数去空格问题
    逻辑器件与热插拔
    ArcGIS中ArcMap图层属性表的中文字段乱码的解决方法
    总结二:linux面经
    Ansible playbook简介与初步实战,实现批量机器应用下载与安装
    插件创建Maven工程
    通过profibus PA转Modbus rtu协议网关把RTU数据传到pa设备上
    换种方式看后端参数接收、建议躺着看!!!
    【场景化解决方案】搭建数据桥梁,Dslink打通泛微系统连接流
    Android 11.0 禁止弹出系统simlock的锁卡弹窗功能实现
  • 原文地址:https://blog.csdn.net/m0_73228309/article/details/138047077