resnet_v2.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
  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. # ==============================================================================
  15. """Contains definitions for the preactivation form of Residual Networks.
  16. Residual networks (ResNets) were originally proposed in:
  17. [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
  18. Deep Residual Learning for Image Recognition. arXiv:1512.03385
  19. The full preactivation 'v2' ResNet variant implemented in this module was
  20. introduced by:
  21. [2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
  22. Identity Mappings in Deep Residual Networks. arXiv: 1603.05027
  23. The key difference of the full preactivation 'v2' variant compared to the
  24. 'v1' variant in [1] is the use of batch normalization before every weight layer.
  25. Typical use:
  26. from tensorflow.contrib.slim.nets import resnet_v2
  27. ResNet-101 for image classification into 1000 classes:
  28. # inputs has shape [batch, 224, 224, 3]
  29. with slim.arg_scope(resnet_v2.resnet_arg_scope()):
  30. net, end_points = resnet_v2.resnet_v2_101(inputs, 1000, is_training=False)
  31. ResNet-101 for semantic segmentation into 21 classes:
  32. # inputs has shape [batch, 513, 513, 3]
  33. with slim.arg_scope(resnet_v2.resnet_arg_scope()):
  34. net, end_points = resnet_v2.resnet_v2_101(inputs,
  35. 21,
  36. is_training=False,
  37. global_pool=False,
  38. output_stride=16)
  39. """
  40. from __future__ import absolute_import
  41. from __future__ import division
  42. from __future__ import print_function
  43. import tensorflow as tf
  44. from nets import resnet_utils
  45. slim = tf.contrib.slim
  46. resnet_arg_scope = resnet_utils.resnet_arg_scope
  47. @slim.add_arg_scope
  48. def bottleneck(inputs, depth, depth_bottleneck, stride, rate=1,
  49. outputs_collections=None, scope=None):
  50. """Bottleneck residual unit variant with BN before convolutions.
  51. This is the full preactivation residual unit variant proposed in [2]. See
  52. Fig. 1(b) of [2] for its definition. Note that we use here the bottleneck
  53. variant which has an extra bottleneck layer.
  54. When putting together two consecutive ResNet blocks that use this unit, one
  55. should use stride = 2 in the last unit of the first block.
  56. Args:
  57. inputs: A tensor of size [batch, height, width, channels].
  58. depth: The depth of the ResNet unit output.
  59. depth_bottleneck: The depth of the bottleneck layers.
  60. stride: The ResNet unit's stride. Determines the amount of downsampling of
  61. the units output compared to its input.
  62. rate: An integer, rate for atrous convolution.
  63. outputs_collections: Collection to add the ResNet unit output.
  64. scope: Optional variable_scope.
  65. Returns:
  66. The ResNet unit's output.
  67. """
  68. with tf.variable_scope(scope, 'bottleneck_v2', [inputs]) as sc:
  69. depth_in = slim.utils.last_dimension(inputs.get_shape(), min_rank=4)
  70. preact = slim.batch_norm(inputs, activation_fn=tf.nn.relu, scope='preact')
  71. if depth == depth_in:
  72. shortcut = resnet_utils.subsample(inputs, stride, 'shortcut')
  73. else:
  74. shortcut = slim.conv2d(preact, depth, [1, 1], stride=stride,
  75. normalizer_fn=None, activation_fn=None,
  76. scope='shortcut')
  77. residual = slim.conv2d(preact, depth_bottleneck, [1, 1], stride=1,
  78. scope='conv1')
  79. residual = resnet_utils.conv2d_same(residual, depth_bottleneck, 3, stride,
  80. rate=rate, scope='conv2')
  81. residual = slim.conv2d(residual, depth, [1, 1], stride=1,
  82. normalizer_fn=None, activation_fn=None,
  83. scope='conv3')
  84. output = shortcut + residual
  85. return slim.utils.collect_named_outputs(outputs_collections,
  86. sc.name,
  87. output)
  88. def resnet_v2(inputs,
  89. blocks,
  90. num_classes=None,
  91. is_training=True,
  92. global_pool=True,
  93. output_stride=None,
  94. include_root_block=True,
  95. spatial_squeeze=True,
  96. reuse=None,
  97. scope=None):
  98. """Generator for v2 (preactivation) ResNet models.
  99. This function generates a family of ResNet v2 models. See the resnet_v2_*()
  100. methods for specific model instantiations, obtained by selecting different
  101. block instantiations that produce ResNets of various depths.
  102. Training for image classification on Imagenet is usually done with [224, 224]
  103. inputs, resulting in [7, 7] feature maps at the output of the last ResNet
  104. block for the ResNets defined in [1] that have nominal stride equal to 32.
  105. However, for dense prediction tasks we advise that one uses inputs with
  106. spatial dimensions that are multiples of 32 plus 1, e.g., [321, 321]. In
  107. this case the feature maps at the ResNet output will have spatial shape
  108. [(height - 1) / output_stride + 1, (width - 1) / output_stride + 1]
  109. and corners exactly aligned with the input image corners, which greatly
  110. facilitates alignment of the features to the image. Using as input [225, 225]
  111. images results in [8, 8] feature maps at the output of the last ResNet block.
  112. For dense prediction tasks, the ResNet needs to run in fully-convolutional
  113. (FCN) mode and global_pool needs to be set to False. The ResNets in [1, 2] all
  114. have nominal stride equal to 32 and a good choice in FCN mode is to use
  115. output_stride=16 in order to increase the density of the computed features at
  116. small computational and memory overhead, cf. http://arxiv.org/abs/1606.00915.
  117. Args:
  118. inputs: A tensor of size [batch, height_in, width_in, channels].
  119. blocks: A list of length equal to the number of ResNet blocks. Each element
  120. is a resnet_utils.Block object describing the units in the block.
  121. num_classes: Number of predicted classes for classification tasks.
  122. If 0 or None, we return the features before the logit layer.
  123. is_training: whether batch_norm layers are in training mode.
  124. global_pool: If True, we perform global average pooling before computing the
  125. logits. Set to True for image classification, False for dense prediction.
  126. output_stride: If None, then the output will be computed at the nominal
  127. network stride. If output_stride is not None, it specifies the requested
  128. ratio of input to output spatial resolution.
  129. include_root_block: If True, include the initial convolution followed by
  130. max-pooling, if False excludes it. If excluded, `inputs` should be the
  131. results of an activation-less convolution.
  132. spatial_squeeze: if True, logits is of shape [B, C], if false logits is
  133. of shape [B, 1, 1, C], where B is batch_size and C is number of classes.
  134. To use this parameter, the input images must be smaller than 300x300
  135. pixels, in which case the output logit layer does not contain spatial
  136. information and can be removed.
  137. reuse: whether or not the network and its variables should be reused. To be
  138. able to reuse 'scope' must be given.
  139. scope: Optional variable_scope.
  140. Returns:
  141. net: A rank-4 tensor of size [batch, height_out, width_out, channels_out].
  142. If global_pool is False, then height_out and width_out are reduced by a
  143. factor of output_stride compared to the respective height_in and width_in,
  144. else both height_out and width_out equal one. If num_classes is 0 or None,
  145. then net is the output of the last ResNet block, potentially after global
  146. average pooling. If num_classes is a non-zero integer, net contains the
  147. pre-softmax activations.
  148. end_points: A dictionary from components of the network to the corresponding
  149. activation.
  150. Raises:
  151. ValueError: If the target output_stride is not valid.
  152. """
  153. with tf.variable_scope(scope, 'resnet_v2', [inputs], reuse=reuse) as sc:
  154. end_points_collection = sc.original_name_scope + '_end_points'
  155. with slim.arg_scope([slim.conv2d, bottleneck,
  156. resnet_utils.stack_blocks_dense],
  157. outputs_collections=end_points_collection):
  158. with slim.arg_scope([slim.batch_norm], is_training=is_training):
  159. net = inputs
  160. if include_root_block:
  161. if output_stride is not None:
  162. if output_stride % 4 != 0:
  163. raise ValueError('The output_stride needs to be a multiple of 4.')
  164. output_stride /= 4
  165. # We do not include batch normalization or activation functions in
  166. # conv1 because the first ResNet unit will perform these. Cf.
  167. # Appendix of [2].
  168. with slim.arg_scope([slim.conv2d],
  169. activation_fn=None, normalizer_fn=None):
  170. net = resnet_utils.conv2d_same(net, 64, 7, stride=2, scope='conv1')
  171. net = slim.max_pool2d(net, [3, 3], stride=2, scope='pool1')
  172. net = resnet_utils.stack_blocks_dense(net, blocks, output_stride)
  173. # This is needed because the pre-activation variant does not have batch
  174. # normalization or activation functions in the residual unit output. See
  175. # Appendix of [2].
  176. net = slim.batch_norm(net, activation_fn=tf.nn.relu, scope='postnorm')
  177. # Convert end_points_collection into a dictionary of end_points.
  178. end_points = slim.utils.convert_collection_to_dict(
  179. end_points_collection)
  180. if global_pool:
  181. # Global average pooling.
  182. net = tf.reduce_mean(net, [1, 2], name='pool5', keep_dims=True)
  183. end_points['global_pool'] = net
  184. if num_classes is not None:
  185. net = slim.conv2d(net, num_classes, [1, 1], activation_fn=None,
  186. normalizer_fn=None, scope='logits')
  187. end_points[sc.name + '/logits'] = net
  188. if spatial_squeeze:
  189. net = tf.squeeze(net, [1, 2], name='SpatialSqueeze')
  190. end_points[sc.name + '/spatial_squeeze'] = net
  191. end_points['predictions'] = slim.softmax(net, scope='predictions')
  192. return net, end_points
  193. resnet_v2.default_image_size = 224
  194. def resnet_v2_block(scope, base_depth, num_units, stride):
  195. """Helper function for creating a resnet_v2 bottleneck block.
  196. Args:
  197. scope: The scope of the block.
  198. base_depth: The depth of the bottleneck layer for each unit.
  199. num_units: The number of units in the block.
  200. stride: The stride of the block, implemented as a stride in the last unit.
  201. All other units have stride=1.
  202. Returns:
  203. A resnet_v2 bottleneck block.
  204. """
  205. return resnet_utils.Block(scope, bottleneck, [{
  206. 'depth': base_depth * 4,
  207. 'depth_bottleneck': base_depth,
  208. 'stride': 1
  209. }] * (num_units - 1) + [{
  210. 'depth': base_depth * 4,
  211. 'depth_bottleneck': base_depth,
  212. 'stride': stride
  213. }])
  214. resnet_v2.default_image_size = 224
  215. def resnet_v2_50(inputs,
  216. num_classes=None,
  217. is_training=True,
  218. global_pool=True,
  219. output_stride=None,
  220. spatial_squeeze=True,
  221. reuse=None,
  222. scope='resnet_v2_50'):
  223. """ResNet-50 model of [1]. See resnet_v2() for arg and return description."""
  224. blocks = [
  225. resnet_v2_block('block1', base_depth=64, num_units=3, stride=2),
  226. resnet_v2_block('block2', base_depth=128, num_units=4, stride=2),
  227. resnet_v2_block('block3', base_depth=256, num_units=6, stride=2),
  228. resnet_v2_block('block4', base_depth=512, num_units=3, stride=1),
  229. ]
  230. return resnet_v2(inputs, blocks, num_classes, is_training=is_training,
  231. global_pool=global_pool, output_stride=output_stride,
  232. include_root_block=True, spatial_squeeze=spatial_squeeze,
  233. reuse=reuse, scope=scope)
  234. resnet_v2_50.default_image_size = resnet_v2.default_image_size
  235. def resnet_v2_101(inputs,
  236. num_classes=None,
  237. is_training=True,
  238. global_pool=True,
  239. output_stride=None,
  240. spatial_squeeze=True,
  241. reuse=None,
  242. scope='resnet_v2_101'):
  243. """ResNet-101 model of [1]. See resnet_v2() for arg and return description."""
  244. blocks = [
  245. resnet_v2_block('block1', base_depth=64, num_units=3, stride=2),
  246. resnet_v2_block('block2', base_depth=128, num_units=4, stride=2),
  247. resnet_v2_block('block3', base_depth=256, num_units=23, stride=2),
  248. resnet_v2_block('block4', base_depth=512, num_units=3, stride=1),
  249. ]
  250. return resnet_v2(inputs, blocks, num_classes, is_training=is_training,
  251. global_pool=global_pool, output_stride=output_stride,
  252. include_root_block=True, spatial_squeeze=spatial_squeeze,
  253. reuse=reuse, scope=scope)
  254. resnet_v2_101.default_image_size = resnet_v2.default_image_size
  255. def resnet_v2_152(inputs,
  256. num_classes=None,
  257. is_training=True,
  258. global_pool=True,
  259. output_stride=None,
  260. spatial_squeeze=True,
  261. reuse=None,
  262. scope='resnet_v2_152'):
  263. """ResNet-152 model of [1]. See resnet_v2() for arg and return description."""
  264. blocks = [
  265. resnet_v2_block('block1', base_depth=64, num_units=3, stride=2),
  266. resnet_v2_block('block2', base_depth=128, num_units=8, stride=2),
  267. resnet_v2_block('block3', base_depth=256, num_units=36, stride=2),
  268. resnet_v2_block('block4', base_depth=512, num_units=3, stride=1),
  269. ]
  270. return resnet_v2(inputs, blocks, num_classes, is_training=is_training,
  271. global_pool=global_pool, output_stride=output_stride,
  272. include_root_block=True, spatial_squeeze=spatial_squeeze,
  273. reuse=reuse, scope=scope)
  274. resnet_v2_152.default_image_size = resnet_v2.default_image_size
  275. def resnet_v2_200(inputs,
  276. num_classes=None,
  277. is_training=True,
  278. global_pool=True,
  279. output_stride=None,
  280. spatial_squeeze=True,
  281. reuse=None,
  282. scope='resnet_v2_200'):
  283. """ResNet-200 model of [2]. See resnet_v2() for arg and return description."""
  284. blocks = [
  285. resnet_v2_block('block1', base_depth=64, num_units=3, stride=2),
  286. resnet_v2_block('block2', base_depth=128, num_units=24, stride=2),
  287. resnet_v2_block('block3', base_depth=256, num_units=36, stride=2),
  288. resnet_v2_block('block4', base_depth=512, num_units=3, stride=1),
  289. ]
  290. return resnet_v2(inputs, blocks, num_classes, is_training=is_training,
  291. global_pool=global_pool, output_stride=output_stride,
  292. include_root_block=True, spatial_squeeze=spatial_squeeze,
  293. reuse=reuse, scope=scope)
  294. resnet_v2_200.default_image_size = resnet_v2.default_image_size