resnet50_modified.py 11.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding: utf-8 -*-
"""
The resnet50 from `tf.keras.applications.Resnet50` has a problem with the convolutional layers.
It basically add bias terms to such layers followed by batch normalizations, which is not correct

https://github.com/tensorflow/tensorflow/issues/37365

This resnet 50 implementation provides a cleaner version
"""

import tensorflow as tf

from tensorflow.keras.regularizers import l2
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
14
15
from tensorflow.keras.layers import Conv2D, Activation, BatchNormalization
from tensorflow.keras.layers import MaxPooling2D
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

global weight_decay
weight_decay = 1e-4


class IdentityBlock(tf.keras.layers.Layer):
    def __init__(
        self, kernel_size, filters, stage, block, weight_decay=1e-4, name=None, **kwargs
    ):

        """Block that has no convolutianal layer as skip connection
        
        Parameters
        ----------
            kernel_size: 
               The kernel size of middle conv layer at main path
            
            filters: 
                list of integers, the filterss of 3 conv layer at main path
            stage: 
              Current stage label, used for generating layer names

            block:
                'a','b'..., current block label, used for generating layer names

        """
        super().__init__(name=name, **kwargs)

        filters1, filters2, filters3 = filters
        bn_axis = 3

        conv_name_1 = "conv" + str(stage) + "_" + str(block) + "_1x1_reduce"
        bn_name_1 = "conv" + str(stage) + "_" + str(block) + "_1x1_reduce/bn"
        layers = [
            Conv2D(
                filters1,
                (1, 1),
                kernel_initializer="orthogonal",
                use_bias=False,
                kernel_regularizer=l2(weight_decay),
                name=conv_name_1,
            )
        ]

        layers += [BatchNormalization(axis=bn_axis, name=bn_name_1)]
        layers += [Activation("relu")]

        conv_name_2 = "conv" + str(stage) + "_" + str(block) + "_3x3"
        bn_name_2 = "conv" + str(stage) + "_" + str(block) + "_3x3/bn"
        layers += [
            Conv2D(
                filters2,
                kernel_size,
                padding="same",
                kernel_initializer="orthogonal",
                use_bias=False,
                kernel_regularizer=l2(weight_decay),
                name=conv_name_2,
            )
        ]
        layers += [BatchNormalization(axis=bn_axis, name=bn_name_2)]
        layers += [Activation("relu")]

        conv_name_3 = "conv" + str(stage) + "_" + str(block) + "_1x1_increase"
        bn_name_3 = "conv" + str(stage) + "_" + str(block) + "_1x1_increase/bn"
        layers += [
            Conv2D(
                filters3,
                (1, 1),
                kernel_initializer="orthogonal",
                use_bias=False,
                kernel_regularizer=l2(weight_decay),
                name=conv_name_3,
            )
        ]
        layers += [BatchNormalization(axis=bn_axis, name=bn_name_3)]
        self.layers = layers

    def call(self, input_tensor, training=None):

        x = input_tensor
        for l in self.layers:
            x = l(x, training=training)

        x = tf.keras.layers.add([x, input_tensor])
        x = Activation("relu")(x)

        return x


