inception_v2_test.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. """Tests for nets.inception_v2."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import numpy as np
  20. import tensorflow as tf
  21. from nets import inception
  22. slim = tf.contrib.slim
  23. class InceptionV2Test(tf.test.TestCase):
  24. def testBuildClassificationNetwork(self):
  25. batch_size = 5
  26. height, width = 224, 224
  27. num_classes = 1000
  28. inputs = tf.random_uniform((batch_size, height, width, 3))
  29. logits, end_points = inception.inception_v2(inputs, num_classes)
  30. self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
  31. self.assertListEqual(logits.get_shape().as_list(),
  32. [batch_size, num_classes])
  33. self.assertTrue('Predictions' in end_points)
  34. self.assertListEqual(end_points['Predictions'].get_shape().as_list(),
  35. [batch_size, num_classes])
  36. def testBuildBaseNetwork(self):
  37. batch_size = 5
  38. height, width = 224, 224
  39. inputs = tf.random_uniform((batch_size, height, width, 3))
  40. mixed_5c, end_points = inception.inception_v2_base(inputs)
  41. self.assertTrue(mixed_5c.op.name.startswith('InceptionV2/Mixed_5c'))
  42. self.assertListEqual(mixed_5c.get_shape().as_list(),
  43. [batch_size, 7, 7, 1024])
  44. expected_endpoints = ['Mixed_3b', 'Mixed_3c', 'Mixed_4a', 'Mixed_4b',
  45. 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_5a',
  46. 'Mixed_5b', 'Mixed_5c', 'Conv2d_1a_7x7',
  47. 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3',
  48. 'MaxPool_3a_3x3']
  49. self.assertItemsEqual(end_points.keys(), expected_endpoints)
  50. def testBuildOnlyUptoFinalEndpoint(self):
  51. batch_size = 5
  52. height, width = 224, 224
  53. endpoints = ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1',
  54. 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c',
  55. 'Mixed_4a', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e',
  56. 'Mixed_5a', 'Mixed_5b', 'Mixed_5c']
  57. for index, endpoint in enumerate(endpoints):
  58. with tf.Graph().as_default():
  59. inputs = tf.random_uniform((batch_size, height, width, 3))
  60. out_tensor, end_points = inception.inception_v2_base(
  61. inputs, final_endpoint=endpoint)
  62. self.assertTrue(out_tensor.op.name.startswith(
  63. 'InceptionV2/' + endpoint))
  64. self.assertItemsEqual(endpoints[:index+1], end_points)
  65. def testBuildAndCheckAllEndPointsUptoMixed5c(self):
  66. batch_size = 5
  67. height, width = 224, 224
  68. inputs = tf.random_uniform((batch_size, height, width, 3))
  69. _, end_points = inception.inception_v2_base(inputs,
  70. final_endpoint='Mixed_5c')
  71. endpoints_shapes = {'Mixed_3b': [batch_size, 28, 28, 256],
  72. 'Mixed_3c': [batch_size, 28, 28, 320],
  73. 'Mixed_4a': [batch_size, 14, 14, 576],
  74. 'Mixed_4b': [batch_size, 14, 14, 576],
  75. 'Mixed_4c': [batch_size, 14, 14, 576],
  76. 'Mixed_4d': [batch_size, 14, 14, 576],
  77. 'Mixed_4e': [batch_size, 14, 14, 576],
  78. 'Mixed_5a': [batch_size, 7, 7, 1024],
  79. 'Mixed_5b': [batch_size, 7, 7, 1024],
  80. 'Mixed_5c': [batch_size, 7, 7, 1024],
  81. 'Conv2d_1a_7x7': [batch_size, 112, 112, 64],
  82. 'MaxPool_2a_3x3': [batch_size, 56, 56, 64],
  83. 'Conv2d_2b_1x1': [batch_size, 56, 56, 64],
  84. 'Conv2d_2c_3x3': [batch_size, 56, 56, 192],
  85. 'MaxPool_3a_3x3': [batch_size, 28, 28, 192]}
  86. self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys())
  87. for endpoint_name in endpoints_shapes:
  88. expected_shape = endpoints_shapes[endpoint_name]
  89. self.assertTrue(endpoint_name in end_points)
  90. self.assertListEqual(end_points[endpoint_name].get_shape().as_list(),
  91. expected_shape)
  92. def testModelHasExpectedNumberOfParameters(self):
  93. batch_size = 5
  94. height, width = 224, 224
  95. inputs = tf.random_uniform((batch_size, height, width, 3))
  96. with slim.arg_scope(inception.inception_v2_arg_scope()):
  97. inception.inception_v2_base(inputs)
  98. total_params, _ = slim.model_analyzer.analyze_vars(
  99. slim.get_model_variables())
  100. self.assertAlmostEqual(10173112, total_params)
  101. def testBuildEndPointsWithDepthMultiplierLessThanOne(self):
  102. batch_size = 5
  103. height, width = 224, 224
  104. num_classes = 1000
  105. inputs = tf.random_uniform((batch_size, height, width, 3))
  106. _, end_points = inception.inception_v2(inputs, num_classes)
  107. endpoint_keys = [key for key in end_points.keys()
  108. if key.startswith('Mixed') or key.startswith('Conv')]
  109. _, end_points_with_multiplier = inception.inception_v2(
  110. inputs, num_classes, scope='depth_multiplied_net',
  111. depth_multiplier=0.5)
  112. for key in endpoint_keys:
  113. original_depth = end_points[key].get_shape().as_list()[3]
  114. new_depth = end_points_with_multiplier[key].get_shape().as_list()[3]
  115. self.assertEqual(0.5 * original_depth, new_depth)
  116. def testBuildEndPointsWithDepthMultiplierGreaterThanOne(self):
  117. batch_size = 5
  118. height, width = 224, 224
  119. num_classes = 1000
  120. inputs = tf.random_uniform((batch_size, height, width, 3))
  121. _, end_points = inception.inception_v2(inputs, num_classes)
  122. endpoint_keys = [key for key in end_points.keys()
  123. if key.startswith('Mixed') or key.startswith('Conv')]
  124. _, end_points_with_multiplier = inception.inception_v2(
  125. inputs, num_classes, scope='depth_multiplied_net',
  126. depth_multiplier=2.0)
  127. for key in endpoint_keys:
  128. original_depth = end_points[key].get_shape().as_list()[3]
  129. new_depth = end_points_with_multiplier[key].get_shape().as_list()[3]
  130. self.assertEqual(2.0 * original_depth, new_depth)
  131. def testRaiseValueErrorWithInvalidDepthMultiplier(self):
  132. batch_size = 5
  133. height, width = 224, 224
  134. num_classes = 1000
  135. inputs = tf.random_uniform((batch_size, height, width, 3))
  136. with self.assertRaises(ValueError):
  137. _ = inception.inception_v2(inputs, num_classes, depth_multiplier=-0.1)
  138. with self.assertRaises(ValueError):
  139. _ = inception.inception_v2(inputs, num_classes, depth_multiplier=0.0)
  140. def testHalfSizeImages(self):
  141. batch_size = 5
  142. height, width = 112, 112
  143. num_classes = 1000
  144. inputs = tf.random_uniform((batch_size, height, width, 3))
  145. logits, end_points = inception.inception_v2(inputs, num_classes)
  146. self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
  147. self.assertListEqual(logits.get_shape().as_list(),
  148. [batch_size, num_classes])
  149. pre_pool = end_points['Mixed_5c']
  150. self.assertListEqual(pre_pool.get_shape().as_list(),
  151. [batch_size, 4, 4, 1024])
  152. def testUnknownImageShape(self):
  153. tf.reset_default_graph()
  154. batch_size = 2
  155. height, width = 224, 224
  156. num_classes = 1000
  157. input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
  158. with self.test_session() as sess:
  159. inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3))
  160. logits, end_points = inception.inception_v2(inputs, num_classes)
  161. self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
  162. self.assertListEqual(logits.get_shape().as_list(),
  163. [batch_size, num_classes])
  164. pre_pool = end_points['Mixed_5c']
  165. feed_dict = {inputs: input_np}
  166. tf.global_variables_initializer().run()
  167. pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
  168. self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024])
  169. def testUnknowBatchSize(self):
  170. batch_size = 1
  171. height, width = 224, 224
  172. num_classes = 1000
  173. inputs = tf.placeholder(tf.float32, (None, height, width, 3))
  174. logits, _ = inception.inception_v2(inputs, num_classes)
  175. self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
  176. self.assertListEqual(logits.get_shape().as_list(),
  177. [None, num_classes])
  178. images = tf.random_uniform((batch_size, height, width, 3))
  179. with self.test_session() as sess:
  180. sess.run(tf.global_variables_initializer())
  181. output = sess.run(logits, {inputs: images.eval()})
  182. self.assertEquals(output.shape, (batch_size, num_classes))
  183. def testEvaluation(self):
  184. batch_size = 2
  185. height, width = 224, 224
  186. num_classes = 1000
  187. eval_inputs = tf.random_uniform((batch_size, height, width, 3))
  188. logits, _ = inception.inception_v2(eval_inputs, num_classes,
  189. is_training=False)
  190. predictions = tf.argmax(logits, 1)
  191. with self.test_session() as sess:
  192. sess.run(tf.global_variables_initializer())
  193. output = sess.run(predictions)
  194. self.assertEquals(output.shape, (batch_size,))
  195. def testTrainEvalWithReuse(self):
  196. train_batch_size = 5
  197. eval_batch_size = 2
  198. height, width = 150, 150
  199. num_classes = 1000
  200. train_inputs = tf.random_uniform((train_batch_size, height, width, 3))
  201. inception.inception_v2(train_inputs, num_classes)
  202. eval_inputs = tf.random_uniform((eval_batch_size, height, width, 3))
  203. logits, _ = inception.inception_v2(eval_inputs, num_classes, reuse=True)
  204. predictions = tf.argmax(logits, 1)
  205. with self.test_session() as sess:
  206. sess.run(tf.global_variables_initializer())
  207. output = sess.run(predictions)
  208. self.assertEquals(output.shape, (eval_batch_size,))
  209. def testLogitsNotSqueezed(self):
  210. num_classes = 25
  211. images = tf.random_uniform([1, 224, 224, 3])
  212. logits, _ = inception.inception_v2(images,
  213. num_classes=num_classes,
  214. spatial_squeeze=False)
  215. with self.test_session() as sess:
  216. tf.global_variables_initializer().run()
  217. logits_out = sess.run(logits)
  218. self.assertListEqual(list(logits_out.shape), [1, 1, 1, num_classes])
  219. if __name__ == '__main__':
  220. tf.test.main()