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