class ConvBlock(tf.keras.layers.Layer):
    def __init__(
        self,
        kernel_size,
        filters,
        stage,
        block,
        strides=(2, 2),
        weight_decay=1e-4,
        name=None,
        **kwargs,
    ):
        """ Block that has a conv layer AS shortcut.
        Parameters
        ----------
            kernel_size: 
               The kernel size of middle conv layer at main path
            
            filters: 
                list of integers, the filterss of 3 conv layer at main path
            stage: 
              Current stage label, used for generating layer names

            block:
                'a','b'..., current block label, used for generating layer names
        """
        super().__init__(name=name, **kwargs)

        filters1, filters2, filters3 = filters
        bn_axis = 3

        conv_name_1 = "conv" + str(stage) + "_" + str(block) + "_1x1_reduce"
        bn_name_1 = "conv" + str(stage) + "_" + str(block) + "_1x1_reduce/bn"
        layers = [
            Conv2D(
                filters1,
                (1, 1),
                strides=strides,
                kernel_initializer="orthogonal",
                use_bias=False,
                kernel_regularizer=l2(weight_decay),
                name=conv_name_1,
            )
        ]
        layers += [BatchNormalization(axis=bn_axis, name=bn_name_1)]
        layers += [Activation("relu")]

        conv_name_2 = "conv" + str(stage) + "_" + str(block) + "_3x3"
        bn_name_2 = "conv" + str(stage) + "_" + str(block) + "_3x3/bn"
        layers += [
            Conv2D(
                filters2,
                kernel_size,
                padding="same",
                kernel_initializer="orthogonal",
                use_bias=False,
                kernel_regularizer=l2(weight_decay),
                name=conv_name_2,
            )
        ]
        layers += [BatchNormalization(axis=bn_axis, name=bn_name_2)]
        layers += [Activation("relu")]

        conv_name_3 = "conv" + str(stage) + "_" + str(block) + "_1x1_increase"
        bn_name_3 = "conv" + str(stage) + "_" + str(block) + "_1x1_increase/bn"
        layers += [
            Conv2D(
                filters3,
                (1, 1),
                kernel_initializer="orthogonal",
                use_bias=False,
                kernel_regularizer=l2(weight_decay),
                name=conv_name_3,
            )
        ]
        layers += [BatchNormalization(axis=bn_axis, name=bn_name_3)]

        conv_name_4 = "conv" + str(stage) + "_" + str(block) + "_1x1_proj"
        bn_name_4 = "conv" + str(stage) + "_" + str(block) + "_1x1_proj/bn"
        shortcut = [
            Conv2D(
                filters3,
                (1, 1),
                strides=strides,
                kernel_initializer="orthogonal",
                use_bias=False,
                kernel_regularizer=l2(weight_decay),
                name=conv_name_4,
            )
        ]
        shortcut += [BatchNormalization(axis=bn_axis, name=bn_name_4)]

        self.layers = layers
        self.shortcut = shortcut

    def call(self, input_tensor, training=None):
        x = input_tensor
        for l in self.layers:
            x = l(x, training=training)

        x_s = input_tensor
        for l in self.shortcut:
            x_s = l(x_s, training=training)

        x = tf.keras.layers.add([x, x_s])
        x = Activation("relu")(x)
        return x


def resnet50_modified(input_tensor=None, input_shape=None, **kwargs):
    """
    The resnet50 from `tf.keras.applications.Resnet50` has a problem with the convolutional layers.
    It basically add bias terms to such layers followed by batch normalizations, which is not correct

    https://github.com/tensorflow/tensorflow/issues/37365

    This resnet 50 implementation provides a cleaner version

    """
    if input_tensor is None:
        input_tensor = tf.keras.Input(shape=input_shape)
    else:
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
228
        if not tf.keras.backend.is_keras_tensor(input_tensor):
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
            input_tensor = tf.keras.Input(tensor=input_tensor, shape=input_shape)

    bn_axis = 3
    # inputs are of size 224 x 224 x 3
    layers = [input_tensor]
    layers += [
        Conv2D(
            64,
            (7, 7),
            strides=(2, 2),
            kernel_initializer="orthogonal",
            use_bias=False,
            trainable=True,
            kernel_regularizer=l2(weight_decay),
            padding="same",
            name="conv1/7x7_s2",
        )
    ]

    # inputs are of size 112 x 112 x 64
    layers += [BatchNormalization(axis=bn_axis, name="conv1/7x7_s2/bn")]
    layers += [Activation("relu")]
    layers += [MaxPooling2D((3, 3), strides=(2, 2))]

    # inputs are of size 56 x 56
    layers += [ConvBlock(3, [64, 64, 256], stage=2, block=1, strides=(1, 1))]
    layers += [IdentityBlock(3, [64, 64, 256], stage=2, block=2)]
    layers += [IdentityBlock(3, [64, 64, 256], stage=2, block=3)]

    # inputs are of size 28 x 28
    layers += [ConvBlock(3, [128, 128, 512], stage=3, block=1)]
    layers += [IdentityBlock(3, [128, 128, 512], stage=3, block=2)]
    layers += [IdentityBlock(3, [128, 128, 512], stage=3, block=3)]
    layers += [IdentityBlock(3, [128, 128, 512], stage=3, block=4)]

    # inputs are of size 14 x 14
    layers += [ConvBlock(3, [256, 256, 1024], stage=4, block=1)]
    layers += [IdentityBlock(3, [256, 256, 1024], stage=4, block=2)]
    layers += [IdentityBlock(3, [256, 256, 1024], stage=4, block=3)]
    layers += [IdentityBlock(3, [256, 256, 1024], stage=4, block=4)]
    layers += [IdentityBlock(3, [256, 256, 1024], stage=4, block=5)]
    layers += [IdentityBlock(3, [256, 256, 1024], stage=4, block=6)]

    # inputs are of size 7 x 7
    layers += [ConvBlock(3, [512, 512, 2048], stage=5, block=1)]
    layers += [IdentityBlock(3, [512, 512, 2048], stage=5, block=2)]
    layers += [IdentityBlock(3, [512, 512, 2048], stage=5, block=3)]

    return tf.keras.Sequential(layers)


