Diff of /inception_resnet_v2.py [000000] .. [968c76]

Switch to unified view

a b/inception_resnet_v2.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
# The content is derived from https://github.com/tensorflow/models/blob/master/slim/nets/inception_resnet_v2.py
16
# ==============================================================================
17
18
"""Contains the definition of the Inception Resnet V2 architecture.
19
20
As described in http://arxiv.org/abs/1602.07261.
21
22
  Inception-v4, Inception-ResNet and the Impact of Residual Connections
23
    on Learning
24
  Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, Alex Alemi
25
"""
26
from __future__ import absolute_import
27
from __future__ import division
28
from __future__ import print_function
29
30
import tensorflow as tf
31
32
slim = tf.contrib.slim
33
34
35
def block35(net, scale = 1.0, activation_fn = tf.nn.relu, scope = None, reuse = None):
36
    """Builds the 35x35 resnet block."""
37
    with tf.variable_scope(scope, 'Block35', [net], reuse = reuse):
38
        with tf.variable_scope('Branch_0'):
39
            tower_conv = slim.conv2d(net, 32, 1, scope = 'Conv2d_1x1')
40
        with tf.variable_scope('Branch_1'):
41
            tower_conv1_0 = slim.conv2d(net, 32, 1, scope = 'Conv2d_0a_1x1')
42
            tower_conv1_1 = slim.conv2d(tower_conv1_0, 32, 3, scope = 'Conv2d_0b_3x3')
43
        with tf.variable_scope('Branch_2'):
44
            tower_conv2_0 = slim.conv2d(net, 32, 1, scope = 'Conv2d_0a_1x1')
45
            tower_conv2_1 = slim.conv2d(tower_conv2_0, 48, 3, scope = 'Conv2d_0b_3x3')
46
            tower_conv2_2 = slim.conv2d(tower_conv2_1, 64, 3, scope = 'Conv2d_0c_3x3')
47
        mixed = tf.concat(axis = 3, values = [tower_conv, tower_conv1_1, tower_conv2_2])
48
        up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn = None,
49
                         activation_fn = None, scope = 'Conv2d_1x1')
50
        net += scale * up
51
        if activation_fn:
52
            net = activation_fn(net)
53
    return net
54
55
56
def block17(net, scale = 1.0, activation_fn = tf.nn.relu, scope = None, reuse = None):
57
    """Builds the 17x17 resnet block."""
58
    with tf.variable_scope(scope, 'Block17', [net], reuse = reuse):
59
        with tf.variable_scope('Branch_0'):
60
            tower_conv = slim.conv2d(net, 192, 1, scope = 'Conv2d_1x1')
61
        with tf.variable_scope('Branch_1'):
62
            tower_conv1_0 = slim.conv2d(net, 128, 1, scope = 'Conv2d_0a_1x1')
63
            tower_conv1_1 = slim.conv2d(tower_conv1_0, 160, [1, 7],
64
                                        scope = 'Conv2d_0b_1x7')
65
            tower_conv1_2 = slim.conv2d(tower_conv1_1, 192, [7, 1],
66
                                        scope = 'Conv2d_0c_7x1')
67
        mixed = tf.concat(axis = 3, values = [tower_conv, tower_conv1_2])
68
        up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn = None,
69
                         activation_fn = None, scope = 'Conv2d_1x1')
70
        net += scale * up
71
        if activation_fn:
72
            net = activation_fn(net)
73
    return net
74
75
76
def block8(net, scale = 1.0, activation_fn = tf.nn.relu, scope = None, reuse = None):
77
    """Builds the 8x8 resnet block."""
78
    with tf.variable_scope(scope, 'Block8', [net], reuse = reuse):
79
        with tf.variable_scope('Branch_0'):
80
            tower_conv = slim.conv2d(net, 192, 1, scope = 'Conv2d_1x1')
81
        with tf.variable_scope('Branch_1'):
82
            tower_conv1_0 = slim.conv2d(net, 192, 1, scope = 'Conv2d_0a_1x1')
83
            tower_conv1_1 = slim.conv2d(tower_conv1_0, 224, [1, 3],
84
                                        scope = 'Conv2d_0b_1x3')
