inception_resnet_v2.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 the definition of the Inception Resnet V2 architecture.
  16. As described in http://arxiv.org/abs/1602.07261.
  17. Inception-v4, Inception-ResNet and the Impact of Residual Connections
  18. on Learning
  19. Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, Alex Alemi
  20. """
  21. from __future__ import absolute_import
  22. from __future__ import division
  23. from __future__ import print_function
  24. import tensorflow as tf
  25. slim = tf.contrib.slim
  26. def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
  27. """Builds the 35x35 resnet block."""
  28. with tf.variable_scope(scope, 'Block35', [net], reuse=reuse):
  29. with tf.variable_scope('Branch_0'):
  30. tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1')
  31. with tf.variable_scope('Branch_1'):
  32. tower_conv1_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1')
  33. tower_conv1_1 = slim.conv2d(tower_conv1_0, 32, 3, scope='Conv2d_0b_3x3')
  34. with tf.variable_scope('Branch_2'):
  35. tower_conv2_0 = slim.conv2d(net, 32, 1, scope='Conv2d_0a_1x1')
  36. tower_conv2_1 = slim.conv2d(tower_conv2_0, 48, 3, scope='Conv2d_0b_3x3')
  37. tower_conv2_2 = slim.conv2d(tower_conv2_1, 64, 3, scope='Conv2d_0c_3x3')
  38. mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_1, tower_conv2_2])
  39. up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None,
  40. activation_fn=None, scope='Conv2d_1x1')
  41. scaled_up = up * scale
  42. if activation_fn == tf.nn.relu6:
  43. # Use clip_by_value to simulate bandpass activation.
  44. scaled_up = tf.clip_by_value(scaled_up, -6.0, 6.0)
  45. net += scaled_up
  46. if activation_fn:
  47. net = activation_fn(net)
  48. return net
  49. def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
  50. """Builds the 17x17 resnet block."""
  51. with tf.variable_scope(scope, 'Block17', [net], reuse=reuse):
  52. with tf.variable_scope('Branch_0'):
  53. tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')
  54. with tf.variable_scope('Branch_1'):
  55. tower_conv1_0 = slim.conv2d(net, 128, 1, scope='Conv2d_0a_1x1')
  56. tower_conv1_1 = slim.conv2d(tower_conv1_0, 160, [1, 7],
  57. scope='Conv2d_0b_1x7')
  58. tower_conv1_2 = slim.conv2d(tower_conv1_1, 192, [7, 1],
  59. scope='Conv2d_0c_7x1')
  60. mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_2])
  61. up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None,
  62. activation_fn=None, scope='Conv2d_1x1')
  63. scaled_up = up * scale
  64. if activation_fn == tf.nn.relu6:
  65. # Use clip_by_value to simulate bandpass activation.
  66. scaled_up = tf.clip_by_value(scaled_up, -6.0, 6.0)
  67. net += scaled_up
  68. if activation_fn:
  69. net = activation_fn(net)
  70. return net
  71. def block8(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
  72. """Builds the 8x8 resnet block."""
  73. with tf.variable_scope(scope, 'Block8', [net], reuse=reuse):
  74. with tf.variable_scope('Branch_0'):
  75. tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')
  76. with tf.variable_scope('Branch_1'):
  77. tower_conv1_0 = slim.conv2d(net, 192, 1, scope='Conv2d_0a_1x1')
  78. tower_conv1_1 = slim.conv2d(tower_conv1_0, 224, [1, 3],
  79. scope='Conv2d_0b_1x3')
  80. tower_conv1_2 = slim.conv2d(tower_conv1_1, 256, [3, 1],
  81. scope='Conv2d_0c_3x1')
  82. mixed = tf.concat(axis=3, values=[tower_conv, tower_conv1_2])
  83. up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn=None,
  84. activation_fn=None, scope='Conv2d_1x1')
  85. scaled_up = up * scale
  86. if activation_fn == tf.nn.relu6:
  87. # Use clip_by_value to simulate bandpass activation.
  88. scaled_up = tf.clip_by_value(scaled_up, -6.0, 6.0)
  89. net += scaled_up
  90. if activation_fn:
  91. net = activation_fn(net)
  92. return net
  93. def inception_resnet_v2_base(inputs,
  94. final_endpoint='Conv2d_7b_1x1',
  95. output_stride=16,
  96. align_feature_maps=False,
  97. scope=None,
  98. activation_fn=tf.nn.relu):
  99. """Inception model from http://arxiv.org/abs/1602.07261.
  100. Constructs an Inception Resnet v2 network from inputs to the given final
  101. endpoint. This method can construct the network up to the final inception
  102. block Conv2d_7b_1x1.
  103. Args:
  104. inputs: a tensor of size [batch_size, height, width, channels].
  105. final_endpoint: specifies the endpoint to construct the network up to. It
  106. can be one of ['Conv2d_1a_3x3', 'Conv2d_2a_3x3', 'Conv2d_2b_3x3',
  107. 'MaxPool_3a_3x3', 'Conv2d_3b_1x1', 'Conv2d_4a_3x3', 'MaxPool_5a_3x3',
  108. 'Mixed_5b', 'Mixed_6a', 'PreAuxLogits', 'Mixed_7a', 'Conv2d_7b_1x1']
  109. output_stride: A scalar that specifies the requested ratio of input to
  110. output spatial resolution. Only supports 8 and 16.
  111. align_feature_maps: When true, changes all the VALID paddings in the network
  112. to SAME padding so that the feature maps are aligned.
  113. scope: Optional variable_scope.
  114. activation_fn: Activation function for block scopes.
  115. Returns:
  116. tensor_out: output tensor corresponding to the final_endpoint.
  117. end_points: a set of activations for external use, for example summaries or
  118. losses.
  119. Raises:
  120. ValueError: if final_endpoint is not set to one of the predefined values,
  121. or if the output_stride is not 8 or 16, or if the output_stride is 8 and
  122. we request an end point after 'PreAuxLogits'.
  123. """
  124. if output_stride != 8 and output_stride != 16:
  125. raise ValueError('output_stride must be 8 or 16.')
  126. padding = 'SAME' if align_feature_maps else 'VALID'
  127. end_points = {}
  128. def add_and_check_final(name, net):
  129. end_points[name] = net
  130. return name == final_endpoint
  131. with tf.variable_scope(scope, 'InceptionResnetV2', [inputs]):
  132. with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d],
  133. stride=1, padding='SAME'):
  134. # 149 x 149 x 32
  135. net = slim.conv2d(inputs, 32, 3, stride=2, padding=padding,
  136. scope='Conv2d_1a_3x3')
  137. if add_and_check_final('Conv2d_1a_3x3', net): return net, end_points
  138. # 147 x 147 x 32
  139. net = slim.conv2d(net, 32, 3, padding=padding,
  140. scope='Conv2d_2a_3x3')
  141. if add_and_check_final('Conv2d_2a_3x3', net): return net, end_points
  142. # 147 x 147 x 64
  143. net = slim.conv2d(net, 64, 3, scope='Conv2d_2b_3x3')
  144. if add_and_check_final('Conv2d_2b_3x3', net): return net, end_points
  145. # 73 x 73 x 64
  146. net = slim.max_pool2d(net, 3, stride=2, padding=padding,
  147. scope='MaxPool_3a_3x3')
  148. if add_and_check_final('MaxPool_3a_3x3', net): return net, end_points
  149. # 73 x 73 x 80
  150. net = slim.conv2d(net, 80, 1, padding=padding,
  151. scope='Conv2d_3b_1x1')
  152. if add_and_check_final('Conv2d_3b_1x1', net): return net, end_points
  153. # 71 x 71 x 192
  154. net = slim.conv2d(net, 192, 3, padding=padding,
  155. scope='Conv2d_4a_3x3')
  156. if add_and_check_final('Conv2d_4a_3x3', net): return net, end_points
  157. # 35 x 35 x 192
  158. net = slim.max_pool2d(net, 3, stride=2, padding=padding,
  159. scope='MaxPool_5a_3x3')
  160. if add_and_check_final('MaxPool_5a_3x3', net): return net, end_points
  161. # 35 x 35 x 320
  162. with tf.variable_scope('Mixed_5b'):
  163. with tf.variable_scope('Branch_0'):
  164. tower_conv = slim.conv2d(net, 96, 1, scope='Conv2d_1x1')
  165. with tf.variable_scope('Branch_1'):
  166. tower_conv1_0 = slim.conv2d(net, 48, 1, scope='Conv2d_0a_1x1')
  167. tower_conv1_1 = slim.conv2d(tower_conv1_0, 64, 5,
  168. scope='Conv2d_0b_5x5')
  169. with tf.variable_scope('Branch_2'):
  170. tower_conv2_0 = slim.conv2d(net, 64, 1, scope='Conv2d_0a_1x1')
  171. tower_conv2_1 = slim.conv2d(tower_conv2_0, 96, 3,
  172. scope='Conv2d_0b_3x3')
  173. tower_conv2_2 = slim.conv2d(tower_conv2_1, 96, 3,
  174. scope='Conv2d_0c_3x3')
  175. with tf.variable_scope('Branch_3'):
  176. tower_pool = slim.avg_pool2d(net, 3, stride=1, padding='SAME',
  177. scope='AvgPool_0a_3x3')
  178. tower_pool_1 = slim.conv2d(tower_pool, 64, 1,
  179. scope='Conv2d_0b_1x1')
  180. net = tf.concat(
  181. [tower_conv, tower_conv1_1, tower_conv2_2, tower_pool_1], 3)
  182. if add_and_check_final('Mixed_5b', net): return net, end_points
  183. # TODO(alemi): Register intermediate endpoints
  184. net = slim.repeat(net, 10, block35, scale=0.17,
  185. activation_fn=activation_fn)
  186. # 17 x 17 x 1088 if output_stride == 8,
  187. # 33 x 33 x 1088 if output_stride == 16
  188. use_atrous = output_stride == 8
  189. with tf.variable_scope('Mixed_6a'):
  190. with tf.variable_scope('Branch_0'):
  191. tower_conv = slim.conv2d(net, 384, 3, stride=1 if use_atrous else 2,
  192. padding=padding,
  193. scope='Conv2d_1a_3x3')
  194. with tf.variable_scope('Branch_1'):
  195. tower_conv1_0 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')
  196. tower_conv1_1 = slim.conv2d(tower_conv1_0, 256, 3,
  197. scope='Conv2d_0b_3x3')
  198. tower_conv1_2 = slim.conv2d(tower_conv1_1, 384, 3,
  199. stride=1 if use_atrous else 2,
  200. padding=padding,
  201. scope='Conv2d_1a_3x3')
  202. with tf.variable_scope('Branch_2'):
  203. tower_pool = slim.max_pool2d(net, 3, stride=1 if use_atrous else 2,
  204. padding=padding,
  205. scope='MaxPool_1a_3x3')
  206. net = tf.concat([tower_conv, tower_conv1_2, tower_pool], 3)
  207. if add_and_check_final('Mixed_6a', net): return net, end_points
  208. # TODO(alemi): register intermediate endpoints
  209. with slim.arg_scope([slim.conv2d], rate=2 if use_atrous else 1):
  210. net = slim.repeat(net, 20, block17, scale=0.10,
  211. activation_fn=activation_fn)
  212. if add_and_check_final('PreAuxLogits', net): return net, end_points
  213. if output_stride == 8:
  214. # TODO(gpapan): Properly support output_stride for the rest of the net.
  215. raise ValueError('output_stride==8 is only supported up to the '
  216. 'PreAuxlogits end_point for now.')
  217. # 8 x 8 x 2080
  218. with tf.variable_scope('Mixed_7a'):
  219. with tf.variable_scope('Branch_0'):
  220. tower_conv = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')
  221. tower_conv_1 = slim.conv2d(tower_conv, 384, 3, stride=2,
  222. padding=padding,
  223. scope='Conv2d_1a_3x3')
  224. with tf.variable_scope('Branch_1'):
  225. tower_conv1 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')
  226. tower_conv1_1 = slim.conv2d(tower_conv1, 288, 3, stride=2,
  227. padding=padding,
  228. scope='Conv2d_1a_3x3')
  229. with tf.variable_scope('Branch_2'):
  230. tower_conv2 = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')
  231. tower_conv2_1 = slim.conv2d(tower_conv2, 288, 3,
  232. scope='Conv2d_0b_3x3')
  233. tower_conv2_2 = slim.conv2d(tower_conv2_1, 320, 3, stride=2,
  234. padding=padding,
  235. scope='Conv2d_1a_3x3')
  236. with tf.variable_scope('Branch_3'):
  237. tower_pool = slim.max_pool2d(net, 3, stride=2,
  238. padding=padding,
  239. scope='MaxPool_1a_3x3')
  240. net = tf.concat(
  241. [tower_conv_1, tower_conv1_1, tower_conv2_2, tower_pool], 3)
  242. if add_and_check_final('Mixed_7a', net): return net, end_points
  243. # TODO(alemi): register intermediate endpoints
  244. net = slim.repeat(net, 9, block8, scale=0.20, activation_fn=activation_fn)
  245. net = block8(net, activation_fn=None)
  246. # 8 x 8 x 1536
  247. net = slim.conv2d(net, 1536, 1, scope='Conv2d_7b_1x1')
  248. if add_and_check_final('Conv2d_7b_1x1', net): return net, end_points
  249. raise ValueError('final_endpoint (%s) not recognized', final_endpoint)
  250. def inception_resnet_v2(inputs, num_classes=1001, is_training=True,
  251. dropout_keep_prob=0.8,
  252. reuse=None,
  253. scope='InceptionResnetV2',
  254. create_aux_logits=True,
  255. activation_fn=tf.nn.relu):
  256. """Creates the Inception Resnet V2 model.
  257. Args:
  258. inputs: a 4-D tensor of size [batch_size, height, width, 3].
  259. Dimension batch_size may be undefined. If create_aux_logits is false,
  260. also height and width may be undefined.
  261. num_classes: number of predicted classes. If 0 or None, the logits layer
  262. is omitted and the input features to the logits layer (before dropout)
  263. are returned instead.
  264. is_training: whether is training or not.
  265. dropout_keep_prob: float, the fraction to keep before final layer.
  266. reuse: whether or not the network and its variables should be reused. To be
  267. able to reuse 'scope' must be given.
  268. scope: Optional variable_scope.
  269. create_aux_logits: Whether to include the auxilliary logits.
  270. activation_fn: Activation function for conv2d.
  271. Returns:
  272. net: the output of the logits layer (if num_classes is a non-zero integer),
  273. or the non-dropped-out input to the logits layer (if num_classes is 0 or
  274. None).
  275. end_points: the set of end_points from the inception model.
  276. """
  277. end_points = {}
  278. with tf.variable_scope(scope, 'InceptionResnetV2', [inputs],
  279. reuse=reuse) as scope:
  280. with slim.arg_scope([slim.batch_norm, slim.dropout],
  281. is_training=is_training):
  282. net, end_points = inception_resnet_v2_base(inputs, scope=scope,
  283. activation_fn=activation_fn)
  284. if create_aux_logits and num_classes:
  285. with tf.variable_scope('AuxLogits'):
  286. aux = end_points['PreAuxLogits']
  287. aux = slim.avg_pool2d(aux, 5, stride=3, padding='VALID',
  288. scope='Conv2d_1a_3x3')
  289. aux = slim.conv2d(aux, 128, 1, scope='Conv2d_1b_1x1')
  290. aux = slim.conv2d(aux, 768, aux.get_shape()[1:3],
  291. padding='VALID', scope='Conv2d_2a_5x5')
  292. aux = slim.flatten(aux)
  293. aux = slim.fully_connected(aux, num_classes, activation_fn=None,
  294. scope='Logits')
  295. end_points['AuxLogits'] = aux
  296. with tf.variable_scope('Logits'):
  297. # TODO(sguada,arnoegw): Consider adding a parameter global_pool which
  298. # can be set to False to disable pooling here (as in resnet_*()).
  299. kernel_size = net.get_shape()[1:3]
  300. if kernel_size.is_fully_defined():
  301. net = slim.avg_pool2d(net, kernel_size, padding='VALID',
  302. scope='AvgPool_1a_8x8')
  303. else:
  304. net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool')
  305. end_points['global_pool'] = net
  306. if not num_classes:
  307. return net, end_points
  308. net = slim.flatten(net)
  309. net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
  310. scope='Dropout')
  311. end_points['PreLogitsFlatten'] = net
  312. logits = slim.fully_connected(net, num_classes, activation_fn=None,
  313. scope='Logits')
  314. end_points['Logits'] = logits
  315. end_points['Predictions'] = tf.nn.softmax(logits, name='Predictions')
  316. return logits, end_points
  317. inception_resnet_v2.default_image_size = 299
  318. def inception_resnet_v2_arg_scope(weight_decay=0.00004,
  319. batch_norm_decay=0.9997,
  320. batch_norm_epsilon=0.001,
  321. activation_fn=tf.nn.relu):
  322. """Returns the scope with the default parameters for inception_resnet_v2.
  323. Args:
  324. weight_decay: the weight decay for weights variables.
  325. batch_norm_decay: decay for the moving average of batch_norm momentums.
  326. batch_norm_epsilon: small float added to variance to avoid dividing by zero.
  327. activation_fn: Activation function for conv2d.
  328. Returns:
  329. a arg_scope with the parameters needed for inception_resnet_v2.
  330. """
  331. # Set weight_decay for weights in conv2d and fully_connected layers.
  332. with slim.arg_scope([slim.conv2d, slim.fully_connected],
  333. weights_regularizer=slim.l2_regularizer(weight_decay),
  334. biases_regularizer=slim.l2_regularizer(weight_decay)):
  335. batch_norm_params = {
  336. 'decay': batch_norm_decay,
  337. 'epsilon': batch_norm_epsilon,
  338. 'fused': None, # Use fused batch norm if possible.
  339. }
  340. # Set activation_fn and parameters for batch_norm.
  341. with slim.arg_scope([slim.conv2d], activation_fn=activation_fn,
  342. normalizer_fn=slim.batch_norm,
  343. normalizer_params=batch_norm_params) as scope:
  344. return scope