def resnet101_modified(input_tensor=None, input_shape=None, **kwargs):
    """
    The resnet101 from `tf.keras.applications.Resnet101` has a problem with the convolutional layers.
    It basically add bias terms to such layers followed by batch normalizations, which is not correct

    https://github.com/tensorflow/tensorflow/issues/37365

    This resnet 10 implementation provides a cleaner version

    """

    if input_tensor is None:
        input_tensor = tf.keras.Input(shape=input_shape)
    else:
        if not tf.keras.backend.is_keras_tensor(input_tensor):
            input_tensor = tf.keras.Input(tensor=input_tensor, shape=input_shape)

    bn_axis = 3
    # inputs are of size 224 x 224 x 3
    layers = [input_tensor]
    layers += [
        Conv2D(
            64,
            (7, 7),
            strides=(2, 2),
            kernel_initializer="orthogonal",
            use_bias=False,
            trainable=True,
            kernel_regularizer=l2(weight_decay),
            padding="same",
            name="conv1/7x7_s2",
        )
    ]

    # inputs are of size 112 x 112 x 64
    layers += [BatchNormalization(axis=bn_axis, name="conv1/7x7_s2/bn")]
    layers += [Activation("relu")]
    layers += [MaxPooling2D((3, 3), strides=(2, 2))]

    # inputs are of size 56 x 56
    layers += [ConvBlock(3, [64, 64, 256], stage=2, block=1, strides=(1, 1))]
    layers += [IdentityBlock(3, [64, 64, 256], stage=2, block=2)]
    layers += [IdentityBlock(3, [64, 64, 256], stage=2, block=3)]

    # inputs are of size 28 x 28
    layers += [ConvBlock(3, [128, 128, 512], stage=3, block=1)]
    layers += [IdentityBlock(3, [128, 128, 512], stage=3, block=2)]
    layers += [IdentityBlock(3, [128, 128, 512], stage=3, block=3)]
    layers += [IdentityBlock(3, [128, 128, 512], stage=3, block=4)]

    # inputs are of size 14 x 14
    # 23 blocks here. That's the only difference from
    # resnet-101
    layers += [ConvBlock(3, [256, 256, 1024], stage=4, block=1)]
    for i in range(2, 24):
        layers += [IdentityBlock(3, [256, 256, 1024], stage=4, block=i)]

    # inputs are of size 7 x 7
    layers += [ConvBlock(3, [512, 512, 2048], stage=5, block=1)]
    layers += [IdentityBlock(3, [512, 512, 2048], stage=5, block=2)]
    layers += [IdentityBlock(3, [512, 512, 2048], stage=5, block=3)]

    return tf.keras.Sequential(layers)


if __name__ == "__main__":
    input_tensor = tf.keras.layers.InputLayer([112, 112, 3])
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
347
    model = resnet50_modified(input_tensor)
348
349
350
351

    print(len(model.variables))
    print(model.summary())