1 # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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 slim_nets.inception_v2."""
17 from __future__ import absolute_import
18 from __future__ import division
19 from __future__ import print_function
22 import tensorflow as tf
24 from nets import inception
26 slim = tf.contrib.slim
29 class InceptionV2Test(tf.test.TestCase):
31 def testBuildClassificationNetwork(self):
33 height, width = 224, 224
36 inputs = tf.random_uniform((batch_size, height, width, 3))
37 logits, end_points = inception.inception_v2(inputs, num_classes)
38 self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
39 self.assertListEqual(logits.get_shape().as_list(),
40 [batch_size, num_classes])
41 self.assertTrue('Predictions' in end_points)
42 self.assertListEqual(end_points['Predictions'].get_shape().as_list(),
43 [batch_size, num_classes])
45 def testBuildBaseNetwork(self):
47 height, width = 224, 224
49 inputs = tf.random_uniform((batch_size, height, width, 3))
50 mixed_5c, end_points = inception.inception_v2_base(inputs)
51 self.assertTrue(mixed_5c.op.name.startswith('InceptionV2/Mixed_5c'))
52 self.assertListEqual(mixed_5c.get_shape().as_list(),
53 [batch_size, 7, 7, 1024])
54 expected_endpoints = ['Mixed_3b', 'Mixed_3c', 'Mixed_4a', 'Mixed_4b',
55 'Mixed_4c', 'Mixed_4d', 'Mixed_4e', 'Mixed_5a',
56 'Mixed_5b', 'Mixed_5c', 'Conv2d_1a_7x7',
57 'MaxPool_2a_3x3', 'Conv2d_2b_1x1', 'Conv2d_2c_3x3',
59 self.assertItemsEqual(end_points.keys(), expected_endpoints)
61 def testBuildOnlyUptoFinalEndpoint(self):
63 height, width = 224, 224
64 endpoints = ['Conv2d_1a_7x7', 'MaxPool_2a_3x3', 'Conv2d_2b_1x1',
65 'Conv2d_2c_3x3', 'MaxPool_3a_3x3', 'Mixed_3b', 'Mixed_3c',
66 'Mixed_4a', 'Mixed_4b', 'Mixed_4c', 'Mixed_4d', 'Mixed_4e',
67 'Mixed_5a', 'Mixed_5b', 'Mixed_5c']
68 for index, endpoint in enumerate(endpoints):
69 with tf.Graph().as_default():
70 inputs = tf.random_uniform((batch_size, height, width, 3))
71 out_tensor, end_points = inception.inception_v2_base(
72 inputs, final_endpoint=endpoint)
73 self.assertTrue(out_tensor.op.name.startswith(
74 'InceptionV2/' + endpoint))
75 self.assertItemsEqual(endpoints[:index+1], end_points)
77 def testBuildAndCheckAllEndPointsUptoMixed5c(self):
79 height, width = 224, 224
81 inputs = tf.random_uniform((batch_size, height, width, 3))
82 _, end_points = inception.inception_v2_base(inputs,
83 final_endpoint='Mixed_5c')
84 endpoints_shapes = {'Mixed_3b': [batch_size, 28, 28, 256],
85 'Mixed_3c': [batch_size, 28, 28, 320],
86 'Mixed_4a': [batch_size, 14, 14, 576],
87 'Mixed_4b': [batch_size, 14, 14, 576],
88 'Mixed_4c': [batch_size, 14, 14, 576],
89 'Mixed_4d': [batch_size, 14, 14, 576],
90 'Mixed_4e': [batch_size, 14, 14, 576],
91 'Mixed_5a': [batch_size, 7, 7, 1024],
92 'Mixed_5b': [batch_size, 7, 7, 1024],
93 'Mixed_5c': [batch_size, 7, 7, 1024],
94 'Conv2d_1a_7x7': [batch_size, 112, 112, 64],
95 'MaxPool_2a_3x3': [batch_size, 56, 56, 64],
96 'Conv2d_2b_1x1': [batch_size, 56, 56, 64],
97 'Conv2d_2c_3x3': [batch_size, 56, 56, 192],
98 'MaxPool_3a_3x3': [batch_size, 28, 28, 192]}
99 self.assertItemsEqual(endpoints_shapes.keys(), end_points.keys())
100 for endpoint_name in endpoints_shapes:
101 expected_shape = endpoints_shapes[endpoint_name]
102 self.assertTrue(endpoint_name in end_points)
103 self.assertListEqual(end_points[endpoint_name].get_shape().as_list(),
106 def testModelHasExpectedNumberOfParameters(self):
108 height, width = 224, 224
109 inputs = tf.random_uniform((batch_size, height, width, 3))
110 with slim.arg_scope(inception.inception_v2_arg_scope()):
111 inception.inception_v2_base(inputs)
112 total_params, _ = slim.model_analyzer.analyze_vars(
113 slim.get_model_variables())
114 self.assertAlmostEqual(10173112, total_params)
116 def testBuildEndPointsWithDepthMultiplierLessThanOne(self):
118 height, width = 224, 224
121 inputs = tf.random_uniform((batch_size, height, width, 3))
122 _, end_points = inception.inception_v2(inputs, num_classes)
124 endpoint_keys = [key for key in end_points.keys()
125 if key.startswith('Mixed') or key.startswith('Conv')]
127 _, end_points_with_multiplier = inception.inception_v2(
128 inputs, num_classes, scope='depth_multiplied_net',
129 depth_multiplier=0.5)
131 for key in endpoint_keys:
132 original_depth = end_points[key].get_shape().as_list()[3]
133 new_depth = end_points_with_multiplier[key].get_shape().as_list()[3]
134 self.assertEqual(0.5 * original_depth, new_depth)
136 def testBuildEndPointsWithDepthMultiplierGreaterThanOne(self):
138 height, width = 224, 224
141 inputs = tf.random_uniform((batch_size, height, width, 3))
142 _, end_points = inception.inception_v2(inputs, num_classes)
144 endpoint_keys = [key for key in end_points.keys()
145 if key.startswith('Mixed') or key.startswith('Conv')]
147 _, end_points_with_multiplier = inception.inception_v2(
148 inputs, num_classes, scope='depth_multiplied_net',
149 depth_multiplier=2.0)
151 for key in endpoint_keys:
152 original_depth = end_points[key].get_shape().as_list()[3]
153 new_depth = end_points_with_multiplier[key].get_shape().as_list()[3]
154 self.assertEqual(2.0 * original_depth, new_depth)
156 def testRaiseValueErrorWithInvalidDepthMultiplier(self):
158 height, width = 224, 224
161 inputs = tf.random_uniform((batch_size, height, width, 3))
162 with self.assertRaises(ValueError):
163 _ = inception.inception_v2(inputs, num_classes, depth_multiplier=-0.1)
164 with self.assertRaises(ValueError):
165 _ = inception.inception_v2(inputs, num_classes, depth_multiplier=0.0)
167 def testHalfSizeImages(self):
169 height, width = 112, 112
172 inputs = tf.random_uniform((batch_size, height, width, 3))
173 logits, end_points = inception.inception_v2(inputs, num_classes)
174 self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
175 self.assertListEqual(logits.get_shape().as_list(),
176 [batch_size, num_classes])
177 pre_pool = end_points['Mixed_5c']
178 self.assertListEqual(pre_pool.get_shape().as_list(),
179 [batch_size, 4, 4, 1024])
181 def testUnknownImageShape(self):
182 tf.reset_default_graph()
184 height, width = 224, 224
186 input_np = np.random.uniform(0, 1, (batch_size, height, width, 3))
187 with self.test_session() as sess:
188 inputs = tf.placeholder(tf.float32, shape=(batch_size, None, None, 3))
189 logits, end_points = inception.inception_v2(inputs, num_classes)
190 self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
191 self.assertListEqual(logits.get_shape().as_list(),
192 [batch_size, num_classes])
193 pre_pool = end_points['Mixed_5c']
194 feed_dict = {inputs: input_np}
195 tf.global_variables_initializer().run()
196 pre_pool_out = sess.run(pre_pool, feed_dict=feed_dict)
197 self.assertListEqual(list(pre_pool_out.shape), [batch_size, 7, 7, 1024])
199 def testUnknowBatchSize(self):
201 height, width = 224, 224
204 inputs = tf.placeholder(tf.float32, (None, height, width, 3))
205 logits, _ = inception.inception_v2(inputs, num_classes)
206 self.assertTrue(logits.op.name.startswith('InceptionV2/Logits'))
207 self.assertListEqual(logits.get_shape().as_list(),
209 images = tf.random_uniform((batch_size, height, width, 3))
211 with self.test_session() as sess:
212 sess.run(tf.global_variables_initializer())
213 output = sess.run(logits, {inputs: images.eval()})
214 self.assertEquals(output.shape, (batch_size, num_classes))
216 def testEvaluation(self):
218 height, width = 224, 224
221 eval_inputs = tf.random_uniform((batch_size, height, width, 3))
222 logits, _ = inception.inception_v2(eval_inputs, num_classes,
224 predictions = tf.argmax(logits, 1)
226 with self.test_session() as sess:
227 sess.run(tf.global_variables_initializer())
228 output = sess.run(predictions)
229 self.assertEquals(output.shape, (batch_size,))
231 def testTrainEvalWithReuse(self):
234 height, width = 150, 150
237 train_inputs = tf.random_uniform((train_batch_size, height, width, 3))
238 inception.inception_v2(train_inputs, num_classes)
239 eval_inputs = tf.random_uniform((eval_batch_size, height, width, 3))
240 logits, _ = inception.inception_v2(eval_inputs, num_classes, reuse=True)
241 predictions = tf.argmax(logits, 1)
243 with self.test_session() as sess:
244 sess.run(tf.global_variables_initializer())
245 output = sess.run(predictions)
246 self.assertEquals(output.shape, (eval_batch_size,))
248 def testLogitsNotSqueezed(self):
250 images = tf.random_uniform([1, 224, 224, 3])
251 logits, _ = inception.inception_v2(images,
252 num_classes=num_classes,
253 spatial_squeeze=False)
255 with self.test_session() as sess:
256 tf.global_variables_initializer().run()
257 logits_out = sess.run(logits)
258 self.assertListEqual(list(logits_out.shape), [1, 1, 1, num_classes])
261 if __name__ == '__main__':