|
| 1 | +import re |
| 2 | +from collections import OrderedDict |
| 3 | + |
| 4 | +import torch |
| 5 | +import torch.nn as nn |
| 6 | +import torch.nn.functional as F |
| 7 | + |
| 8 | +__all__ = ['DenseNet', 'densenet121', 'densenet169', 'densenet201', 'densenet161'] |
| 9 | + |
| 10 | +model_urls = { |
| 11 | + 'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth', |
| 12 | + 'densenet169': 'https://download.pytorch.org/models/densenet169-b2777c0a.pth', |
| 13 | + 'densenet201': 'https://download.pytorch.org/models/densenet201-c1103571.pth', |
| 14 | + 'densenet161': 'https://download.pytorch.org/models/densenet161-8d451a50.pth', |
| 15 | +} |
| 16 | + |
| 17 | + |
| 18 | +class _DenseLayer(nn.Sequential): |
| 19 | + def __init__(self, num_input_features, growth_rate, bn_size, drop_rate): |
| 20 | + super(_DenseLayer, self).__init__() |
| 21 | + self.add_module('norm1', nn.BatchNorm2d(num_input_features)), |
| 22 | + self.add_module('relu1', nn.ReLU(inplace=True)), |
| 23 | + self.add_module('conv1', nn.Conv2d(num_input_features, bn_size * |
| 24 | + growth_rate, kernel_size=1, stride=1, |
| 25 | + bias=False)), |
| 26 | + self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)), |
| 27 | + self.add_module('relu2', nn.ReLU(inplace=True)), |
| 28 | + self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate, |
| 29 | + kernel_size=3, stride=1, padding=1, |
| 30 | + bias=False)), |
| 31 | + self.drop_rate = drop_rate |
| 32 | + |
| 33 | + def forward(self, x): |
| 34 | + new_features = super(_DenseLayer, self).forward(x) |
| 35 | + if self.drop_rate > 0: |
| 36 | + new_features = F.dropout(new_features, p=self.drop_rate, |
| 37 | + training=self.training) |
| 38 | + return torch.cat([x, new_features], 1) |
| 39 | + |
| 40 | + |
| 41 | +class _DenseBlock(nn.Sequential): |
| 42 | + def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate): |
| 43 | + super(_DenseBlock, self).__init__() |
| 44 | + for i in range(num_layers): |
| 45 | + layer = _DenseLayer(num_input_features + i * growth_rate, growth_rate, |
| 46 | + bn_size, drop_rate) |
| 47 | + self.add_module('denselayer%d' % (i + 1), layer) |
| 48 | + |
| 49 | + |
| 50 | +class _Transition(nn.Sequential): |
| 51 | + def __init__(self, num_input_features, num_output_features): |
| 52 | + super(_Transition, self).__init__() |
| 53 | + self.add_module('norm', nn.BatchNorm2d(num_input_features)) |
| 54 | + self.add_module('relu', nn.ReLU(inplace=True)) |
| 55 | + self.add_module('conv', nn.Conv2d(num_input_features, num_output_features, |
| 56 | + kernel_size=1, stride=1, bias=False)) |
| 57 | + self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2)) |
| 58 | + |
| 59 | + |
| 60 | +class DenseNet(nn.Module): |
| 61 | + r"""Densenet-BC model class, based on |
| 62 | + `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ |
| 63 | +
|
| 64 | + Args: |
| 65 | + growth_rate (int) - how many filters to add each layer (`k` in paper) |
| 66 | + block_config (list of 4 ints) - how many layers in each pooling block |
| 67 | + num_init_features (int) - the number of filters to learn in the first convolution layer |
| 68 | + bn_size (int) - multiplicative factor for number of bottle neck layers |
| 69 | + (i.e. bn_size * k features in the bottleneck layer) |
| 70 | + drop_rate (float) - dropout rate after each dense layer |
| 71 | + num_classes (int) - number of classification classes |
| 72 | + """ |
| 73 | + |
| 74 | + def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16), |
| 75 | + num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000, |
| 76 | + **kwargs): |
| 77 | + |
| 78 | + super(DenseNet, self).__init__() |
| 79 | + |
| 80 | + # First convolution |
| 81 | + self.features = nn.Sequential(OrderedDict([ |
| 82 | + ('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, |
| 83 | + padding=3, bias=False)), |
| 84 | + ('norm0', nn.BatchNorm2d(num_init_features)), |
| 85 | + ('relu0', nn.ReLU(inplace=True)), |
| 86 | + ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)), |
| 87 | + ])) |
| 88 | + |
| 89 | + # Each denseblock |
| 90 | + num_features = num_init_features |
| 91 | + for i, num_layers in enumerate(block_config): |
| 92 | + block = _DenseBlock(num_layers=num_layers, num_input_features=num_features, |
| 93 | + bn_size=bn_size, growth_rate=growth_rate, |
| 94 | + drop_rate=drop_rate) |
| 95 | + self.features.add_module('denseblock%d' % (i + 1), block) |
| 96 | + num_features = num_features + num_layers * growth_rate |
| 97 | + if i != len(block_config) - 1: |
| 98 | + trans = _Transition(num_input_features=num_features, |
| 99 | + num_output_features=num_features // 2) |
| 100 | + self.features.add_module('transition%d' % (i + 1), trans) |
| 101 | + num_features = num_features // 2 |
| 102 | + |
| 103 | + # Final batch norm |
| 104 | + self.features.add_module('norm5', nn.BatchNorm2d(num_features)) |
| 105 | + |
| 106 | + self.out_dim = num_features |
| 107 | + |
| 108 | + # Official init from torch repo. |
| 109 | + for m in self.modules(): |
| 110 | + if isinstance(m, nn.Conv2d): |
| 111 | + nn.init.kaiming_normal_(m.weight) |
| 112 | + elif isinstance(m, nn.BatchNorm2d): |
| 113 | + nn.init.constant_(m.weight, 1) |
| 114 | + nn.init.constant_(m.bias, 0) |
| 115 | + elif isinstance(m, nn.Linear): |
| 116 | + nn.init.constant_(m.bias, 0) |
| 117 | + |
| 118 | + def forward(self, x): |
| 119 | + features = self.features(x) |
| 120 | + out = F.relu(features, inplace=True) |
| 121 | + out = F.adaptive_avg_pool2d(out, (1, 1)).view(features.size(0), -1) |
| 122 | + return out |
| 123 | + |
| 124 | + |
| 125 | +def _load_state_dict(model, model_url, progress): |
| 126 | + pass |
| 127 | + |
| 128 | +def _densenet(arch, growth_rate, block_config, num_init_features, pretrained, progress, |
| 129 | + **kwargs): |
| 130 | + model = DenseNet(growth_rate, block_config, num_init_features, **kwargs) |
| 131 | + if pretrained: |
| 132 | + _load_state_dict(model, model_urls[arch], progress) |
| 133 | + return model |
| 134 | + |
| 135 | + |
| 136 | +def densenet121(pretrained=False, progress=True, **kwargs): |
| 137 | + r"""Densenet-121 model from |
| 138 | + `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ |
| 139 | +
|
| 140 | + Args: |
| 141 | + pretrained (bool): If True, returns a model pre-trained on ImageNet |
| 142 | + progress (bool): If True, displays a progress bar of the download to stderr |
| 143 | + """ |
| 144 | + return _densenet('densenet121', 32, (6, 12, 24, 16), 64, pretrained, progress, |
| 145 | + **kwargs) |
| 146 | + |
| 147 | + |
| 148 | +def densenet161(pretrained=False, progress=True, **kwargs): |
| 149 | + r"""Densenet-161 model from |
| 150 | + `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ |
| 151 | +
|
| 152 | + Args: |
| 153 | + pretrained (bool): If True, returns a model pre-trained on ImageNet |
| 154 | + progress (bool): If True, displays a progress bar of the download to stderr |
| 155 | + """ |
| 156 | + return _densenet('densenet161', 48, (6, 12, 36, 24), 96, pretrained, progress, |
| 157 | + **kwargs) |
| 158 | + |
| 159 | + |
| 160 | +def densenet169(pretrained=False, progress=True, **kwargs): |
| 161 | + r"""Densenet-169 model from |
| 162 | + `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ |
| 163 | +
|
| 164 | + Args: |
| 165 | + pretrained (bool): If True, returns a model pre-trained on ImageNet |
| 166 | + progress (bool): If True, displays a progress bar of the download to stderr |
| 167 | + """ |
| 168 | + return _densenet('densenet169', 32, (6, 12, 32, 32), 64, pretrained, progress, |
| 169 | + **kwargs) |
| 170 | + |
| 171 | + |
| 172 | +def densenet201(pretrained=False, progress=True, **kwargs): |
| 173 | + r"""Densenet-201 model from |
| 174 | + `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ |
| 175 | +
|
| 176 | + Args: |
| 177 | + pretrained (bool): If True, returns a model pre-trained on ImageNet |
| 178 | + progress (bool): If True, displays a progress bar of the download to stderr |
| 179 | + """ |
| 180 | + return _densenet('densenet201', 32, (6, 12, 48, 32), 64, pretrained, progress, |
| 181 | + **kwargs) |
0 commit comments