|
a |
|
b/model/model.py |
|
|
1 |
from tensorflow.keras import backend as K |
|
|
2 |
from tensorflow.keras.applications.densenet import DenseNet121 |
|
|
3 |
from tensorflow.keras.applications.densenet import DenseNet169 |
|
|
4 |
# Model Imports |
|
|
5 |
from tensorflow.keras.applications.resnet_v2 import ResNet50V2 |
|
|
6 |
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Multiply, Concatenate, Input |
|
|
7 |
from tensorflow.keras.models import Model |
|
|
8 |
|
|
|
9 |
|
|
|
10 |
# Parallelize Custom Block |
|
|
11 |
def parallelize_block(tensor, ratio=128): |
|
|
12 |
nb_channel = K.int_shape(tensor)[-1] |
|
|
13 |
|
|
|
14 |
# Averaging |
|
|
15 |
x = GlobalAveragePooling2D()(tensor) |
|
|
16 |
x = Dense(nb_channel // ratio, activation='relu')(x) |
|
|
17 |
x = Dense(nb_channel, activation='sigmoid')(x) |
|
|
18 |
|
|
|
19 |
# Weighting |
|
|
20 |
x = Multiply()([tensor, x]) |
|
|
21 |
return x |
|
|
22 |
|
|
|
23 |
|
|
|
24 |
# MAIN MODEL |
|
|
25 |
def ParallelXNet(n_classes, tau=128, input_shape=(320, 320, 3), weights='imagenet', output_activation="sigmoid"): |
|
|
26 |
# Combined Input |
|
|
27 |
combinedInput = Input(batch_shape=(None, None, None, 3)) |
|
|
28 |
|
|
|
29 |
# Base models preoaded with imagenet weights |
|
|
30 |
resnetV2_m = ResNet50V2(weights=weights, include_top=False, |
|
|
31 |
input_shape=input_shape, input_tensor=combinedInput) |
|
|
32 |
densenet121_m = DenseNet121(weights=weights, include_top=False, |
|
|
33 |
input_shape=input_shape, input_tensor=combinedInput) |
|
|
34 |
densenet169_m = DenseNet169(weights=weights, include_top=False, |
|
|
35 |
input_shape=input_shape, input_tensor=combinedInput) |
|
|
36 |
|
|
|
37 |
for layer in resnetV2_m.layers: |
|
|
38 |
layer._name = layer.name + str("_0") |
|
|
39 |
|
|
|
40 |
for layer in densenet121_m.layers: |
|
|
41 |
layer._name = layer.name + str("_1") |
|
|
42 |
|
|
|
43 |
for layer in densenet169_m.layers: |
|
|
44 |
layer._name = layer.name + str("_2") |
|
|
45 |
|
|
|
46 |
base_model_output = [ |
|
|
47 |
resnetV2_m.output, |
|
|
48 |
densenet121_m.output, |
|
|
49 |
densenet169_m.output |
|
|
50 |
] |
|
|
51 |
|
|
|
52 |
# Concatenating the models |
|
|
53 |
c_model = Concatenate()(base_model_output) |
|
|
54 |
|
|
|
55 |
# Passing via parallelize block |
|
|
56 |
par_c_model = parallelize_block( |
|
|
57 |
tensor=c_model, |
|
|
58 |
ratio=tau |
|
|
59 |
) |
|
|
60 |
|
|
|
61 |
# Final Average Pooling layer |
|
|
62 |
x = GlobalAveragePooling2D()(par_c_model) |
|
|
63 |
|
|
|
64 |
# Final Dense Layer |
|
|
65 |
detection_output = Dense(n_classes, activation=output_activation)(x) |
|
|
66 |
|
|
|
67 |
return Model(inputs=combinedInput, outputs=detection_output) |