model_definitions.py 12.4 KB
Newer Older
Martin Lank's avatar
Martin Lank committed
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
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential

from utils import DATASET_DEFAULT_V3_TRAIN

img_width = 640
img_height = 480
num_classes = 6

w = 480
h = 360


def get_model(experiment_number):
    try:
        return globals()['get_exp_' + str(experiment_number)]()
    except:
        raise Exception("No model defined for experiment " + str(experiment_number))

def efficent_net(b_ver, dataset, fine_tuning=False, exp_number_to_fine_tune=None):
    if fine_tuning and exp_number_to_fine_tune is None:
        raise Exception("Exp number must be specified for fine tuning!")

    new_dim = 360

    inputs = keras.Input(shape=(img_height, img_width, 3))
    efnets = [
        keras.applications.efficientnet.EfficientNetB0,
        keras.applications.efficientnet.EfficientNetB1,
        keras.applications.efficientnet.EfficientNetB2,
        keras.applications.efficientnet.EfficientNetB3,
        keras.applications.efficientnet.EfficientNetB4,
        keras.applications.efficientnet.EfficientNetB5,
        keras.applications.efficientnet.EfficientNetB6,
        keras.applications.efficientnet.EfficientNetB7,
    ]

    base_model = efnets[b_ver](
        weights='imagenet',  # Load weights pre-trained on ImageNet.
        input_shape=(new_dim, new_dim, 3),
        include_top=False)  # Do not include the ImageNet classifier at the top.

    base_model.trainable = False

    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.Resizing(new_dim, new_dim, interpolation='bilinear'),
    ])

    x = data_augmentation(inputs)
    x = tf.keras.applications.efficientnet.preprocess_input(x)
    x = base_model(x, training=False)
    x = keras.layers.GlobalAveragePooling2D()(x)
    x = keras.layers.Dropout(0.2)(x)

    outputs = keras.layers.Dense(num_classes)(x)
    model = keras.Model(inputs, outputs)

    if fine_tuning:
        model.load_weights('training_' + str(exp_number_to_fine_tune) + '/cp_best.ckpt')
        model.compile(optimizer='adam', metrics=['accuracy'],
                      loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))
        base_model.trainable = True

        # Freeze all the layers before the `fine_tune_at` layer
        for layer in base_model.layers[:50 + b_ver * 50]:
            layer.trainable = False

    return model, 'adam' if not fine_tuning else keras.optimizers.Adam(1e-5), dataset


def efficent_net_v2(ver, dataset, fine_tuning=False, exp_number_to_fine_tune=None):

    new_dims = {
        '21k-s': 384,
        'b3-360': 360,
        'b3-300': 300
    }

    import tensorflow_hub as hub
    
    version_urls = {
        "21k-s": 'https://tfhub.dev/google/imagenet/efficientnet_v2_imagenet21k_ft1k_s/feature_vector/2',
        "b3-300": 'https://tfhub.dev/google/imagenet/efficientnet_v2_imagenet1k_b3/feature_vector/2',
        "b3-360": 'https://tfhub.dev/google/imagenet/efficientnet_v2_imagenet1k_b3/feature_vector/2'
    }
   
    model = keras.Sequential([
        keras.layers.InputLayer(input_shape=(img_height, img_width, 3)),
        layers.experimental.preprocessing.Resizing(new_dims[ver], new_dims[ver], interpolation='bilinear'),
        layers.experimental.preprocessing.Rescaling(scale=1. / 255),
        hub.KerasLayer(version_urls[ver], trainable=fine_tuning),        
        layers.Dropout(0.2),
        keras.layers.Dense(num_classes, kernel_regularizer=tf.keras.regularizers.l2(0.0001))
    ])


100
    if exp_number_to_fine_tune is not None:        
Martin Lank's avatar
Martin Lank committed
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
        model.load_weights('training_' + str(exp_number_to_fine_tune) + '/cp_best.ckpt')
        model.compile(optimizer='adam', metrics=['accuracy'],
                      loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))
     
    return model, 'adam' if not fine_tuning else keras.optimizers.Adam(1e-5), dataset


def get_exp_201():
    return xception(DATASET_DEFAULT_V3_TRAIN)


def get_exp_202():
    return xception(DATASET_DEFAULT_V3_TRAIN, True, 201)


def get_exp_203():
    return efficent_net(b_ver=0, dataset=DATASET_DEFAULT_V3_TRAIN)


def get_exp_204():
    return efficent_net(b_ver=0, dataset=DATASET_DEFAULT_V3_TRAIN, fine_tuning=True, exp_number_to_fine_tune=203)


def get_exp_205():
    return efficent_net(b_ver=1, dataset=DATASET_DEFAULT_V3_TRAIN)


def get_exp_206():
    return efficent_net(b_ver=1, dataset=DATASET_DEFAULT_V3_TRAIN, fine_tuning=True, exp_number_to_fine_tune=205)


def get_exp_207():
    return efficent_net(b_ver=2, dataset=DATASET_DEFAULT_V3_TRAIN)


def get_exp_208():
    return efficent_net(b_ver=2, dataset=DATASET_DEFAULT_V3_TRAIN, fine_tuning=True, exp_number_to_fine_tune=207)


