resnet_v1.py 15 KB

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