85
            tower_conv1_2 = slim.conv2d(tower_conv1_1, 256, [3, 1],
86
                                        scope = 'Conv2d_0c_3x1')
87
        mixed = tf.concat(axis = 3, values = [tower_conv, tower_conv1_2])
88
        up = slim.conv2d(mixed, net.get_shape()[3], 1, normalizer_fn = None,
89
                         activation_fn = None, scope = 'Conv2d_1x1')
90
        net += scale * up
91
        if activation_fn:
92
            net = activation_fn(net)
93
    return net
94
95
96
def inception_resnet_v2(inputs, is_training = True,
97
                            reuse = None,
98
                            scope = 'InceptionResnetV2'):
99
    """Creates the Inception Resnet V2 model.
100
101
  Args:
102
    inputs: a 4-D tensor of size [batch_size, height, width, 3].
103
    num_classes: number of predicted classes.
104
    is_training: whether is training or not.
105
    dropout_keep_prob: float, the fraction to keep before final layer.
106
    reuse: whether or not the network and its variables should be reused. To be
107
      able to reuse 'scope' must be given.
108
    scope: Optional variable_scope.
109
110
  Returns:
111
    logits: the logits outputs of the model.
112
    end_points: the set of end_points from the inception model.
113
  """
114
    end_points = { }
115
116
    with tf.variable_scope(scope, 'InceptionResnetV2', [inputs], reuse = reuse):
117
        with slim.arg_scope([slim.batch_norm, slim.dropout],
118
                            is_training = is_training):
119
            with slim.arg_scope([slim.conv2d, slim.max_pool2d, slim.avg_pool2d],
120
                                stride = 1, padding = 'SAME'):
121
                # 149 x 149 x 32
122
                net = slim.conv2d(inputs, 32, 3, stride = 2, padding = 'VALID',
123
                                  scope = 'Conv2d_1a_3x3')
124
                end_points['Conv2d_1a_3x3'] = net
125
                # 147 x 147 x 32
126
                net = slim.conv2d(net, 32, 3, padding = 'VALID',
127
                                  scope = 'Conv2d_2a_3x3')
128
                end_points['Conv2d_2a_3x3'] = net
129
                # 147 x 147 x 64
130
                net = slim.conv2d(net, 64, 3, scope = 'Conv2d_2b_3x3')
131
                end_points['Conv2d_2b_3x3'] = net
132
                # 73 x 73 x 64
133
                net = slim.max_pool2d(net, 3, stride = 2, padding = 'VALID',
134
                                      scope = 'MaxPool_3a_3x3')
135
                end_points['MaxPool_3a_3x3'] = net
136
                # 73 x 73 x 80
137
                net = slim.conv2d(net, 80, 1, padding = 'VALID',
138
                                  scope = 'Conv2d_3b_1x1')
139
                end_points['Conv2d_3b_1x1'] = net
140
                # 71 x 71 x 192
141
                net = slim.conv2d(net, 192, 3, padding = 'VALID',
142
                                  scope = 'Conv2d_4a_3x3')
143
                end_points['Conv2d_4a_3x3'] = net
144
                # 35 x 35 x 192
145
                net = slim.max_pool2d(net, 3, stride = 2, padding = 'VALID',
146
                                      scope = 'MaxPool_5a_3x3')
147
                end_points['MaxPool_5a_3x3'] = net
148
149
                # 35 x 35 x 320
150
                with tf.variable_scope('Mixed_5b'):
151
                    with tf.variable_scope('Branch_0'):
152
                        tower_conv = slim.conv2d(net, 96, 1, scope = 'Conv2d_1x1')
153
                    with tf.variable_scope('Branch_1'):
154
                        tower_conv1_0 = slim.conv2d(net, 48, 1, scope = 'Conv2d_0a_1x1')
155
                        tower_conv1_1 = slim.conv2d(tower_conv1_0, 64, 5,
156
                                                    scope = 'Conv2d_0b_5x5')
157
                    with tf.variable_scope('Branch_2'):
158
                        tower_conv2_0 = slim.conv2d(net, 64, 1, scope = 'Conv2d_0a_1x1')
159
                        tower_conv2_1 = slim.conv2d(tower_conv2_0, 96, 3,
160
                                                    scope = 'Conv2d_0b_3x3')
