import tensorflow as tf
import keras_cv
import tensorflow_datasets as tfds
from tensorflow.keras import optimizers
from tensorflow.keras import callbacks
import numpy as np
BATCH_SIZE = 4
IMAGE_SIZE = (640, 640, 3)
NUM_CLASSES = 80
LEARNING_RATE = 0.001
EPOCHS = 100
def load_coco_dataset(split, batch_size=BATCH_SIZE, image_size=IMAGE_SIZE[:2]):
dataset = tfds.load(
"coco/2017",
split=split,
with_info=False,
shuffle_files=True
)
def process_data(sample):
image = tf.cast(sample["image"], tf.float32) / 255.0
image = tf.image.resize(image, image_size)
boxes = sample["objects"]["bbox"]
boxes = keras_cv.bounding_box.convert_format(
boxes,
source="rel_yxyx",
target="xywh"
)
classes = tf.cast(sample["objects"]["label"], tf.float32)
classes = tf.expand_dims(classes, axis=-1)
bounding_boxes = tf.concat([boxes, classes], axis=-1)
bounding_boxes = {
"boxes": bounding_boxes[..., :4],
"classes": bounding_boxes[..., 4]
}
return {"images": image, "bounding_boxes": bounding_boxes}
dataset = dataset.map(process_data, num_parallel_calls=tf.data.AUTOTUNE)
dataset = dataset.apply(
tf.data.experimental.dense_to_ragged_batch(batch_size)
return dataset.prefetch(tf.data.AUTOTUNE)
train_ds = load_coco_dataset("train", batch_size=BATCH_SIZE)
val_ds = load_coco_dataset("validation", batch_size=BATCH_SIZE)
model = keras_cv.models.YOLOV8Detector(
num_classes=NUM_CLASSES,
bounding_box_format="xywh",
backbone=keras_cv.models.YOLOV8Backbone.from_preset(
"yolo_v8_m_backbone_coco"
),
fpn_depth=2
)
model.compile(
optimizer=optimizers.Adam(learning_rate=LEARNING_RATE),
classification_loss="binary_crossentropy",
box_loss="ciou"
)
checkpoint = callbacks.ModelCheckpoint(
"yolov8_checkpoint.keras",
save_best_only=True,
monitor="val_loss"
)
early_stop = callbacks.EarlyStopping(
monitor="val_loss",
patience=10,
restore_best_weights=True
)
model.fit(
train_ds,
validation_data=val_ds,
epochs=EPOCHS,
callbacks=[checkpoint, early_stop]
)