forked from xuannianz/EfficientDet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
255 lines (221 loc) · 12.5 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
from functools import reduce
# from keras import layers
# from keras import initializers
# from keras import models
# from keras_ import EfficientNetB0, EfficientNetB1, EfficientNetB2
# from keras_ import EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6
from tensorflow.keras import layers
from tensorflow.keras import initializers
from tensorflow.keras import models
from tfkeras import EfficientNetB0, EfficientNetB1, EfficientNetB2
from tfkeras import EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6
from layers import ClipBoxes, RegressBoxes, FilterDetections, wBiFPNAdd, BatchNormalization
from initializers import PriorProbability
w_bifpns = [64, 88, 112, 160, 224, 288, 384]
image_sizes = [512, 640, 768, 896, 1024, 1280, 1408]
backbones = [EfficientNetB0, EfficientNetB1, EfficientNetB2,
EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6]
def DepthwiseConvBlock(kernel_size, strides, name, freeze_bn=False):
f1 = layers.DepthwiseConv2D(kernel_size=kernel_size, strides=strides, padding='same',
use_bias=False, name='{}_dconv'.format(name))
f2 = BatchNormalization(freeze=freeze_bn, name='{}_bn'.format(name))
f3 = layers.ReLU(name='{}_relu'.format(name))
return reduce(lambda f, g: lambda *args, **kwargs: g(f(*args, **kwargs)), (f1, f2, f3))
def ConvBlock(num_channels, kernel_size, strides, name, freeze_bn=False):
f1 = layers.Conv2D(num_channels, kernel_size=kernel_size, strides=strides, padding='same',
use_bias=False, name='{}_conv'.format(name))
f2 = BatchNormalization(freeze=freeze_bn, name='{}_bn'.format(name))
f3 = layers.ReLU(name='{}_relu'.format(name))
return reduce(lambda f, g: lambda *args, **kwargs: g(f(*args, **kwargs)), (f1, f2, f3))
def build_BiFPN(features, num_channels, id, freeze_bn=False):
if id == 0:
_, _, C3, C4, C5 = features
P3_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P3'.format(id))(
C3)
P4_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P4'.format(id))(
C4)
P5_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P5'.format(id))(
C5)
P6_in = ConvBlock(num_channels, kernel_size=3, strides=2, freeze_bn=freeze_bn, name='BiFPN_{}_P6'.format(id))(
C5)
P7_in = ConvBlock(num_channels, kernel_size=3, strides=2, freeze_bn=freeze_bn, name='BiFPN_{}_P7'.format(id))(
P6_in)
else:
P3_in, P4_in, P5_in, P6_in, P7_in = features
P3_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P3'.format(id))(
P3_in)
P4_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P4'.format(id))(
P4_in)
P5_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P5'.format(id))(
P5_in)
P6_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P6'.format(id))(
P6_in)
P7_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P7'.format(id))(
P7_in)
# upsample
P7_U = layers.UpSampling2D()(P7_in)
P6_td = layers.Add()([P7_U, P6_in])
P6_td = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P6'.format(id))(P6_td)
P6_U = layers.UpSampling2D()(P6_td)
P5_td = layers.Add()([P6_U, P5_in])
P5_td = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P5'.format(id))(P5_td)
P5_U = layers.UpSampling2D()(P5_td)
P4_td = layers.Add()([P5_U, P4_in])
P4_td = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P4'.format(id))(P4_td)
P4_U = layers.UpSampling2D()(P4_td)
P3_out = layers.Add()([P4_U, P3_in])
P3_out = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P3'.format(id))(P3_out)
# downsample
P3_D = layers.MaxPooling2D(strides=(2, 2))(P3_out)
P4_out = layers.Add()([P3_D, P4_td, P4_in])
P4_out = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P4'.format(id))(P4_out)
P4_D = layers.MaxPooling2D(strides=(2, 2))(P4_out)
P5_out = layers.Add()([P4_D, P5_td, P5_in])
P5_out = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P5'.format(id))(P5_out)
P5_D = layers.MaxPooling2D(strides=(2, 2))(P5_out)
P6_out = layers.Add()([P5_D, P6_td, P6_in])
P6_out = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P6'.format(id))(P6_out)
P6_D = layers.MaxPooling2D(strides=(2, 2))(P6_out)
P7_out = layers.Add()([P6_D, P7_in])
P7_out = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P7'.format(id))(P7_out)
return P3_out, P4_out, P5_out, P6_out, P7_out
def build_wBiFPN(features, num_channels, id, freeze_bn=False):
if id == 0:
_, _, C3, C4, C5 = features
P3_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P3'.format(id))(
C3)
P4_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P4'.format(id))(
C4)
P5_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P5'.format(id))(
C5)
P6_in = ConvBlock(num_channels, kernel_size=3, strides=2, freeze_bn=freeze_bn, name='BiFPN_{}_P6'.format(id))(
C5)
P7_in = ConvBlock(num_channels, kernel_size=3, strides=2, freeze_bn=freeze_bn, name='BiFPN_{}_P7'.format(id))(
P6_in)
else:
P3_in, P4_in, P5_in, P6_in, P7_in = features
P3_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P3'.format(id))(
P3_in)
P4_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P4'.format(id))(
P4_in)
P5_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P5'.format(id))(
P5_in)
P6_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P6'.format(id))(
P6_in)
P7_in = ConvBlock(num_channels, kernel_size=1, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_P7'.format(id))(
P7_in)
# upsample
P7_U = layers.UpSampling2D()(P7_in)
P6_td = wBiFPNAdd(name='w_bi_fpn_add' if id == 0 else f'w_bi_fpn_add_{8 * id}')([P7_U, P6_in])
P6_td = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P6'.format(id))(P6_td)
P6_U = layers.UpSampling2D()(P6_td)
P5_td = wBiFPNAdd(name=f'w_bi_fpn_add_{8 * id + 1}')([P6_U, P5_in])
P5_td = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P5'.format(id))(P5_td)
P5_U = layers.UpSampling2D()(P5_td)
P4_td = wBiFPNAdd(name=f'w_bi_fpn_add_{8 * id + 2}')([P5_U, P4_in])
P4_td = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P4'.format(id))(P4_td)
P4_U = layers.UpSampling2D()(P4_td)
P3_out = wBiFPNAdd(name=f'w_bi_fpn_add_{8 * id + 3}')([P4_U, P3_in])
P3_out = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_U_P3'.format(id))(P3_out)
# downsample
P3_D = layers.MaxPooling2D(strides=(2, 2))(P3_out)
P4_out = wBiFPNAdd(name=f'w_bi_fpn_add_{8 * id + 4}')([P3_D, P4_td, P4_in])
P4_out = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P4'.format(id))(P4_out)
P4_D = layers.MaxPooling2D(strides=(2, 2))(P4_out)
P5_out = wBiFPNAdd(name=f'w_bi_fpn_add_{8 * id + 5}')([P4_D, P5_td, P5_in])
P5_out = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P5'.format(id))(P5_out)
P5_D = layers.MaxPooling2D(strides=(2, 2))(P5_out)
P6_out = wBiFPNAdd(name=f'w_bi_fpn_add_{8 * id + 6}')([P5_D, P6_td, P6_in])
P6_out = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P6'.format(id))(P6_out)
P6_D = layers.MaxPooling2D(strides=(2, 2))(P6_out)
P7_out = wBiFPNAdd(name=f'w_bi_fpn_add_{8 * id + 7}')([P6_D, P7_in])
P7_out = DepthwiseConvBlock(kernel_size=3, strides=1, freeze_bn=freeze_bn, name='BiFPN_{}_D_P7'.format(id))(P7_out)
return P3_out, P4_out, P5_out, P6_out, P7_out
def build_regress_head(width, depth, num_anchors=9):
options = {
'kernel_size': 3,
'strides': 1,
'padding': 'same',
# 'kernel_initializer': initializers.normal(mean=0.0, stddev=0.01, seed=None),
'kernel_initializer': initializers.RandomNormal(mean=0.0, stddev=0.01, seed=None),
'bias_initializer': 'zeros'
}
inputs = layers.Input(shape=(None, None, width))
outputs = inputs
for i in range(depth):
outputs = layers.Conv2D(
filters=width,
activation='relu',
**options
)(outputs)
outputs = layers.Conv2D(num_anchors * 4, **options)(outputs)
# (b, num_anchors_this_feature_map, 4)
outputs = layers.Reshape((-1, 4))(outputs)
return models.Model(inputs=inputs, outputs=outputs, name='box_head')
def build_class_head(width, depth, num_classes=20, num_anchors=9):
options = {
'kernel_size': 3,
'strides': 1,
'padding': 'same',
# 'kernel_initializer': initializers.normal(mean=0.0, stddev=0.01, seed=None),
}
inputs = layers.Input(shape=(None, None, width))
outputs = inputs
for i in range(depth):
outputs = layers.Conv2D(
filters=width,
activation='relu',
kernel_initializer=initializers.RandomNormal(mean=0.0, stddev=0.01, seed=None),
bias_initializer='zeros',
**options
)(outputs)
# outputs = layers.Conv2D(num_anchors * num_classes, **options)(outputs)
outputs = layers.Conv2D(
filters=num_classes * num_anchors,
kernel_initializer=initializers.RandomNormal(mean=0.0, stddev=0.01, seed=None),
bias_initializer=PriorProbability(probability=0.01),
name='pyramid_classification',
**options
)(outputs)
# (b, num_anchors_this_feature_map, 4)
outputs = layers.Reshape((-1, num_classes))(outputs)
outputs = layers.Activation('sigmoid')(outputs)
return models.Model(inputs=inputs, outputs=outputs, name='class_head')
def efficientdet(phi, num_classes=20, weighted_bifpn=False, freeze_bn=False, score_threshold=0.01):
assert phi in range(7)
input_size = image_sizes[phi]
input_shape = (input_size, input_size, 3)
# input_shape = (None, None, 3)
image_input = layers.Input(input_shape)
w_bifpn = w_bifpns[phi]
d_bifpn = 2 + phi
w_head = w_bifpn
d_head = 3 + int(phi / 3)
backbone_cls = backbones[phi]
# features = backbone_cls(include_top=False, input_shape=input_shape, weights=weights)(image_input)
features = backbone_cls(input_tensor=image_input, freeze_bn=freeze_bn)
if weighted_bifpn:
for i in range(d_bifpn):
features = build_wBiFPN(features, w_bifpn, i, freeze_bn=freeze_bn)
else:
for i in range(d_bifpn):
features = build_BiFPN(features, w_bifpn, i, freeze_bn=freeze_bn)
regress_head = build_regress_head(w_head, d_head)
class_head = build_class_head(w_head, d_head, num_classes=num_classes)
regression = [regress_head(feature) for feature in features]
regression = layers.Concatenate(axis=1, name='regression')(regression)
classification = [class_head(feature) for feature in features]
classification = layers.Concatenate(axis=1, name='classification')(classification)
model = models.Model(inputs=[image_input], outputs=[regression, classification], name='efficientdet')
# apply predicted regression to anchors
# anchors = tf.tile(tf.expand_dims(tf.constant(anchors), axis=0), (tf.shape(regression)[0], 1, 1))
anchors_input = layers.Input((None, 4))
boxes = RegressBoxes(name='boxes')([anchors_input, regression])
boxes = ClipBoxes(name='clipped_boxes')([image_input, boxes])
# filter detections (apply NMS / score threshold / select top-k)
detections = FilterDetections(
name='filtered_detections',
score_threshold=score_threshold
)([boxes, classification])
prediction_model = models.Model(inputs=[image_input, anchors_input], outputs=detections, name='efficientdet_p')
return model, prediction_model