def get_exp_209():
    return efficent_net_v2(ver='21k-s', dataset=DATASET_DEFAULT_V3_TRAIN)


def get_exp_210():
    return efficent_net_v2(ver='21k-s', dataset=DATASET_DEFAULT_V3_TRAIN, fine_tuning=True, exp_number_to_fine_tune=209)


def get_exp_211():
    return efficent_net_v2(ver='b3-300', dataset=DATASET_DEFAULT_V3_TRAIN)


def get_exp_212():
    return efficent_net_v2(ver='b3-300', dataset=DATASET_DEFAULT_V3_TRAIN, fine_tuning=True,
                           exp_number_to_fine_tune=211)


def get_exp_213():
    return efficent_net_v2(ver='b3-360', dataset=DATASET_DEFAULT_V3_TRAIN)


def get_exp_214():
    return efficent_net_v2(ver='b3-360', dataset=DATASET_DEFAULT_V3_TRAIN, fine_tuning=True,
                           exp_number_to_fine_tune=213)
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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360


def mobilenet(dataset, preprocessing: keras.Sequential = None, fine_tuning=False, exp_number=None, new_dim=360):
    if fine_tuning and exp_number is None:
        raise Exception("Exp number must be specified for fine tuning!")

    inputs = keras.Input(shape=(img_height, img_width, 3))

    base_model = keras.applications.MobileNet(
        weights='imagenet',  # Load weights pre-trained on ImageNet.
        input_shape=(new_dim, new_dim, 3),
        include_top=False)  # Do not include the ImageNet classifier at the top.

    base_model.trainable = False

    resize_layer = layers.experimental.preprocessing.Resizing(new_dim, new_dim, interpolation='bilinear')
    if preprocessing is None:
        preprocessing = keras.Sequential([resize_layer])
    # else:
    #     preprocessing.add(resize_layer)

    x = preprocessing(inputs)
    x = tf.keras.applications.mobilenet.preprocess_input(x)
    x = base_model(x, training=False)
    x = keras.layers.GlobalAveragePooling2D()(x)
    x = keras.layers.Dropout(0.2)(x)

    outputs = keras.layers.Dense(num_classes)(x)
    model = keras.Model(inputs, outputs)

    if fine_tuning:
        model.load_weights('training_' + str(exp_number) + '/cp_best.ckpt')
        model.compile(optimizer='adam', metrics=['accuracy'],
                      loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))
        base_model.trainable = True

    return model, 'adam' if not fine_tuning else keras.optimizers.Adam(1e-5), dataset


def get_exp_215():
    rotation_factor = 0.03  # * 2pi = about 10° degrees rotation
    zoom_factor = (0.234, 0.234)  # when full rotation specified above, the zoom will remove tha paddings

    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomRotation((-rotation_factor, rotation_factor)),
        layers.experimental.preprocessing.RandomZoom(height_factor=zoom_factor, width_factor=zoom_factor),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation)


def get_exp_216():
    rotation_factor = 0.0138  # * 2pi = about 5° degrees rotation
    zoom_factor = (0.134, 0.134)  # when full rotation specified above, the zoom will remove tha paddings

    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomRotation((-rotation_factor, rotation_factor)),
        layers.experimental.preprocessing.RandomZoom(height_factor=zoom_factor, width_factor=zoom_factor),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation)


def get_exp_217():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomFlip(mode="horizontal"),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation)


# 217 fine tuning
def get_exp_218():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomFlip(mode="horizontal"),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation, True, 217)


# another 10 epochs of 218 .. best was probably 35 epochs totally BEST SO FAR EVER
def get_exp_219():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomFlip(mode="horizontal"),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation, True, 218)


def get_exp_220():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomContrast(factor=0.1),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation)


def get_exp_221():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomContrast(factor=0.2),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation)


def get_exp_222():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomContrast(factor=0.3),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation)


def get_exp_223():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomCrop(360, 360)
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation)


def get_exp_224():
    dim = 224
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomCrop(dim, dim)
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation, new_dim=dim)


# finetuning of 221
def get_exp_225():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomContrast(factor=0.2),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation, True, 221)


def get_exp_226():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomContrast(factor=0.2),
        layers.experimental.preprocessing.RandomFlip(mode="horizontal"),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation)


def get_exp_227():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomContrast(factor=0.2),
        layers.experimental.preprocessing.RandomFlip(mode="horizontal"),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation, True, 226)


# fine tuning of 220
def get_exp_228():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomContrast(factor=0.1),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation, True, 220)


def get_exp_229():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomContrast(factor=0.1),
        layers.experimental.preprocessing.RandomFlip(mode="horizontal"),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation)


# fine tuning 229
def get_exp_230():
    data_augmentation = keras.Sequential([
        layers.experimental.preprocessing.RandomContrast(factor=0.1),
        layers.experimental.preprocessing.RandomFlip(mode="horizontal"),
        layers.experimental.preprocessing.Resizing(360, 360, interpolation='bilinear')
    ])

    return mobilenet(DATASET_DEFAULT_V3_TRAIN, data_augmentation, True, 229)