161
                        tower_conv2_2 = slim.conv2d(tower_conv2_1, 96, 3,
162
                                                    scope = 'Conv2d_0c_3x3')
163
                    with tf.variable_scope('Branch_3'):
164
                        tower_pool = slim.avg_pool2d(net, 3, stride = 1, padding = 'SAME',
165
                                                     scope = 'AvgPool_0a_3x3')
166
                        tower_pool_1 = slim.conv2d(tower_pool, 64, 1,
167
                                                   scope = 'Conv2d_0b_1x1')
168
                    net = tf.concat(axis = 3, values = [tower_conv, tower_conv1_1,
169
                                        tower_conv2_2, tower_pool_1])
170
171
                end_points['Mixed_5b'] = net
172
                net = slim.repeat(net, 10, block35, scale = 0.17)
173
174
                # 17 x 17 x 1024
175
                with tf.variable_scope('Mixed_6a'):
176
                    with tf.variable_scope('Branch_0'):
177
                        tower_conv = slim.conv2d(net, 384, 3, stride = 2, padding = 'VALID',
178
                                                 scope = 'Conv2d_1a_3x3')
179
                    with tf.variable_scope('Branch_1'):
180
                        tower_conv1_0 = slim.conv2d(net, 256, 1, scope = 'Conv2d_0a_1x1')
181
                        tower_conv1_1 = slim.conv2d(tower_conv1_0, 256, 3,
182
                                                    scope = 'Conv2d_0b_3x3')
183
                        tower_conv1_2 = slim.conv2d(tower_conv1_1, 384, 3,
184
                                                    stride = 2, padding = 'VALID',
185
                                                    scope = 'Conv2d_1a_3x3')
186
                    with tf.variable_scope('Branch_2'):
187
                        tower_pool = slim.max_pool2d(net, 3, stride = 2, padding = 'VALID',
188
                                                     scope = 'MaxPool_1a_3x3')
189
                    net = tf.concat(axis = 3, values = [tower_conv, tower_conv1_2, tower_pool])
190
191
                end_points['Mixed_6a'] = net
192
                net = slim.repeat(net, 20, block17, scale = 0.10)
193
194
                end_points['BeforeAux'] = net
195
196
                # Auxiliary tower
197
                with tf.variable_scope('AuxLogits'):
198
                    aux = slim.avg_pool2d(net, 5, stride = 1, padding = 'SAME',
199
                                          scope = 'Conv2d_1a_3x3')
200
                    aux = slim.conv2d(aux, 128, 1, scope = 'Conv2d_1b_1x1')
201
                    aux = slim.conv2d(aux, 768, 5,
202
                                      padding = 'SAME', scope = 'Conv2d_2a_5x5')
203
204
                    end_points['AuxBeforeScoring'] = aux
205
206
        return aux, end_points
207
208
inception_resnet_v2.default_image_size = 299
209
210
211
def inception_resnet_v2_arg_scope(weight_decay = 0.00004,
212
                                  batch_norm_decay = 0.9997,
213
                                  batch_norm_epsilon = 0.001):
214
    """Yields the scope with the default parameters for inception_resnet_v2.
215
216
  Args:
217
    weight_decay: the weight decay for weights variables.
218
    batch_norm_decay: decay for the moving average of batch_norm momentums.
219
    batch_norm_epsilon: small float added to variance to avoid dividing by zero.
220
221
  Returns:
222
    a arg_scope with the parameters needed for inception_resnet_v2.
223
  """
224
    # Set weight_decay for weights in conv2d and fully_connected layers.
225
226
    with slim.arg_scope([slim.conv2d, slim.fully_connected],
227
                        weights_regularizer = slim.l2_regularizer(weight_decay),
228
                        biases_regularizer = slim.l2_regularizer(weight_decay)):
229
        batch_norm_params = {
230
            'decay': batch_norm_decay,
231
            'epsilon': batch_norm_epsilon
232
        }
233
        # Set activation_fn and parameters for batch_norm.
234
        with slim.arg_scope([slim.conv2d], activation_fn = tf.nn.relu,
235
                            normalizer_fn = slim.batch_norm,
236
                            normalizer_params = batch_norm_params) as scope:
237
            return scope