-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrain.py
330 lines (262 loc) · 10.1 KB
/
train.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
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
import itertools
import pathlib
import os.path
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
DATASET_DIR = pathlib.Path(
tf.keras.utils.get_file(
fname="American_Sign_Language_Letters_Multiclass.tar",
origin="file:./datasets/American_Sign_Language_Letters_Multiclass.tar.gz",
file_hash="f76def78d7efbfd23ca9340a58fce1026dca21500efa2764caa064fa843fdf23",
extract=True,
)
).with_suffix("")
CHECKPOINT_PATH: str = "./checkpoint/"
TFLITE_FNAME: str = "model.tflite"
MODEL_DIAGRAM_PATH: str = "/tmp/"
BATCH_SIZE: int = 64
IMAGE_SIZE: tuple[int, int] = (160, 160)
IMAGE_SHAPE: tuple[int, int, int] = IMAGE_SIZE + (3,)
VALIDATION_SPLIT: float = 0.2
DATA_AUGMENTATION_FACTOR: float = 0.03
DROPOUT_RATE: float = 0.2
L2_REGULARIZATION: float = 0.0001
BASE_LEARNING_RATE: float = 0.005
BASE_LR_DECAY_STEPS: int = 300
BASE_LR_DECAY_RATE: float = 0.85
INITIAL_EPOCHS: int = 64
FINE_TUNE_LEARNING_RATE: float = 0.00005
FINE_TUNE_LR_DECAY_STEPS: int = 200
FINE_TUNE_LR_DECAY_RATE: float = 0.95
FINE_TUNE_EPOCHS: int = 32
FINE_TUNE_AT: int = 80
EARLYSTOP_MIN_DELTA: float = 0.00001
EARLYSTOP_PATIENCE: int = 3
OPTIMIZE_TFLITE: bool = False
NUM_CALIBRATION_EXAMPLES: int = 150
def build_dataset(validation_split: float, subset: str) -> tf.data.Dataset:
return tf.keras.preprocessing.image_dataset_from_directory( # type: ignore
directory=DATASET_DIR,
validation_split=validation_split,
subset=subset,
seed=123,
image_size=IMAGE_SIZE,
batch_size=BATCH_SIZE,
)
def split_dataset(
validation_split: float,
) -> tuple[tf.data.Dataset, tf.data.Dataset, tuple[str]]:
train_dataset: tf.data.Dataset = build_dataset(validation_split, "training")
validation_dataset: tf.data.Dataset = build_dataset(validation_split, "validation")
class_names: tuple[str] = train_dataset.class_names
train_dataset = train_dataset.cache().prefetch(buffer_size=tf.data.AUTOTUNE)
validation_dataset = validation_dataset.cache().prefetch(
buffer_size=tf.data.AUTOTUNE
)
return train_dataset, validation_dataset, class_names
def build_model(num_classes: int) -> tuple[tf.keras.Model, tf.keras.Model]:
base_model: tf.keras.Model = tf.keras.applications.mobilenet_v2.MobileNetV2(
input_shape=IMAGE_SHAPE,
include_top=False,
weights="imagenet",
pooling="avg",
)
tf.keras.utils.plot_model(
base_model, to_file=MODEL_DIAGRAM_PATH + "base_model.png", show_shapes=True
)
base_model.trainable = False
data_augmentation: tf.keras.Sequential = tf.keras.Sequential(
[
tf.keras.layers.RandomFlip(mode="horizontal", input_shape=IMAGE_SHAPE),
tf.keras.layers.RandomRotation(factor=DATA_AUGMENTATION_FACTOR),
tf.keras.layers.RandomTranslation(
height_factor=DATA_AUGMENTATION_FACTOR,
width_factor=DATA_AUGMENTATION_FACTOR,
),
tf.keras.layers.RandomZoom(
height_factor=DATA_AUGMENTATION_FACTOR,
width_factor=DATA_AUGMENTATION_FACTOR,
),
]
)
inputs = tf.keras.Input(shape=IMAGE_SHAPE)
x = data_augmentation(inputs)
x = tf.keras.applications.mobilenet_v2.preprocess_input(x)
x = base_model(x, training=False)
x = tf.keras.layers.Dropout(rate=DROPOUT_RATE)(x)
outputs = tf.keras.layers.Dense(
num_classes,
activation="softmax",
kernel_regularizer=tf.keras.regularizers.l2(l2=L2_REGULARIZATION),
name="outputs",
)(x)
model: tf.keras.Model = tf.keras.Model(inputs, outputs)
tf.keras.utils.plot_model(
model, to_file=MODEL_DIAGRAM_PATH + "fine_tune_model.png", show_shapes=True
)
lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
BASE_LEARNING_RATE,
decay_steps=BASE_LR_DECAY_STEPS,
decay_rate=BASE_LR_DECAY_RATE,
staircase=True,
)
model.compile(
optimizer=tf.keras.optimizers.Nadam(learning_rate=lr_schedule), # type: ignore
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=["accuracy"],
)
return base_model, model
def fine_tune_model(base_model: tf.keras.Model, model: tf.keras.Model):
base_model.trainable = True
for layer in base_model.layers[:FINE_TUNE_AT]:
layer.trainable = False
lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
FINE_TUNE_LEARNING_RATE,
decay_steps=FINE_TUNE_LR_DECAY_STEPS,
decay_rate=FINE_TUNE_LR_DECAY_RATE,
staircase=True,
)
model.compile(
optimizer=tf.keras.optimizers.Nadam(learning_rate=lr_schedule), # type: ignore
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=["accuracy"],
)
return base_model, model
def plot_summary(
acc: tuple[float],
val_acc: tuple[float],
loss: tuple[float],
val_loss: tuple[float],
) -> None:
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label="Training Accuracy")
plt.plot(val_acc, label="Validation Accuracy")
plt.ylim([0.0, 1.0])
plt.plot(
[INITIAL_EPOCHS - 1, INITIAL_EPOCHS - 1], plt.ylim(), label="Start Fine Tuning"
)
plt.legend(loc="lower left")
plt.title("Training and Validation Accuracy")
plt.subplot(2, 1, 2)
plt.plot(loss, label="Training Loss")
plt.plot(val_loss, label="Validation Loss")
plt.ylim([0.0, 4.0])
plt.plot(
[INITIAL_EPOCHS - 1, INITIAL_EPOCHS - 1], plt.ylim(), label="Start Fine Tuning"
)
plt.legend(loc="lower left")
plt.title("Training and Validation Loss")
plt.xlabel("epoch")
plt.show()
def get_representative_dataset(dataset):
return itertools.islice(
([image[None, ...]] for images, _ in dataset for image in images),
NUM_CALIBRATION_EXAMPLES,
)
def save_model(model):
tf.saved_model.save(model, CHECKPOINT_PATH)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
if OPTIMIZE_TFLITE:
converter.optimizations = set([tf.lite.Optimize.DEFAULT])
if NUM_CALIBRATION_EXAMPLES:
converter.representative_dataset = ( # type: ignore
get_representative_dataset
)
lite_model_content = converter.convert()
with open(os.path.join(CHECKPOINT_PATH, TFLITE_FNAME), "wb") as f:
f.write(lite_model_content)
def load_model():
interpreter = tf.lite.Interpreter(
model_path=os.path.join(CHECKPOINT_PATH, TFLITE_FNAME)
)
# print(interpreter.get_signature_list())
classify_lite = interpreter.get_signature_runner("serving_default")
return classify_lite
def lite_model(interpreter, images):
interpreter.allocate_tensors()
interpreter.set_tensor(interpreter.get_input_details()[0]["index"], images)
interpreter.invoke()
return interpreter.get_tensor(interpreter.get_output_details()[0]["index"])
def evaluate_model(model, dataset):
y_pred = []
y_true = []
for images, labels in dataset:
for image, label in zip(images, labels):
y_pred.append(np.argmax(model(image[None, ...]).numpy()[0]))
y_true.append(label.numpy())
return y_pred, y_true
def evaluate_tflite(classify_lite, dataset):
y_pred = []
y_true = []
for images, labels in dataset:
for image, label in zip(images, labels):
y_pred.append(np.argmax(classify_lite(input_2=image[None, ...])["outputs"]))
y_true.append(label.numpy())
return y_pred, y_true
if __name__ == "__main__":
train_dataset, validation_dataset, class_names = split_dataset(VALIDATION_SPLIT)
print(f"Class names:\n{class_names}")
base_model, model = build_model(len(class_names))
print(f"Base model layer count: {len(base_model.layers)}")
model.summary()
print(f"Trainable variables in our model: {len(model.trainable_variables)}")
earlystop_callback = tf.keras.callbacks.EarlyStopping(
monitor="val_accuracy",
min_delta=EARLYSTOP_MIN_DELTA, # type: ignore
patience=EARLYSTOP_PATIENCE,
restore_best_weights=True,
verbose=1,
)
history = model.fit(
train_dataset,
callbacks=[earlystop_callback],
epochs=INITIAL_EPOCHS,
validation_data=validation_dataset,
)
if earlystop_callback.stopped_epoch and earlystop_callback.stopped_epoch > 0:
if earlystop_callback.best_epoch and earlystop_callback.best_epoch > 0:
INITIAL_EPOCHS = earlystop_callback.best_epoch + 1
else:
INITIAL_EPOCHS = earlystop_callback.stopped_epoch + 1
base_model, model = fine_tune_model(base_model, model)
model.summary()
print(f"Number of trainable variables: {len(model.trainable_variables)}")
fine_tune_history = model.fit(
train_dataset,
callbacks=[earlystop_callback],
epochs=(INITIAL_EPOCHS + FINE_TUNE_EPOCHS),
initial_epoch=INITIAL_EPOCHS,
validation_data=validation_dataset,
)
acc: tuple[float] = (
history.history["accuracy"] + fine_tune_history.history["accuracy"]
)
val_acc: tuple[float] = (
history.history["val_accuracy"] + fine_tune_history.history["val_accuracy"]
)
loss: tuple[float] = history.history["loss"] + fine_tune_history.history["loss"]
val_loss: tuple[float] = (
history.history["val_loss"] + fine_tune_history.history["val_loss"]
)
save_model(model)
plot_summary(acc, val_acc, loss, val_loss)
# print("-" * 20, "RESULTS", "-" * 20)
# model_predictions, model_labels = evaluate_model(model, validation_dataset)
# classify_lite = load_model()
# tflite_predictions, tflite_labels = evaluate_tflite(
# classify_lite, validation_dataset
# )
# results: list[dict[str, str]] = []
# for model_label, model_prediction, tflite_prediction in zip(
# model_labels, model_predictions, tflite_predictions
# ):
# results.append(
# {
# "true": class_names[model_label],
# "model_pred": class_names[model_prediction],
# "tflite_pred": class_names[tflite_prediction],
# }
# )
# # print(results)