r"""Densenet-BC model class, based on `"Densely Connected Convolutional Networks" `_ Args: growth_rate (int) - how many filters to add each layer (`k` in paper) block_config (list of 4 ints) - how many layers in each pooling block
| 148 | |
| 149 | |
| 150 | class DenseNet(nn.Module): |
| 151 | r"""Densenet-BC model class, based on |
| 152 | `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_ |
| 153 | |
| 154 | Args: |
| 155 | growth_rate (int) - how many filters to add each layer (`k` in paper) |
| 156 | block_config (list of 4 ints) - how many layers in each pooling block |
| 157 | num_init_features (int) - the number of filters to learn in the first convolution layer |
| 158 | bn_size (int) - multiplicative factor for number of bottle neck layers |
| 159 | (i.e. bn_size * k features in the bottleneck layer) |
| 160 | drop_rate (float) - dropout rate after each dense layer |
| 161 | num_classes (int) - number of classification classes |
| 162 | memory_efficient (bool) - If True, uses checkpointing. Much more memory efficient, |
| 163 | but slower. Default: *False*. See `"paper" <https://arxiv.org/pdf/1707.06990.pdf>`_ |
| 164 | """ |
| 165 | |
| 166 | def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16), |
| 167 | num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000, memory_efficient=False): |
| 168 | |
| 169 | super(DenseNet, self).__init__() |
| 170 | |
| 171 | # First convolution |
| 172 | self.features = nn.Sequential(OrderedDict([ |
| 173 | ('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2, |
| 174 | padding=3, bias=False)), |
| 175 | ('norm0', nn.BatchNorm2d(num_init_features)), |
| 176 | ('relu0', nn.ReLU(inplace=False)), |
| 177 | ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)), |
| 178 | ])) |
| 179 | |
| 180 | # Each denseblock |
| 181 | num_features = num_init_features |
| 182 | for i, num_layers in enumerate(block_config): |
| 183 | block = _DenseBlock( |
| 184 | num_layers=num_layers, |
| 185 | num_input_features=num_features, |
| 186 | bn_size=bn_size, |
| 187 | growth_rate=growth_rate, |
| 188 | drop_rate=drop_rate, |
| 189 | memory_efficient=memory_efficient |
| 190 | ) |
| 191 | self.features.add_module('denseblock%d' % (i + 1), block) |
| 192 | num_features = num_features + num_layers * growth_rate |
| 193 | if i != len(block_config) - 1: |
| 194 | trans = _Transition(num_input_features=num_features, |
| 195 | num_output_features=num_features // 2) |
| 196 | self.features.add_module('transition%d' % (i + 1), trans) |
| 197 | num_features = num_features // 2 |
| 198 | |
| 199 | # Final batch norm |
| 200 | self.features.add_module('norm5', nn.BatchNorm2d(num_features)) |
| 201 | |
| 202 | # Linear layer |
| 203 | self.classifier = nn.Linear(num_features, num_classes) |
| 204 | |
| 205 | # Official init from torch repo. |
| 206 | for m in self.modules(): |
| 207 | if isinstance(m, nn.Conv2d): |