densenet.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import numpy as np
  18. import paddle
  19. from paddle import ParamAttr
  20. import paddle.nn as nn
  21. from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
  22. from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
  23. from paddle.nn.initializer import Uniform
  24. import math
  25. __all__ = [
  26. "DenseNet121", "DenseNet161", "DenseNet169", "DenseNet201", "DenseNet264"
  27. ]
  28. class BNACConvLayer(nn.Layer):
  29. def __init__(self,
  30. num_channels,
  31. num_filters,
  32. filter_size,
  33. stride=1,
  34. pad=0,
  35. groups=1,
  36. act="relu",
  37. name=None):
  38. super(BNACConvLayer, self).__init__()
  39. self._batch_norm = BatchNorm(
  40. num_channels,
  41. act=act,
  42. param_attr=ParamAttr(name=name + '_bn_scale'),
  43. bias_attr=ParamAttr(name + '_bn_offset'),
  44. moving_mean_name=name + '_bn_mean',
  45. moving_variance_name=name + '_bn_variance')
  46. self._conv = Conv2D(
  47. in_channels=num_channels,
  48. out_channels=num_filters,
  49. kernel_size=filter_size,
  50. stride=stride,
  51. padding=pad,
  52. groups=groups,
  53. weight_attr=ParamAttr(name=name + "_weights"),
  54. bias_attr=False)
  55. def forward(self, input):
  56. y = self._batch_norm(input)
  57. y = self._conv(y)
  58. return y
  59. class DenseLayer(nn.Layer):
  60. def __init__(self, num_channels, growth_rate, bn_size, dropout, name=None):
  61. super(DenseLayer, self).__init__()
  62. self.dropout = dropout
  63. self.bn_ac_func1 = BNACConvLayer(
  64. num_channels=num_channels,
  65. num_filters=bn_size * growth_rate,
  66. filter_size=1,
  67. pad=0,
  68. stride=1,
  69. name=name + "_x1")
  70. self.bn_ac_func2 = BNACConvLayer(
  71. num_channels=bn_size * growth_rate,
  72. num_filters=growth_rate,
  73. filter_size=3,
  74. pad=1,
  75. stride=1,
  76. name=name + "_x2")
  77. if dropout:
  78. self.dropout_func = Dropout(p=dropout, mode="downscale_in_infer")
  79. def forward(self, input):
  80. conv = self.bn_ac_func1(input)
  81. conv = self.bn_ac_func2(conv)
  82. if self.dropout:
  83. conv = self.dropout_func(conv)
  84. conv = paddle.concat([input, conv], axis=1)
  85. return conv
  86. class DenseBlock(nn.Layer):
  87. def __init__(self,
  88. num_channels,
  89. num_layers,
  90. bn_size,
  91. growth_rate,
  92. dropout,
  93. name=None):
  94. super(DenseBlock, self).__init__()
  95. self.dropout = dropout
  96. self.dense_layer_func = []
  97. pre_channel = num_channels
  98. for layer in range(num_layers):
  99. self.dense_layer_func.append(
  100. self.add_sublayer(
  101. "{}_{}".format(name, layer + 1),
  102. DenseLayer(
  103. num_channels=pre_channel,
  104. growth_rate=growth_rate,
  105. bn_size=bn_size,
  106. dropout=dropout,
  107. name=name + '_' + str(layer + 1))))
  108. pre_channel = pre_channel + growth_rate
  109. def forward(self, input):
  110. conv = input
  111. for func in self.dense_layer_func:
  112. conv = func(conv)
  113. return conv
  114. class TransitionLayer(nn.Layer):
  115. def __init__(self, num_channels, num_output_features, name=None):
  116. super(TransitionLayer, self).__init__()
  117. self.conv_ac_func = BNACConvLayer(
  118. num_channels=num_channels,
  119. num_filters=num_output_features,
  120. filter_size=1,
  121. pad=0,
  122. stride=1,
  123. name=name)
  124. self.pool2d_avg = AvgPool2D(kernel_size=2, stride=2, padding=0)
  125. def forward(self, input):
  126. y = self.conv_ac_func(input)
  127. y = self.pool2d_avg(y)
  128. return y
  129. class ConvBNLayer(nn.Layer):
  130. def __init__(self,
  131. num_channels,
  132. num_filters,
  133. filter_size,
  134. stride=1,
  135. pad=0,
  136. groups=1,
  137. act="relu",
  138. name=None):
  139. super(ConvBNLayer, self).__init__()
  140. self._conv = Conv2D(
  141. in_channels=num_channels,
  142. out_channels=num_filters,
  143. kernel_size=filter_size,
  144. stride=stride,
  145. padding=pad,
  146. groups=groups,
  147. weight_attr=ParamAttr(name=name + "_weights"),
  148. bias_attr=False)
  149. self._batch_norm = BatchNorm(
  150. num_filters,
  151. act=act,
  152. param_attr=ParamAttr(name=name + '_bn_scale'),
  153. bias_attr=ParamAttr(name + '_bn_offset'),
  154. moving_mean_name=name + '_bn_mean',
  155. moving_variance_name=name + '_bn_variance')
  156. def forward(self, input):
  157. y = self._conv(input)
  158. y = self._batch_norm(y)
  159. return y
  160. class DenseNet(nn.Layer):
  161. def __init__(self, layers=60, bn_size=4, dropout=0, class_dim=1000):
  162. super(DenseNet, self).__init__()
  163. supported_layers = [121, 161, 169, 201, 264]
  164. assert layers in supported_layers, \
  165. "supported layers are {} but input layer is {}".format(
  166. supported_layers, layers)
  167. densenet_spec = {
  168. 121: (64, 32, [6, 12, 24, 16]),
  169. 161: (96, 48, [6, 12, 36, 24]),
  170. 169: (64, 32, [6, 12, 32, 32]),
  171. 201: (64, 32, [6, 12, 48, 32]),
  172. 264: (64, 32, [6, 12, 64, 48])
  173. }
  174. num_init_features, growth_rate, block_config = densenet_spec[layers]
  175. self.conv1_func = ConvBNLayer(
  176. num_channels=3,
  177. num_filters=num_init_features,
  178. filter_size=7,
  179. stride=2,
  180. pad=3,
  181. act='relu',
  182. name="conv1")
  183. self.pool2d_max = MaxPool2D(kernel_size=3, stride=2, padding=1)
  184. self.block_config = block_config
  185. self.dense_block_func_list = []
  186. self.transition_func_list = []
  187. pre_num_channels = num_init_features
  188. num_features = num_init_features
  189. for i, num_layers in enumerate(block_config):
  190. self.dense_block_func_list.append(
  191. self.add_sublayer(
  192. "db_conv_{}".format(i + 2),
  193. DenseBlock(
  194. num_channels=pre_num_channels,
  195. num_layers=num_layers,
  196. bn_size=bn_size,
  197. growth_rate=growth_rate,
  198. dropout=dropout,
  199. name='conv' + str(i + 2))))
  200. num_features = num_features + num_layers * growth_rate
  201. pre_num_channels = num_features
  202. if i != len(block_config) - 1:
  203. self.transition_func_list.append(
  204. self.add_sublayer(
  205. "tr_conv{}_blk".format(i + 2),
  206. TransitionLayer(
  207. num_channels=pre_num_channels,
  208. num_output_features=num_features // 2,
  209. name='conv' + str(i + 2) + "_blk")))
  210. pre_num_channels = num_features // 2
  211. num_features = num_features // 2
  212. self.batch_norm = BatchNorm(
  213. num_features,
  214. act="relu",
  215. param_attr=ParamAttr(name='conv5_blk_bn_scale'),
  216. bias_attr=ParamAttr(name='conv5_blk_bn_offset'),
  217. moving_mean_name='conv5_blk_bn_mean',
  218. moving_variance_name='conv5_blk_bn_variance')
  219. self.pool2d_avg = AdaptiveAvgPool2D(1)
  220. stdv = 1.0 / math.sqrt(num_features * 1.0)
  221. self.out = Linear(
  222. num_features,
  223. class_dim,
  224. weight_attr=ParamAttr(
  225. initializer=Uniform(-stdv, stdv), name="fc_weights"),
  226. bias_attr=ParamAttr(name="fc_offset"))
  227. def forward(self, input):
  228. conv = self.conv1_func(input)
  229. conv = self.pool2d_max(conv)
  230. for i, num_layers in enumerate(self.block_config):
  231. conv = self.dense_block_func_list[i](conv)
  232. if i != len(self.block_config) - 1:
  233. conv = self.transition_func_list[i](conv)
  234. conv = self.batch_norm(conv)
  235. y = self.pool2d_avg(conv)
  236. y = paddle.flatten(y, start_axis=1, stop_axis=-1)
  237. y = self.out(y)
  238. return y
  239. def DenseNet121(**args):
  240. model = DenseNet(layers=121, **args)
  241. return model
  242. def DenseNet161(**args):
  243. model = DenseNet(layers=161, **args)
  244. return model
  245. def DenseNet169(**args):
  246. model = DenseNet(layers=169, **args)
  247. return model
  248. def DenseNet201(**args):
  249. model = DenseNet(layers=201, **args)
  250. return model
  251. def DenseNet264(**args):
  252. model = DenseNet(layers=264, **args)
  253. return model