text_plain_output_1.png
from tensorflow.keras import layers

from tensorflow.keras.layers.experimental import preprocessing

from tensorflow.keras.models import Sequential

import datetime

import tensorflow as tf

def create_tensorboard_callback(dir_name, experiment_name):
    """
    Creates a TensorBoard callback instand to store log files.
    Stores log files with the filepath: "dir_name/experiment_name/current_datetime/"
    Args:
    dire_name: target directory to store TensorBoard log files
    experiment_name: name of experiment directory (e.g. efficientnet_model_1)
    """
    log_dir = dir_name + '/' + experiment_name + '/' + datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
    tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir)
    return tensorboard_callback

train_dir = '101_food_classes_10_percent/train/'
test_dir = '101_food_classes_10_percent/test/'

IMG_SIZE = (224, 224)
train_data_all_10_percent = tf.keras.preprocessing.image_dataset_from_directory(train_dir, label_mode='categorical', image_size=IMG_SIZE)
test_data = tf.keras.preprocessing.image_dataset_from_directory(test_dir, label_mode='categorical', image_size=IMG_SIZE, shuffle=False)

checkpoint_path = '101_classes_10_percent_data_model_checkpoint'
checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_weights_only=True, monitor='val_accuracy', save_best_only=True)

data_augmentation = Sequential([preprocessing.RandomFlip('horizontal'), preprocessing.RandomRotation(0.2), preprocessing.RandomHeight(0.2), preprocessing.RandomWidth(0.2), preprocessing.RandomZoom(0.2)], name='Data_Augmentation')

base_model = tf.keras.applications.EfficientNetB0(include_top=False)
base_model.trainable = False
inputs = layers.Input(shape=(224, 224, 3), name='input_layer')
x = data_augmentation(inputs)
x = base_model(x, training=False)
x = layers.GlobalAveragePooling2D(name='global_avg_pooling')(x)
outputs = layers.Dense(len(train_data_all_10_percent.class_names), activation='softmax')(x)
model = tf.keras.Model(inputs, outputs)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history_all_classes_10_percent = model.fit(train_data_all_10_percent, epochs=5, validation_data=test_data, validation_steps=int(0.15 * len(test_data)), callbacks=[checkpoint_callback])

eval_results = model.evaluate(test_data)
eval_results

base_model.trainable = True
for layer in base_model.layers[:-5]:
    layer.trainable = False

model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), metrics=['accuracy'])
history_all_classes_10_percent_fine_tune = model.fit(train_data_all_10_percent, epochs=10, validation_data=test_data, validation_steps=int(0.15 * len(test_data)), callbacks=[checkpoint_callback], initial_epoch=history_all_classes_10_percent.epoch[-1])